Skip to content

Instantly share code, notes, and snippets.

@ngocson2vn
Last active October 4, 2021 03:19
Show Gist options
  • Save ngocson2vn/eb8c1ad83211f8b79df46b28788f9843 to your computer and use it in GitHub Desktop.
Save ngocson2vn/eb8c1ad83211f8b79df46b28788f9843 to your computer and use it in GitHub Desktop.
Using terraform with AWS SSO

Using terraform with AWS SSO

1. Install the AWS CLI version 2

https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html

2. Configuring the AWS CLI to use AWS Single Sign-On

https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html

3. Export AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and AWS_SESSION_TOKEN

vim aws-sso-login.sh

#!/bin/bash

select profile in stg perf prod platform
do
  export AWS_PROFILE=$profile
  echo AWS_PROFILE=$AWS_PROFILE

  aws sso login | grep Successully
  sso_cached_file=$(ls -1tr ~/.aws/sso/cache/ | grep -v botocore | tail -n1)

  account=$(aws configure get sso_account_id)
  roleName=$(aws configure get sso_role_name)
  accessToken=$(cat ~/.aws/sso/cache/${sso_cached_file} | jq -r '.accessToken')
  roleCredentials=$(aws sso get-role-credentials --account=$account --role-name=$roleName --access-token=$accessToken --no-cli-pager)

  export AWS_ACCESS_KEY_ID=$(echo ${roleCredentials} | jq -r '.roleCredentials.accessKeyId')
  export AWS_SECRET_ACCESS_KEY=$(echo ${roleCredentials} | jq -r '.roleCredentials.secretAccessKey')
  export AWS_SESSION_TOKEN=$(echo ${roleCredentials} | jq -r '.roleCredentials.sessionToken')

  aws sts get-caller-identity --no-cli-pager

  break
done

4. Create an alias

vim ~/.bashrc

alias sso="source /path/to/aws-sso-login.sh"

5. Play

sso
1) stg
2) prod
#? 1
AWS_PROFILE=stg
Successully logged into Start URL: https://d-xxxxxxxxxx.awsapps.com/start
{
    "UserId": "XXXXXXXXXXXXXXXXXXXXX:[email protected]",
    "Account": "xxxxxxxxxxxx",
    "Arn": "arn:aws:sts::xxxxxxxxxxxx:assumed-role/yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy"
}

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