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

时间:2016-08-23 00:19:33

标签: 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_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'"}

1 个答案:

答案 0 :(得分:2)

如果等号右边的任何内容未定义,则带有debug

var=hostvars[item]['ec2_id']模块不会失败。
如果括号中的部分无法模板化,msg={{hostvars[item]['ec2_id']}}将会失败。

在您的示例中,localhost可能会失败,因为我几乎可以确定没有为localhost定义ec2_id

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

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