aws cli使用中,可能会有在多个IAM账户中进行切换的需求,手动切换~/.aws/目录下的configcredentials是十分费力的事情。还好aws cli本身就可以支持多个aws credentials

配置多个profile

aws configure时,加上--profile参数来命名不同的账户, 依次输入access id, access key, region和output format。

1
2
$ aws configure --profile user1
$ aws configure --profile user2

此时生成的configcredentials文件中,会使用账户名来分割不同的配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[carlshen@carl-macpro-lan ~]$ cat ~/.aws/config
[profile user1]
output = json
region = us-west-2
[profile user2]
output = json
region = ap-northeast-2
[carlshen@carl-macpro-lan ~]$
[carlshen@carl-macpro-lan ~]$ cat ~/.aws/credentials
[user1]
aws_access_key_id = AKIAXXXXXXXXXXXXXXXX
aws_secret_access_key = XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
[user2]
aws_access_key_id = AKIAXXXXXXXXXXXXXXXX
aws_secret_access_key = XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
[carlshen@carl-macpro-lan ~]$

使用多个profile

基本用法

使用的时候,在命令后面加上参数--profile user_name即可使用user_name对应的profile

1
$ aws s3 ls --profile user_name

如下命令使用user2的profile来查看S3下的bucket list

1
2
3
[carlshen@carl-macpro-lan ~]$ aws s3 ls --profile user2
2017-10-24 11:18:38 carl-test-at-seoul
[carlshen@carl-macpro-lan ~]$

简化

每次输入--profile user_name是很繁琐的事情,在Mac或者Linux下,可以使用alias来简化

1
$ alias aws_user_name='aws --profile user_name'

这样,每次使用的时候,直接使用aws_user_name来使用user_name的profile来运行aws命令

以下命令设置aws_user2为使用user2的profile来运行aws命名

1
2
3
4
[carlshen@carl-macpro-lan ~]$ alias aws_user2='aws --profile user2'
[carlshen@carl-macpro-lan ~]$ aws_user2 s3 ls
2017-10-24 11:18:38 carl-test-at-seoul
[carlshen@carl-macpro-lan ~]$

添加到~/.bashrc中使得alias永久生效

1
$ echo "alias aws_user2='aws --profile user2'" >> ~/.bashrc

设置默认profile

如果有一个账号是使用的比较频繁的,而不想每次都使用alias的方式来运行aws,那么也可以设置环境变量AWS_DEFAULT_PROFILE为频繁使用的账号名,此时输入aws时候,会自动使用指定的账号配置

1
$ export AWS_DEFAULT_PROFILE=user2

运行结果如下:

1
2
3
4
5
6
7
8
9
10
11
12
## 没有设置AWS_DEFAULT_PROFILE时
[carlshen@carl-macpro-lan ~]$ echo $AWS_DEFAULT_PROFILE
[carlshen@carl-macpro-lan ~]$ aws s3 ls
Unable to locate credentials. You can configure credentials by running "aws configure".
[carlshen@carl-macpro-lan ~]$
## 设置了AWS_DEFAULT_PROFILE为user2后,aws默认就会使用user2的profile
[carlshen@carl-macpro-lan ~]$ export AWS_DEFAULT_PROFILE=user2
[carlshen@carl-macpro-lan ~]$ aws s3 ls
2017-10-24 11:18:38 carl-test-at-seoul
[carlshen@carl-macpro-lan ~]$

添加到~/.bashrc中来使AWS_DEFAULT_PROFILE永久生效

1
$ echo "export AWS_DEFAULT_PROFILE=user2" >> ~/.bashrc

Reference

  1. 配置 AWS CLI - http://docs.aws.amazon.com/zh_cn/cli/latest/userguide/cli-chap-getting-started.html

留言