简体   繁体   中英

referencing the instance id of an EC2 resource just created in Ansible

I am having a difficult time referencing the instance id of an EC2 resource that I have just created. After I create it, I would immediately like to terminate it. My code is below:

Thank you, Bill

---
- name: Example of provisioning servers
  hosts: 127.0.0.1

  connection: local
  tasks:
   - name: set_fact1
     set_fact: foo = 1

   - name: Create security group
     local_action:
       module: ec2_group
       name: ep2
       description: Access to the Episode2 servers
       region: us-east-1
       rules:
         - proto: tcp
           from_port: 22
           to_port: 22
           cidr_ip: 0.0.0.0/0

   - name: Launch instances
     local_action:
       module: ec2
       instance_tags:
        Name: server1
        Env: myenv
       region: us-east-1
       keypair: ansiblekeypair
       group: ep2
       instance_type: m1.small
       image: ami-1aae3a0c
       count: 1
       wait: yes
     register: ec2

   - name: Terminate instances that were previously launched
     ec2:
       state: absent
       region: us-east-1
       instance_ids: "{{ ec2.instance_id[0] }}"
     with_items: ec2

You need to reference ec2.instances[0].id .

It is useful to use - debug: var=ec2 task or run playbook with -vv switch to see detailed values of registered variables and check what properties are available for use.

If you want to terminate the instances just launched (assuming that their tags are specific) you could also use the exact_count facility:

   exact_count: 0
   count_tag: 
     - Name: server1
     - Env: myenv

As per the doc (highlights are mine):

exact_count

An integer value which indicates how many instances that match the count_tag parameter should be running. Instances are either created or terminated based on this value.

and count_tag :

Used with exact_count to determine how many nodes based on a specific tag criteria should be running . [...]

It would give something like:

- name: Terminate instances
     local_action:
       module: ec2
       instance_tags:
        Name: server1
        Env: myenv
       region: us-east-1
       keypair: ansiblekeypair
       exact_count: 0
       count_tag: 
         - Name: server1
         - Env: myenv
       wait: yes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM