Class: Terrafying::Components::DynamicSet

Inherits:
Terrafying::Context
  • Object
show all
Includes:
Usable
Defined in:
lib/terrafying/components/dynamicset.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Usable

#egress_security_group, #ingress_security_group, #path_mtu_setup!, #pingable_by, #pingable_by_cidr, #security_group, #used_by, #used_by_cidr

Constructor Details

#initializeDynamicSet

Returns a new instance of DynamicSet.



22
23
24
# File 'lib/terrafying/components/dynamicset.rb', line 22

def initialize
  super
end

Instance Attribute Details

#asgObject (readonly)

Returns the value of attribute asg.



10
11
12
# File 'lib/terrafying/components/dynamicset.rb', line 10

def asg
  @asg
end

#nameObject (readonly)

Returns the value of attribute name.



10
11
12
# File 'lib/terrafying/components/dynamicset.rb', line 10

def name
  @name
end

#stackObject (readonly)

Returns the value of attribute stack.



10
11
12
# File 'lib/terrafying/components/dynamicset.rb', line 10

def stack
  @stack
end

Class Method Details

.create_in(vpc, name, options = {}) ⇒ Object



14
15
16
# File 'lib/terrafying/components/dynamicset.rb', line 14

def self.create_in(vpc, name, options = {})
  DynamicSet.new.create_in vpc, name, options
end

.find_in(vpc, name) ⇒ Object



18
19
20
# File 'lib/terrafying/components/dynamicset.rb', line 18

def self.find_in(vpc, name)
  DynamicSet.new.find_in vpc, name
end

Instance Method Details

#attach_load_balancer(load_balancer) ⇒ Object



167
168
169
170
171
172
173
174
175
# File 'lib/terrafying/components/dynamicset.rb', line 167

def attach_load_balancer(load_balancer)
  load_balancer.targets.each.with_index do |target, i|
    resource :aws_autoscaling_attachment, "#{load_balancer.name}-#{@name}-#{i}".gsub(%r{^(\d)}, '_\1'),
             autoscaling_group_name: @asg,
             alb_target_group_arn: target.target_group
  end

  used_by(load_balancer) if load_balancer.application?
end

#autoscale_on_load_balancer(load_balancer, target_value:, disable_scale_in:) ⇒ Object



177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
# File 'lib/terrafying/components/dynamicset.rb', line 177

def autoscale_on_load_balancer(load_balancer, target_value:, disable_scale_in:)
  load_balancer.targets.each.with_index do |target, i|
    policy_ident = "#{load_balancer.name}-#{@name}-#{i}".gsub(%r{^(\d)}, '_\1')
    policy_name = "#{load_balancer.name}-#{@name}-#{i}"
    lb_arn = load_balancer.id.to_s.gsub(/id/, 'arn_suffix')
    tg_arn = target.target_group.to_s.gsub(/id/, 'arn_suffix')
    listener = "aws_lb_listener.#{target.listener.to_s.split('.')[1]}"
    autoscaling_attachment = "aws_autoscaling_attachment.#{policy_ident}"

    resource :aws_autoscaling_policy, policy_ident,
             name: policy_name,
             autoscaling_group_name: @asg,
             policy_type: 'TargetTrackingScaling',
             target_tracking_configuration: {
               predefined_metric_specification: {
                 predefined_metric_type: 'ALBRequestCountPerTarget',
                 resource_label: "#{lb_arn}/#{tg_arn}"
               },
               target_value: target_value,
               disable_scale_in: disable_scale_in
             },
             depends_on: [listener, autoscaling_attachment]
  end
end

#create_in(vpc, name, options = {}) ⇒ Object



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
# File 'lib/terrafying/components/dynamicset.rb', line 32

