rubycfn 0.4.10 → 0.5.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +22 -1
  3. data/Gemfile.lock +48 -46
  4. data/README.md +46 -71
  5. data/bin/rubycfn +17 -73
  6. data/lib/cli_methods.rb +2 -2
  7. data/lib/rubycfn/version.rb +1 -1
  8. data/rubycfn.gemspec +1 -1
  9. data/templates/.env +2 -0
  10. data/templates/.env.acceptance +1 -0
  11. data/templates/.env.dependencies.rspec +6 -0
  12. data/templates/.env.development +1 -0
  13. data/templates/.env.production +1 -0
  14. data/templates/.env.rspec +1 -0
  15. data/templates/.env.test +1 -0
  16. data/templates/{.gitignore.erb → .gitignore} +7 -0
  17. data/templates/{.rubocop.yml.erb → .rubocop.yml} +17 -1
  18. data/templates/{Gemfile.erb → Gemfile} +0 -1
  19. data/templates/README.md +58 -0
  20. data/templates/{Rakefile.erb → Rakefile} +15 -8
  21. data/templates/config.yaml +68 -0
  22. data/templates/lib/aws_helper/aws_sdk.rb +30 -0
  23. data/templates/{compiler.rb.erb → lib/aws_helper/compiler.rb} +15 -9
  24. data/templates/lib/aws_helper/dependencies.rb +35 -0
  25. data/templates/{deploy.rb.erb → lib/aws_helper/deploy.rb} +5 -4
  26. data/templates/lib/aws_helper/helpers.rb +3 -0
  27. data/templates/{main_aws_helper.rb.erb → lib/aws_helper/main.rb} +0 -0
  28. data/templates/{upload_stack.rb.erb → lib/aws_helper/upload_stack.rb} +8 -6
  29. data/templates/lib/core/applications.rb +625 -0
  30. data/templates/lib/core/assume_role.rb +40 -0
  31. data/templates/lib/core/classes.rb +25 -0
  32. data/templates/{core_compile.rb.erb → lib/core/compile.rb} +1 -0
  33. data/templates/lib/core/dependencies.rb +29 -0
  34. data/templates/{core_deploy.rb.erb → lib/core/deploy.rb} +20 -10
  35. data/templates/lib/core/git.rb +15 -0
  36. data/templates/lib/core/init.rb +221 -0
  37. data/templates/{core_upload.rb.erb → lib/core/upload.rb} +0 -0
  38. data/templates/{main.rb.erb → lib/main.rb} +8 -6
  39. data/templates/lib/shared_concerns/global_variables.rb +56 -0
  40. data/templates/{helper_methods.rb.erb → lib/shared_concerns/helper_functions.rb} +0 -0
  41. data/templates/lib/shared_concerns/helper_methods.rb +3 -0
  42. data/templates/{shared_methods.rb.erb → lib/shared_concerns/shared_methods.rb} +11 -0
  43. data/templates/lib/stacks/acm_stack/certificate_manager.rb +79 -0
  44. data/templates/{new_stack.rb.erb → lib/stacks/acm_stack/main.rb} +3 -4
  45. data/templates/lib/stacks/ecs_stack/ecs_cluster.rb +344 -0
  46. data/templates/lib/stacks/ecs_stack/lifecycle_hook.rb +190 -0
  47. data/templates/lib/stacks/ecs_stack/load_balancer.rb +70 -0
  48. data/templates/{ecs_stack.rb.erb → lib/stacks/ecs_stack/main.rb} +3 -0
  49. data/templates/lib/stacks/ecs_stack/rollback.rb +77 -0
  50. data/templates/{project_stack.rb.erb → lib/stacks/parent_stack/main.rb} +2 -2
  51. data/templates/lib/stacks/parent_stack/parent.rb +18 -0
  52. data/templates/lib/stacks/vpc_stack/infra_vpc.rb +193 -0
  53. data/templates/{vpc_stack.rb.erb → lib/stacks/vpc_stack/main.rb} +1 -2
  54. data/templates/{parent_stack_spec.rb.erb → spec/lib/parent_spec.rb} +2 -5
  55. data/templates/{spec_helper.rb.erb → spec/spec_helper.rb} +2 -2
  56. metadata +61 -51
  57. data/format.vim +0 -3
  58. data/templates/.env.erb +0 -4
  59. data/templates/.env.production.erb +0 -6
  60. data/templates/.env.rspec.erb +0 -6
  61. data/templates/.env.test.erb +0 -6
  62. data/templates/.gitlab-ci.yml.erb +0 -75
  63. data/templates/aws_sdk.rb.erb +0 -18
  64. data/templates/core_diff.rb.erb +0 -59
  65. data/templates/dependencies.rb.erb +0 -23
  66. data/templates/ecs_stack_concern.rb.erb +0 -20
  67. data/templates/global_variables.rb.erb +0 -16
  68. data/templates/helpers.rb.erb +0 -7
  69. data/templates/new_concern.rb.erb +0 -10
  70. data/templates/project_concern.rb.erb +0 -26
  71. data/templates/subnets.rb.erb +0 -18
  72. data/templates/vpc_concerns.rb.erb +0 -87
  73. data/templates/vpc_spec.rb.erb +0 -39
