-
Notifications
You must be signed in to change notification settings - Fork 0
/
account_b_region_a.yml
364 lines (346 loc) · 13.5 KB
/
account_b_region_a.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
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
# *
# * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# * SPDX-License-Identifier: MIT-0
# *
# * Permission is hereby granted, free of charge, to any person obtaining a copy of this
# * software and associated documentation files (the "Software"), to deal in the Software
# * without restriction, including without limitation the rights to use, copy, modify,
# * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
# * permit persons to whom the Software is furnished to do so.
# *
# * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
# * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# *
AWSTemplateFormatVersion: 2010-09-09
Description: Automating cross-account backup of Amazon RDS Oracle databases with AWS Backup - Account B, Region A
Metadata:
AWS::CloudFormation::Interface:
ParameterGroups:
- Label:
default: "AWS Backup Configuration"
Parameters:
- pBackupIAMRoleName
- pBackupVaultName
- pAWSOrganizationID
- pDestinationAWSRegion
- pKeyAdminIdentity
ParameterLabels:
pBackupIAMRoleName:
default: AWS Backup IAM Role
pBackupVaultName:
default: AWS Backup Vault Name
pAWSOrganizationID:
default: AWS Organization ID
pDestinationAWSRegion:
default: AWS Backup Destination Region
pKeyAdminIdentity:
default: IAM user, IAM role or account root that gets permissions to manage the AWS KMS key
Parameters:
pBackupIAMRoleName:
Type: String
Description: A name for the IAM role, up to 64 characters in length.
pBackupVaultName:
Type: String
Description: The name of a logical container where backups are stored. Backup vaults are identified by names that are unique to the account used to create them and the AWS Region where they are created.
pAWSOrganizationID:
Type: String
Description: AWS Organizations ID
pDestinationAWSRegion:
Type: String
Description: AWS Region for cross-region backups. Do not select the same region where this CloudFormation stack is being created.
AllowedValues:
- us-east-1
- us-east-2
- us-west-1
- us-west-2
- ap-south-1
- ap-northeast-1
- ap-northeast-2
- ap-northeast-3
- ap-southeast-1
- ap-southeast-2
- ca-central-1
- eu-central-1
- eu-west-1
- eu-west-2
- eu-west-3
- eu-north-1
- sa-east-1
pKeyAdminIdentity:
Type: String
Description: 'The principal element of the KMS key administrator. For example, "root", "user/ExampleAdminUser" or "role/ExampleAdminRole"'
Resources:
# IAM Role for AWS Backup
rAWSBackupIAMRole:
Type: AWS::IAM::Role
Properties:
Description: Allows AWS Backup to call AWS services on your behalf
AssumeRolePolicyDocument: |
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "backup.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AWSBackupServiceRolePolicyForBackup
RoleName: !Ref pBackupIAMRoleName
rIAMPolicyRDSServiceLinkedRole:
Type: AWS::IAM::Policy
Properties:
PolicyName: service-role-rds
Roles:
- !Ref rAWSBackupIAMRole
PolicyDocument: !Sub |
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "iam:CreateServiceLinkedRole",
"Resource": "arn:aws:iam::${AWS::AccountId}:role/aws-service-role/rds.amazonaws.com/AWSServiceRoleForRDS"
}
]
}
# AWS KMS Key and AWS Backup Vault
# Note: Second policy statement is not supported through the web console, only through CloudFormation or API call.
rKMSCMK:
Type: AWS::KMS::Key
Properties:
EnableKeyRotation: true
Description: KMS key for AWS Backup Vault
KeyPolicy: !Sub |
{
"Version": "2012-10-17",
"Id": "backup-vault-policy-${pBackupVaultName}",
"Statement": [
{
"Sid": "Enable IAM User Permissions",
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::${AWS::AccountId}:${pKeyAdminIdentity}"
},
"Action": [
"kms:PutKeyPolicy",
"kms:ScheduleKeyDeletion",
"kms:EnableKeyRotation",
"kms:DescribeKey",
"kms:CreateAlias",
"kms:DeleteAlias",
"kms:CreateGrant",
"kms:GetKeyPolicy"
],
"Resource": "*"
},
{
"Sid": "Allow access from AWS Organizations accounts to copy backups",
"Effect": "Allow",
"Principal": {
"AWS": "*"
},
"Action": [
"kms:CreateGrant",
"kms:Decrypt",
"kms:GenerateDataKey*",
"kms:DescribeKey"
],
"Resource": "*",
"Condition": {
"StringEquals": {
"aws:PrincipalOrgID": "${pAWSOrganizationID}"
}
}
}
]
}
rKMSCMKAlias:
Type: AWS::KMS::Alias
Properties:
AliasName: !Sub "alias/cmk-${pBackupVaultName}"
TargetKeyId: !Ref rKMSCMK
rBackupVault:
Type: AWS::Backup::BackupVault
Properties:
AccessPolicy: !Sub |
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "Enable backup vault access",
"Effect": "Allow",
"Principal": "*",
"Action": "backup:CopyIntoBackupVault",
"Resource": "arn:aws:backup:${AWS::Region}:${AWS::AccountId}:backup-vault:${pBackupVaultName}",
"Condition": {
"StringEquals": {
"aws:PrincipalOrgID": "${pAWSOrganizationID}"
}
}
}
]
}
BackupVaultName: !Ref pBackupVaultName
EncryptionKeyArn: !GetAtt rKMSCMK.Arn
# EventBridge and Lambda Rule for Cross-Region Backup Copies
rLambdaIAMRole:
Type: "AWS::IAM::Role"
Properties:
Path: "/"
RoleName: AWSBackupRDSAuroraLambdaRole
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
-
Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- sts:AssumeRole
Policies:
- PolicyName: Cloudwatch-Backup-Policy
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- backup:StartCopyJob
- backup:DescribeRecoveryPoint
Resource: '*'
- Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource:
- arn:aws:logs:*:*:*
- PolicyName: LambdaPolicy-AssumeRole
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- iam:PassRole
Resource: !GetAtt rAWSBackupIAMRole.Arn
Description: "Allows Lambda functions to call AWS services on your behalf"
rLambdaFunction:
Type: AWS::Lambda::Function
Properties:
Description: Lambda Function that triggers an AWS Backup Vault Copy in a different region
Environment:
Variables:
role_name: !GetAtt rAWSBackupIAMRole.Arn
destination_region: !Ref pDestinationAWSRegion
FunctionName: "AWSBackup-RDS-Aurora-Cross-Region-Backup-Copy"
Handler: index.lambda_handler
Code:
ZipFile: |
import json, boto3, os, logging, time, sys
def lambda_handler(event, context):
# Logging configuration
logger = logging.getLogger()
logger.setLevel(logging.INFO)
logging.getLogger("boto3").setLevel(logging.WARNING)
logging.getLogger("botocore").setLevel(logging.WARNING)
logger.debug('Incoming Event')
logger.debug(event)
# Function variables
backup_vault_name = event['detail']['destinationBackupVaultArn'].split(':')[6]
source_region = event['detail']['destinationBackupVaultArn'].split(':')[3]
lifecycle_value = 'CalculatedLifecycle'
logger.info('Backup source account: ' + event['account'])
logger.info('Recovery Point ARN to be copied: ' + event['detail']['destinationRecoveryPointArn'])
# Environment variables
destination_region = os.environ.get('destination_region')
logger.info('Sending backup to the following AWS Region: ' + destination_region)
role_name = os.environ.get('role_name')
# Boto3 client
backup_connection = boto3.client('backup')
# Boto3 call to retrieve recovery point retention/lifecycle value
recovery_point = backup_connection.describe_recovery_point(
BackupVaultName = backup_vault_name,
RecoveryPointArn = event['detail']['destinationRecoveryPointArn']
)
logger.debug('Recovery Point Information')
logger.debug(recovery_point)
# If value is found, it will be passed to the start copy job boto3 call
try:
if lifecycle_value in recovery_point:
response = backup_connection.start_copy_job(
RecoveryPointArn = event['detail']['destinationRecoveryPointArn'],
SourceBackupVaultName = backup_vault_name,
DestinationBackupVaultArn = event['detail']['destinationBackupVaultArn'].replace(source_region,destination_region),
IamRoleArn = role_name,
Lifecycle={
'DeleteAfterDays': int(recovery_point['Lifecycle']['DeleteAfterDays'])
}
)
# Else, value has not been defined and will not be defined in start copy job boto3 call
else:
response = backup_connection.start_copy_job(
RecoveryPointArn = event['detail']['destinationRecoveryPointArn'],
SourceBackupVaultName = backup_vault_name,
DestinationBackupVaultArn = event['detail']['destinationBackupVaultArn'].replace(source_region,destination_region),
IamRoleArn = role_name
)
except Exception as e:
logger.error(str(e))
logger.info('AWS Backup Copy Job ID: ' + response['CopyJobId'])
return json.dumps(response, default=str)
MemorySize: 128
Role: !GetAtt rLambdaIAMRole.Arn
ReservedConcurrentExecutions: 5
Runtime: python3.8
Timeout: 3
TracingConfig:
Mode: "PassThrough"
rLambdaPermission:
Type: "AWS::Lambda::Permission"
Properties:
Action: lambda:InvokeFunction
FunctionName: !GetAtt rLambdaFunction.Arn
Principal: events.amazonaws.com
SourceArn: !GetAtt rEventsRule.Arn
rEventsEventBusPolicy:
Type: "AWS::Events::EventBusPolicy"
Properties:
StatementId: "AWSBackupCopyCompleteEvent"
Action: "events:PutEvents"
Condition:
Key: "aws:PrincipalOrgID"
Type: "StringEquals"
Value: !Ref pAWSOrganizationID
Principal: "*"
rEventsRule:
Type: "AWS::Events::Rule"
Properties:
Name: "AWSBackupCopyCompleteRule"
Description: "EventBridge Rule for CopyCompleteJob event to trigger cross-region backup copy for RDS/Aurora resources"
EventPattern: !Sub |
{
"source": ["aws.backup"],
"account": [{
"anything-but": "${AWS::AccountId}"
}],
"detail-type": ["Copy Job State Change"],
"detail": {
"state": ["COMPLETED"],
"resourceType": ["RDS", "Aurora"]
}
}
State: "ENABLED"
Targets:
-
Arn: !GetAtt rLambdaFunction.Arn
Id: "TargetFunctionV1"
EventBusName: "default"