Skip to content

Commit 7e63779

Browse files
authored
Merge pull request #754 from mniw/support-imds-v2
use IMDSv2 to retrieve ec2 metadata
2 parents 9879570 + 686a097 commit 7e63779

File tree

1 file changed

+14
-2
lines changed

1 file changed

+14
-2
lines changed

lib/specinfra/ec2_metadata.rb

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,13 @@ def initialize(host_inventory)
55
@host_inventory = host_inventory
66

77
@base_uri = 'http://169.254.169.254/latest/meta-data/'
8+
@token_uri = 'http://169.254.169.254/latest/api/token'
9+
@token = ''
810
@metadata = {}
911
end
1012

1113
def get
14+
@token = get_token
1215
@metadata = get_metadata
1316
self
1417
end
@@ -64,7 +67,7 @@ def inspect
6467
def get_metadata(path='')
6568
metadata = {}
6669

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

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

8689
def get_endpoint(path)
87-
ret = @host_inventory.backend.run_command("curl -s #{@base_uri}#{path}")
90+
ret = @host_inventory.backend.run_command("curl -H \"X-aws-ec2-metadata-token: #{@token}\" -s #{@base_uri}#{path}")
91+
if ret.success?
92+
ret.stdout
93+
else
94+
nil
95+
end
96+
end
97+
98+
def get_token
99+
ret = @host_inventory.backend.run_command("curl -X PUT -H \"X-aws-ec2-metadata-token-ttl-seconds: 21600\" -s #{@token_uri}")
88100
if ret.success?
89101
ret.stdout
90102
else

0 commit comments

Comments
 (0)