Technology

Remove an EC2 host with Ansible

I spent forever trying to understand the built in Ansible ec2 modules.  What I was trying to figure out seemed simple:  How do you delete all your ec2 instances?  Nothing too clever.  Turns out it was easier to create the instances than delete it (for me anyway).  So I'm writing this down here so I remember. I've also created an Ansible playbook github repository where I'll be putting all the stuff I use.   I also plan on doing a post where I show how my environment was set up. For now, here is the playbook:
# Delete's AWS images
# this post has way to get images. 
# call with: ansible-playbook terminate-ec2.yml
# requires that you have boto installed and a ~/.boto file installed.
# the .boto file should have the following env variables: 
# aws_access_key_id = ABCD...
# aws_secret_access_key = ZYXWVUTSR..

- hosts: ec2
  gather_facts: True
  connection: local
  vars: 
    - region: 'us-west-2'
  tasks:
    - name: Gather EC2 facts
      local_action: ec2_facts

    - debug: var=hostvars[inventory_hostname]
    - debug: msg="{{ hostvars[inventory_hostname]['ec2_id'] }}"

    - name: Terminate instances 
      local_action: ec2
        state='absent'
        instance_ids='{{ ec2_id }}'
        region='{{ region }}'
        wait=True
The tricky part for me was trying to get the data from the ec2_facts module into the rest of the playbook.  It turns out that ec2_facts loads the data into the hostvars[inventory_hostname] variable.  I was looking for instance_id as the variable, but it didn't populate this.  This may be that I have an older version of Ansible (1.2.7) that comes installed with homebrew on the mac. If you find this ec2_id variable doesn't work for getting the instance ID of the AWS instance, then take a look at the debug statements to see what is populated in the hostsvars[inventory_hostname] I should also point out that the host group that it uses above 'ec2' is from the ec2.py executable that comes with Ansible that I put in my inventory directory. More on that in a coming post.