Skip to content

Instantly share code, notes, and snippets.

@manicminer
Last active January 25, 2024 12:27
Show Gist options
  • Save manicminer/06ca15567f139db2e8281be7211e80f9 to your computer and use it in GitHub Desktop.
Save manicminer/06ca15567f139db2e8281be7211e80f9 to your computer and use it in GitHub Desktop.
Ansible invocation with assumed IAM role

Ansible invocation with assumed IAM role

How it works

  • boto3 initializes a session using the specified profile, for which it assumes a role as configured in your ~/.aws/config
  • Python script with above session initialization prints out shell-compatible environment variables of the temporary credentials
  • Wrapper script sets these a la eval
  • By the time Ansible runs, the AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and AWS_SECURITY_TOKEN (for boto2) / AWS_SESSION_TOKEN (for boto3) are all set, and are consumed by boto2 in the inventory script and other boto2-based modules

Notes

  • This uses a custom variable AWS_STS_PROFILE because setting plain ol' AWS_PROFILE makes boto2 barf when said profile is configured with a role_arn
  • See ansible/ansible#25718 for background
#!/usr/bin/env python
import boto3, sys
if len(sys.argv) > 1:
session = boto3.Session(profile_name=sys.argv[1])
credentials = session.get_credentials().get_frozen_credentials()
print('export AWS_ACCESS_KEY_ID="{0}"\nexport AWS_SECRET_ACCESS_KEY="{1}"\nexport AWS_SECURITY_TOKEN="{2}"\bexport AWS_SESSION_TOKEN="{2}"'.format(credentials.access_key, credentials.secret_key, credentials.token))
/bin/bash
# Get script directory
DIR="$(cd `dirname $0` && pwd)"
# Check for custom variable AWS_STS_PROFILE
[ -n "${AWS_STS_PROFILE}" ] && eval $("${DIR}/assumed-role-credentials.py" "${AWS_STS_PROFILE}")
time ansible-playbook -vv "$@"
exit $?
$ AWS_STS_PROFILE=my-named-profile ./playbook.sh
[profile my-named-profile]
region = us-east-1
role_arn = arn:aws:iam::123456789012:role/my-special-role
credential_source = Ec2InstanceMetadata
@XDanny322
Copy link

XDanny322 commented Jun 29, 2018

Just want to leave a comment here, that is is awesome! The linked Github issue was bugging me for a while, and this workaround is on point!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment