Skip to content

Instantly share code, notes, and snippets.

@deekayen
Last active November 21, 2019 19:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deekayen/0dbc557f04e8b72bb10407f6e130ee4b to your computer and use it in GitHub Desktop.
Save deekayen/0dbc557f04e8b72bb10407f6e130ee4b to your computer and use it in GitHub Desktop.
Query AWS to find instances and volumes without Name tags using an Ansible playbook. In Ansible Tower, use a null inventory along with an AWS cloud credential. Extend this with another task to stop instances with no Name tag.
---
- hosts: 127.0.0.1
connection: local
become: no
vars:
aws_region: us-east-1
tasks:
- name: "Query instances with no Name tag value." # noqa 301
shell: >
set -o pipefail;
aws ec2 describe-instances \
--output text \
--region "{{ aws_region }}"
--query 'Reservations[].Instances[?!not_null(Tags[?Key == `Name`].Value)] | [].[InstanceId]'
args:
executable: /bin/bash
changed_when: false
register: ec2_name_absent
- debug:
var: ec2_name_absent
verbosity: 1
- name: Check that there are no EC2 instances missing the product tag.
assert:
that:
- (ec2_name_absent.stdout | trim | length) == 0
success_msg: "EC2 instances correctly tagged."
- name: "Query for volumes with no Name tag." # noqa 301
shell: >
set -o pipefail;
aws ec2 describe-volumes \
--output text \
--region "{{ aws_region }}"
--query 'Volumes[?!not_null(Tags[?Key == `Name`].Value)] | [].[VolumeId]'
args:
executable: /bin/bash
changed_when: false
register: volume_name_absent
- debug:
var: volume_name_absent
verbosity: 1
- name: Check that there are no EC2 volumes missing the Name tag.
assert:
that:
- (volume_name_absent.stdout | trim | length) == 0
success_msg: "EC2 instances correctly tagged."
fail_msg: >
Tag these!
{{ volume_name_absent.stdout | trim }}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment