referencing the instance id of an EC2 resource just created

20 views
Skip to first unread message

Bill L.

unread,
Jun 20, 2017, 5:18:28 PM6/20/17
to Ansible Project
Hello,
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

Michael Bushey

unread,
Jun 20, 2017, 9:21:59 PM6/20/17
to Ansible Project
I don't think this works in Ansible. The ec2 functionality seems very marginal and defective. I split the playbooks into two parts. The first spins up the instance. Then I go to the aws console to assign the correct IAM role to the instance as I can't figure out how to do this in Ansible. Then I run

ssh {IP or name} "test -e /usr/bin/python || (apt -qqy update && apt install -qqy python-minimal)"

to install python 2.x so Ansible can run commands on the machine. Then I can run the second playbook to configure the server.

Bill L.

unread,
Jun 21, 2017, 9:38:13 AM6/21/17
to Ansible Project
Hmm. That seems rather complex. Do you happen to know what the prescribed method of doing this is? Does Ansible recommend using add_hosts module? 
Reply all
Reply to author
Forward
0 new messages