要在 CLI 中承担 AWS 角色,我执行以下命令:
aws sts assume-role --role-arn arn:aws:iam::123456789123:role/myAwesomeRole --role-session-name test --region eu-central-1
这给了我一个遵循模式的输出:
{
"Credentials": {
"AccessKeyId": "someAccessKeyId",
"SecretAccessKey": "someSecretAccessKey",
"SessionToken": "someSessionToken",
"Expiration": "2020-08-04T06:52:13+00:00"
},
"AssumedRoleUser": {
"AssumedRoleId": "idOfTheAssummedRole",
"Arn": "theARNOfTheRoleIWantToAssume"
}
}
然后我手动复制并粘贴
AccessKeyId
、SecretAccessKey
和 SessionToken
的值到一堆导出中,如下所示:
export AWS_ACCESS_KEY_ID="someAccessKeyId"
export AWS_SECRET_ACCESS_KEY="someSecretAccessKey"
export AWS_SESSION_TOKEN="someSessionToken"
最终担当这个角色。
我怎样才能一次性做到这一点?我的意思是,无需手动干预将
aws sts ...
命令的输出复制并粘贴到 exports
上。
没有
jq
,没有 eval
,没有多重导出 - 使用 printf
内置(即不会通过 /proc
泄露凭证)和命令替换:
export $(printf "AWS_ACCESS_KEY_ID=%s AWS_SECRET_ACCESS_KEY=%s AWS_SESSION_TOKEN=%s" \
$(aws sts assume-role \
--role-arn arn:aws:iam::123456789012:role/MyAssumedRole \
--role-session-name MySessionName \
--query "Credentials.[AccessKeyId,SecretAccessKey,SessionToken]" \
--output text))
最后,一位同事与我分享了这个很棒的片段,可以一次性完成工作:
eval $(aws sts assume-role --role-arn arn:aws:iam::123456789123:role/myAwesomeRole --role-session-name test | jq -r '.Credentials | "export AWS_ACCESS_KEY_ID=\(.AccessKeyId)\nexport AWS_SECRET_ACCESS_KEY=\(.SecretAccessKey)\nexport AWS_SESSION_TOKEN=\(.SessionToken)\n"')
除了 AWS CLI 之外,它只需要
jq
,通常安装在任何 Linux 桌面上。
您可以将 IAM 角色存储为 AWS CLI 中的配置文件,它将自动为您代入该角色。
以下是在 AWS CLI 中使用 IAM 角色 - AWS 命令行界面的示例:
[profile marketingadmin]
role_arn = arn:aws:iam::123456789012:role/marketingadminrole
source_profile = user1
这句话是说:
--profile marketingadmin
user1
AssumeRole
这意味着您只需调用这样的命令,它将承担该角色并自动使用返回的凭据:
aws s3 ls --profile marketingadmin
Arcones的答案很好,但这是一种不需要jq的方法:
eval $(aws sts assume-role \
--role-arn arn:aws:iam::012345678901:role/TrustedThirdParty \
--role-session-name=test \
--query 'join(``, [`export `, `AWS_ACCESS_KEY_ID=`,
Credentials.AccessKeyId, ` ; export `, `AWS_SECRET_ACCESS_KEY=`,
Credentials.SecretAccessKey, `; export `, `AWS_SESSION_TOKEN=`,
Credentials.SessionToken])' \
--output text)
您可以按照指南将 aws config 与外部源结合使用:通过外部流程获取凭证。 创建一个 shell 脚本,例如 assume-role.sh:
#!/bin/sh
aws sts --profile $2 assume-role --role-arn arn:aws:iam::123456789012:role/$1 \
--role-session-name test \
--query "Credentials" \
| jq --arg version 1 '. + {Version: $version|tonumber}'
在 ~/.aws/config 带有 shell 脚本的配置文件:
[profile desktop]
region=ap-southeast-1
output=json
[profile external-test]
credential_process = "/path/assume-role.sh" test desktop
[profile external-test2]
credential_process = "/path/assume-role.sh" test2 external-test
我遇到了同样的问题,我使用 CLI 为我提供的运行时之一进行了管理。
一旦获得凭据,我就使用了这种方法,即使不是那么优雅(我使用 PHP 运行时,但您可以使用 CLI 中可用的内容):
- export AWS_ACCESS_KEY_ID=`php -r 'echo json_decode(file_get_contents("credentials.json"))->Credentials->AccessKeyId;'`
- export AWS_SECRET_ACCESS_KEY=`php -r 'echo json_decode(file_get_contents("credentials.json"))->Credentials->SecretAccessKey;'`
- export AWS_SESSION_TOKEN=`php -r 'echo json_decode(file_get_contents("credentials.json"))->Credentials->SessionToken;'`
其中 credentials.json 是假定角色的输出:
aws sts assume-role --role-arn "arn-of-the-role" --role-session-name "arbitrary-session-name" > credentials.json
显然这只是一种方法,特别是在您实现流程自动化的情况下很有帮助。它对我有用,但我不知道这是否是最好的。当然不是最线性的。
如果您想将凭据添加到文件,则基于 Nev Stokes 的答案
使用
printf
printf "
[ASSUME-ROLE]
aws_access_key_id = %s
aws_secret_access_key = %s
aws_session_token = %s
x_security_token_expires = %s" \
$(aws sts assume-role --role-arn "arn:aws:iam::<acct#>:role/<role-name>" \
--role-session-name <session-name> \
--query "Credentials.[AccessKeyId,SecretAccessKey,SessionToken,Expiration]" \
--output text) >> ~/.aws/credentials
如果你愿意的话
awk
aws sts assume-role \
--role-arn "arn:aws:iam::<acct#>:role/<role-name>" \
--role-session-name <session-name> \
--query "Credentials.[AccessKeyId,SecretAccessKey,SessionToken,Expiration]" \
--output text | awk '
BEGIN {print "[ROLE-NAME]"}
{ print "aws_access_key_id = " $1 }
{ print "aws_secret_access_key = " $2 }
{ print "aws_session_token = " $3 }
{ print "x_security_token_expires = " $4}' >> ~/.aws/credentials
要更新
~/.aws/credentials
文件中的凭据,请在运行上述命令之一之前运行 sed
命令。
sed -i -e '/ROLE-NAME/,+4d' ~/.aws/credentials
SESSION=$(aws sts assume-role \
--role-arn arn:aws:iam::123456789012:role/MyAssumedRole \
--role-session-name MySessionName \
--query "Credentials.[AccessKeyId,SecretAccessKey,SessionToken]" \
--output text)
export AWS_ACCESS_KEY_ID=$(echo $SESSION | cut -d' ' -f1)
export AWS_SECRET_ACCESS_KEY=$(echo $SESSION | cut -d' ' -f2)
export AWS_SESSION_TOKEN=$(echo $SESSION | cut -d' ' -f3)
如果有人想使用凭证文件登录:
#!/bin/bash
# Replace the variables with your own values
ROLE_ARN=<role_arn>
PROFILE=<profile_name>
REGION=<region>
# Assume the role
TEMP_CREDS=$(aws sts assume-role --role-arn "$ROLE_ARN" --role-session-name "temp-session" --output json)
# Extract the necessary information from the response
ACCESS_KEY=$(echo $TEMP_CREDS | jq -r .Credentials.AccessKeyId)
SECRET_KEY=$(echo $TEMP_CREDS | jq -r .Credentials.SecretAccessKey)
SESSION_TOKEN=$(echo $TEMP_CREDS | jq -r .Credentials.SessionToken)
# Put the information into the AWS CLI credentials file
aws configure set aws_access_key_id "$ACCESS_KEY" --profile "$PROFILE"
aws configure set aws_secret_access_key "$SECRET_KEY" --profile "$PROFILE"
aws configure set aws_session_token "$SESSION_TOKEN" --profile "$PROFILE"
aws configure set region "$REGION" --profile "$PROFILE"
# Verify the changes have been made
aws configure list --profile "$PROFILE"
基于 Nev Stoke 答案的强大脚本,只需将有用的变量提供给当前的 shell 会话:
#!/bin/bash
# Check if the script is sourced or not
if [ "$0" = "$BASH_SOURCE" ]; then
echo "This script needs to be sourced. Use the following command:"
echo ". $BASH_SOURCE <account_id> <role_name> <role_session_name>"
exit 1
fi
# Function to check prerequisites
check_prerequisites() {
# Check if AWS CLI is installed
if ! command -v aws &> /dev/null
then
echo "AWS CLI not installed. Please install it and try again."
return 1
fi
# Check for correct number of arguments
if [ "$#" -ne 3 ]; then
echo "Usage: . $0 <account_id> <role_name> <role_session_name>"
return 1
fi
}
# Main function to assume role
assume_role() {
# Assign arguments to variables
account_id=$1
role_name=$2
role_session_name=$3
# Construct role ARN
role_arn="arn:aws:iam::${account_id}:role/${role_name}"
# Assume the role and retrieve credentials
read -r access_key secret_key session_token <<< $(aws sts assume-role \
--role-arn "$role_arn" \
--role-session-name "$role_session_name" \
--query "Credentials.[AccessKeyId,SecretAccessKey,SessionToken]" \
--output text)
# Check if the credentials were successfully retrieved
if [ -z "$access_key" ] || [ -z "$secret_key" ] || [ -z "$session_token" ]; then
echo "Failed to assume role. Please check your inputs and AWS configuration."
return 1
fi
# Export the credentials
export AWS_ACCESS_KEY_ID=$access_key
export AWS_SECRET_ACCESS_KEY=$secret_key
export AWS_SESSION_TOKEN=$session_token
echo "AWS credentials exported successfully."
}
# Run the checks
check_prerequisites "$@" || return 1
# If checks pass, assume the role
assume_role "$@"