-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathCommon-PrivateAMIFunctions.yaml
175 lines (166 loc) · 6.27 KB
/
Common-PrivateAMIFunctions.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
AWSTemplateFormatVersion: 2010-09-09
Description: Common-PrivateAMIFunctions Template.
This creates Lambda Functions related to Private AMIs. This is currently a placeholder for future Private AMI lookup functionality, which will not exist until we finish the Build VPC and Pipelines.
Metadata:
AWS::CloudFormation::Interface:
ParameterGroups:
- Label:
default: Stack Dependencies
Parameters:
- LayersStackName
- BucketsStackName
- TopicsStackName
- Label:
default: Function Configuration
Parameters:
- LogRetention
ParameterLabels:
LayersStackName:
default: Layers Stack Name
BucketsStackName:
default: Buckets Stack Name
TopicsStackName:
default: Topics Stack Name
LogRetention:
default: Log Retention
Parameters:
LayersStackName:
Description: Name of the CloudFormation Stack containing Layers
Type: String
MinLength: 2
MaxLength: 64
Default: Layers
AllowedPattern: ^[A-Z][-a-zA-Z0-9]*$
ConstraintDescription: must begin with an upper case letter and contain alphanumeric characters and dashes.
BucketsStackName:
Description: Name of the CloudFormation Stack containing Buckets
Type: String
MinLength: 2
MaxLength: 64
Default: Buckets
AllowedPattern: ^[A-Z][-a-zA-Z0-9]*$
ConstraintDescription: must begin with an upper case letter and contain alphanumeric characters and dashes.
TopicsStackName:
Description: Name of the CloudFormation Stack containing Topics
Type: String
MinLength: 2
MaxLength: 64
Default: Topics
AllowedPattern: ^[A-Z][-a-zA-Z0-9]*$
ConstraintDescription: must begin with an upper case letter and contain alphanumeric characters and dashes.
LogRetention:
Description: Number of days to retain CloudWatch Log Events for all AMI Lookup Lambda Functions
Type: Number
Default: 30
AllowedValues:
- 1
- 3
- 5
- 7
- 14
- 30
- 60
- 90
ConstraintDescription: must be 1, 3, 5, 7, 14, 30, 60 or 90.
Resources:
Role:
Type: AWS::IAM::Role
Properties:
Path: /
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
Policies:
- PolicyName: DescribeImagesPolicy
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- ec2:DescribeImages
Resource: '*'
BaselineAmazonLinuxImageLogGroup:
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: /aws/lambda/BaselineAmazonLinuxImage
RetentionInDays: !Ref LogRetention
BaselineAmazonLinuxImageFunction:
Type: AWS::Lambda::Function
Properties:
FunctionName: BaselineAmazonLinuxImage
Description: A Lambda function that looks up the Baseline Amazon Linux Image for a given OS Variant and Region.
Role: !GetAtt Role.Arn
Runtime: nodejs10.x
Timeout: 30
Layers:
- !ImportValue
Fn::Sub: ${LayersStackName}-AsyncCustomResourceLayerVersionArn
Handler: index.handler
Code:
ZipFile: |
const response = require('cfn-response-promise');
const AWS = require('aws-sdk');
AWS.config.apiVersions = {
ec2: '2016-11-15'
};
const osNameToFilter = {
'Amazon Linux' : 'Baseline Amazon Linux' // List default first
};
exports.handler = async (event, context) => {
console.info(`Request body:\n${JSON.stringify(event)}`);
switch (event.RequestType) {
case 'Create':
case 'Update':
try {
const accountId = event.ResourceProperties.AccountId || context.invokedFunctionArn.split(':')[4];
const region = event.ResourceProperties.Region || process.env.AWS_REGION;
const osName = event.ResourceProperties.OSName || Object.keys(osNameToFilter)[0];
let amiNameFilter = (! osNameToFilter[osName]) ? osNameToFilter[Object.keys(osNameToFilter)[0]] : osNameToFilter[osName];
amiNameFilter += '-*';
console.info(`OS: ${osName}`);
console.info(`Filter: ${amiNameFilter}`);
const ec2 = new AWS.EC2({region: region});
console.info(`Calling: DescribeImages...`);
const params = {
Filters: [{ Name: 'name', Values: [amiNameFilter]}],
Owners: [accountId]
};
const data = await ec2.describeImages(params).promise();
if (data.Images.length > 0) {
const image = data.Images.sort((x, y) => y.CreationDate.localeCompare(x.CreationDate))[0];
const responseData = {
Name: image.Name,
CreationDate: image.CreationDate
};
console.info(`Image: ${image.Name} (${image.ImageId})`);
await response.send(event, context, response.SUCCESS, responseData, image.ImageId);
}
else {
throw new Error(`Could not find Image(s) matching pattern ${amiNameFilter}`);
}
}
catch (err) {
const responseData = {Error: `${(err.code) ? err.code : 'Error'}: ${err.message}`};
console.error(responseData.Error);
await response.send(event, context, response.FAILED, responseData);
}
break;
case 'Delete':
await response.send(event, context, response.SUCCESS);
}
};
DependsOn: BaselineAmazonLinuxImageLogGroup
Outputs:
BaselineAmazonLinuxImageFunctionArn:
Description: The BaselineAmazonLinuxImage Lambda Function ARN
Value: !GetAtt BaselineAmazonLinuxImageFunction.Arn
Export:
Name: !Sub ${AWS::StackName}-BaselineAmazonLinuxImageFunctionArn