首页 > 解决方案 > 如何在ansible playbook的另一个任务中循环set_fact属性

问题描述

我在我的 ansible 剧本中使用 set_fact 结果中的 with_items 进行循环。

- set_fact:
    TAGNAME: "TEST-EC2-0{{item}}"
    TAGOWNER: LOGIN
    TAGROLE: DB
  with_sequence: start=01 end="{{ count }}"
  register: tagname

下面是 set_fact 使用调试的结果,我得到了这个。

"results": [
    {
        "_ansible_ignore_errors": null, 
        "_ansible_item_label": "1", 
        "_ansible_item_result": true, 
        "_ansible_no_log": false, 
        "ansible_facts": {
            "TAGNAME": "TEST-EC2-01", 
            "TAGOWNER": "LOGIN", 
            "TAGROLE": "DB"
        }, 
        "changed": false, 
        "failed": false, 
        "item": "1"
    }, 
    {
        "_ansible_ignore_errors": null, 
        "_ansible_item_label": "2", 
        "_ansible_item_result": true, 
        "_ansible_no_log": false, 
        "ansible_facts": {
            "TAGNAME": "TEST-EC2-02", 
            "TAGOWNER": "LOGIN", 
            "TAGROLE": "DB"
        }, 
        "changed": false, 
        "failed": false, 
        "item": "2"
    }
]

有了这个给定的输出,每当我使用 COUNT 模块创建多个实例时,我想使用下面 ec2 任务中的所有“TAGNAME”进行标记。

    ec2:
    ....
    ....
    ....
    instance_tags:
        Name: "{{ item.TAGNAME }}"
        Owner: "LOGIN"
    with_items: "{{ tagname.results }}"

但是当我触发剧本时,我遇到了错误

fatal: [localhost]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'item' is undefined\n\nThe error appears to have been in 'local/apps/roles/EC2_Deploy/tasks/ec2_creation.yml': line 217, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- name: Create Instances\n  ^ here\n"}

我不确定我错过了什么和在哪里。有人可以帮我吗?

标签: loopsansibleansible-facts

解决方案


推荐阅读