【问题标题】:Ansible with_items if item is definedAnsible with_items 如果项目已定义
【发布时间】:2016-02-18 00:42:49
【问题描述】:

Ansible 1.9.4.

脚本应该只在定义了一些变量的主机上执行一些任务。它可以正常工作,但不适用于with_items 语句。

- debug: var=symlinks
  when: symlinks is defined

- name: Create other symlinks
  file: src={{ item.src }} dest={{ item.dest }} state=link
  with_items: "{{ symlinks }}"
  when: symlinks is defined

但我明白了:

TASK: [app/symlinks | debug var=symlinks] *********************
skipping: [another-host-yet]

TASK: [app/symlinks | Create other symlinks] ******************
fatal: [another-host-yet] => with_items expects a list or a set

也许我做错了什么?

【问题讨论】:

  • symlinks的值是多少?
  • 问题是同一个主机,这个变量没有定义

标签: ansible


【解决方案1】:
with_items: "{{ symlinks | default([]) }}"

【讨论】:

    【解决方案2】:

    这种行为的原因是条件在循环内的工作方式不同。如果定义了循环,则在迭代项目时为每个项目评估条件。但是循环本身需要一个有效的列表。

    这也提到了in the docs

    请注意,当将 when 与 with_items 结合使用时(请参阅Loops),请注意 when 语句是针对每个项目单独处理的。这是设计使然:

    tasks:
      - command: echo {{ item }}
        with_items: [ 0, 2, 4, 6, 8, 10 ]
        when: item > 5
    

    我认为这是一个糟糕的设计选择,对于这个功能,他们最好引入with_when 之类的东西。

    正如您自己已经弄清楚的那样,您可以默认为一个空列表。

    with_items: "{{ symlinks  | default([]) }}"
    

    最后,如果列表是从 var 动态加载的,比如 x,请使用:

    with_items: "{{ symlinks[x|default('')] | default([])}}" 
    

    当 'x' 未定义时,这将默认为一个空列表

    因此,使用default({}) 回退到一个空字典:

    # service_facts skips, then dict2items fails?
    with_dict: "{{ ansible_facts.services|default({})|dict2items|selectattr('key', 'match', '[^@]+@.+\\.service')|list|items2dict }}"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-10
      • 1970-01-01
      • 1970-01-01
      • 2019-12-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多