Get Short Term Credentials For AWS CLI Using SSO
Reference:https://dev.to/slsbytheodo/understand-the-aws-sso-login-configuration-4am7
https://github.com/aws/aws-cli/issues/7496
Note: Make sure you are using aws cli v2.
Step 1: Create a file ~/.aws/config like this. Replace values for <AWS_ACCOUNT_ID>,<ROLE_NAME>,<REGION> and <SSO_URL> accordingly.
[profile xg_np]
sso_session = aws
sso_account_id = <AWS_ACCOUNT_ID>
sso_role_name = <ROLE_NAME>
region = <REGION>
[profile xg_prod]
sso_session = aws
sso_account_id = <AWS_ACCOUNT_ID>
sso_role_name = <ROLE_NAME>
region = <REGION>
[profile sg_prod]
sso_session = aws
sso_account_id = <AWS_ACCOUNT_ID>
sso_role_name = <ROLE_NAME>
region = <REGION>
[profile sg_np]
sso_session = aws
sso_account_id = <AWS_ACCOUNT_ID>
sso_role_name = <ROLE_NAME>
region = <REGION>
[sso-session aws]
sso_start_url = <SSO_URL>
sso_region = <REGION>
sso_registration_scopes = sso:account:access
Step2: Now you can execute following commands:
aws sso login --sso-session aws
aws s3 ls --profile xg_np
aws s3 ls --profile xg_prod
or
export AWS_PROFILE=xg_np
aws s3 ls
export AWS_PROFILE=xg_prod
aws s3 ls
Step 3: If you want to assume a role after SSO login, then you can create ~/.aws/config like this
[profile np_sso]
sso_session = aws
sso_account_id = <AWS_ACCOUNT_ID>
sso_role_name = <ROLE_NAME>
region = <REGION>
[sso-session aws]
sso_start_url = <SSO_URL>
sso_region = <REGION>
sso_registration_scopes = sso:account:access
[profile np_assume]
role_arn = <ASSUME ROLE ARN>
region = <REGION>
output = json
cli_pager =
source_profile = np_sso
Now you can execute following commands:
aws sso login --sso-session aws
aws s3 ls --profile np_assume
or
export AWS_PROFILE=np_assume
aws s3 ls
If you face any issue, use following config
[profile sso-role]
sso_start_url = <SSO_URL>
sso_region = <REGION>
sso_registration_scopes = sso:account:access
sso_account_id = <AWS_ACCOUNT_ID>
sso_role_name = <ROLE_NAME>
[profile assumed-role]
role_arn = <ASSUMED_ROLE_ARN>
source_profile = sso-role
and then execute
aws sso login --profile sso-role
Once you are done, you can use aws sso logout command to clear your session. If you are using assumed role, your credentials will work even after sso logout. You may refer to https://repost.aws/questions/QUMKxSN5WQQTWCm0Bd-3UIPA/how-to-invalidate-the-sso-access-token-after-log-in-logout-from-aws for details.
If you need to export credentials as environment variables, you can use a script like this
#!/bin/bash
export $(printf "AWS_ACCESS_KEY_ID=%s AWS_SECRET_ACCESS_KEY=%s AWS_SESSION_TOKEN=%s" \
$(aws sts assume-role \
--role-arn <ARN>\
--role-session-name non-prod \
--query "Credentials.[AccessKeyId,SecretAccessKey,SessionToken]" \
--output text --profile <PROFILE_NAME>))
#echo $AWS_ACCESS_KEY_ID
#echo $AWS_SECRET_ACCESS_KEY
#echo $AWS_SESSION_TOKEN