---
title: "A Definitive Guide to Leveraging the AWS Terraform IAM Role"
description: "Discover this definitive guide to the AWS Terraform IAM role and take your devops game to the next level in this ATA Learning tutorial."
canonical: "https://adamtheautomator.com/terraform-iam-role/"
---

# A Definitive Guide to Leveraging the AWS Terraform IAM Role

> Discover this definitive guide to the AWS Terraform IAM role and take your devops game to the next level in this ATA Learning tutorial.

Source: https://adamtheautomator.com/terraform-iam-role/

---

ATA Learning

Tap to hide

[

ATA Learning

](/)

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Search for:  

*   [](https://twitter.com/adbertram)
*   [](https://github.com/Adam-the-Automator)
*   [](https://www.linkedin.com/company/adam-the-automator-llc)
*   [](/feed/)

![A Definitive Guide to Leveraging the AWS Terraform IAM Role](https://adamtheautomator.com/wp-content/uploads/2022/07/A-Definitive-Guide-to-Leveraging-the-AWS-Terraform-IAM-Role.jpg)

# A Definitive Guide to Leveraging the AWS Terraform IAM Role

[![](https://secure.gravatar.com/avatar/2beb65fca997135120ed98dc6a2e57dcdf1a7d7d2f5ff687b5d91dc7ccd7a6b5?s=192&d=mm&r=g)Sagar](https://adamtheautomator.com/author/shanky-mendiratta/)5 August 20226 min. read

Categories: [DevOps](/category/devops/)

Tags:[AWS](/tag/aws/)[Terraform](/tag/terraform/)

Table of Contents

*   [Prerequisites](#prerequisites)
*   [Building the Configuration for a Terraform IAM Role](#building-the-configuration-for-a-terraform-iam-role)
*   [Creating the Terraform IAM Role and Role Policy](#creating-the-terraform-iam-role-and-role-policy)
*   [Verifying the Terraform IAM Role and Policy](#verifying-the-terraform-iam-role-and-policy)
*   [Testing the Terraform IAM Role Access with AWS S3](#testing-the-terraform-iam-role-access-with-aws-s3)
*   [Testing the Terraform IAM Role Access with AWS RDS Database](#testing-the-terraform-iam-role-access-with-aws-rds-database)
*   [Conclusion](#conclusion)

Do you access your AWS services and other components using the generic password? If you do, aren’t the repeated credential prompts after your session expires annoying you? Perhaps it’s time you switch to using a Terraform [IAM role](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html) instead.

An IAM role is similar to an IAM user that contains specific permission, allowing you to access and manage all the AWS services within the AWS infrastructure.

In this tutorial, you will learn how to provision an AWS IAM role and attach a policy to a role using the Terraform IAM Module. You’ll also test the Terraform IAM role permissions to access some AWS services and resources through hands-on examples.

## **Prerequisites**

This post will be a step-by-step tutorial. If you’d like to follow along, ensure you have the following in place:

*   An [Amazon Web Service (AWS) account](https://repost.aws/knowledge-center/create-and-activate-aws-account). You may [register a free-tier account](https://aws.amazon.com/free/) if you don’t have one.
*   A code editor. Even though you can use any text editor to work with Terraform configuration files, consider using [Visual Studio (VS) Code](https://code.visualstudio.com/), as it understands the HCL Terraform language.
*   [Terraform](https://developer.hashicorp.com/terraform/enterprise/install/pre-install-checklist). This tutorial uses Terraform v1.1.5 running on Ubuntu 20.04 LTS, but any operating system with Terraform should work.

Related:[How to Install Terraform on Linux and Windows](https://adamtheautomator.com/install-terraform/)

## Building the Configuration for a Terraform IAM Role

Terraform is an infrastructure as code tool that allows you to build, change, and version infrastructure via a configuration. But first, you must build a Terraform configuration for the AWS IAM role.

This configuration uses the Terraform IAM module to create the AWS IAM role and attach policies. Follow the below steps to create the configuration.

1\. Log in to the Ubuntu machine with your favorite [SSH](https://adamtheautomator.com/ssh-chrome-extension/) client.

Related:[How to Set up the SSH Chrome Extension](https://adamtheautomator.com/ssh-chrome-extension/)

2\. Next, run the commands below to create a working directory called ~/terraform-iam-role-demo_._ This folder will contain all the configuration files you’ll be using in this tutorial.

```bash
mkdir ~/terraform-iam-role-demo
cd ~/terraform-iam-role-demo
```

> _Note: The Terraform configuration below is specific to this tutorial and the AWS subscription it uses. Make sure to customize the configuration as needed or if you encounter errors._

3\. Open your preferred code editor and create a file called _main.tf_ inside the _~/terraform-iam-role_ directory. This _main.tf_ file is the Terraform configuration for the AWS IAM module.

Copy and paste the following configuration to the _main.tf_ file and save the changes.

```powershell
resource "aws_iam_role" "role" {
  name = "instance-role"

  assume_role_policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": "sts:AssumeRole",
      "Principal": {
        "Service": "ec2.amazonaws.com", "s3.amazonaws.com"
      },
      "Effect": "Allow",
      "Sid": ""
    }
  ]
}
EOF
}

resource "aws_iam_instance_profile" "test_profile" {
  name = "instance_profile"
  role = aws_iam_role.role.name
}

resource "aws_iam_policy" "policy" {
  name        = "iam-policy-for-instance-role"
  description = "iam-policy-for-instance-role"

  policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": [
        "ec2:Describe*","s3:Get*"
      ],
      "Effect": "Allow",
      "Resource": "*"
    },
    {
      "Effect": "Allow",
      "Action": "rds:*",
      "Resource": [
           "arn:aws:rds:*:063048070623:db:*",
           "arn:aws:rds:*:063048070623:cluster-endpoint:*",
           "arn:aws:rds:*:063048070623:cluster:*"
          ]
     }
  ]
}
EOF
}

resource "aws_iam_role_policy_attachment" "test-attach" {
  role       = aws_iam_role.role.name
  policy_arn = aws_iam_policy.policy.arn
}

resource "aws_s3_bucket" "b" {
  bucket = "my-s3-test-bucket"

  tags = {
    Name        = "My bucket"
    Environment = "Dev"
  }
}
```

4\. Create another file in _~/terraform-iam-role-demo_ named _provider.tf_ and populate the file with the content below. The _provider.tf_ file contains [Terraform providers](https://developer.hashicorp.com/terraform/language/providers) as Terraform depends on the plugins to connect or interact with cloud providers or API services.

> _Including all configuration values in a single configuration file is possible. But to keep things clear for developers and admins, breaking the logic and variables into separate files is preferable._

```bash
# Declaring the AWS Provider
provider "aws" {
   region = "us-east-1"
 }
```

> _The tutorial creates resources in the us-east-1 region. But a list of_ [_regions that AWS support_](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html#concepts-available-regions) _is also available._

Related:[Getting Started with the Terraform AWS Provider](https://adamtheautomator.com/terraform-aws/)

5\. Finally, run the tree command to verify all required files in the _~/terraform-cloudwatch-demo_ directory, as shown below.

```bash
tree
```

![Verifying the new Terraform configuration files](https://adamtheautomator.com/wp-content/uploads/2022/07/image-369.png)

Verifying the new Terraform configuration files

## Creating the Terraform IAM Role and Role Policy

Now that you have set up the Terraform configuration file and variables files, it’s time to initiate Terraform and create the IAM role and role policy. In the end, you’ll attach the Policy with the IAM role.

To provision the AWS IAM role and role policy, like all other Terraform configurations, Terraform uses three commands in sequence ([terraform init](https://developer.hashicorp.com/terraform/cli/commands/init), [terraform plan](https://developer.hashicorp.com/terraform/cli/commands/plan), and [terraform apply](https://developer.hashicorp.com/terraform/cli/commands/apply)).

> _If the Terraform configuration files you created are not correctly formatted, run the [terraform fmt](https://developer.hashicorp.com/terraform/cli/commands/fmt) command to fix them._

1\. Run the terraform init command in the ~/_terraform-backend-demo_ directory. Doing so initializes the plugins and providers required to work with resources.

```bash
terraform init
```

If all goes well, you’ll see the message that says Terraform has been successfully initialized in the output, as shown below.

![](https://s3.us-west-2.amazonaws.com/secure.notion-static.com/9e9cc03f-b3d1-4395-83d1-5f393b8954cb/Untitled.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Content-Sha256=UNSIGNED-PAYLOAD&X-Amz-Credential=AKIAT73L2G45EIPT3X45%2F20220724%2Fus-west-2%2Fs3%2Faws4_request&X-Amz-Date=20220724T010049Z&X-Amz-Expires=86400&X-Amz-Signature=2c98c2661a43dcc7035384ec89a352c5aea59efa69812fcb461fe0e9cfd65c27&X-Amz-SignedHeaders=host&response-content-disposition=filename%20%3D%22Untitled.png%22&x-id=GetObject)

Running the Terraform initialization.

2\. Next, run the terraform plan command to ensure your syntax of configuration files is correct and gives you a resource provisioning blueprint in your infrastructure.

```bash
terraform plan
```

Once the command completes, you’ll see a message like Plan: “X” to add, “Y” to change, or “Z” to destroy in the output. Below, the Plan shows 4, which means adding four new resources.

![Running terraform plan using the terraform plan command](https://adamtheautomator.com/wp-content/uploads/2022/07/image-370.png)

Running terraform plan using the terraform plan command

3\. Finally, run the terraform apply the command to provision the AWS IAM role and policy based on each configuration (_\*.tf_) in the current directory.

The –auto-approve parameter automatically accepts all prompts while running the command.

```bash
terraform apply --auto-approve
```

![Applying the Terraform configuration](https://adamtheautomator.com/wp-content/uploads/2022/07/image-371.png)

Applying the Terraform configuration

## Verifying the Terraform IAM Role and Policy

You should have created the IAM role and IAM policy with Terraform. But how do you know they exist in your AWS cloud? Verify the AWS IAM role and Policy by manually checking the AWS Management Console.

1\. Open your favorite web browser and log in to the [AWS Management Console](https://aws.amazon.com/console/).

2\. On the console’s home page, type IAM in the search box and click ‘IAM’ to open the Identity and Access Management page. Your browser automatically redirects the page to the IAM page.

![Navigating to the AWS IAM Service Page](https://adamtheautomator.com/wp-content/uploads/2022/07/image-372.png)

Navigating to the AWS IAM Service Page

3\. Once on the Identity and Access Management page, click Roles on the left navigation menu. You should see the instance role you created. Click on instance-role to view the details of the role.

![Viewing the IAM role on the Identity and Access Management page](https://adamtheautomator.com/wp-content/uploads/2022/07/image-373.png)

Viewing the IAM role on the Identity and Access Management page

4\. Further in the instance-role, you will see the Policy (iam-policy-for-instance-role) that you attached. Also, here you will notice that the instance profile is created as selected in the right box. Further click on the iam-policy-for-instance-role Policy.

![Viewing the IAM policy inside](https://adamtheautomator.com/wp-content/uploads/2022/07/image-374.png)

Viewing the IAM policy inside

5\. After you click on the Policy you created, you will see all the permissions you defined in the terraform configuration file (_main.tf_).

![Viewing the IAM policy permissions on Identity and Access Management page](https://adamtheautomator.com/wp-content/uploads/2022/07/image-375.png)

Viewing the IAM policy permissions on Identity and Access Management page

6\. Finally, once you’ve verified the IAM role and policies, attach the IAM instance profile to your Ubuntu machine from the AWS EC2 console, as shown below. Navigate to AWS EC2 page and choose the EC2 result, as shown below.

![Search results for EC2](https://adamtheautomator.com/wp-content/uploads/2022/07/image-376.png)

Search results for EC2

7\. Next, On the Instance page, click on the Instance state → Security → Modify IAM role.

![Modifying the IAM role in the AWS account](https://adamtheautomator.com/wp-content/uploads/2022/07/image-377.png)

Modifying the IAM role in the AWS account

Select instance\_profile from the IAM role drop-down box and click on Update IAM role.

![Attaching the IAM instance profile](https://adamtheautomator.com/wp-content/uploads/2022/07/image-378.png)

Attaching the IAM instance profile

## Testing the Terraform IAM Role Access with AWS S3

In the previous two sections, you created the IAM role and IAM policy using Terraform and later verified them in the Amazon Management console. In this section, you will test the Terraform IAM role permissions.

Specifically, you’ll test the Terraform IAM role permission to access the AWS S3 bucket objects. Assuming you are still logged into your Ubuntu machine, follow these steps.

1\. First, on the terminal, run the aws s3 ls command. By running this command, you will see the list of all the buckets. But if you specify the bucket name in the aws s3 ls command, you’ll only list the specified bucket’s content in your AWS account.

Here, the –recursive means the command will also list all the objects of subdirectories and –human-readable.

```powershell
# Listing all the tickets in the AWS account
aws ls 
# Listing all the objects of the bucket (my-s3-test-bucket-for-iam) in the AWS account
aws s3 ls s3://my-s3-test-bucket-for-iam --recursive --human-readable
```

![Listing all the objects in the AWS S3 bucket](https://adamtheautomator.com/wp-content/uploads/2022/07/image-379.png)

Listing all the objects in the AWS S3 bucket

2\. After listing bucket objects (my-s3-test-bucket-for-iam), run the below command to copy the contents to your Ubuntu computer.

```powershell
# Copying all the objects of the bucket (my-s3-test-bucket-for-iam) in the tmp directory
aws s3 cp s3://my-s3-test-bucket-for-iam/ATA.txt.txt /tmp
```

As you can see below, the IAM role attached to the Ubuntu machine can now perform actions on the AWS S3 service, such as copying objects to the Ubuntu machine. Best of all, you did not have to re-authenticate manually with credentials.

![Copying all the objects from the AWS S3 bucket to the tmp directory](https://adamtheautomator.com/wp-content/uploads/2022/07/image-380.png)

Copying all the objects from the AWS S3 bucket to the tmp directory

## Testing the Terraform IAM Role Access with AWS RDS Database

Earlier in the previous section, you learned how to retrieve the objects of the AWS S3 bucket; this time, quickly dive in and know how you can read all the properties of the AWS RDS database using the IAM role attached to the Ubuntu machine.

Assuming you are still logged into the Ubuntu machine, run the below `aws rds describe` command to describe the database instance. In the below example, the database name is `database-3`.

```powershell
aws rds describe-db-instances --db-instance-identifier database-3
```

After you execute the command, you will see all the details of database-3 in the terminal output.

![Describing the AWS RDS using the Terraform IAM role](https://adamtheautomator.com/wp-content/uploads/2022/07/image-381.png)

Describing the AWS RDS using the Terraform IAM role

## Conclusion

This tutorial taught you how to set up AWS IAM roles and policies using the Terraform cloud tool. You also learned to test the IAM role in examples, such as listing an AWS RDS database instance information and copying AWS S3 objects to the Ubuntu machine.

You now have a fully functional Terraform IAM role in your AWS account. What do you plan to secure in the AWS cloud using this IAM role and Policy?

Share this article

[Share on X](https://twitter.com/intent/tweet?url=https%3A%2F%2Fadamtheautomator.com%2Fterraform-iam-role%2F&text=A%20Definitive%20Guide%20to%20Leveraging%20the%20AWS%20Terraform%20IAM%20Role)[Share on Facebook](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fadamtheautomator.com%2Fterraform-iam-role%2F)[Share on LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fadamtheautomator.com%2Fterraform-iam-role%2F)

## Related Posts

![](https://adamtheautomator.com/wp-content/uploads/2022/08/Which-Tool-Terraform-vs-Cloudformation-in-the-Fight-for-AWS.jpg)

### [Which Tool? Terraform vs. Cloudformation in the Fight for AWS](/terraform-vs-cloudformation/)

Learn which tool, Terraform vs Cloudformation is right for infrastructure as configuration with AWS in this ATA Learning tutorial!

![](https://adamtheautomator.com/wp-content/uploads/2022/02/Learn-How-to-Deploy-Terraform-Autoscaling-Groups-Quickly.jpg)

### [Learn How to Deploy Terraform Autoscaling Groups Quickly](/terraform-autoscaling-group/)

Learn how to achieve zero downtime with your AWS EC2 instances by deploying Terraform autoscaling groups quickly in this step-by-step tutorial!

![](https://adamtheautomator.com/wp-content/uploads/2022/07/Move-Development-to-the-Cloud-with-the-AWS-Cloud9-IDE.jpg)

### [Simplify Development with AWS Cloud9: Your Cloud-Based IDE](/aws-cloud9/)

Simplify your development workflow, boost productivity, and unlock the power of collaboration with a cloud-based IDE. This AWS Cloud9 tutorial shows you how.

## Categories

*   [IT Ops](/category/it-ops/)
*   [Cloud](/category/cloud/)
*   [DevOps](/category/devops/)
*   [Home Ops](/category/home-ops/)
*   [Information Security](/category/infosec/)
*   [Software Development](/category/software-development/)

## Site

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Copyright 2026© ATA Learning | [Privacy Policy](/privacy/)
