ruanbekker
2/10/2014 - 8:21 PM

gets iam security credentials from instance metadata and writes them to awscli environment variables and .s3cfg (for s3cmd)

gets iam security credentials from instance metadata and writes them to awscli environment variables and .s3cfg (for s3cmd)

#!/bin/bash

# gets iam security credentials from instance metadata and writes them to
# awscli environment variables and .s3cfg (for s3cmd)

# Usage: ec2-get-security-credentials ROLENAME DEFAULT_REGION
# ROLE=$1
# DEFAULT_REGION=$2


if [ -n "$1" ] ; then
    # get jq for json queries
    curl -O http://stedolan.github.io/jq/download/linux64/jq
    chmod +x jq

    # get security credentials from instance metadata
    curl -o security-credentials.json http://169.254.169.254/latest/meta-data/iam/security-credentials/$1/

    export AWS_ACCESS_KEY_ID=$(cat security-credentials.json | ./jq -r '.AccessKeyId')
    export AWS_SECRET_ACCESS_KEY=$(cat security-credentials.json | ./jq -r '.SecretAccessKey')
    export AWS_SECURITY_TOKEN=$(cat security-credentials.json | ./jq -r '.Token')

    # Write to .s3cfg
    echo '[default]' > .awscli
    echo aws_access_key_id=$AWS_ACCESS_KEY_ID >> .awscli
    echo aws_secret_access_key=$AWS_SECRET_ACCESS_KEY >> .awscli
    echo aws_security_token=$AWS_SECURITY_TOKEN >> .awscli
    
    # Write to .s3cfg
    echo '[default]' > .s3cfg
    echo access_key=$AWS_ACCESS_KEY_ID >> .s3cfg
    echo secret_key=$AWS_SECRET_ACCESS_KEY >> .s3cfg
    echo access_token=$AWS_SECURITY_TOKEN >> .s3cfg

    if [ -n "$2" ] ; then
	export AWS_DEFAULT_REGION=$2
        echo region=$2 >> .awscli
    fi
	
else
    echo 'ERR: No role name specificed'
fi