Skip to content

Commit e229618

Browse files
To reduce cost script to find EC2 without MegaOps tags and unused EBS volumes. This scipt failed when found some resources without proper tags or EBS in state availabe (unassigned)
Signed-off-by: Mariusz Jóźwiak <[email protected]>
1 parent a746752 commit e229618

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

site.maintenance.find-untagged.yml

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
- hosts: localhost
2+
connection: local
3+
vars:
4+
_ec2_filters:
5+
- "running"
6+
- "stopped"
7+
- "pending"
8+
- "shutting-down"
9+
- "stopping"
10+
_ec2_ebs_list_to_review: []
11+
_ec2_untagged_list: []
12+
_ec2_list_to_review :
13+
roles:
14+
- role: cs.aws-rds-facts
15+
tasks:
16+
- name: List of mageops instances
17+
ec2_instance_info:
18+
filters:
19+
"tag:Infrastructure": 'mageops'
20+
"tag:Tool": 'ansible'
21+
instance-state-name: "{{ _ec2_filters }}"
22+
region: "{{ aws_region }}"
23+
register: _ec2_list_mageops
24+
25+
- name: List of all EC2 instances
26+
ec2_instance_info:
27+
filters:
28+
instance-state-name: "{{ _ec2_filters }}"
29+
region: "{{ aws_region }}"
30+
register: _ec2_list_all
31+
32+
- name: Generate difference between both list
33+
set_fact:
34+
_ec2_untagged_list: "{{ _ec2_untagged_list + [{ 'id' : item.instance_id, 'name' : item.tags.Name | default('') }] }}"
35+
when: item.instance_id not in aws_ec2_whitelist
36+
with_items: "{{ _ec2_list_all.instances | difference(_ec2_list_mageops.instances) }}"
37+
38+
- name: Find unused EBS volumes
39+
ec2_vol_info:
40+
filters:
41+
status: "available"
42+
region: "{{ aws_region }}"
43+
register: _ec2_ebs_list
44+
45+
- name: Set unused EBS volumes list
46+
set_fact:
47+
_ec2_ebs_list_to_review: "{{ _ec2_ebs_list_to_review + [item.id] }}"
48+
with_items: "{{ _ec2_ebs_list.volumes }}"
49+
50+
- name: Generate string to EC2 end output
51+
set_fact:
52+
_ec2_list_to_review: "{{ (_ec2_list_to_review) }} ID : {{ item.id }} Name : {{ item.name }}"
53+
with_items: "{{ _ec2_untagged_list }}"
54+
55+
- name: Failed when some resources found
56+
fail:
57+
msg: |
58+
{% if (_ec2_ebs_list.volumes | length) > 0 %} EBS volumes to review: {{ _ec2_ebs_list_to_review | join(',') }} {% endif %}
59+
{% if (_ec2_untagged_list | length) > 0 %} EC2 instances to review:
60+
{{ _ec2_list_to_review }} {% endif %}
61+
when: "{{ (_ec2_untagged_list | length > 0) or (_ec2_ebs_list.volumes | length >0) }}"

0 commit comments

Comments
 (0)