我正在尝试在我的任务中使用hostvars。 但是,似乎有道理的是插入variables,然后尝试在主variablesdict对象中查找它。 这是我的代码:
- name: Configure the instance hosts: rundeck-masters sudo: True gather_facts: True tasks: - name: Gather EC2 facts ec2_facts: # show all known facts for this host - debug: msg={{ hostvars[groups['rundeck-masters'][0]][ansible_ec2_instance_id] }} - name: Snapshot the instance local_action: module: ec2_ami description: "Rundeck master - {{ ansible_date_time.date }}" instance_id: "{{ hostvars[groups['rundeck-masters'][0]][ansible_ec2_instance_id] }}" wait: no
而我得到的错误是:
TASK: [debug msg={{ hostvars[groups['rundeck-masters'][0]][ansible_ec2_instance_id] }}] *** fatal: [ec2-xx-xx-xx-xx.eu-west-1.compute.amazonaws.com] => One or more undefined variables: 'dict object' has no attribute u'i-12341234'
所以实例ID显然是在hostvars字典中,但我似乎没有任何实际使用它作为ec2_ami模块的instance_id参数的方法。
我究竟做错了什么? 引用debugging信息没有任何区别,删除大括号只是打印字面hostvarsstring。
看来答案是引用variables名:'ansible_ec2_instance_id',即:
- debug: msg="{{ hostvars[groups['rundeck-masters'][0]]['ansible_ec2_instance_id'] }}"
现在它工作正常。