Ansible:为新创建的实例分配一个弹性IP

Ansible: allocating an elastic ip to newly created instance

我正在使用 ansible 创建一个新实例,并希望将弹性 ip 关联到它。我应该在 instance_id 中写什么值? instance_id: "{{ newinstance.instances[0].id }}" ???但是这个值好像是错误的,因为我检查后有一个输出:

TASK: [Allocating elastic IP to instance]     *************************************
fatal: [localhost] => One or more undefined variables: 'dict object' has no attribute 'instances'

---
- name: Setup an EC2 instance
  hosts: localhost
  connection: local
  tasks:

    - name: Create an EC2 machine
      ec2:
        aws_access_key: my_access_key
        aws_secret_key: my_secret_key
        key_name: my_key
        instance_type: t1.micro
        region: us-east-1
        image: some_ami
        wait: yes
        vpc_subnet_id: my_subnet
        assign_public_ip: yes
      register: newinstance

    - name: Allocating elastic IP to instance
      ec2_eip:
        aws_access_key: my_access_key
        aws_secret_key: my_secret_key
        in_vpc: yes
        reuse_existing_ip_allowed: yes
        state: present
        region: us-east-1
        instance_id: "{{ newinstance.instances[0].id }}"
      register: instance_eip
    - debug: var=instance_eip.public_ip

    - name: Wait for SSH to start
      wait_for:
        host: "{{ newinstance.instances[0].private_ip }}"
        port: 22
        timeout: 300
        sudo: false
      delegate_to: "127.0.0.1"

    - name: Add the machine to the inventory
      add_host:
        hostname: "{{ newinstance.instances[0].private_ip }}"
        groupname: new

我应该用什么代替“{{ newinstance.instances[0].id }}”?同样的问题是关于“{{ newinstance.instances[0].private_ip }}”。

您基本上是在尝试从 Ansible 任务的 JSON 输出中解析数据,该任务已提供给您的变量。 instance_ids 是新实例 JSON 的数组和子实例。同样 private_ip 是 newinstance

的直接子代
---
- name: Setup an EC2 instance
  hosts: localhost
  connection: local
  tasks:

 - name: Create an EC2 machine
   ec2:
    aws_access_key: my_access_key
    aws_secret_key: my_secret_key
    key_name: my_key
    instance_type: t1.micro
    region: us-east-1
    image: some_ami
    wait: yes
    vpc_subnet_id: my_subnet
    assign_public_ip: yes
  register: newinstance

- name: Allocating elastic IP to instance
  ec2_eip:
    aws_access_key: my_access_key
    aws_secret_key: my_secret_key
    in_vpc: yes
    reuse_existing_ip_allowed: yes
    state: present
    region: us-east-1
    instance_id: "{{ newinstance.instance_ids[0] }}"
  register: instance_eip
- debug: var=instance_eip.public_ip

- name: Wait for SSH to start
  wait_for:
    host: "{{ newinstance.private_ip }}"
    port: 22
    timeout: 300
    sudo: false
  delegate_to: "127.0.0.1"

- name: Add the machine to the inventory
  add_host:
    hostname: "{{ newinstance.private_ip }}"
    groupname: new