AWS Cloudformation 从私有 S3 AWS4-HMAC-SHA256 下载文件

AWS Cloudformation download file from private S3 AWS4-HMAC-SHA256

我正在尝试使用此模板在 cloudformation 构建期间从 S3 存储桶下载文件。

失败并显示以下错误消息。

The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256.

使用此模板

https://raw.githubusercontent.com/awslabs/aws-hangouts/master/20140130_cfn/s3-role-authentication.json

 2017-08-26 03:13:38,763 [ERROR] Unhandled exception during build: Failed to retrieve https://hello.s3.amazonaws.com/index.html: HTTP Error 400 : <?xml version="1.0" encoding="UTF-8"?>
<Error><Code>InvalidRequest</Code><Message>The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256.</Message><RequestId>5328A90F4EBF081D</RequestId><HostId>nUyURkNRX7Ty5xU1LiY3wO/aFDzjiWYw9JWq0PlVdmjMCqUP7sG8FN1w5BwmtEWc8IKpeMqkv6k=</HostId></Error>
Traceback (most recent call last):
  File "/opt/aws/bin/cfn-init", line 171, in <module>
    worklog.build(metadata, configSets)
  File "/usr/lib/python2.7/site-packages/cfnbootstrap/construction.py", line 129, in build
    Contractor(metadata).build(configSets, self)

这是从私有 S3 下载文件的正确步骤。

https://aws.amazon.com/blogs/devops/authenticated-file-downloads-with-cloudformation/

我也收到 "AWS4-HMAC-SHA256" 错误,我会解释这个场景以及我是如何解决这个问题的,这样它会对别人有所帮助。出现错误是因为我的存储桶与我提供我的 cloudformation 堆栈的区域不同。

  • 使用https://<bucket-region>amazonaws.com/<bucket>/<file-name>作为bucket对象url
  • 您需要在身份验证部分使用 相同的角色,该角色在 EC2 实例的 实例配置文件 中使用。

这是cloudformation模板

Resources:
  MyEC2:
    Type: "AWS::EC2::Instance"
    Properties:
      IamInstanceProfile: !Ref IAMRoleS3FullAccessInstanceProfile 
    ......
    Metadata:
      AWS::CloudFormation::Authentication:
        S3BucketAccessCredential:
          type: "S3"
          roleName: !Ref IAMRoleS3FullAccess

      AWS::CloudFormation::Init:
        config:
          .....
          files:
            /etc/nginx/sites-available/webserver:
              source: "https://<bucket-region>amazonaws.com/<bucket>/<file-name>"
              mode: "000600"
              owner: root
              group: root
              authentication: "S3BucketAccessCredential"

  # S3 Access role
  IAMRoleS3FullAccess:
    Type: AWS::IAM::Role
    Properties:
      ManagedPolicyArns: 
        - "arn:aws:iam::aws:policy/AmazonS3FullAccess"
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
        - Effect: Allow
          Principal:
            Service:
            - ec2.amazonaws.com
          Action:
          - sts:AssumeRole
      Path: "/"

  # Instance profile
  IAMRoleS3FullAccessInstanceProfile:
    Type: AWS::IAM::InstanceProfile
    Properties:
      Path: "/"
      Roles:
      - !Ref IAMRoleS3FullAccess