@@ -0,0 +1,3 @@
1
+ def stack_to_hash(stack_name)
2
+ @stack_hashes[stack_name] = git_revision
3
+ end
@@ -1,4 +1,8 @@
1
+ require_relative "../core/git"
2
+
1
3
  def upload_stacks
4
+ Dotenv.load(".env.private")
5
+ Dotenv.load(".env.dependencies.#{ENV["ENVIRONMENT"]}")
2
6
  env_vars = load_env_vars
3
7
 
4
8
  set_aws_credentials(
@@ -7,21 +11,19 @@ def upload_stacks
7
11
  env_vars[:aws_secret_access_key]
8
12
  )
9
13
 
10
- s3 = create_bucket_if_not_exists(
11
- env_vars[:aws_region],
12
- env_vars[:artifact_bucket]
13
- )
14
+ s3 = Aws::S3::Resource.new(region: env_vars[:aws_region])
14
15
 
15
16
  stacks = compile_stacks(true)
17
+ raise "CLOUDFORMATIONBUCKET not found in <%= project_name %>#{ENV["ENVIRONMENT"].capitalize}DependencyStack outputs" unless ENV["CLOUDFORMATIONBUCKET"]
16
18
  stacks.each do |stack_name, stack|
17
19
  next if JSON.parse(stack)["Resources"].nil?
18
20
  hash = @stack_hashes[stack_name.to_sym]
19
21
  local_file = "#{env_vars[:environment]}-#{stack_name.downcase}.json"
20
22
  s3_filename = "#{env_vars[:environment]}-#{stack_name.downcase}-#{hash}.json"
21
23
  # content = JSON.parse(stack).to_json
22
- obj = s3.bucket(env_vars[:artifact_bucket]).object(s3_filename)
24
+ obj = s3.bucket(ENV["CLOUDFORMATIONBUCKET"]).object(s3_filename)
23
25
  content = File.open("build/#{local_file}").read
24
26
  obj.put(body: content)
25
- puts "Uploaded #{stack_name} to s3://#{env_vars[:artifact_bucket]}/#{s3_filename}"
27
+ puts "Uploaded #{stack_name} to s3://#{ENV["CLOUDFORMATIONBUCKET"]}/#{s3_filename}"
26
28
  end
27
29
  end
