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.



24
25
26
# File 'lib/terrafying/components/dynamicset.rb', line 24

def initialize()
  super
end

Instance Attribute Details

#asgObject (readonly)

Returns the value of attribute asg.



12
13
14
# File 'lib/terrafying/components/dynamicset.rb', line 12

def asg
  @asg
end

#nameObject (readonly)

Returns the value of attribute name.



12
13
14
# File 'lib/terrafying/components/dynamicset.rb', line 12

def name
  @name
end

Class Method Details

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



16
17
18
# File 'lib/terrafying/components/dynamicset.rb', line 16

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

.find_in(vpc, name) ⇒ Object



20
21
22
# File 'lib/terrafying/components/dynamicset.rb', line 20

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

Instance Method Details

#attach_load_balancer(load_balancer) ⇒ Object



126
127
128
129
130
131
132
133
134
135
# File 'lib/terrafying/components/dynamicset.rb', line 126

def attach_load_balancer(load_balancer)
  load_balancer.target_groups.each.with_index { |target_group, i|
    resource :aws_autoscaling_attachment, "#{load_balancer.name}-#{@name}-#{i}", {
               autoscaling_group_name: @asg,
               alb_target_group_arn: target_group
             }
  }

  self.used_by(load_balancer) if load_balancer.type == "application"
end

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



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

def create_in(vpc, name, options={})
  options = {
    public: false,
    ami: aws.ami("base-image-59a5b709", owners=["136393635417"]),
    instance_type: "t2.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,
  }.merge(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,
                               egress: [
                                 {
                                   from_port: 0,
                                   to_port: 0,
                                   protocol: -1,
                                   cidr_blocks: ["0.0.0.0/0"],
                                 }
                               ],
                             }

  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: options[:instance_profile] && options[:instance_profile].id,
                             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,
                             },
                             depends_on: options[:instance_profile] ? options[:instance_profile].resource_names : [],
                           }

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

  if options.has_key?(:health_check)
    raise 'Health check needs a type and grace_period' if ! options[:health_check].has_key?(:type) and ! options[:health_check].has_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][:tags]).map { |k,v| { Key: k, Value: v, PropagateAtLaunch: true }}

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

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

  self
end

#find_in(vpc, name) ⇒ Object



28
29
30
31
32
# File 'lib/terrafying/components/dynamicset.rb', line 28

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

  self
end

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



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

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]}",
          HealthCheckGracePeriod: health_check[:grace_period],
          LaunchConfigurationName: "#{launch_config}",
          MaxSize: "#{instances[:max]}",
          MetricsCollection: [
            {
              Granularity: "1Minute",
              Metrics: [
                "GroupMinSize",
                "GroupMaxSize",
                "GroupDesiredCapacity",
                "GroupInServiceInstances",
                "GroupPendingInstances",
                "GroupStandbyInstances",
                "GroupTerminatingInstances",
                "GroupTotalInstances"
              ]
            },
          ],
          MinSize: "#{instances[:min]}",
          DesiredCapacity: "#{instances[:desired]}",
          Tags: tags,
          TerminationPolicies: [
            "Default"
          ],
          VPCZoneIdentifier: subnets
        }
      }
    },
    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]}",
        MaxBatchSize: "#{instances[:desired]}",
        PauseTime: "PT10M",
        WaitOnResourceSignals: true,
      }
    }
  elsif rolling_update
    template[:Resources][:AutoScalingGroup][:UpdatePolicy] = {
      AutoScalingRollingUpdate: {
        MinInstancesInService: "#{instances[:min]}",
        MaxBatchSize: "1",
        PauseTime: "PT0S"
      }
    }
  end

  JSON.pretty_generate(template)
end

#instances_by_tags(tags = {}) ⇒ Object



205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
# File 'lib/terrafying/components/dynamicset.rb', line 205

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

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

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

  instances
end