Ansible 何时填充hostvars数据以及如何访问它?

Ansible 何时填充hostvars数据以及如何访问它?,ansible,Ansible,这是我的剧本: - name: Tag ec2 instances hosts: localhost tasks: - name: Print Hosts debug: var=hostvars[item]['ec2_id'] with_inventory_hostnames: all - name: Print Hosts 2 debug: msg={{hostvars[item]['ec2_id']}} with_i

这是我的剧本:

- name: Tag ec2 instances 
  hosts: localhost
  tasks:
    - name: Print Hosts
      debug: var=hostvars[item]['ec2_id']
      with_inventory_hostnames: all

    - name: Print Hosts 2
      debug: msg={{hostvars[item]['ec2_id']}}
      with_inventory_hostnames: all

    - name: Tag Hosts
      ec2_tag:
        resource: "{{ hostvars[item]['ec2_id'] }}"
        region: ap-southeast-2
        args:
          tags: {mytag: 'myvalue'}
      with_inventory_hostnames: all
有人能解释为什么第二个任务失败并出现以下错误,而第一个任务成功了吗

...
ok: [localhost] => (item=172.31.11.37) => {
    "hostvars[item]['ec2_id']": "i-xxxxxx", 
    "item": "172.31.11.37"
}

TASK [Print Hosts 2] ***********************************************************
fatal: [localhost]: FAILED! => {"failed": true, "msg": "'dict object' has no attribute 'ec2_id'"}

如果等号右边的任何内容未定义,则带
var=hostvars[item]['ec2_id']
调试
模块不会失败。
msg={{hostvars[item]['ec2_id']}}
将在大括号中的部分无法模板化时失败

在您的示例中,这对于
localhost
可能会失败,因为我几乎可以肯定
ec2\u id
没有为localhost定义

为了避免这种情况,可以对循环应用
when
语句,如下所示:

- name: Print Hosts 2
  debug: msg={{hostvars[item]['ec2_id']}}
  when: hostvars[item]['ec2_id'] is defined
  with_inventory_hostnames: all

如果等号右边的任何内容未定义,则带
var=hostvars[item]['ec2_id']
调试
模块不会失败。
msg={{hostvars[item]['ec2_id']}}
将在大括号中的部分无法模板化时失败

在您的示例中,这对于
localhost
可能会失败,因为我几乎可以肯定
ec2\u id
没有为localhost定义

为了避免这种情况,可以对循环应用
when
语句,如下所示:

- name: Print Hosts 2
  debug: msg={{hostvars[item]['ec2_id']}}
  when: hostvars[item]['ec2_id'] is defined
  with_inventory_hostnames: all

我不明白!同一对象用于两个任务,但在第二个任务中失败。感谢用户2864740。我明白你的意思。要将问题标题更改为“何时填充hostvars数据以及如何访问它?”有关如何解决此问题的任何建议,请执行:
-name:Tag ec2 instances hosts:localhost tasks:-name:Print hosts debug:var=hostvars[item]['ec2_id']with\u inventory\u hostnames:all register:ught\name:New Print Hosts\debug:msg={item[“hostvars[item]['ec2\u id']”]]}}with\u items:ught.results-name:Tag Hosts ec2\u Tag:state:present resource:{{{{item[\'hostvars[item]['ec2\u id']\]}}地区:ap-Southast-2标签:关机下午:不,不,项目:丑陋。结果
您可以回答自己的问题,但不要将答案放在评论中。无法理解!同一对象用于两个任务,但在第二个任务中失败。感谢用户2864740。我明白你的意思。要将问题标题更改为“何时填充hostvars数据以及如何访问它?”有关如何解决此问题的任何建议,请执行:
-name:Tag ec2 instances hosts:localhost tasks:-name:Print hosts debug:var=hostvars[item]['ec2_id']with\u inventory\u hostnames:all register:ught\name:New Print Hosts\debug:msg={item[“hostvars[item]['ec2\u id']”]]}}with\u items:ught.results-name:Tag Hosts ec2\u Tag:state:present resource:{{{{item[\'hostvars[item]['ec2\u id']\]}}地区:ap-Southast-2标签:关机下午:不,项目:丑陋。结果
您可以回答自己的问题,但不要将答案放在评论中。非常感谢康斯坦丁!多么愚蠢的问题!不确定localhost是否是列表中的第一个,因此任务在开始时失败,或者ansible是否先检查整个列表,然后运行循环。非常感谢Konstantin!多么愚蠢的问题!不确定localhost是否是列表中的第一个,因此任务在开始时失败,或者ansible是否先检查整个列表,然后运行循环。