def create_in(vpc, name, options = {})
  options = {
    public: false,
    eip: false,
    ami: aws.ami('base-image-fc-75aa2aef', owners = ['477284023816']),
    instance_type: 't3a.micro',
    instances: { min: 1, max: 1, desired: 1, tags: {} },
    ports: [],
    instance_profile: nil,
    security_groups: [],
    tags: {},
    ssh_group: vpc.ssh_group,
    subnets: vpc.subnets.fetch(:private, []),
    depends_on: [],
    rolling_update: :simple,
    metadata_options: nil,
    vpc_endpoints_egress: []
  }.merge(options)

   = options[:metadata_options]

  ident = "#{tf_safe(vpc.name)}-#{name}"

  @name = ident
  @ports = enrich_ports(options[:ports])

  @security_group = resource :aws_security_group, ident,
                             name: "dynamicset-#{ident}",
                             description: "Describe the ingress and egress of the service #{ident}",
                             tags: options[:tags],
                             vpc_id: vpc.id

  vpc_endpoints_egress = options[:vpc_endpoints_egress]
  if vpc_endpoints_egress.empty?
    default_egress_rule(ident, @security_group)
  else
    vpc_endpoint_egress_rules(ident, @security_group, vpc, vpc_endpoints_egress)
  end

  path_mtu_setup!

  launch_config = resource :aws_launch_configuration, ident,
                           name_prefix: "#{ident}-",
                           image_id: options[:ami],
                           instance_type: options[:instance_type],
                           user_data: options[:user_data],
                           iam_instance_profile: profile_from(options[:instance_profile]),
                           associate_public_ip_address: options[:public],
                           root_block_device: {
                             volume_type: 'gp2',
                             volume_size: 32
                           },
                           security_groups: [
                             vpc.internal_ssh_security_group,
                             @security_group
                           ].push(*options[:security_groups]),
                           lifecycle: {
                             create_before_destroy: true
                           },
                           metadata_options: options[:metadata_options],
                           depends_on: resource_name_from(options[:instance_profile])

  if options[:instances][:track]
    instances = instances_by_tags(Name: ident)
    if instances
      options[:instances] = options[:instances].merge(instances)
    end
  end

  if options.key?(:health_check)
    raise 'Health check needs a type and grace_period' if !options[:health_check].key?(:type) && !options[:health_check].key?(:grace_period)
  else
    options = {
      health_check: {
        type: 'EC2',
        grace_period: 0
      }
    }.merge(options)
  end
  tags = { Name: ident, service_name: name }.merge(options[:tags]).merge(options[:instances].fetch(:tags, {})).map { |k, v| { Key: k, Value: v, PropagateAtLaunch: true } }

  resource :aws_cloudformation_stack, ident,
           name: ident,
           disable_rollback: true,
           lifecycle: {
             ignore_changes: ['disable_rollback']
           },
           template_body: generate_template(
             options[:health_check], options[:instances], launch_config,
             options[:subnets].map(&:id), tags, options[:rolling_update]
           )

  @stack = "arn:aws:cloudformation:#{aws.region}:#{aws.}:stack/#{ident}/*"

  @asg = output_of(:aws_cloudformation_stack, ident, 'outputs["AsgName"]')

  self
end

#default_egress_rule(ident, security_group) ⇒ Object



149
150
151
152
153
154
155
156
157
# File 'lib/terrafying/components/dynamicset.rb', line 149

def default_egress_rule(ident, security_group)
  resource :aws_security_group_rule, "#{ident}-default-egress",
           security_group_id: security_group,
           type: 'egress',
           from_port: 0,
           to_port: 0,
           protocol: -1,
           cidr_blocks: ['0.0.0.0/0']
end

#find_in(vpc, name) ⇒ Object



26
27
28
29
30
# File 'lib/terrafying/components/dynamicset.rb', line 26

def find_in(vpc, name)
  @name = "#{vpc.name}-#{name}"

  self
end

#generate_template(health_check, instances, launch_config, subnets, tags, rolling_update) ⇒ Object



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
# File 'lib/terrafying/components/dynamicset.rb', line 202

