Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix for metadata token #88

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions s3iam.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,12 @@ def prereposetup_hook(conduit):
if isinstance(repo, YumRepository) and repo.s3_enabled:
replace_repo(repos, repo)

class PutRequest(urllib2.Request):
"""class to handling putting with urllib2"""

def get_method(self, *args, **kwargs):
return 'PUT'


class S3Repository(YumRepository):
"""Repository object for Amazon S3, using IAM Roles."""
Expand Down Expand Up @@ -189,8 +195,10 @@ def grab(self):
if self.access_id and self.secret_key:
self.grabber.set_credentials(self.access_id, self.secret_key)
elif self.delegated_role:
self.grabber.get_imdsv2_credentials()
self.grabber.get_delegated_role_credentials(self.delegated_role)
else:
self.grabber.get_imdsv2_credentials()
self.grabber.get_role()
self.grabber.get_credentials()
return self.grabber
Expand Down Expand Up @@ -226,13 +234,32 @@ def __init__(self, repo):
self.secret_key = None
self.token = None

def get_imdsv2_credentials(self):
"""Need token for querying metadata"""
request = PutRequest(
urlparse.urljoin(
"http://169.254.169.254",
"/latest/api/token"
))
request.add_header('X-aws-ec2-metadata-token-ttl-seconds', 300)

try:
response = urllib2.urlopen(request)
self.imdsv2_token = (response.read())
except Exception:
response = None
finally:
if response:
response.close()

def get_role(self):
"""Read IAM role from AWS metadata store."""
request = urllib2.Request(
urlparse.urljoin(
"http://169.254.169.254",
"/latest/meta-data/iam/security-credentials/"
))
request.add_header('X-aws-ec2-metadata-token', self.imdsv2_token)

try:
response = urllib2.urlopen(request)
Expand All @@ -256,6 +283,8 @@ def get_credentials(self):
"latest/meta-data/iam/security-credentials/",
), self.iamrole))

request.add_header('X-aws-ec2-metadata-token', self.imdsv2_token)

try:
response = urllib2.urlopen(request)
data = json.loads(response.read())
Expand Down Expand Up @@ -313,6 +342,7 @@ def get_instance_region(self):
"/latest/meta-data/placement/availability-zone"
))

request.add_header('X-aws-ec2-metadata-token', self.imdsv2_token)
response = None
try:
response = urllib2.urlopen(request)
Expand Down