2016-11-28 113 views

回答

11

,你可以使用下面的命令來設置環境變量

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` 
+1

這應該是公認的答案。官方CLI FTW – wilco

4

以前沒有辦法,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=... 

的變量導出到當前的環境變量,執行輸出作爲命令(再次,一旦你已經回顧了源代碼;]):

從shell

PROFILES=$(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 

只是把它放在一個文件,然後它來源:

+0

這真是太棒了,但是在@Frederic發佈正式API回答後回答時,應該提到CLI是建議的和受支持的方法。 – wilco

1

我喜歡的出口所需的配置腳本凱的想法,所以我寫了一個太()。

0

這些都不允許配置文件中的角色假設(我大量使用)。我在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}') 
+0

我一直在計劃製作一個這個時間允許的工具。 –

相關問題