def generate_template(health_check, instances, launch_config, subnets, tags, rolling_update)
  template = {
    Resources: {
      AutoScalingGroup: {
        Type: 'AWS::AutoScaling::AutoScalingGroup',
        Properties: {
          Cooldown: '300',
          HealthCheckType: (health_check[:type]).to_s,
          HealthCheckGracePeriod: health_check[:grace_period],
          LaunchConfigurationName: launch_config.to_s,
          MetricsCollection: [
            {
              Granularity: '1Minute',
              Metrics: %w[
                GroupMinSize
                GroupMaxSize
                GroupDesiredCapacity
                GroupInServiceInstances
                GroupPendingInstances
                GroupStandbyInstances
                GroupTerminatingInstances
                GroupTotalInstances
              ]
            }
          ],
          MaxSize: instances[:max].to_s,
          MinSize: instances[:min].to_s,
          DesiredCapacity: instances[:desired] ? instances[:desired].to_s : nil,
          Tags: tags,
          TerminationPolicies: [
            'Default'
          ],
          VPCZoneIdentifier: subnets
        }.compact
      }
    },
    Outputs: {
      AsgName: {
        Description: 'The name of the auto scaling group',
        Value: {
          Ref: 'AutoScalingGroup'
        }
      }
    }
  }

  if rolling_update == :signal
    template[:Resources][:AutoScalingGroup][:UpdatePolicy] = {
      AutoScalingRollingUpdate: {
        MinInstancesInService: (instances[:desired]).to_s,
        MaxBatchSize: (instances[:desired]).to_s,
        PauseTime: 'PT10M',
        WaitOnResourceSignals: true,
        SuspendProcesses: %w[HealthCheck ReplaceUnhealthy AZRebalance AlarmNotification ScheduledActions]
      }
    }
  elsif rolling_update
    template[:Resources][:AutoScalingGroup][:UpdatePolicy] = {
      AutoScalingRollingUpdate: {
        MinInstancesInService: (instances[:min]).to_s,
        MaxBatchSize: '1',
        PauseTime: 'PT0S',
        SuspendProcesses: %w[HealthCheck ReplaceUnhealthy AZRebalance AlarmNotification ScheduledActions]
      }
    }
  end

  JSON.pretty_generate(template)
end

#instances_by_tags(tags = {}) ⇒ Object



272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
# File 'lib/terrafying/components/dynamicset.rb', line 272

def instances_by_tags(tags = {})
  begin
    asgs = aws.asgs_by_tags(tags)

    raise "Didn't find only one ASG :(" if asgs.count != 1

    instances = {
      min: asgs[0].min_size,
      max: asgs[0].max_size,
      desired: asgs[0].desired_capacity
    }
  rescue RuntimeError => e
    warn("instances_by_tags: #{e}")
    instances = nil
  end

  instances
end

#profile_from(profile) ⇒ Object



159
160
161
# File 'lib/terrafying/components/dynamicset.rb', line 159

def profile_from(profile)
  profile.respond_to?(:id) ? profile.id : profile
end

#resource_name_from(profile) ⇒ Object



163
164
165
# File 'lib/terrafying/components/dynamicset.rb', line 163

def resource_name_from(profile)
  profile.respond_to?(:resource_name) ? [profile.resource_name] : []
end

#vpc_endpoint_egress_rules(ident, security_group, vpc, vpc_endpoints) ⇒ Object



131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'lib/terrafying/components/dynamicset.rb', line 131

def vpc_endpoint_egress_rules(ident, security_group, vpc, vpc_endpoints)
  prefix_ids = vpc_endpoints.map do | e |
    vpc_endpoint = data :aws_vpc_endpoint, "#{ident}-#{tf_safe(e)}", {
      vpc_id: vpc.id,
      service_name: e,
    }
    vpc_endpoint[:prefix_list_id]
  end

  resource :aws_security_group_rule, "#{ident}-vpc-endpoint-egress",
           security_group_id: security_group,
           type: 'egress',
           from_port: 0,
           to_port: 0,
           protocol: -1,
           prefix_list_ids: prefix_ids
end