即使“aws s3 cp”有效,cfn-init 也无法下载 S3 文件

sas*_*alm 4 amazon-web-services aws-cloudformation amazon-iam

我有一个 CloudFormation 脚本,它使用一个AWS::CloudFormation::Init部分从 S3 存储桶下载文件,但失败并出现访问被拒绝 (403) 的情况。

我已s3access使用AWS::IAM::InstanceProfile. 下载带有作品的文件aws s3

[ec2-user@ip-172-31-26-26 ~]$ aws s3 cp s3://my-bucket/test-file 
.download: s3://my-bucket/test-file to ./test-file           
Run Code Online (Sandbox Code Playgroud)

cfn-init失败了:

[ec2-user@ip-172-31-26-26 ~]$ sudo /opt/aws/bin/cfn-init -v --stack test --resource EC2 --region us-east-2
构建期间发生错误:无法检索 https://s3.us-east-2.amazonaws.com/my-bucket/test-file:HTTP 错误 403:

我尝试显式设置 IAM 角色,但也失败了:

[ec2-user@ip-172-31-26-26 ~]$ sudo /opt/aws/bin/cfn-init -v --stack test --resource EC2 --region us-east-2 --role= s3访问
AccessDenied:用户:arn:aws:sts :: 196375698259:assumed-role / s3access / i-044499612c92b50f5无权执行:cloudformation:DescribeStackResource对资源:arn:aws:cloudformation:us-east-2:196375698259:stack/测试/*

我正在考虑aws s3 cp s3://my-bucket/test-file ./直接使用用户数据,但我想知道为什么AWS::CloudFormation::Init无法承担分配给 EC2 实例的角色。

我只发现一个类似的问题 - How can I access protected S3 files in a CFN script? ,但解决方案是应用 IAM 角色,我已经这样做了,但cfn-init仍然失败。

小智 5

我需要添加AWS::CloudFormation::Authentication到. 详情见:MetadataEC2Instance

https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-authentication.html#cfn-cloudformation-authentication-rolename

例如:

EC2Instance:
    Type: 'AWS::EC2::Instance'    
        Metadata:  
            AWS::CloudFormation::Authentication:  
                 rolebased:  
                     type: S3  
                     roleName: !Ref EC2InstanceIAMRole  
                     buckets:  
                         - !Ref TemplateBucket  
            ...  
Run Code Online (Sandbox Code Playgroud)

该角色可以访问相关的TemplateBucket.

该角色也被分配给EC2 instance.

有关该角色的一些详细信息如下:

https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2.html

在添加此内容之前,我可以通过 aws cli 从 s3 下载文件,但cfn-init无法正常工作并出现以下错误:

Error occurred during build: Failed to retrieve https://s3.amazonaws.com/FILE: HTTP Error 403 : <?xml version="1.0" encoding="UTF-8"?>
<Error><Code>AccessDenied</Code><Message>Access Denied</Message><RequestId>ID</RequestId><HostId>ID</HostId></Error>  
Run Code Online (Sandbox Code Playgroud)