如何临时切换AWS CLI的配置文件?

时间:2018-04-08 09:49:19

标签: bash shell amazon-web-services command-line aws-cli

(1。)成功为AWS CLI配置第二个配置文件后,我尝试使用以下命令在我的bash会话中将配置文件设置为user2失败:

export AWS_PROFILE=user2

...根据这里的建议:https://docs.aws.amazon.com/cli/latest/userguide/cli-multiple-profiles.html

(2。)以下命令有效:

aws s3 ls --profile user2

所以我知道AWS CLI和user2配置文件都在我的计算机上运行。

(3。)然而,当我后来(即在输入“export AWS_PROFILE = user2”之后)尝试类似的事情:

aws s3 ls

... AWS的回复假设我想将其作为默认用户(NOT user2)

进行查询

(4。)因此,我可以从命令行使用user2配置文件的唯一方法是继续将“--profile user2”附加到每个命令,这很乏味。

(5)

echo $AWS_PROFILE

的产率:

>> user2

,正如所料。

知道这里发生了什么吗?我确定我在某个地方犯了一些愚蠢的错误。

7 个答案:

答案 0 :(得分:7)

Per @ kintuparantu的建议,对我有用的是:

export AWS_DEFAULT_PROFILE=user2

之后,命令如下:

aws s3 ls

...是从适当的帐户处理的。谢谢!

答案 1 :(得分:1)

你可以看到它是如何运作的

$ export AWS_PROFILE=myprofile
$ aws s3 ls --debug 2>&1 | grep profile
2018-04-08 19:19:17,990 - MainThread - botocore.session - DEBUG - Loading variable profile from environment with value 'myprofile'.

我怀疑这对你有不同的作用。

您还可以验证

$ AWS_PROFILE=myprofile aws s3 ls --debug 2>&1 | grep profile

$ aws s3 ls --profile myprofile --debug 2>&1 | grep profile

都给出相同的结果。

答案 2 :(得分:0)

AWS cli具有三种读取变量的方式

  • key_id / key_secret的环境变量
  • 通过cred / config配置文件(通常在〜/ .aws / cre ...中)
  • 内联提供的手动值
  

请参阅:https://docs.aws.amazon.com/cli/latest/topic/config-vars.html#credentials

一种方法将被另一种方法覆盖。基于OP,可能是虽然DEFAULT_PROFILE设置为userX,但AWS_ACCESS_KEY_ID和/或AWS_SECRET_ACCESS_KEY环境变量设置为其他值。

您可以对shell函数进行别名,该函数通过使用

将凭据加载到当前环境中
"export AWS_ACCESS_KEY_ID=XXXXXXX;"... and more

或者通过机密管理器更安全地加载

"export AWS_ACCESS_KEY_ID=$(aws configure get aws_access_key_id --profile XXXX)"... and more

导出所有访问密钥/秘密等,然后检查是否通过内存将正确的凭据装入

aws configure list

最后..将变量重置为“默认” ..作为一种习惯,以确保您作为AWS角色执行所需的工作;特别是在使用多个配置文件时。希望这会有所帮助。

答案 3 :(得分:0)

user@machine:~/.aws$ aws --version
aws-cli/2.1.2 Python/3.7.3 Linux/5.4.0-53-generic exe/x86_64.linuxmint.20

如果我有很多命名的个人资料,我会在 .bashrc 中添加别名。

例如:

alias harry-tuttle='export AWS_PROFILE=harry-tuttle'

然后,切换配置文件将成为一个键入更少的命令。

要查看您的所有个人资料,

aws configure list-profiles`

答案 4 :(得分:0)

You can add the profile flag

aws s3 ls --profile marketingadmin

答案 5 :(得分:0)

windows 使用

set AWS_DEFAULT_PROFILE=user2

答案 6 :(得分:0)

接受的答案假定您使用的是 Linux 或 Mac 终端。我为两个操作系统添加了命令。

窗口

set AWS_PROFILE=profile_name

Linux 或 Mac

export AWS_PROFILE=profile_name

这些将设置您每次执行 aws 命令时将使用的 aws 配置文件。但如果您只是想为一个 aws 命令临时切换配置文件。

aws [command] [sub-command] --profile [profile-name]