Skip to content

Commit baafee3

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]> Final
1 parent a746752 commit baafee3

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

site.maintenance.find-untagged.yml

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

0 commit comments

Comments
 (0)