-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtemplate.yml
107 lines (91 loc) · 3.18 KB
/
template.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
AWSTemplateFormatVersion: '2010-09-09'
Description: >
Creates a Cloudwatch Event that triggers
a Lambda function to create Snapshot to the
specified Database in RDS with a custom interval
Parameters:
RDSIdentifier:
Description: The RDS Instance Identifier
Type: String
CronInterval:
Description: Interval in cron or rate expression
Type: String
Resources:
LambdaRole:
Type: AWS::IAM::Role
Properties:
Path: /
AssumeRolePolicyDocument:
Statement:
-
Effect: Allow
Principal:
Service: [lambda.amazonaws.com]
Action: ['sts:AssumeRole']
ManagedPolicyArns:
- 'arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole'
Policies:
- PolicyName: TakeSnapshotFunctionPolicy
PolicyDocument:
Statement:
-
Effect: Allow
Action:
- 'rds:CreateDBSnapshot'
Resource:
- !Join ['', ['arn:aws:rds:', !Ref "AWS::Region", ':', !Ref "AWS::AccountId", ':db:', !Ref "RDSIdentifier"]]
- !Join ['', ['arn:aws:rds:', !Ref "AWS::Region", ':', !Ref "AWS::AccountId", ':snapshot:*']]
TakeSnapshotFunction:
Type: AWS::Lambda::Function
Properties:
Handler: 'index.handler'
Role: !GetAtt LambdaRole.Arn
Runtime: 'python3.7'
Environment:
Variables:
RDS_ID: !Ref RDSIdentifier
Code:
ZipFile: |
import boto3
import time
import json
import os
RDS_ID = os.getenv('RDS_ID')
client = boto3.client('rds')
def handler(event, context):
res = client.describe_db_snapshots(
DBInstanceIdentifier=RDS_ID,
)
snapshots = res["DBSnapshots"]
snapshots = list(filter(lambda x: x["SnapshotType"] == "manual" and x["Status"] is not "deleted" and x["DBSnapshotIdentifier"].startswith("snapshot"), snapshots))
snapshots.sort(key=lambda x: x["SnapshotCreateTime"])
if len(snapshots) > 50:
last_snapshot = snapshots[0]
snapshot_id = last_snapshot["DBSnapshotIdentifier"]
client.delete_db_snapshot(
DBSnapshotIdentifier=snapshot_id
)
new_snapshot_id = "snapshot-" + time.strftime("%Y-%m-%d-%H-%M-%S")
print("Taking snapshot of " + RDS_ID)
client.create_db_snapshot(
DBInstanceIdentifier=RDS_ID,
DBSnapshotIdentifier=new_snapshot_id
)
print("Snapshot created: " + new_snapshot_id)
return "OK"
EventRule:
Type: AWS::Events::Rule
Properties:
ScheduleExpression: !Ref CronInterval
State: ENABLED
Targets:
-
Id: "1"
Arn: !GetAtt TakeSnapshotFunction.Arn
TakeSnapshotFunctionPermission:
Type: AWS::Lambda::Permission
Properties:
Action: 'lambda:InvokeFunction'
FunctionName: !GetAtt TakeSnapshotFunction.Arn
Principal: 'events.amazonaws.com'
SourceArn: !GetAtt EventRule.Arn