-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.yml
171 lines (149 loc) · 6.24 KB
/
stack.yml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
---
AWSTemplateFormatVersion: '2010-09-09'
Description: 'Daily Tag Report Email - Antoine Cichowicz | Github: Yris Ops'
Parameters:
EmailAddress:
Type: String
Description: The email address to receive the tag report
Event:
Type: String
Description: The time when the report is sent
Default: "cron(0 0 * * ? *)"
Resources:
LambdaExecutionRole:
Type: 'AWS::IAM::Role'
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- 'sts:AssumeRole'
Principal:
Service:
- 'lambda.amazonaws.com'
Path: /
ManagedPolicyArns:
- "arn:aws:iam::aws:policy/ReadOnlyAccess"
Policies:
- PolicyName: 'lambda-execution-policy'
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action: sns:Publish
Resource: !Ref SNSTopicDailyTagLambda
SNSTopicDailyTagLambda:
Type: 'AWS::SNS::Topic'
Properties:
DisplayName: 'Tag Report SNS Topic'
Subscription:
- Endpoint: !Ref EmailAddress
Protocol: email
DailyTagReportLambda:
Type: 'AWS::Lambda::Function'
Properties:
Environment:
Variables:
TopicDailyTagLambdaSNS: !Ref SNSTopicDailyTagLambda
Timeout: 300
Code:
ZipFile: |
import boto3
import os
SNSTopicDailyTagLambdaArn = (os.environ['TopicDailyTagLambdaSNS'])
def lambda_handler(event, context):
report = generate_tag_report()
return report
def count_tags(response, tag_count_dict):
for resource in response:
for tag in resource.get('Tags', []):
key = tag['Key']
value = tag.get('Value', '')
if key not in tag_count_dict:
tag_count_dict[key] = {'count': 1, 'values': [value]}
else:
tag_count_dict[key]['count'] += 1
tag_count_dict[key]['values'].append(value)
return tag_count_dict
def create_tag_report(tag_count, tag_type):
report = f"\n{tag_type} Tag Report:\n"
for tag in tag_count:
report += f"- {tag}: {tag_count[tag]['count']}\n"
report += f" values: {', '.join(tag_count[tag]['values'])}\n"
return report
def generate_tag_report():
# Initialize the AWS resource clients
sns = boto3.client('sns', region_name='us-east-1')
ec2 = boto3.client('ec2')
elbv2 = boto3.client('elbv2')
# Dictionaries to store the tag counts for each resource type
ec2_tag_count = {}
security_group_tag_count = {}
volume_tag_count = {}
key_pair_tag_count = {}
load_balancer_tag_count = {}
# Generate EC2 tag report
response = ec2.describe_instances()
for reservation in response['Reservations']:
for instance in reservation['Instances']:
for tag in instance['Tags']:
key = tag['Key']
value = tag.get('Value', '')
if key not in ec2_tag_count:
ec2_tag_count[key] = {'count': 1, 'values': [value]}
else:
ec2_tag_count[key]['count'] += 1
ec2_tag_count[key]['values'].append(value)
security_group_tag_count = count_tags(ec2.describe_security_groups()['SecurityGroups'], security_group_tag_count)
volume_tag_count = count_tags(ec2.describe_volumes()['Volumes'], volume_tag_count)
key_pair_tag_count = count_tags(ec2.describe_key_pairs()['KeyPairs'], key_pair_tag_count)
response = elbv2.describe_load_balancers()
for load_balancer in response['LoadBalancers']:
if load_balancer['LoadBalancerName'] not in load_balancer_tag_count:
load_balancer_tag_count[load_balancer['LoadBalancerName']] = 1
else:
load_balancer_tag_count[load_balancer['LoadBalancerName']] += 1
# Format the tag report
report = "EC2 Tag Report:\n"
for tag in ec2_tag_count:
report += f"- {tag}: {ec2_tag_count[tag]['count']}\n"
report += f" values: {', '.join(ec2_tag_count[tag]['values'])}\n"
report += create_tag_report(security_group_tag_count, "Security Group")
report += create_tag_report(volume_tag_count, "EBS Volume")
report += create_tag_report(key_pair_tag_count, "EC2 Key Pair")
report += "\nLoad Balancer Report:\n"
for load_balancer_name in load_balancer_tag_count:
report += f"- {load_balancer_name}: {load_balancer_tag_count[load_balancer_name]}\n"
report += "\nhttps://github.com/Yris-ops\n"
response = sns.publish(
TopicArn=SNSTopicDailyTagLambdaArn,
Message=report,
Subject='Daily Tags Report'
)
return report
Handler: 'index.lambda_handler'
Role: !GetAtt "LambdaExecutionRole.Arn"
Runtime: 'python3.8'
EventRule:
Type: AWS::Events::Rule
Properties:
Name: DailyTagReportEventRule
ScheduleExpression: !Ref Event
State: "ENABLED"
Targets:
- Arn: !GetAtt [DailyTagReportLambda, Arn]
Id: DailyTagReportEventTarget
PermissionForEventsToInvokeLambda:
Type: AWS::Lambda::Permission
Properties:
FunctionName: !GetAtt DailyTagReportLambda.Arn
Action: 'lambda:InvokeFunction'
Principal: 'events.amazonaws.com'
SourceArn: !GetAtt EventRule.Arn
Outputs:
TopicDailyTagLambdaSNS:
Description: Arn for SNS topic related to alarms
Export:
Name: !Sub '${AWS::StackName}-SNSTopicDailyTagReport'
Value: !Ref SNSTopicDailyTagLambda