使用Terraform等特定第三方工具时,指定AWS CLI配置文件并不容易,我喜欢使用比配置文件更好的环境变量。有没有办法将AWS CLI配置文件导出到环境变量?
有没有办法让我的AWS CLI直接将当前配置文件导出为AWS_ACCESS_KEY_ID
和AWS_SECRET_ACCESS_ID
环境变量到我的会话?
使用Terraform等特定第三方工具时,指定AWS CLI配置文件并不容易,我喜欢使用比配置文件更好的环境变量。有没有办法将AWS CLI配置文件导出到环境变量?
有没有办法让我的AWS CLI直接将当前配置文件导出为AWS_ACCESS_KEY_ID
和AWS_SECRET_ACCESS_ID
环境变量到我的会话?
,你可以使用下面的命令来设置环境变量
aws configure get default.aws_access_key_id
aws configure get default.aws_secret_access_key
,如果您有其他的个人资料可以更改,另一种方式来写的是
aws configure get aws_access_key_id --profile <new_profile>
aws configure get aws_secret_access_key --profile <new_profile>
因此,例如,这将是
export TF_VAR_access_key=`aws configure get default.aws_access_key_id`
以前没有办法,but there is now.
我写了一个脚本,做的正是这一点,aws-env
:
usage: aws-env [-h] [-n] profile
Extract AWS credentials for a given profile as environment variables.
positional arguments:
profile The profile in ~/.aws/credentials to extract credentials
for.
optional arguments:
-h, --help show this help message and exit
-n, --no-export Do not use export on the variables.
如果您信任该程序的输出,你可以用它在你的shell会话中导出指定的配置文件中的变量:
$ aws-env profile-name
export AWS_ACCESS_KEY_ID=...
export AWS_SECRET_ACCESS_KEY=...
$ aws-env -n profile-name
AWS_ACCESS_KEY_ID=...
AWS_SECRET_ACCESS_KEY=...
的变量导出到当前的环境变量,执行输出作为命令(再次,一旦你已经回顾了源代码;]):
从shellPROFILES=$(awk -F"\\\]|\\\[" '/^\[/{print $2}' ~/.aws/credentials)
select PROFILE in $PROFILES; do
export AWS_ACCESS_KEY_ID="$(aws configure get aws_access_key_id --profile $PROFILE)"
export AWS_SECRET_ACCESS_KEY="$(aws configure get aws_secret_access_key --profile $PROFILE)"
export AWS_DEFAULT_REGION="$(aws configure get region --profile $PROFILE)"
break
done
echo AWS_ACCESS_KEY_ID=$AWS_ACCESS_KEY_ID
echo AWS_SECRET_ACCESS_KEY=$(echo $AWS_SECRET_ACCESS_KEY|tr '[:print:]' '*')
echo AWS_DEFAULT_REGION=$AWS_DEFAULT_REGION
只是把它放在一个文件,然后它来源:
这真是太棒了,但是在@Frederic发布正式API回答后回答时,应该提到CLI是建议的和受支持的方法。 – wilco
我喜欢的出口所需的配置脚本凯的想法,所以我写了一个太()。
这些都不允许配置文件中的角色假设(我大量使用)。我在python3中使用了以下非常短的脚本,它使用boto3来完成角色假设等的繁重工作。这可能会有所帮助。
#!/usr/bin/env python3
# export the AWS environment for a given profile
import boto3
import argparse
parser = argparse.ArgumentParser(prog="exportaws",
description="Extract AWS credentials for a profile as env variables.")
parser.add_argument("profile", help="profile name in ~/.aws/config.")
args = parser.parse_args()
creds = boto3.session.Session(profile_name=args.profile).get_credentials()
print(f'export AWS_ACCESS_KEY={creds.access_key}')
print(f'export AWS_SECRET_ACCESS_KEY={creds.secret_key}')
print(f'export AWS_SESSION_TOKEN={creds.token}')
我一直在计划制作一个这个时间允许的工具。 –
这应该是公认的答案。官方CLI FTW – wilco