当我像运行 aws 命令时aws s3 ls,它使用默认配置文件。我可以创建一个新的配置文件来使用附加到 EC2 实例的角色吗?如果是这样,我该如何编写凭据/配置文件?
3 回答
4
boto3 查找凭据的机制是搜索可能位置的列表,并在找到凭据后立即停止。Boto3 搜索凭据的顺序是:
- 在
boto.client()方法中将凭据作为参数传递- 创建
Session对象时将凭据作为参数传递- 环境变量
- 共享凭证文件(
~/.aws/credentials)- AWS 配置文件 (
~/.aws/config)- 担任角色提供者
- Boto2 配置文件(
/etc/boto.cfg和~/.boto)- 配置了 IAM 角色的 Amazon EC2 实例上的实例元数据服务。
由于在实例元数据服务之前会查询共享凭证文件,因此如果提供了凭证文件,则无法使用分配的 IAM 角色。
尝试一个想法:您可以在 EC2 实例上创建另一个用户,该用户的目录中没有凭证文件~/.aws/。在这种情况下,将使用后面的方法。我没有尝试过,但使用sudo su可能足以更改为其他用户并使用 IAM 角色。
于 2020-07-30T07:57:09.220 回答
0
这就是我们解决这个问题的方法。我写这个答案,以防这对寻找答案的其他人有价值。
- 将角色“some-role”添加到 ID 为“i-xxxxxx”的实例
$ aws iam create-instance-profile --instance-profile-name some-profile-name
$ aws iam add-role-to-instance-profile --instance-profile-name some-profile-name --role-name some_role
$ aws ec2 associate-iam-instance-profile --iam-instance-profile Name=some-profile-name --instance-id i-xxxxxx
- 附上“sts:AssumeRole”
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": [
"ec2.amazonaws.com"
]
},
"Action": [
"sts:AssumeRole"
]
}
]
}
$ aws iam update-assume-role-policy --role-name some-role --policy-document file://policy.json
- 在实例中定义配置文件添加“some-operator-profile”以使用 EC2 实例角色。~/.aws/config
[profile some-operator-profile]
credential_source = Ec2InstanceMetadata
- 使用 EC2 提供的角色做你想做的事
$ aws --profile some-operator-profile s3 ls
于 2020-08-05T06:38:28.737 回答
0
不幸的是,如果您有凭证文件、使用环境变量或通过 SDK 指定 IAM 密钥/IAM 密钥,这些将始终比使用角色本身具有更高的优先级。
如果不经常需要凭证,您可以创建 EC2s IAM 角色在需要执行这些交互时可以承担的另一个角色(使用sts:AssumeRole )。然后,您将删除磁盘上的凭据文件。
如果您必须在磁盘上有凭据文件,建议在服务器上创建另一个用户专门用于使用这些凭据。由于凭据文件仅默认用于该用户,因此所有其他用户将不会使用此文件(除非在 SDK/CLI 交互中明确说明作为参数)。
确保尽可能锁定您创建的本地用户,以减少未经授权的用户访问用户及其凭据的机会。
于 2020-07-30T07:56:43.030 回答