ansible - 在 Ansible 中一起使用 set_facts 和 with_items

标签 ansible

我目前使用的是 Ansible 1.7.2。我有以下测试手册:

---
- hosts: localhost
  tasks:
  - name: set fact 1
    set_fact: foo="[ 'zero' ]"

  - name: set fact 2
    set_fact: foo="{{ foo }} + [ 'one' ]"

  - name: set fact 3
    set_fact: foo="{{ foo }} + [ 'two', 'three' ]"

  - name: set fact 4
    set_fact: foo="{{ foo }} + [ '{{ item }}' ]"
    with_items:
      - four
      - five
      - six

  - debug: var=foo

第一个任务设置一个事实,即一个包含一个项目的列表。后续任务会向该列表附加更多值。前三个任务按预期工作,但最后一个任务却没有。这是我运行此命令时的输出:

PLAY [localhost] **************************************************************

GATHERING FACTS ***************************************************************
ok: [localhost]

TASK: [set fact 1] ************************************************************
ok: [localhost]

TASK: [set fact 2] ************************************************************
ok: [localhost]

TASK: [set fact 3] ************************************************************
ok: [localhost]

TASK: [set fact 4] ************************************************************
ok: [localhost] => (item=four)
ok: [localhost] => (item=five)
ok: [localhost] => (item=six)

TASK: [debug var=foo] *********************************************************
ok: [localhost] => {
    "foo": [
        "zero",
        "one",
        "two",
        "three",
        "six"
    ]
}

PLAY RECAP ********************************************************************
localhost                  : ok=6    changed=0    unreachable=0    failed=0

考虑到任务 4 中的 with_items 以及输出显示任务正确迭代该列表中的项目这一事实,我预计结果将包含从 0 到 6 的所有数字。但最后一个任务似乎只是用列表中的最后一项来评估 set_fact 。这可能是 Ansible 中的一个错误吗?

编辑:我也刚刚在 ansible 1.8 上测试了这个,输出是相同的。

最佳答案

有一个解决方法可能会有所帮助。您可以“注册”每次 set_fact 迭代的结果,然后将该结果映射到列表:

---
- hosts: localhost
  tasks:
  - name: set fact
    set_fact: foo_item="{{ item }}"
    with_items:
      - four
      - five
      - six
    register: foo_result

  - name: make a list
    set_fact: foo="{{ foo_result.results | map(attribute='ansible_facts.foo_item') | list }}"

  - debug: var=foo

输出:

< TASK: debug var=foo >
 ---------------------
    \   ^__^
     \  (oo)\_______
        (__)\       )\/\
            ||----w |
            ||     ||


ok: [localhost] => {
    "var": {
        "foo": [
            "four", 
            "five", 
            "six"
        ]
    }
}

关于ansible - 在 Ansible 中一起使用 set_facts 和 with_items,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29399581/

相关文章:

ansible - 合并两个默认的 Ansible 主机文件,其中一个是 ec2.py?

python - Pip 正在回滚 setuptools 的卸载

ansible - Ansible 模板模块和复制模块有什么区别?

ansible - 从特定组的 ansible list 中获取变量

linux - Ansible wait_for 重启

loops - 如何在 Ansible 中强制执行 with_dict 的顺序?

ansible - 如何编写仅在任务文件中的任何其他先前任务已更改时才运行的Ansible角色任务?

python - Ansible:tasks/main.yml 文件中的操作语句存在冲突

linux - 是否有用于写入 ini 文件的 GNU/Linux 命令?

ssh - 使用 ansible 添加多个 SSH key