Skip to content

Commit

Permalink
use IMDSv2 to retrieve ec2 metadata
Browse files Browse the repository at this point in the history
  • Loading branch information
Masato Niwa committed Jul 24, 2024
1 parent 9879570 commit 686a097
Showing 1 changed file with 14 additions and 2 deletions.
16 changes: 14 additions & 2 deletions lib/specinfra/ec2_metadata.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,13 @@ def initialize(host_inventory)
@host_inventory = host_inventory

@base_uri = 'http://169.254.169.254/latest/meta-data/'
@token_uri = 'http://169.254.169.254/latest/api/token'
@token = ''
@metadata = {}
end

def get
@token = get_token
@metadata = get_metadata
self
end
Expand Down Expand Up @@ -64,7 +67,7 @@ def inspect
def get_metadata(path='')
metadata = {}

keys = @host_inventory.backend.run_command("curl -s #{@base_uri}#{path}").stdout.split("\n")
keys = @host_inventory.backend.run_command("curl -H \"X-aws-ec2-metadata-token: #{@token}\" -s #{@base_uri}#{path}").stdout.split("\n")

keys.each do |key|
if key =~ %r{/$}
Expand All @@ -84,7 +87,16 @@ def get_metadata(path='')
end

def get_endpoint(path)
ret = @host_inventory.backend.run_command("curl -s #{@base_uri}#{path}")
ret = @host_inventory.backend.run_command("curl -H \"X-aws-ec2-metadata-token: #{@token}\" -s #{@base_uri}#{path}")
if ret.success?
ret.stdout
else
nil
end
end

def get_token
ret = @host_inventory.backend.run_command("curl -X PUT -H \"X-aws-ec2-metadata-token-ttl-seconds: 21600\" -s #{@token_uri}")
if ret.success?
ret.stdout
else
Expand Down

0 comments on commit 686a097

Please sign in to comment.