@@ -0,0 +1,625 @@
1
+ def to_bool(val)
2
+ return false unless val.nil? || val.empty?
3
+ return false unless val != "true"
4
+ true
5
+ end
6
+
7
+ def env_vars_to_array(val)
8
+ if val.nil? || val.empty?
9
+ return [
10
+ {
11
+ Name: "WITHOUT_ENV",
12
+ Value: "true"
13
+ }
14
+ ]
15
+ end
16
+ vars = []
17
+
18
+ # Create an array of variables to pass to this application.
19
+ # Resolve any references to its intrinsic function.
20
+ val.keys.each_with_index do |object, index|
21
+ value = val.values[index].class == Symbol && Kernel.class_eval(":#{val.values[index]}") || val.values[index]
22
+
23
+ # Support ${ENV_VAR} in config_yaml
24
+ if value =~ /\$\{([^\}]*)\}/
25
+ capture = $1
26
+ value = ENV[capture]
27
+ end
28
+
29
+ vars.push(
30
+ Name: object,
31
+ Value: value
32
+ )
33
+ end
34
+ vars
35
+ end
36
+
37
+ @ignore_params = {}
38
+
39
+ # Return the mandatory Stack parameters and add all defined ENV vars from config.yaml
40
+ def parent_parameters(env_vars, simple_name)
41
+ params = {
42
+ "Vpc": :vpc_stack.ref("Outputs.Vpc"),
43
+ "Cluster": :ecs_stack.ref("Outputs.EcsCluster"),
44
+ "Listener": :ecs_stack.ref("Outputs.EcsLoadBalancerListener"),
45
+ "EcsServiceAutoScalingRoleArn": :ecs_stack.ref("Outputs.EcsAutoScalingRoleArn"),
46
+ "HostedZoneId": "HOSTEDZONEID".ref,
47
+ "HostedZoneName": "HOSTEDZONENAME".ref,
48
+ "LoadBalancerDnsName": :ecs_stack.ref("Outputs.EcsLoadBalancerUrl"),
49
+ "CanonicalHostedZoneId": :ecs_stack.ref("Outputs.EcsLoadBalancerHostedZoneId"),
50
+ "CertificateProviderFunctionArn": :acm_stack.ref("Outputs.CertificateProviderFunctionArn"),
51
+ "ApplicationDeploymentFailureRollbackFunctionArn": :ecs_stack.ref("Outputs.ApplicationDeploymentFailureRollbackFunctionArn")
52
+ }
53
+
54
+ env_vars.each do |var|
55
+ TOPLEVEL_BINDING.eval("@ignore_params[:#{simple_name}] ||= []")
56
+ if var[:Value].class == Hash && var[:Value].keys[0] == :Ref
57
+ TOPLEVEL_BINDING.eval("@ignore_params[:#{simple_name}].push(\"#{var[:Name]}\")")
58
+ next
59
+ end
60
+ params[var[:Name].cfnize] = var[:Value]
61
+ end
62
+ params
63
+ end
64
+
65
+ def application_parameters(env_vars)
66
+ vars = []
67
+
68
+ env_vars.each do |var|
69
+ if var[:Value].class == Hash && var[:Value].keys[0] == :Ref
70
+ vars.push(
71
+ Name: var[:Name],
72
+ Value: var[:Value]
73
+ )
74
+ else
75
+ vars.push(
76
+ Name: var[:Name],
77
+ Value: var[:Name].cfnize.ref
78
+ )
79
+ end
80
+ end
81
+ vars
82
+ end
83
+
84
+ # Generate nested stacks for each defined application, and create module dynamically.
85
+ def create_applications
86
+ return if infra_config["environments"][environment]["cluster_size"].nil? || infra_config["environments"][environment]["cluster_size"].to_i.zero?
87
+ resource :applications_stack,
88
+ amount: infra_config["applications"].count,
89
+ type: "AWS::CloudFormation::Stack" do |r, index|
90
+ env_vars = env_vars_to_array(infra_config["applications"].values[index]["env"])
91
+ application_vars = application_parameters(env_vars) # rubocop:disable Lint/UselessAssignment
92
+ name = infra_config["applications"].keys[index]
93
+ resource_name = name.tr("-", "_").cfnize
94
+ simple_name = resource_name.downcase
95
+ app_config = infra_config["applications"].values[index]
96
+ is_essential = to_bool(app_config["essential"].to_s)
97
+
98
+ r._id("#{resource_name}Stack")
99
+ r.property(:template_url) { "#{simple_name}stack" }
100
+ r.property(:parameters) { parent_parameters(env_vars, simple_name) }
101
+ Object.const_set("#{resource_name}Stack", Module.new).class_eval <<-RUBY
102
+ extend ActiveSupport::Concern
103
+ include Rubycfn
104
+
105
+ included do
106
+
107
+ def get_aliases(val)
108
+ aliases = []
109
+ return aliases if val["aliases"].nil?
110
+ return aliases if val["aliases"][environment].nil?
111
+ val["aliases"][environment]
112
+ end
113
+
114
+ ignore_params = TOPLEVEL_BINDING.eval("@ignore_params[:#{simple_name}]")
115
+ application_vars.each do |var|
116
+ next if ignore_params.include? var[:Name]
117
+ Object.class_eval("parameter var[:Name].to_sym, description: 'Value for ENV var \#{var[:Name]}'")
118
+ end
119
+
120
+ parameter :vpc,
121
+ description: "The VPC that the ECS cluster is deployed to",
122
+ type: "AWS::EC2::VPC::Id"
123
+
124
+ parameter :cluster,
125
+ description: "ECS Cluster ID",
126
+ type: "String"
127
+
128
+ parameter :listener,
129
+ description: "The Application Load Balancer listener to register with",
130
+ type: "String"
131
+
132
+ parameter :ecs_service_auto_scaling_role_arn,
133
+ description: "The ECS service auto scaling role ARN",
134
+ type: "String"
135
+
136
+ parameter :hosted_zone_id,
137
+ description: "Hosted Zone ID",
138
+ type: "String"
139
+
140
+ parameter :hosted_zone_name,
141
+ description: "Hosted Zone Name",
142
+ type: "String"
143
+
144
+ parameter :load_balancer_dns_name,
145
+ description: "URL of the ECS ALB",
146
+ type: "String"
147
+
148
+ parameter :canonical_hosted_zone_id,
149
+ description: "Canonical Hosted Zone Id of ALB",
150
+ type: "String"
151
+
152
+ parameter :certificate_provider_function_arn,
153
+ description: "ARN of certificate provider",
154
+ type: "String"
155
+
156
+ parameter :application_deployment_failure_rollback_function_arn,
157
+ description: "ARN of ECS deployment failure Lambda",
158
+ type: "String"
159
+
160
+ variable :aliases,
161
+ value: app_config,
162
+ filter: :get_aliases
163
+
164
+ variable :min_override,
165
+ value: app_config[environment].nil? ? "" : app_config[environment]["min"].to_s
166
+
167
+ variable :min,
168
+ value: min_override.empty? ? app_config["min"].to_s : min_override
169
+
170
+ variable :max_override,
171
+ value: app_config[environment].nil? ? "" : app_config[environment]["max"].to_s
172
+
173
+ variable :max,
174
+ value: max_override.empty? ? app_config["max"].to_s : max_override
175
+
176
+ variable :container_port,
177
+ value: app_config["container_port"].to_s
178
+
179
+ variable :memory_override,
180
+ value: app_config[environment].nil? ? "" : app_config[environment]["mem"].to_s
181
+
182
+ variable :memory,
183
+ value: memory_override.empty? ? app_config["mem"].to_s : memory_override
184
+
185
+ variable :image,
186
+ value: app_config["image"]
187
+
188
+ variable :env_vars,
189
+ value: app_config["env"],
190
+ filter: :env_vars_to_array
191
+
192
+ variable :priority,
193
+ value: app_config["priority"].to_s
194
+
195
+
196
+ description generate_stack_description("#{resource_name}Stack")
197
+
198
+ resource :service,
199
+ amount: max.to_i.positive? ? 1 : 0,
200
+ type: "AWS::ECS::Service" do |r|
201
+ r.property(:service_name) { "#{environment}-<%= project_name %>-#{simple_name}" }
202
+ r.property(:cluster) { :cluster.ref }
203
+ r.property(:role) { :service_role.ref }
204
+ r.property(:health_check_grace_period_seconds) { 120 }
205
+ r.property(:desired_count) { min.to_i }
206
+ r.property(:task_definition) { :task_definition.ref }
207
+ r.property(:load_balancers) do
208
+ [
209
+ "ContainerName": "#{simple_name}-service",
210
+ "ContainerPort": container_port.to_i,
211
+ "TargetGroupArn": :target_group.ref
212
+ ]
213
+ end
214
+ end
215
+
216
+ resource :application_deployment_health,
217
+ amount: max.to_i.positive? ? 1 : 0,
218
+ type: "Custom::EcsDeploymentCheck" do |r|
219
+ r.property(:service_token) { :application_deployment_failure_rollback_function_arn.ref }
220
+ r.property("AWSRegion") { "${AWS::Region}".fnsub }
221
+ r.property(:service) { "#{environment}-<%= project_name %>-#{simple_name}" }
222
+ r.property(:cluster) { :cluster.ref }
223
+ end
224
+
225
+ resource :task_definition,
226
+ amount: max.to_i.positive? ? 1 : 0,
227
+ type: "AWS::ECS::TaskDefinition" do |r|
228
+ r.property(:family) { "#{simple_name}-service" }
229
+ r.property(:container_definitions) do
230
+ [
231
+ {
232
+ "Name": "#{simple_name}-service",
233
+ "Essential": #{is_essential},
234
+ "Image": image,
235
+ "Memory": memory.to_i,
236
+ "Environment": application_vars,
237
+ "PortMappings": [
238
+ {
239
+ "ContainerPort": container_port.to_i
240
+ }
241
+ ],
242
+ "LogConfiguration": {
243
+ "LogDriver": "awslogs",
244
+ "Options": {
245
+ "awslogs-group": :cloud_watch_logs_group.ref,
246
+ "awslogs-region": "AWS::Region".ref
247
+ }
248
+ }
249
+ }
250
+ ]
251
+ end
252
+ end
253
+
254
+ resource :cloud_watch_logs_group,
255
+ amount: max.to_i.positive? ? 1 : 0,
256
+ type: "AWS::Logs::LogGroup" do |r|
257
+ r.property(:log_group_name) { ["AWS::StackName".ref, "-#{simple_name}"].fnjoin }
258
+ r.property(:retention_in_days) { 30 }
259
+ end
260
+
261
+ resource :target_group,
262
+ amount: max.to_i.positive? ? 1 : 0,
263
+ type: "AWS::ElasticLoadBalancingV2::TargetGroup" do |r|
264
+ r.property(:vpc_id) { :vpc.ref }
265
+ r.property(:port) { container_port.to_i }
266
+ r.property(:protocol) { "HTTP" }
267
+ r.property(:matcher) do
268
+ {
269
+ "HttpCode": "200-299"
270
+ }
271
+ end
272
+ r.property(:health_check_interval_seconds) { 10 }
273
+ r.property(:health_check_path) { "/" }
274
+ r.property(:health_check_protocol) { "HTTP" }
275
+ r.property(:health_check_timeout_seconds) { 5 }
276
+ r.property(:healthy_threshold_count) { 2 }
277
+ end
278
+
279
+ resource :listener_rule,
280
+ amount: max.to_i.positive? ? 1 : 0,
281
+ type: "AWS::ElasticLoadBalancingV2::ListenerRule" do |r|
282
+ r.property(:listener_arn) { :listener.ref }
283
+ r.property(:priority) { priority.to_i }
284
+ r.property(:conditions) do
285
+ [
286
+ {
287
+ "Field": "host-header",
288
+ "Values": [
289
+ ["origin", name.tr("_", "-"), :hosted_zone_name.ref].fnjoin("."),
290
+ [name.tr("_", "-"), :hosted_zone_name.ref].fnjoin(".")
291
+ ] + aliases
292
+ }
293
+ ]
294
+ end
295
+ r.property(:actions) do
296
+ [
297
+ {
298
+ "TargetGroupArn": :target_group.ref,
299
+ "Type": "forward"
300
+ }
301
+ ]
302
+ end
303
+ end
304
+
305
+ assume_role_policy_document = {
306
+ "Statement": [
307
+ {
308
+ "Effect": "Allow",
309
+ "Principal": {
310
+ "Service": [
311
+ "ecs.amazonaws.com"
312
+ ]
313
+ },
314
+ "Action": [
315
+ "sts:AssumeRole"
316
+ ]
317
+ }
318
+ ]
319
+ }
320
+
321
+ resource :service_role,
322
+ amount: max.to_i.positive? ? 1 : 0,
323
+ type: "AWS::IAM::Role" do |r|
324
+ r.property(:role_name) { "ecs-service-${AWS::StackName}".fnsub }
325
+ r.property(:path) { "/" }
326
+ r.property(:assume_role_policy_document) { JSON.pretty_generate(assume_role_policy_document) }
327
+ r.property(:policies) do
328
+ [
329
+ {
330
+ "PolicyName": "ecs-service-${AWS::StackName}".fnsub,
331
+ "PolicyDocument": {
332
+ "Version": "2012-10-17",
333
+ "Statement": [
334
+ {
335
+ "Effect": "Allow",
336
+ "Action": [
337
+ "ec2:AuthorizeSecurityGroupIngress",
338
+ "ec2:Describe*",
339
+ "elasticloadbalancing:DeregisterInstancesFromLoadBalancer",
340
+ "elasticloadbalancing:Describe*",
341
+ "elasticloadbalancing:RegisterInstancesWithLoadBalancer",
342
+ "elasticloadbalancing:DeregisterTargets",
343
+ "elasticloadbalancing:DescribeTargetGroups",
344
+ "elasticloadbalancing:DescribeTargetHealth",
345
+ "elasticloadbalancing:RegisterTargets"
346
+ ],
347
+ "Resource": "*"
348
+ },
349
+ {
350
+ "Effect": "Allow",
351
+ "Action": [
352
+ "ec2:DescribeTags",
353
+ "ecs:CreateCluster",
354
+ "ecs:DeregisterContainerInstance",
355
+ "ecs:DiscoverPollEndpoint",
356
+ "ecs:Poll",
357
+ "ecs:RegisterContainerInstance",
358
+ "ecs:StartTelemetrySession",
359
+ "ecs:UpdateContainerInstancesState",
360
+ "ecs:Submit*",
361
+ "ecr:GetAuthorizationToken",
362
+ "ecr:BatchCheckLayerAvailability",
363
+ "ecr:GetDownloadUrlForLayer",
364
+ "ecr:BatchGetImage",
365
+ "logs:CreateLogStream",
366
+ "logs:PutLogEvents"
367
+ ],
368
+ "Resource": "*"
369
+ }
370
+ ]
371
+ }
372
+ }
373
+ ]
374
+ end
375
+ end
376
+
377
+ resource :application_load_balancer_record,
378
+ amount: max.to_i.positive? ? 1 : 0,
379
+ type: "AWS::Route53::RecordSet" do |r|
380
+ r.property(:type) { "A" }
381
+ r.property(:name) { ["origin", name.tr("_", "-"), :hosted_zone_name.ref].fnjoin(".") }
382
+ r.property(:hosted_zone_id) { :hosted_zone_id.ref }
383
+ r.property(:alias_target) do
384
+ {
385
+ "DNSName": :load_balancer_dns_name.ref,
386
+ "EvaluateTargetHealth": true,
387
+ "HostedZoneId": :canonical_hosted_zone_id.ref
388
+ }
389
+ end
390
+ end
391
+
392
+ resource :service_scalable_target,
393
+ amount: max.to_i.positive? ? 1 : 0,
394
+ type: "AWS::ApplicationAutoScaling::ScalableTarget" do |r|
395
+ r.property(:max_capacity) { max.to_i }
396
+ r.property(:min_capacity) { min.to_i }
397
+ r.property(:resource_id) { ["service", :cluster.ref, :service.ref(:name)].fnjoin("/") }
398
+ r.property(:role_arn) { :ecs_service_auto_scaling_role_arn.ref }
399
+ r.property(:scalable_dimension) { "ecs:service:DesiredCount" }
400
+ r.property(:service_namespace) { "ecs" }
401
+ end
402
+
403
+ resource :service_scale_out_policy,
404
+ amount: max.to_i.positive? ? 1 : 0,
405
+ type: "AWS::ApplicationAutoScaling::ScalingPolicy" do |r|
406
+ r.property(:policy_name) { "ServiceScaleOutPolicy" }
407
+ r.property(:policy_type) { "StepScaling" }
408
+ r.property(:scaling_target_id) { :service_scalable_target.ref }
409
+ r.property(:step_scaling_policy_configuration) do
410
+ {
411
+ "AdjustmentType": "ChangeInCapacity",
412
+ "Cooldown": 300,
413
+ "MetricAggregationType": "Average",
414
+ "StepAdjustments": [
415
+ {
416
+ "MetricIntervalLowerBound": 0,
417
+ "ScalingAdjustment": 1
418
+ }
419
+ ]
420
+ }
421
+ end
422
+ end
423
+
424
+ resource :service_scale_in_policy,
425
+ amount: max.to_i.positive? ? 1 : 0,
426
+ type: "AWS::ApplicationAutoScaling::ScalingPolicy" do |r|
427
+ r.property(:policy_name) { "ServiceScaleInPolicy" }
428
+ r.property(:policy_type) { "StepScaling" }
429
+ r.property(:scaling_target_id) { :service_scalable_target.ref }
430
+ r.property(:step_scaling_policy_configuration) do
431
+ {
432
+ "AdjustmentType": "ChangeInCapacity",
433
+ "Cooldown": 600,
434
+ "MetricAggregationType": "Average",
435
+ "StepAdjustments": [
436
+ {
437
+ "MetricIntervalUpperBound": 0,
438
+ "ScalingAdjustment": -1
439
+ }
440
+ ]
441
+ }
442
+ end
443
+ end
444
+
445
+ resource :cpu_scale_out_alarm,
446
+ amount: max.to_i.positive? ? 1 : 0,
447
+ type: "AWS::CloudWatch::Alarm" do |r|
448
+ r.property(:alarm_name) { "CPU utilization greater than 90% on #{simple_name}-#{environment}" }
449
+ r.property(:alarm_description) { "Alarm if cpu utilization greater than 90% of reserved cpu" }
450
+ r.property(:namespace) { "AWS/ECS" }
451
+ r.property(:metric_name) { "CPUUtilization" }
452
+ r.property(:dimensions) do
453
+ [
454
+ {
455
+ "Name": "ClusterName",
456
+ "Value": :cluster.ref
457
+ },
458
+ {
459
+ "Name": "ServiceName",
460
+ "Value": :service.ref(:name)
461
+ }
462
+ ]
463
+ end
464
+ r.property(:statistic) { "Maximum" }
465
+ r.property(:period) { "60" }
466
+ r.property(:evaluation_periods) { "3" }
467
+ r.property(:threshold) { "90" }
468
+ r.property(:comparison_operator) { "GreaterThanThreshold" }
469
+ r.property(:alarm_actions) { [:service_scale_out_policy.ref] }
470
+ end
471
+
472
+ resource :cpu_scale_in_alarm,
473
+ amount: max.to_i.positive? ? 1 : 0,
474
+ type: "AWS::CloudWatch::Alarm" do |r|
475
+ r.property(:alarm_name) { "CPU utilization less than 70% on #{simple_name}-#{environment}" }
476
+ r.property(:alarm_description) { "Alarm if cpu utilization greater than 70% of reserved cpu" }
477
+ r.property(:namespace) { "AWS/ECS" }
478
+ r.property(:metric_name) { "CPUUtilization" }
479
+ r.property(:dimensions) do
480
+ [
481
+ {
482
+ "Name": "ClusterName",
483
+ "Value": :cluster.ref
484
+ },
485
+ {
486
+ "Name": "ServiceName",
487
+ "Value": :service.ref(:name)
488
+ }
489
+ ]
490
+ end
491
+ r.property(:statistic) { "Maximum" }
492
+ r.property(:period) { "60" }
493
+ r.property(:evaluation_periods) { "10" }
494
+ r.property(:threshold) { "70" }
495
+ r.property(:comparison_operator) { "LessThanThreshold" }
496
+ r.property(:alarm_actions) { [:service_scale_in_policy.ref] }
497
+ end
498
+
499
+ resource :ecs_application_certificate,
500
+ amount: max.to_i.positive? ? 1 : 0,
501
+ type: "Custom::Certificate" do |r|
502
+ r.property(:service_token) { :certificate_provider_function_arn.ref }
503
+ r.property(:region) { "us-east-1" }
504
+ r.property(:domain_name) { [name.tr("_", "-"), :hosted_zone_name.ref].fnjoin(".") }
505
+ r.property(:validation_method) { "DNS" }
506
+ end
507
+
508
+ resource :ecs_application_issued_certificate,
509
+ amount: max.to_i.positive? ? 1 : 0,
510
+ type: "Custom::IssuedCertificate" do |r|
511
+ r.property(:service_token) { :certificate_provider_function_arn.ref }
512
+ r.property(:region) { "us-east-1" }
513
+ r.property(:certificate_arn) { :ecs_application_certificate.ref }
514
+ end
515
+
516
+ resource :ecs_application_dns_record,
517
+ amount: max.to_i.positive? ? 1 : 0,
518
+ type: "Custom::CertificateDNSRecord" do |r|
519
+ r.property(:service_token) { :certificate_provider_function_arn.ref }
520
+ r.property(:region) { "us-east-1" }
521
+ r.property(:domain_name) { [name.tr("_", "-"), :hosted_zone_name.ref].fnjoin(".") }
522
+ r.property(:certificate_arn) { :ecs_application_certificate.ref }
523
+ end
524
+
525
+ resource :ecs_application_validation_record,
526
+ amount: max.to_i.positive? ? 1 : 0,
527
+ type: "AWS::Route53::RecordSetGroup" do |r|
528
+ r.property(:hosted_zone_id) { :hosted_zone_id.ref }
529
+ r.property(:record_sets) do
530
+ [
531
+ {
532
+ "Name": :ecs_application_dns_record.ref(:name),
533
+ "Type": :ecs_application_dns_record.ref(:type),
534
+ "TTL": 60,
535
+ "Weight": 1,
536
+ "SetIdentifier": :ecs_application_certificate.ref,
537
+ "ResourceRecords": [
538
+ :ecs_application_dns_record.ref(:value)
539
+ ]
540
+ }
541
+ ]
542
+ end
543
+ end
544
+
545
+ resource :cloudfront_distribution,
546
+ depends_on: [
547
+ :ecs_application_issued_certificate,
548
+ :application_deployment_health
549
+ ],
550
+ amount: max.to_i.positive? ? 1 : 0,
551
+ type: "AWS::CloudFront::Distribution" do |r|
552
+ r.property(:distribution_config) do
553
+ {
554
+ "Comment": ["Distribution config for", [name.tr("_", "-"), :hosted_zone_name.ref].fnjoin(".")].fnjoin(" "),
555
+ "Aliases": [
556
+ [name.tr("_", "-"), :hosted_zone_name.ref].fnjoin(".")
557
+ ],
558
+ "DefaultCacheBehavior": {
559
+ "AllowedMethods": %w(GET HEAD OPTIONS PUT PATCH POST DELETE),
560
+ "DefaultTTL": 0,
561
+ "TargetOriginId": "EcsApplication",
562
+ "ForwardedValues": {
563
+ "QueryString": true,
564
+ "Cookies": {
565
+ "Forward": "all"
566
+ },
567
+ "Headers": ["*"]
568
+ },
569
+ "MaxTTL": 0,
570
+ "MinTTL": 0,
571
+ "ViewerProtocolPolicy": "redirect-to-https"
572
+ },
573
+ "Enabled": true,
574
+ "HttpVersion": "http2",
575
+ "IPV6Enabled": false,
576
+ "Origins": [
577
+ {
578
+ "DomainName": ["origin", name.tr("_", "-"), :hosted_zone_name.ref].fnjoin("."),
579
+ "Id": "EcsApplication",
580
+ "CustomOriginConfig": {
581
+ "OriginProtocolPolicy": "http-only",
582
+ "HTTPPort": container_port.to_i,
583
+ "OriginKeepaliveTimeout": 5,
584
+ "OriginReadTimeout": 30
585
+ }
586
+ }
587
+ ],
588
+ "PriceClass": "PriceClass_All",
589
+ "ViewerCertificate": {
590
+ "AcmCertificateArn": :ecs_application_certificate.ref,
591
+ "SslSupportMethod": "sni-only"
592
+ }
593
+ }
594
+ end
595
+ r.property(:tags) do
596
+ [
597
+ {
598
+ "Key": "Environment",
599
+ "Value": environment.to_s
600
+ }
601
+ ]
602
+ end
603
+ end
604
+
605
+ resource :application_cloudfront_dns_record,
606
+ amount: max.to_i.positive? ? 1 : 0,
607
+ type: "AWS::Route53::RecordSetGroup" do |r|
608
+ r.property(:hosted_zone_id) { :hosted_zone_id.ref }
609
+ r.property(:record_sets) do
610
+ [
611
+ {
612
+ "Name": [name.tr("_", "-"), :hosted_zone_name.ref].fnjoin("."),
613
+ "Type": "A",
614
+ "AliasTarget": {
615
+ "HostedZoneId": "Z2FDTNDATAQYW2",
616
+ "DNSName": :cloudfront_distribution.ref(:domain_name)
617
+ }
618
+ }
619
+ ]
620
+ end
621
+ end
622
+ end
623
+ RUBY
624
+ end
625
+ end