Last active
August 23, 2016 12:44
-
-
Save muresan/ddb04f54d0572259d9a84dabeb2ce23a to your computer and use it in GitHub Desktop.
Fetch an object (my use case: pem file) from S3, using an assumed IAM role and copy it to stdout
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
import os | |
import re | |
import sys | |
import urllib3 | |
import boto3 | |
CERT_BUCKET_IAM_ROLE = os.environ['CERT_BUCKET_IAM_ROLE'] | |
CERT_BUCKET_NAME = os.environ['CERT_BUCKET_NAME'] | |
CERT_OBJECT_NAME = os.environ['CERT_OBJECT_NAME'] | |
S3_BUCKET_CREDS = ('http://169.254.169.254/latest/meta-data/iam/' | |
'security-credentials/' + CERT_BUCKET_IAM_ROLE) | |
http = urllib3.PoolManager() | |
response = http.request('GET',S3_BUCKET_CREDS).data | |
security_creds = json.loads(response.decode('utf-8')) | |
s3 = boto3.resource('s3', | |
aws_access_key_id=security_creds['AccessKeyId'], | |
aws_secret_access_key=security_creds['SecretAccessKey'], | |
aws_session_token=security_creds['Token']) | |
cert_object = s3.Object(CERT_BUCKET_NAME, CERT_OBJECT_NAME) | |
cert = cert_object.get()['Body'].read() | |
#cert_escaped = re.sub(r'\n', r'\\n', cert.decode('utf-8')) | |
#sys.stdout.write(cert_escaped) | |
sys.stdout.write(cert.decode('utf-8')) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
resource "aws_s3_bucket" "s3_certs" { | |
bucket = "s3_certs" | |
acl = "private" | |
} | |
resource "aws_iam_role" "3certs_read" { | |
name = "3certs_read" | |
assume_role_policy = <<EOF | |
{ | |
"Version": "2012-10-17", | |
"Statement": [ | |
{ | |
"Action": "sts:AssumeRole", | |
"Principal": { | |
"Service": "ec2.amazonaws.com" | |
}, | |
"Effect": "Allow" | |
}, | |
{ | |
"Effect": "Allow", | |
"Principal": { | |
"AWS": "arn:aws:iam::999999999999:root" | |
}, | |
"Action": "sts:AssumeRole" | |
} | |
] | |
} | |
EOF | |
} | |
resource "aws_iam_role_policy" "s3certs_read_policy" { | |
name = "s3certs_read_policy" | |
role = "${aws_iam_role.s3certs_read.id}" | |
policy = <<EOF | |
{ | |
"Version": "2012-10-17", | |
"Statement": [ | |
{ | |
"Effect": "Allow", | |
"Action": [ | |
"s3:Get*", | |
"s3:List*" | |
], | |
"Resource": [ | |
"arn:aws:s3:::${aws_s3_bucket.s3certs.id}/*", | |
"arn:aws:s3:::${aws_s3_bucket.s3certs.id}" | |
] | |
} | |
] | |
} | |
EOF | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment