-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample.yml
190 lines (182 loc) · 9.4 KB
/
example.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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
Description: Example stack that demo's how to use cf-shim to add resources from boto3
Resources:
LambdaRole:
Type: "AWS::IAM::Role"
Properties:
AssumeRolePolicyDocument:
Statement:
-
Effect: Allow
Principal:
Service:
- "lambda.amazonaws.com"
Action: ["sts:AssumeRole"]
Policies:
-
PolicyName: "ShimLambdaRole"
PolicyDocument:
Statement:
-
Effect: Allow
Action: ["logs:CreateLogGroup","logs:CreateLogStream","logs:PutLogEvents"]
Resource: ["arn:aws:logs:*:*:*"]
- # This allows the shim to access EVERYTHING. You probably don't want to run this in a production AWS account
Effect: Allow
Action: ["*"]
Resource: ["*"]
################################################################
# INCLUDE THIS RESOURCE HERE (plus a lambdarole such as above) #
################################################################
ShimLambda:
Type: "AWS::Lambda::Function"
Properties:
Handler: "index.handler"
Role: !GetAtt LambdaRole.Arn
Runtime: "python3.6"
Timeout: "300"
Code:
ZipFile: |
import cfnresponse
import sys
from subprocess import Popen, PIPE
from datetime import date, datetime
from functools import reduce
import operator
import importlib
import json
def json_serial(obj):
"""JSON serializer for objects not serializable by default json code"""
if isinstance(obj, (datetime, date)):
return obj.isoformat()
raise TypeError ("Type %s not serializable" % type(obj))
sys.path.insert(0,"/tmp/")
proc = Popen(["pip", "install", "boto3","botocore","-t","/tmp/"], stdout=PIPE, stderr=PIPE)
out, err = proc.communicate()
exitcode = proc.returncode
if exitcode != 0:
raise ImportError("Issue installing boto3. Check logs")
print([exitcode, out, err])
import botocore
importlib.reload(botocore)
import boto3
importlib.reload(boto3)
def handler(event, context):
try: # giant try catch so that we can report to CF as soon as a failure occurs
print("Event Data:")
print(event) # print out the event so we can debug easily
try:
client = boto3.client(event['ResourceProperties']['Service'], region_name=event['ResourceProperties']['Region'])
except KeyError:
client = boto3.client(event['ResourceProperties']['Service'])
try: #just return back if no function defined
method_name = event['ResourceProperties'][event['RequestType']]
except KeyError:
cfnresponse.send(event, context, cfnresponse.SUCCESS, {}, event['LogicalResourceId'])
method = getattr(client, method_name)
try:
args = event['ResourceProperties'][event['RequestType']+"Data"]
except KeyError:
args = {}
try:
# this is hacky but probably works fine replaces "$PhysicalResourceId$" in any section of the object with our recorded physicalresourceid
args = json.loads(json.dumps(args, default=json_serial).replace("$PhysicalResourceId$",event['PhysicalResourceId']).replace("\"booltrue\"", "true").replace("\"boolfalse\"", "false"))
except KeyError:
args = json.loads(json.dumps(args, default=json_serial).replace("\"booltrue\"", "true").replace("\"boolfalse\"", "false"))
pass
response = method(**args)
print("Response Data:")
print(response)
try:
response = json.loads(json.dumps(response, default=json_serial))
except:
pass
try: #use existing physical_resource_id if exists
physical_resource_id =event['PhysicalResourceId']
except KeyError:
try:
physical_resource_id = reduce(operator.getitem, event['ResourceProperties']['PhysicalResourceId'].split("."), response)
except KeyError:
physical_resource_id = event['LogicalResourceId']
print("Sending success")
cfnresponse.send(event, context, cfnresponse.SUCCESS, response, physical_resource_id)
print("All Done")
except:
cfnresponse.send(event, context, cfnresponse.FAILED, {}, event['LogicalResourceId'])
raise
#################
# Example usage #
#################
CustomSNS: # in this example we will create an SNS topic without using CloudFormation prematives
Type: Custom::CFShim
DependsOn: [ShimLambda]
Properties:
ServiceToken: !GetAtt ShimLambda.Arn
Service: "sns"
Create: "create_topic" # http://boto3.readthedocs.io/en/latest/reference/services/sns.html#SNS.Client.create_topic
PhysicalResourceId: "TopicArn" #this is the variable from the boto3 method response that sets the physicalresourceid
Delete: "delete_topic"
Update: "set_topic_attributes"
CreateData:
Name: "TestTopicNameTest"
DeleteData:
TopicArn: "$PhysicalResourceId$"
UpdateData:
TopicArn: "$PhysicalResourceId$"
AttributeName: "DisplayName"
AttributeValue: "TestUpdate4"
CustomACM: # in this example we will create an SNS topic without using CloudFormation prematives
Type: Custom::CFShim
DependsOn: [ShimLambda]
Properties:
ServiceToken: !GetAtt ShimLambda.Arn
Region: "us-east-1" # in case you need a resource in another region
Service: "acm"
Create: "request_certificate" # http://boto3.readthedocs.io/en/latest/reference/services/acm.html#ACM.Client.request_certificate
PhysicalResourceId: "CertificateArn"
Delete: "delete_certificate"
CreateData:
DomainName: "test.mwheeler.org"
DomainValidationOptions:
-
DomainName: test.mwheeler.org
ValidationDomain: mwheeler.org
DeleteData:
CertificateArn: "$PhysicalResourceId$"
SSMVPCEndpoint:
Type: Custom::SSM_VPC_CFShim
DependsOn: [ShimLambda]
Properties:
ServiceToken: !GetAtt ShimLambda.Arn
Service: "ec2"
Create: "create_vpc_endpoint" # http://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Client.create_vpc_endpoint
PhysicalResourceId: "VpcEndpoint.VpcEndpointId"
Delete: "delete_vpc_endpoints"
CreateData:
VpcEndpointType: "Interface"
VpcId: "vpc-75fffc11"
ServiceName: "com.amazonaws.ap-southeast-1.ssm"
SubnetIds: ["subnet-52538335"]
SecurityGroupIds: ["sg-5907bc3f"]
# PrivateDnsEnabled: true
DeleteData:
VpcEndpointIds:
- "$PhysicalResourceId$"
# CertificateArn: "$PhysicalResourceId$"
#add in delete_vpc_endpoints for delete / cleanup
# Example using to enable backups on a dynabodb table
TableBackups:
Type: Custom::CFShim
DependsOn: [ShimLambda]
Properties:
ServiceToken: !GetAtt ShimLambda.Arn
Service: "dynamodb"
Create: "update_continuous_backups" # http://boto3.readthedocs.io/en/latest/reference/services/sns.html#SNS.Client.create_topic
Delete: "update_continuous_backups"
CreateData:
TableName: !Ref DynamoDBTable
PointInTimeRecoverySpecification:
PointInTimeRecoveryEnabled: booltrue
DeleteData:
TableName: !Ref DynamoDBTable
PointInTimeRecoverySpecification:
PointInTimeRecoveryEnabled: boolfalse