Skip to content

Instantly share code, notes, and snippets.

@juliedavila
Created July 11, 2018 14:40
Show Gist options
  • Select an option

  • Save juliedavila/122f6eff04a7d5df8f9e9f18bbbf94bb to your computer and use it in GitHub Desktop.

Select an option

Save juliedavila/122f6eff04a7d5df8f9e9f18bbbf94bb to your computer and use it in GitHub Desktop.
Purge EC2 Tags that aren't explicitly passed in with Ansible
# you'll need to have a variable called aws_tags_desired which should be dict with k/v pairs of the tags you want
# also define aws_tags_region
# Note that this is task file, so you'll need to include it or make it the main.yml for a role's tasks directory
- name: Get EC2 Facts
ec2_metadata_facts:
register: ec2_facts
- name: Get instance details at the AWS console level
ec2_instance_facts:
region: "{{ aws_tags_region }}"
instance_ids:
- "{{ ansible_facts['ec2_instance_id'] }}"
delegate_to: localhost
register: instance_facts
- name: Set cloudformation tags
set_fact:
cf_tags:
'aws:cloudformation:logical-id': "{{ instance_facts['instances'][0]['tags']['aws:cloudformation:logical-id'] }}"
'aws:cloudformation:stack-id': "{{ instance_facts['instances'][0]['tags']['aws:cloudformation:stack-id'] }}"
'aws:cloudformation:stack-name': "{{ instance_facts['instances'][0]['tags']['aws:cloudformation:stack-name'] }}"
when:
- instance_facts['instances'][0]['tags']['aws:cloudformation:logical-id'] is defined
- name: Set Desired tags
set_fact:
desired_tags: "{{ aws_tags_desired }}"
- name: Add cft tags if needed
set_fact:
desired_tags: "{{ desired_tags | combine(cf_tags) }}"
when: cf_tags is defined
- name: Get list of current tags
delegate_to: localhost
become: no
ec2_tag:
state: list
region: "{{ aws_tags_region }}"
resource: "{{ ec2_facts.ansible_facts.ansible_ec2_instance_id }}"
register: tag_list
- set_fact:
tags_to_delete: "{{ tags_to_delete|default({}) | combine({ item.key : item.value }) }}"
when: "{{ not item.key in desired_tags or desired_tags[item.key] != item.value }}"
with_dict: "{{ tag_list.tags }}"
delegate_to: localhost
- name: Remove necessary tags
delegate_to: localhost
become: no
ec2_tag:
state: absent
region: "{{ aws_tags_region }}"
resource: "{{ ec2_facts.ansible_facts.ansible_ec2_instance_id }}"
tags: "{{ tags_to_delete }}"
with_dict: "{{ tags_to_delete }}"
when: "{{ tags_to_delete is defined }}"
- name: Set instance tags
become: no
ec2_tag:
region: "{{ aws_tags_region }}"
resource: "{{ ec2_facts.ansible_facts.ansible_ec2_instance_id }}"
tags: "{{ desired_tags }}"
delegate_to: localhost
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment