-
Notifications
You must be signed in to change notification settings - Fork 1
/
user-and-notification.template.yml
247 lines (235 loc) · 8.78 KB
/
user-and-notification.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
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
---
AWSTemplateFormatVersion: "2010-09-09"
Description: |-
Creates an IAM user to perform updates to a Hosted Zone as well as a framework
to notify whenever that user actually performs an update.
This is ideal for situations where the IAM user and the Route 53 hosted zone
exist within the same AWS account.
Parameters:
HostedZoneId:
Description: The ID of the hosted zone to update records in
Type: String
DnsName:
Description: >-
The normalized fully qualified domain name of the record to update.
Type: String
NotificationEmail:
Description: >-
The email address to send change notifications to. It need to be a valid
email address. If this is not provided, the notification framework will
not be created.
Type: String
Default: NOT_PROVIDED
SecretName:
Description: >-
The name of the AWS Secrets Manager Secret that will store the user's
created IAM Access Key (and secret access key).
Type: String
Default: __NOT PROVIDED__
Conditions:
CreateNotificationFramework: !Not [!Equals [NOT_PROVIDED, !Ref NotificationEmail]]
SecretNameProvided: !Not [!Equals [__NOT PROVIDED__, !Ref SecretName]]
Resources:
Route53UpdateUser:
Type: AWS::IAM::User
Properties:
Tags:
- Key: Purpose
Value: !Sub Allows updating ${HostedZoneId} to support Dynamic DNS updates
Route53UserAccessKey:
Type: AWS::IAM::AccessKey
Properties:
UserName: !Ref Route53UpdateUser
Status: Active
Route53UserAccessKeySecret:
Type: AWS::SecretsManager::Secret
Properties:
Name: !If
- SecretNameProvided
- !Ref SecretName
- !Sub "dynamic-route53/${DnsName}/${Route53UpdateUser}/${Route53UserAccessKey}"
Description: !Sub >-
Key pair for the IAM user created in ${AWS::StackName} to update resource
records for ${DnsName} in Hosted Zone ${HostedZoneId}.
SecretString: !Sub >-
{
"Username": "${Route53UpdateUser}",
"AccessKeyId": "${Route53UserAccessKey}",
"SecretAccessKey": "${Route53UserAccessKey.SecretAccessKey}"
}
AllowRoute53UpdatePolicy:
Type: AWS::IAM::Policy
Properties:
PolicyName: "AllowRoute53UpdatePolicy"
Users: [!Ref Route53UpdateUser]
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action: route53:ChangeResourceRecordSets
Resource: !Sub "arn:${AWS::Partition}:route53:::hostedzone/${HostedZoneId}"
Condition:
ForAllValues:StringEquals:
route53:ChangeResourceRecordSetsNormalizedRecordNames: [!Ref DnsName]
route53:ChangeResourceRecordSetsRecordTypes: ["A", "AAAA"]
route53:ChangeResourceRecordSetsActions: ["UPSERT"]
NotificationTopic:
Condition: CreateNotificationFramework
Type: AWS::SNS::Topic
NotificationSubscriptions:
Condition: CreateNotificationFramework
Type: AWS::SNS::Subscription
Properties:
Endpoint: !Ref NotificationEmail
Protocol: email
TopicArn: !Ref NotificationTopic
NotificationRole:
Condition: CreateNotificationFramework
Type: AWS::IAM::Role
Properties:
Description: >-
Allow publishing to the Route 53 notification topic
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
Policies:
- PolicyName: publish-notification-topic
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action: sns:Publish
Resource: !Ref NotificationTopic
ManagedPolicyArns:
- !Sub arn:${AWS::Partition}:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
NotificationTransform:
Condition: CreateNotificationFramework
Type: AWS::Lambda::Function
Properties:
MemorySize: 128
Environment:
Variables:
TOPIC_ARN: !Ref NotificationTopic
Role: !GetAtt NotificationRole.Arn
Runtime: nodejs18.x
Handler: index.handler
Code:
ZipFile: |
const { SNSClient, PublishCommand } = require("@aws-sdk/client-sns");
const client = new SNSClient();
// The Route 53 APIs that we're truly concerned with only exist in the
// commercial partition but we'll make this somewhat generic just in case.
// This won't support `aws-iso` or `aws-iso-b`.
function consoleDomain(region) {
if (region.startsWith("us-gov")) {
return "console.amazonaws-us-gov.com";
} else if (region.startsWith("cn-")) {
return "console.amazonaws.cn";
} else {
return "console.aws.amazon.com";
}
}
exports.handler = async function(event, context) {
console.log("Processing event: " + event.id);
const details = event.detail;
const userName = details.userIdentity.userName;
const hostedZone = details.requestParameters.hostedZoneId;
const cloudTrailId = details.eventID;
const region = details.awsRegion;
const changes = details.requestParameters.changeBatch.changes;
const changeStr = JSON.stringify(changes, null, 2);
const messageLines = [];
messageLines.push(`${userName} made the following changes to ${hostedZone}`);
messageLines.push(
`For more information see https://${consoleDomain(region)}/cloudtrail/home?region=${region}#/events/${cloudTrailId}.`
)
try {
if (!Array.isArray(changes)) {
changes = [changes];
}
const detailLines = [];
changes.forEach((change, i) => {
const section = `Change #${i + 1}:`;
const action = change.action;
const name = change.resourceRecordSet.name;
const type = change.resourceRecordSet.type;
const ttl = change.resourceRecordSet.tTL; // not a typo -- this is the correct field in the data
const records = change.resourceRecordSet.resourceRecords.map((rr) => rr.value).join(", ");
const changeDetails = [
section,
` Action: ${action}`,
` Name: ${name}`,
` Record Type: ${type}`,
` TTL: ${ttl}`,
` Records: ${records}`,
];
detailLines.push(changeDetails.join("\n"));
});
messageLines.push(detailLines.join("\n"));
} catch (err) {
messageLines.push(changeStr);
}
const publishCommand = new PublishCommand({
TopicArn: process.env.TOPIC_ARN,
Subject: `${hostedZone} Updated`,
Message: messageLines.join('\n'),
});
try {
const result = await client.send(publishCommand);
console.log(`Message ID published: ${result.MessageId}`);
} catch (err) {
console.error(err, err.stack);
}
}
UpdateRule:
Condition: CreateNotificationFramework
Type: AWS::Events::Rule
Properties:
Description: Checks when the Route 53 update user performs updates to the zone
Targets:
- Id: notification-transform-v1
Arn: !GetAtt NotificationTransform.Arn
EventPattern:
source:
- aws.route53
detail-type:
- AWS API Call via CloudTrail
detail:
eventSource:
- route53.amazonaws.com
eventName:
- ChangeResourceRecordSets
requestParameters:
hostedZoneId:
- !Ref HostedZoneId
userIdentity:
arn:
- !GetAtt Route53UpdateUser.Arn
EventBridgeNotificationPermission:
Condition: CreateNotificationFramework
Type: AWS::Lambda::Permission
Properties:
FunctionName: !GetAtt NotificationTransform.Arn
Action: lambda:InvokeFunction
Principal: events.amazonaws.com
SourceArn: !GetAtt UpdateRule.Arn
Outputs:
Route53UpdateUser:
Description: >-
The IAM user created specifically to modify the Route 53 Hosted Zone. It
will likely be necessary to create an Access Key for this User so that it
can login.
Value: !Ref Route53UpdateUser
AccessKeySecret:
Value: !Ref Route53UserAccessKeySecret
AccessKeyId:
Value: !Ref Route53UserAccessKey
NotificationTopic:
Condition: CreateNotificationFramework
Description: >-
The SNS topic where changes to the hosted zone will be published.
Value: !Ref NotificationTopic