-
Notifications
You must be signed in to change notification settings - Fork 0
/
alb_autoscaling_route53_a_alias.py
326 lines (305 loc) · 10.6 KB
/
alb_autoscaling_route53_a_alias.py
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
from troposphere import Base64, Join, Parameter, Ref, Template, Output, FindInMap, GetAtt, Select, Export, Sub
import troposphere.autoscaling as autoscaling
import troposphere.elasticloadbalancingv2 as elb
import troposphere.route53 as route53
t = Template()
# Windows server 2016 Base
def AddAMI(template):
t.add_mapping("windowsAMI", {
"us-east-1": {"AMI": "ami-b06249a7"},
"us-east-2": {"AMI": "ami-20683245"},
"us-west-1": {"AMI": "ami-d3a8fdb3"},
"us-west-2": {"AMI": "ami-b9b71ad9"},
"eu-west-1": {"AMI": "ami-32792a41"},
"eu-west-2": {"AMI": "ami-29353f4d"},
"eu-central-1": {"AMI": "ami-c0f237af"}
})
def main():
# Meta
t.add_version("2010-09-09")
t.add_description("Template for auto-scaling windows instances bootstrapped with a powershell script in "
"the instance launchconfiguration userdata. The instances ALB will be used as "
"an A Alias target for a Route53 hosted zone. "
"This template also showcases Metadata Parameter Grouping, "
"Special AWS Parameter Types, "
"and Cloudformation Outputs with Exports which can be imported into "
"other templates."
)
t.add_metadata({
"Author": "https://github.com/hmain/",
"LastUpdated": "2017 01 31",
"Version": "1",
})
# Parameter grouping
t.add_metadata(
{
"AWS::CloudFormation::Interface": {
"ParameterGroups": [
{
"Label": {"default": "Global parameters"},
"Parameters": ["environment"]
},
{
"Label": {"default": "Application Loadbalancer"},
"Parameters": ["albSubnets", "loadbalancerPrefix", "loadBalancerArn", "albPaths", "albPort", ]
},
{
"Label": {"default": "VPC"},
"Parameters": ["ec2Subnets", "VPC", "securityGroup"]
},
{
"Label": {"default": "EC2"},
"Parameters": ["ec2Name", "ec2Type", "ec2Key"]
},
{
"Label": {"default": "Auto-scaling"},
"Parameters": ["asgCapacity", "asgMinSize", "asgMaxSize", "asgCooldown", "asgHealthGrace"]
},
{
"Label": {"default": "Route53"},
"Parameters": ["route53HostedZoneId", "route53HostedZoneName"]
}
]
}
}
)
AddAMI(t)
environment = t.add_parameter(Parameter(
"environment",
Default="dev",
Type="String",
Description="Development or Production environment",
AllowedValues=[
"dev",
"prod"
],
ConstraintDescription="dev or prod",
))
route53_hosted_zone_id = t.add_parameter(Parameter(
"route53HostedZoneId",
Default="",
Type="AWS::Route53::HostedZone::Id",
Description="Route53 DNS zone ID"
))
route53_hosted_zone_name = t.add_parameter(Parameter(
"route53HostedZoneName",
Default="my.aws.dns.com",
Type="String",
Description="Route53 hosted zone name"
))
security_group = t.add_parameter(Parameter(
"securityGroup",
Default="",
Type="List<AWS::EC2::SecurityGroup::Id>",
Description="Which security groups to use"
))
alb_paths = t.add_parameter(Parameter(
"albPaths",
Default="/",
Type="CommaDelimitedList",
Description="Path-patterns you want the loadbalancer to point to in your application"
))
albPort = t.add_parameter(Parameter(
"albPort",
Default="80",
Type="Number",
Description="Which loadbalancer port to use"
))
ec2_subnets = t.add_parameter(Parameter(
"ec2Subnets",
Default="",
Type="List<AWS::EC2::Subnet::Id>",
Description="Private subnets for the instances."
))
alb_subnets = t.add_parameter(Parameter(
"albSubnets",
Default="",
Type="List<AWS::EC2::Subnet::Id>",
Description="Public subnets for the load balancer."
))
loadbalancer_prefix = t.add_parameter(Parameter(
"loadbalancerPrefix",
Default="",
Type="String",
Description="Specify a prefix for your loadbalancer",
))
vpc = t.add_parameter(Parameter(
"VPC",
Default="",
Type="AWS::EC2::VPC::Id",
Description="Environment VPC"
))
# Auto scaling group parameters
asg_capacity = t.add_parameter(Parameter(
"asgCapacity",
Default="0",
Type="Number",
Description="Number of instances"
))
asg_min_size = t.add_parameter(Parameter(
"asgMinSize",
Default="0",
Type="Number",
Description="Minimum size of AutoScalingGroup"
))
asg_max_size = t.add_parameter(Parameter(
"asgMaxSize",
Default="1",
Type="Number",
Description="Maximum size of AutoScalingGroup"
))
asg_cooldown = t.add_parameter(Parameter(
"asgCooldown",
Default="300",
Type="Number",
Description="Cooldown before starting/stopping another instance"
))
asg_health_grace = t.add_parameter(Parameter(
"asgHealthGrace",
Default="300",
Type="Number",
Description="Wait before starting/stopping another instance"
))
# EC2 parameters
ec2_name = t.add_parameter(Parameter(
"ec2Name",
Default="myApplication",
Type="String",
Description="Name of the instances"
))
ec2_type = t.add_parameter(Parameter(
"ec2Type",
Default="t2.large",
Type="String",
Description="Instance type."
))
ec2_key = t.add_parameter(Parameter(
"ec2Key",
Default="",
Type="AWS::EC2::KeyPair::KeyName",
Description="EC2 Key Pair"
))
# Launchconfiguration
EC2LaunchConfiguration = t.add_resource(autoscaling.LaunchConfiguration(
"EC2LaunchConfiguration",
ImageId=FindInMap("windowsAMI", Ref("AWS::Region"), "AMI"),
KeyName=Ref(ec2_key),
SecurityGroups=Ref(security_group),
InstanceType=Ref(ec2_type),
AssociatePublicIpAddress=False,
UserData=Base64(Join('\n', [
"<powershell>",
# Start logging
"start-transcript -append -path c:/Temp/cloudInit.log",
"write-output 'start'",
"get-date -f FileDateTime 2>&1 | Write-Output",
# Install AWS cli
"(new-object net.webclient).DownloadFile('https://s3.amazonaws.com/aws-cli/AWSCLI64.msi', 'aws-cli.msi') 2>&1 | Write-Output",
"msiexec /i aws-cli.msi /quiet 2>&1 | Write-Output",
"Import-Module AWSPowerShell 2>&1 | Write-Output",
# Install IIS
"Install-WindowsFeature -Name 'Web-Server' 2>&1 | Write-Output",
"Get-WindowsFeature -Name Web-*45* | Install-WindowsFeature 2>&1 | Write-Output",
"Get-WindowsFeature -Name NET-Framework-45-* | Install-WindowsFeature 2>&1 | Write-Output",
# Stop logging
"get-date -f FileDateTime 2>&1 | Write-Output",
"write-output 'end'",
"stop-transcript",
"</powershell>",
])),
))
# Application ELB
alb_target_group = t.add_resource(elb.TargetGroup(
"albTargetGroup",
HealthCheckPath=Select("0", Ref(alb_paths)),
HealthCheckIntervalSeconds="30",
HealthCheckProtocol="HTTP",
HealthCheckTimeoutSeconds="10",
HealthyThresholdCount="4",
Matcher=elb.Matcher(
HttpCode="200"),
Name=Ref(ec2_name),
Port=80,
Protocol="HTTP",
UnhealthyThresholdCount="3",
VpcId=Ref(vpc)
))
# Auto scaling group
auto_scaling_group = t.add_resource(autoscaling.AutoScalingGroup(
"autoScalingGroup",
DesiredCapacity=Ref(asg_capacity),
Tags=autoscaling.Tags(
Environment=Ref(environment)
),
VPCZoneIdentifier=Ref(ec2_subnets),
TargetGroupARNs=[Ref(alb_target_group)],
MinSize=Ref(asg_min_size),
MaxSize=Ref(asg_max_size),
Cooldown=Ref(asg_cooldown),
LaunchConfigurationName=Ref(EC2LaunchConfiguration),
HealthCheckGracePeriod=Ref(asg_health_grace),
HealthCheckType="EC2",
))
# Application Load Balancer
application_load_balancer = t.add_resource(elb.LoadBalancer(
"applicationLoadBalancer",
Name=Ref(loadbalancer_prefix),
Scheme="internet-facing",
Subnets=Ref(alb_subnets),
SecurityGroups=Ref(security_group)
))
alb_listener = t.add_resource(elb.Listener(
"albListener",
Port=Ref(albPort),
Protocol="HTTP",
LoadBalancerArn=Ref(application_load_balancer),
DefaultActions=[elb.Action(
Type="forward",
TargetGroupArn=Ref(alb_target_group)
)]
))
alb_listener_rule = t.add_resource(elb.ListenerRule(
"albListenerRule",
ListenerArn=Ref(alb_listener),
Conditions=[elb.Condition(
Field="path-pattern",
Values=Ref(alb_paths)
)],
Actions=[elb.Action(
Type="forward",
TargetGroupArn=Ref(alb_target_group)
)],
Priority="1"
))
# Route53
route53_roundrobin = t.add_resource(route53.RecordSetGroup(
"route53RoundRobin",
HostedZoneId=Ref(route53_hosted_zone_id),
RecordSets=[
route53.RecordSet(
Weight=1,
SetIdentifier=Join(".", [Ref(environment), Ref(route53_hosted_zone_name), "ELB"]),
Name=Join(".", [Ref(environment), Ref(route53_hosted_zone_name)]),
Type="A",
AliasTarget=route53.AliasTarget(
GetAtt(application_load_balancer, "CanonicalHostedZoneID"),
GetAtt(application_load_balancer, "DNSName")
)
)
]
))
t.add_output(
Output(
"URL",
Description="URL of the website",
Value=Join("", [
"http://",
GetAtt(application_load_balancer, "DNSName"),
Select("0", Ref(alb_paths))
]),
Export=Export(Sub("${AWS::StackName}-URL")),
)
)
print(t.to_json())
if __name__ == '__main__':
main()