-
Notifications
You must be signed in to change notification settings - Fork 0
/
template.yaml
220 lines (201 loc) · 6.28 KB
/
template.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
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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
Parameters:
MyLambdaVPCAccessExecutionRole:
Description: ARN of the role
Default: arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole
Type: String
ConstraintDescription: Use default value or provide other lambda execution policy role
DBInstanceID:
Default: myDBInstance
Description: My database instance
Type: String
MinLength: 1
MaxLength: 63
AllowedPattern: '[a-zA-Z][a-zA-Z0-9]*'
ConstraintDescription: Must begin with a letter and contain only alphanumeric characters.
DBName:
Default: myDB
Description: My database
Type: String
MinLength: 1
MaxLength: 64
AllowedPattern: '[a-zA-Z][a-zA-Z0-9]*'
DBInstanceClass:
Default: db.t2.micro
Description: DB instance class
Type: String
ConstraintDescription: Must select a valid DB instance type.
DBStorageType:
Default: gp2
Description: DB storage type
Type: String
AllowedValues:
- gp2
- io1
- standard
DBAllocatedStorage:
Default: 20
Description: The size of the database (GiB)
Type: Number
MinValue: 20
MaxValue: 30
ConstraintDescription: must be between 20 and 65536 GiB.
DBUsername:
NoEcho: true
Description: Username for MySQL database access
Type: String
MinLength: 1
MaxLength: 16
DBPassword:
NoEcho: true
Description: Password MySQL database access
Type: String
MinLength: 8
MaxLength: 41
Resources:
MyLambdaAccessRdsRole:
Type: AWS::IAM::Role
Properties:
Description: Allow Lambda to access AWS resources
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- sts:AssumeRole
ManagedPolicyArns:
- !Ref MyLambdaVPCAccessExecutionRole
myVPC:
Type: AWS::EC2::VPC
Properties:
CidrBlock: 10.0.0.0/16
InstanceTenancy: default
Tags:
- Key: name
Value: demoVPC
MyVpcSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: SG for DB
GroupName: MyDBVpcSecurityGroup
VpcId: !Ref myVPC
SecurityGroupIngress:
- IpProtocol: -1
CidrIp: 0.0.0.0/0
SecurityGroupEgress:
- IpProtocol: -1
CidrIp: 0.0.0.0/0
MyPrivateSubnetA:
Type: AWS::EC2::Subnet
Properties:
VpcId: !Ref myVPC
CidrBlock: 10.0.1.0/24
AvailabilityZone: eu-central-1a
MyPrivateSubnetB:
Type: AWS::EC2::Subnet
Properties:
VpcId: !Ref myVPC
CidrBlock: 10.0.2.0/24
AvailabilityZone: eu-central-1b
MyDBSubnetGroup:
Type: AWS::RDS::DBSubnetGroup
Properties:
DBSubnetGroupDescription: Private subnets gropu
SubnetIds:
- !Ref MyPrivateSubnetA
- !Ref MyPrivateSubnetB
Tags:
- Key: name
Value: demoVPC
MyDB:
Type: 'AWS::RDS::DBInstance'
Properties:
DBInstanceIdentifier: !Ref DBInstanceID
DBName: !Ref DBName
DBInstanceClass: !Ref DBInstanceClass
StorageType: !Ref DBStorageType
AllocatedStorage: !Ref DBAllocatedStorage
Engine: mysql
EngineVersion: 8.0.28
MasterUsername: !Ref DBUsername
MasterUserPassword: !Ref DBPassword
VPCSecurityGroups:
- !Ref MyVpcSecurityGroup
DBSubnetGroupName: !Ref MyDBSubnetGroup
AvailabilityZone: eu-central-1a
PyMsqlLayer:
Type: AWS::Lambda::LayerVersion
Properties:
CompatibleRuntimes:
- python3.8
Content:
#change bucket name with your created bucket
S3Bucket: cf-templates-15ynh9svu8qip-eu-central-1
S3Key: pymysql.zip
Description: pymysql lib stored in s3 bucket
LayerName: pymysql-lib
MyLambdaAccessingRDS:
DependsOn:
- MyDB
- MyLambdaAccessRdsRole
- PyMsqlLayer
Type: AWS::Lambda::Function
Properties:
Description: Create ExampleDB table in RDS, add few records and printout
FunctionName: LambdaAccessRds
Handler: index.handler
MemorySize: 128
Role: !GetAtt MyLambdaAccessRdsRole.Arn
Runtime: python3.8
Environment:
Variables:
RDS_HOST: !GetAtt MyDB.Endpoint.Address
MYSQL_USERNAME: !Ref DBUsername
MYSQL_PASSWORD: !Ref DBPassword
DBName: !Ref DBName
Layer: !Ref PyMsqlLayer
Code:
ZipFile: |
import sys
import logging
import pymysql
import os
rds_host = os.environ['RDS_HOST']
name = os.environ['MYSQL_USERNAME']
password = os.environ['MYSQL_PASSWORD']
db_name = os.environ['DBName']
logger = logging.getLogger()
logger.setLevel(logging.INFO)
try:
conn = pymysql.connect(host=rds_host, user=name, passwd=password, db=db_name, connect_timeout=5)
except pymysql.MySQLError as e:
logger.error("ERROR: Unexpected error: Could not connect to MySQL instance.")
logger.error(e)
sys.exit()
logger.info("SUCCESS: Connection to RDS MySQL instance succeeded")
def handler(event, context):
"""
This function fetches content from MySQL RDS instance
"""
item_count = 0
with conn.cursor() as cur:
cur.execute("create table Employee ( EmpID int NOT NULL, Name varchar(255) NOT NULL, PRIMARY KEY (EmpID))")
cur.execute('insert into Employee (EmpID, Name) values(1, "Joe")')
cur.execute('insert into Employee (EmpID, Name) values(2, "Bob")')
cur.execute('insert into Employee (EmpID, Name) values(3, "Mary")')
conn.commit()
cur.execute("select * from Employee")
for row in cur:
item_count += 1
logger.info(row)
#print(row)
conn.commit()
return "Added %d items from RDS MySQL table" %(item_count)
VpcConfig:
SecurityGroupIds:
- !Ref MyVpcSecurityGroup
SubnetIds:
- !Ref MyPrivateSubnetA
- !Ref MyPrivateSubnetB