niketp
niketp

Reputation: 459

How to access contents of an s3 bucket through cloudformation template?

I currently have set up an S3 Bucket with a single file in it. I also have a cloudformation template that spins up an ec2 instance with an IAM role that I believe allows access to this S3 Bucket. How exactly do I access this file in my ec2 instance? I would like this file to be present on the instance right when the stack finishes deploying.

Upvotes: 0

Views: 1971

Answers (1)

FacePalm
FacePalm

Reputation: 11748

You need to attach a role to your instance. Here's an example

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 assumes the role : ListS3BucketsRole .
ListS3BucketsPolicy is attached to ListS3BucketsRole which allows the role to list all s3 objects.

With this your EC2 instance can list files on S3

Upvotes: 1

Related Questions