【问题标题】:Configure instance profile for EC2 instances to attach/detach/wait for EBS volumes and work with S3?为 EC2 实例配置实例配置文件以附加/分离/等待 EBS 卷并使用 S3?
【发布时间】:2021-12-25 11:04:12
【问题描述】:

我希望实例在其初始化脚本中附加 EBS 卷(通过 UserData 传递)。

我在 EC2 实例上安装了 awscli,但它缺少凭据。

如何允许我的实例在不复制我的凭据的情况下附加卷(并使用 S3)?

据我了解,我需要将策略添加到 IAM 角色/实例配置文件。我找到了这个教程: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_examples_ec2_ebs-owner.html 但我不明白 Condition 是什么以及它是否是强制性的。

为简化起见,我想让我的实例与我的所有 EBS 驱动器和 S3 一起工作。 (如果可以将工作仅限于 EBS 驱动器/S3 存储桶,其名称以某个前缀开头,那就更好了)

如何使用 boto3 创建这样的实例配置文件,以便 awscli 不需要凭据?

谢谢!

UPD:我尝试使用以下代码创建实例配置文件,并在使用创建的实例配置文件启动的实例上执行 aws ec2 attach-volume 时收到以下错误。我错过了什么?

name = 'myname'
trust_relationship_policy_document = dict(
    Version = '2012-10-17',
    Statement = dict(
        Effect = 'Allow',
        Principal = dict(Service = 'ec2.amazonaws.com'),
        Action = 'sts:AssumeRole'
    )
)

policy_document = dict(
    Version = '2012-10-17',
    Statement = [dict(
        Effect = 'Allow',
        Action = [
            'ec2:AttachVolume',
            'ec2:DetachVolume'
        ],
        Resource = 'arn:aws:ec2:*:*:instance/*',
    )]
)

iam.create_role(RoleName = name, AssumeRolePolicyDocument = json.dumps(trust_relationship_policy_document))
policy_arn = iam.create_policy(PolicyName = name, PolicyDocument = json.dumps(policy_document))['Policy']['Arn']
iam.attach_role_policy(RoleName = name, PolicyArn = policy_arn)
iam.create_instance_profile(InstanceProfileName = name)
iam.add_role_to_instance_profile(InstanceProfileName = name, RoleName = name)

# An error occurred (UnauthorizedOperation) when calling the AttachVolume operation: You are not authorized to perform this operation. Encoded authorization failure message:

【问题讨论】:

  • 使用具有相关 IAM 权限的 IAM 角色启动 EC2 实例。您还可以将 IAM 角色附加到正在运行的实例。
  • @jarmod 这有多久了?多年来,您可以修改现有的实例配置文件,但添加一个实例配置文件和以前没有的实例是不受支持的
  • @jordanm 您可以将 IAM 角色attach 分配给正在运行或停止的实例。不确定这是什么时候首次引入的,但快速浏览一下 Wayback 机器表明它至少从 2017 年初就可以使用。

标签: amazon-web-services amazon-ec2 boto3 amazon-iam amazon-ebs


【解决方案1】:

在启动 Amazon EC2 实例之前,创建一个具有必要权限的 IAM 角色。如果您想允许附加任何 EBS 卷,则可以省略条件。

然后,使用与该实例关联的 IAM 角色启动 Amazon EC2 实例。这将自动向 AWS CLI 和实例上想要访问您的 AWS 服务的任何其他软件提供凭证。

然后您的脚本可以调用aws ec2 attach-volume 等。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-03
    • 2016-10-01
    • 2018-12-29
    • 2021-11-21
    • 2020-07-20
    • 2016-01-04
    • 2013-06-24
    • 2021-11-26
    相关资源
    最近更新 更多