Getting the tags of an EC2 instance in Ansible

Say you are working on some Ansible for a client and they say to you “Hey, I really like the stuff you did but it’d be helpful if I knew what box I was SSH’d into.” since EC2 hostnames default to a dashed notation of their private IP address.

“Sure, this is 2016” you say foolishly, “someone has obviously already done this and it’s probably just an extra task”. Oh, how wrong you are.

A quick Google search later, you find out there is the ec2_facts module, which essentially acts as a wrapper around the EC2 metadata service. Surely AWS just lets you query for the tags associated with your instance through this, right? Wrong.

For some reason, even in the year 2016, Amazon has decided you have to go through their other API’s to get the tags because of course they did. So you keep digging through the Ansible modules assuming that some kind soul wrote something to do this exact thing.

Aha! You have found it. The ec2_tag module has a state: list that allows you list the tags. In the example they show they even show you using the ec2_facts module to get the region and instance ID and feeding that into the ec2_tag module to eventually get the Name tag. Awesome! You place that into your playbook, run it and…

…boom…

You are (probably) told you need to install boto, since by default Ansible runs these tasks remotely on the hosts you’re provisioning and you (probably) didn’t need boto on there to begin with. And if you go and install pip and then boto, you still need to provide AWS credentials so the EC2 instance you’re on can go and query the tags (or you could assign an IAM Role if you’re slick). But you think to yourself “this is really dumb and I don’t want to deal with the headaches of storing AWS creds in my vars and I can query this from my laptop so why can’t I just do that and why is this sentence so long now?” Finally you go and ask someone way smarter than you are and after talking about filter plugins and lookup plugins and custom modules, they casually mention local actions and since you already have boto installed locally on your laptop, everything magically works. And with that, you write a blog post, close your laptop and go to sleep.

  - name: Gather EC2 instance metadata
    action: ec2_facts

  - name: Obtain EC2 tags for this instance
    local_action:
      module: ec2_tag
      region: "{{ ansible_ec2_placement_region }}"
      resource: "{{ ansible_ec2_instance_id }}"
      state: list
    register: ec2_tags

  - name: Set hostname to match EC2 Name
    hostname: name={{ ec2_tags.tags.Name }}
 
76
Kudos
 
76
Kudos