paint-brush
Attach an IAM Role to an EC2 Instance with CloudFormationby@mlabouardy
21,202 reads
21,202 reads

Attach an IAM Role to an EC2 Instance with CloudFormation

by Mohamed LabouardyOctober 28th, 2017
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

In this post, I will show you guys how to create an <strong>EC2</strong> instance and attach an <strong>IAM</strong> role to it so you can access your <strong>S3</strong> buckets.

Company Mentioned

Mention Thumbnail
featured image - Attach an IAM Role to an EC2 Instance with CloudFormation
Mohamed Labouardy HackerNoon profile picture

CloudFormation allows you to manage your AWS infrastructure by defining it in code.

In this post, I will show you guys how to create an EC2 instance and attach an IAM role to it so you can access your S3 buckets.

First, you’ll need a template that specifies the resources that you want in your stack. For this step, you use a sample template that I already prepared:

The template creates a basic EC2 instance that uses an IAM Role with S3 List Policy. It also creates a security group which allows SSH access from anywhere.

Note: I used also the Parameters section to declare values that can be passed to the template when you create the stack.

Now we defined the template. Sign in to AWS Management Console then navigate to CloudFormation, and click on “Create Stack“. Upload the JSON file:

You would be asked to assign a name to this stack, and choose your EC2 specs configuration & SSH KeyPair:

Make sure to check the box “I ackownledge the AWS CloudFormation might create IAM resources” in order to create the IAM Policy & Role:

Once launched, you will get the following screen with launching process events:

After a while, you will get the CREATE_COMPLETE message in the status tab:

Once done, on the output tab, you should see how to connect via SSH to your instance:

If you point your terminal to the value shown in the output tab, you should be able to connect via SSH to server:

|ssh [email protected] -i vpc.pem

Let’s check if we can list the S3 buckets using the AWS CLI:

|aws s3 ls

Awesome ! so we are able to list the buckets, but what if we want to create a new bucket:

It didn’t work, and it’s normal because the IAM Role attached to the instance doesn’t have enough permission (CreateBucket action).