Ansible - 如何循环并获取新 EC2 实例的属性

Ansible - How to loop and get attributes of new EC2 instances

我正在使用这个 play 创建一组新的 EC2 实例

- hosts: localhost
  connection: local
  gather_facts: False
  tasks:
    - name: Provision a set of instances
      ec2:
        assign_public_ip: yes
        aws_access_key: XXXXXXXXXX
        aws_secret_key: XXXXXXXXXX
        group_id: XXXXXXXXXX
        instance_type: t2.micro
        image: ami-32a85152
        vpc_subnet_id: XXXXXXXXXX
        region: XXXXXXXXXX
        user_data: "{{ lookup('file', '/SOME_PATH/cloud-config.yaml') }}"
        wait: true
        exact_count: 1
        count_tag:
          Name: Demo
        instance_tags:
          Name: Demo
      register: ec2
    - name: Add new CoreOS machines to coreos-launched group
      add_host: hostname="{{ item.public_ip }}" groups=coreos-launched
      with_items: "{{ ec2.instances }}"
    - name: Wait for SSH to come up
      wait_for: host="{{ item.public_dns_name }}" port=22 delay=60 timeout=320
      with_items: "{{ ec2.instances }}"

现在,我需要为每台新机器创建一个 SSL/TLS 证书。为此,我需要他们的私有 IP。然而,我不知道如何访问我在上次玩时注册的“{{ ec2.instances }}”

我在同一个剧本中尝试了一些东西来做这样的事情

- hosts: coreos-launched
  gather_facts: False
  tasks:
    - name: Find the current machine IP addresse
      command: echo "{{ item.private_ip }}" > /tmp/private_ip
      with_items: "{{ ec2.instances }}"
      sudo: yes

但是没有任何成功。有没有办法在同一个剧本但不同的剧本中使用“{{ ec2.instances }}”项目?

-- 编辑--

按照 Theo 的建议,我设法使用

获取实例属性
- name: Gather current facts
  action: ec2_facts
  register: ec2_facts
- name: Use the current facts
  command: echo "{{ ec2_facts.ansible_facts.ansible_ec2_local_ipv4 }}"
  with_items: "{{ ec2_facts }}"

了解 return 结构(缺少文档)的最佳方法是将其包装在调试任务中。

  - name: Debug ec2 variable
    debug: var=ec2.instances

从那里,按照结构获取您要查找的变量。

此外(遵循幂等模型),您可以使用 ec2_remote_facts 模块从实例中获取事实并在以后调用它们 plays/tasks。

有关调用已注册变量的详细信息,请参阅 Variables -- Ansible Documentation