How to create AWS CloudFormation S3 Access Role and Policy for EC2 instances

In Amazon AWS cloud when using CloudFormation, we need to specify rules and policies for our servers (EC2 instances) to be able to access certain resources in AWS. This is needed since all interactions between elements are essentially API calls to some other service.

Below are CloudFormation rules and policies to access S3 service (yaml version):

  S3AccessRole: 
    Type: "AWS::IAM::Role"
    Properties: 
      AssumeRolePolicyDocument: 
        Version: "2012-10-17"
        Statement: 
          - 
            Effect: "Allow"
            Principal: 
              Service: 
                - "ec2.amazonaws.com"
            Action: 
              - "sts:AssumeRole"
      Path: "/"
  S3AccessPolicy: 
    Type: "AWS::IAM::Policy"
    Properties: 
      PolicyName: "AmazonS3ReadOnlyAccess"
      PolicyDocument: 
        Version: "2012-10-17"
        Statement: 
          - 
            Effect: "Allow"
            Action: "*"
            Resource: "*"
      Roles: 
        - 
          Ref: "S3AccessRole"
  S3AccessInstanceProfile: 
    Type: "AWS::IAM::InstanceProfile"
    Properties: 
      Path: "/"
      Roles: 
        - 
          Ref: "S3AccessRole"

Sources: