Ansible:如何在任务中访问主机变量?

nei*_*eil 6 ansible

我正在尝试在我的任务中使用主机变量。但似乎 ansible 正在插入变量,然后尝试在主变量 dict 对象中查找它。这是我的代码:

- 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
Run Code Online (Sandbox Code Playgroud)

我得到的错误是:

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'
Run Code Online (Sandbox Code Playgroud)

所以实例 ID 显然在 hostvars 字典中,但我似乎没有任何方法将它实际用作 ec2_ami 模块的 instance_id 参数。

我究竟做错了什么?引用 debug msg 没有区别,删除大括号只会打印文字 hostvars 字符串。

nei*_*eil 7

似乎答案是引用变量名称:'ansible_ec2_instance_id',即:

- debug: msg="{{ hostvars[groups['rundeck-masters'][0]]['ansible_ec2_instance_id'] }}"
Run Code Online (Sandbox Code Playgroud)

现在它可以正常工作。