/ aws

Gather ec2 facts and tags of an instance

To get an instance tags we can use the "list" state of the ec2_tags module. We collect the ec2_facts to get the instance id, then use that to register and ec2_tags variable that we can access, the end

- name: facts
  hosts: localhost
  connection: local
  gather_facts: True
    - name: Get instance ec2 facts
      action: ec2_facts
      register: ec2_facts
    - name: Get instance tags
        module: ec2_tag
        region: "{{ ansible_ec2_placement_region }}"
        resource: "{{ ansible_ec2_instance_id }}"
        state: list
      register: ec2_tags

    - debug: var=ec2_tags

result will look like this:

ok: [localhost] => {
    "changed": false,
    "ec2_tags": {
        "changed": false,
        "tags": {
            "Name": "s-s1-logging-elasticsearch-01",
            "app": "my-app",
            "environment": "dev",

And I can access individual tags using:

- debug: var=ec2_tags['tags']['Name']
- debug: var=ec2_tags['tags']['app']
- debug: var=ec2_tags['tags']['environment']