Attach an IAM Role to an EC2 Instance with CloudFormation by@mlabouardy
21,155 reads

Attach an IAM Role to an EC2 Instance with CloudFormation

Read on Terminal Reader

Too Long; Didn't Read

Company Mentioned

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


Mohamed Labouardy
react to story with heart


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).


. . . comments & more!
Hackernoon hq - po box 2206, edwards, colorado 81632, usa