如何通过cloudformation模板访问s3存储桶的内容?

时间:2019-02-01 16:39:26

标签: amazon-web-services amazon-s3 amazon-ec2 amazon-cloudformation

我目前已经建立了一个S3存储桶,其中只有一个文件。我还拥有一个cloudformation模板,该模板可以启动具有IAM角色的ec2实例,我相信该角色允许访问此S3存储桶。如何在ec2实例中访问该文件?我希望该文件在堆栈完成部署后立即出现在实例上。

1 个答案:

答案 0 :(得分:1)

您需要将角色附加到实例。这是一个例子

AWSTemplateFormatVersion: '2010-09-09'
Description: Attach IAM Role to an EC2
Resources:
  Test:
    Type: AWS::EC2::Instance
    Properties:
      InstanceType:
        Ref: InstanceType
      IamInstanceProfile:
        Ref: ListS3BucketsInstanceProfile
  ListS3BucketsInstanceProfile:
    Type: AWS::IAM::InstanceProfile
    Properties:
      Path: "/"
      Roles:
      - Ref: ListS3BucketsRole
  ListS3BucketsPolicy:
    Type: AWS::IAM::Policy
    Properties:
      PolicyName: ListS3BucketsPolicy
      PolicyDocument:
        Statement:
        - Effect: Allow
          Action:
          - s3:List*
          Resource: "*"
      Roles:
      - Ref: ListS3BucketsRole
  ListS3BucketsRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
        - Effect: Allow
          Principal:
            Service:
            - ec2.amazonaws.com
          Action:
          - sts:AssumeRole
      Path: "/"

ListS3BucketsInstanceProfile担任角色:ListS3BucketsRole
ListS3BucketsPolicy附加到ListS3BucketsRole上,该角色可以列出所有s3对象。

通过此操作,您的EC2实例可以列出S3上的文件