-
Notifications
You must be signed in to change notification settings - Fork 85
/
Copy pathEC2Tagger.yaml
executable file
·141 lines (124 loc) · 4.4 KB
/
EC2Tagger.yaml
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
AWSTemplateFormatVersion: '2010-09-09'
Description: Remediation Lamabda to tag EC2 instances with tags specified in environment variable.
Parameters:
Memory:
Description: Memory to allocate to Lambda function
Type: Number
Default: 128
SNSTopicArn:
Description: ARN for SNS topic to subscribe the lambda function to
Type: String
Resources:
LambdaFunction:
Type: AWS::Lambda::Function
Properties:
FunctionName: "EC2Tagger"
Handler: index.handler
Runtime: python3.8
Role: !GetAtt LambdaFunctionRole.Arn
MemorySize: !Ref Memory
Timeout: 600
Code:
ZipFile: |
import boto3
import logging
from botocore.config import Config
from os import getenv
import json
logger = logging.getLogger()
log_level = getenv("LOGLEVEL", "INFO")
level = logging.getLevelName(log_level)
logger.setLevel(level)
tags_string = getenv("TAGS", '[{"Key": "Create_Auto_Alarms", "Value": ""}]')
def boto3_client(resource, assumed_credentials=None):
config = Config(
retries=dict(
max_attempts=40
)
)
if assumed_credentials:
client = boto3.client(
resource,
aws_access_key_id=assumed_credentials['AccessKeyId'],
aws_secret_access_key=assumed_credentials['SecretAccessKey'],
aws_session_token=assumed_credentials['SessionToken'],
config=config
)
else:
client = boto3.client(
resource,
config=config
)
return client
def tag_ec2(instance_id, tags):
try:
ec2_client = boto3_client('ec2')
# does instance have appropriate alarm tag?
ec2_client.create_tags(
Resources=[
instance_id
],
Tags=tags
)
except Exception as e:
# If any other exceptions which we didn't expect are raised
# then fail and log the exception message.
logger.error('Failure tagging instance {} with tags: {} : {}'.format(instance_id, tags, e))
raise
def handler(event, context):
logger.info('Event received: {}'.format(event))
if 'Records' in event:
for record in event['Records']:
instance_id = record['Sns']['Message']
logger.info('adding tags to {}'.format(instance_id))
logger.info('tags string is: {}'.format(tags_string))
try:
tags = json.loads(tags_string)
except Exception as e:
logger.error('Failure parsing JSON tags environment variable string: {}: {} : {}'.format(tags_string, e))
raise
tag_ec2(instance_id, tags)
Environment:
Variables:
TAGS: '[{"Key": "Create_Auto_Alarms", "Value": ""}]'
LambdaFunctionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- sts:AssumeRole
Path: "/"
Policies:
- PolicyName: "Lambda_Permissions"
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- ec2:CreateTags
Resource: "*"
- Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource: "*"
SubscribeSNSLambda:
Type: AWS::SNS::Subscription
Properties:
Endpoint: !GetAtt LambdaFunction.Arn
Protocol: lambda
TopicArn: !Ref SNSTopicArn
LambdaInvokePermission:
Type: AWS::Lambda::Permission
Properties:
Action: lambda:InvokeFunction
Principal: sns.amazonaws.com
SourceArn: !Ref SNSTopicArn
FunctionName: !GetAtt LambdaFunction.Arn