Class: JFlow::TerminationProtector

Inherits:
Object
  • Object
show all
Defined in:
lib/jflow/termination_protector.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(asg_client = nil, ec2_client = nil) ⇒ TerminationProtector

Returns a new instance of TerminationProtector.



8
9
10
11
# File 'lib/jflow/termination_protector.rb', line 8

def initialize(asg_client = nil, ec2_client = nil)
  @asg_client = asg_client || Aws::AutoScaling::Client.new(region: region, credentials: Aws::InstanceProfileCredentials.new)
  @ec2_client = ec2_client || Aws::EC2::Client.new(region: region, credentials: Aws::InstanceProfileCredentials.new)
end

Instance Attribute Details

#asg_clientObject

Returns the value of attribute asg_client.



6
7
8
# File 'lib/jflow/termination_protector.rb', line 6

def asg_client
  @asg_client
end

#ec2_clientObject

Returns the value of attribute ec2_client.



6
7
8
# File 'lib/jflow/termination_protector.rb', line 6

def ec2_client
  @ec2_client
end

Instance Method Details

#get_asg_nameObject



26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/jflow/termination_protector.rb', line 26

def get_asg_name
  instance_tags = ec2_client.describe_tags(filters: [
    {
      name: "resource-id",
      values: [instance_id]
    }
  ])[0]
  asg_name = instance_tags.select{|tag| tag.key == "aws:autoscaling:groupName"}.first.value
  JFlow.configuration.logger.debug "Discovered autoscaling group name #{asg_name}"

  asg_name
end

#instance_dataObject

Returns a hash of instance data, including region, instance id + more



22
23
24
# File 'lib/jflow/termination_protector.rb', line 22

def instance_data
  @instance_data ||= JSON.parse(Net::HTTP.get(URI.parse('http://169.254.169.254/latest/dynamic/instance-identity/document')))
end

#instance_idObject



17
18
19
# File 'lib/jflow/termination_protector.rb', line 17

def instance_id
  instance_data['instanceId']
end

#regionObject



13
14
15
# File 'lib/jflow/termination_protector.rb', line 13

def region
  instance_data['region']
end

#set_protection(protect_status) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/jflow/termination_protector.rb', line 39

def set_protection(protect_status)
  @previous_protect_status ||= false
  return if @previous_protect_status == protect_status
  @previous_protect_status = protect_status

  JFlow.configuration.logger.debug "Setting termination protection status to #{protect_status} for instance #{instance_id} in region #{region}"
  begin
    asg_client.set_instance_protection({
      instance_ids: [instance_id],
      auto_scaling_group_name: get_asg_name,
      protected_from_scale_in: protect_status
    })
  rescue => e
    JFlow.configuration.logger.debug "Something went wrong setting termination proection: #{e.inspect}"
    JFlow.handle_exception(e)
  end
end