Search code examples
amazon-ec2aws-cloudformationamazon-amiaws-marketplace

How to launch EC2 instance using AWS cloudformation


I've submitted my AMI to the AWS Marketplace but it has been rejected saying I need to convert my manual instructions into a CloudFormation template. My manual instructions for the users currently state that:

- User must create a new Role
- Assign AWSS3FullAccess to this role
- Launch the AMI with WebSecurityGroup (port 80 and 443)

I have not used CloudFormation before so I would like to ask a couple of questions

  1. Is it possible to create a CloudFormation template such that it would: 1) create a new role 2) assign a policy to this role 3) Create an EC2 Instance with the AMI (amiID would be specified) with this role and WebSecurityGroup.

  2. I've created the following template that creates a new role and assigns it full S3 access.

But I'm not sure how to do the rest. How can I launch an EC2 instance with this new role and specify my AMI id?

AWSTemplateFormatVersion: '2010-09-09'
Description: Sample

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

Solution

  • Within your Amazon CloudFormation template, you would define the following resources:

    • IAM::Role (as you have already done)
    • IAM::InstanceProfile (which allows a Role to be assumed by an Amazon EC2 instance)
    • EC2::SecurityGroup
    • AWS::EC2::Instance which would refer to the InstanceProfile, your AMI and the Security Group

    For some examples, see:

    The last link typically provides examples with each resource type, so it's a matter of copying the examples and then customizing for your use-case.