Ansible:为新创建的实例分配弹性ip

时间:2015-10-27 09:41:46

标签: amazon-web-services ansible

我正在使用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}}”。

1 个答案:

答案 0 :(得分:3)

您基本上是在尝试解析Ansible任务的JSON输出中的数据,该输出将提供给您的变量。 instance_ids是newinstance 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