如何在aws cli中使用多个配置文件
aws cli使用中,可能会有在多个IAM账户中进行切换的需求,手动切换~/.aws/目录下的config和credentials是十分费力的事情。还好aws cli本身就可以支持多个aws credentials
配置多个profile
aws configure时,加上--profile参数来命名不同的账户, 依次输入access id, access key, region和output format。
1 | $ aws configure --profile user1 |
此时生成的config和credentials文件中,会使用账户名来分割不同的配置
1 | [carlshen@carl-macpro-lan ~]$ cat ~/.aws/config |
使用多个profile
基本用法
使用的时候,在命令后面加上参数--profile user_name即可使用user_name对应的profile
1 | $ aws s3 ls --profile user_name |
如下命令使用user2的profile来查看S3下的bucket list
1 | [carlshen@carl-macpro-lan ~]$ aws s3 ls --profile user2 |
简化
每次输入--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 | [carlshen@carl-macpro-lan ~]$ alias aws_user2='aws --profile user2' |
添加到~/.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 | ## 没有设置AWS_DEFAULT_PROFILE时 |
添加到~/.bashrc中来使AWS_DEFAULT_PROFILE永久生效
1 | $ echo "export AWS_DEFAULT_PROFILE=user2" >> ~/.bashrc |