5 Simple Steps to Master Terraform IaM Roles
Tags: aws, iam, cybersecurity, roles
Published: 2023-10-26 17:55:21

Venturing into the vast realm of cloud infrastructure, IAM roles stand as critical pillars, anchoring your security blueprint. As more businesses set sail into cloud migration or expansion, the pressing challenge remains: overseeing who or what gets the privilege of accessing your services.

61% of companies state [securing digital identities](https://www.idsalliance.org/white-paper/2023-trends-in-securing-digital-identities/) is one of their top three priorities. But even if you have the most brilliant minds in your team, or access to endless resources, manually managing IAM access for large-scale projects is humanly impossible. You must combine IAM solutions with an Infrastructure as Code (IaC) tool like Terraform.

Combining IAM with Terraform makes headache-inducing tasks like access control provisioning or role assignment much more manageable. This article discusses the benefits of using AWS IAM roles with Terraform and gives you a complete tutorial and tips on how to get started.

[](https://blog.slauth.io/terraform-iam-roles#heading-the-role-of-iam-roles "Permalink")The role of IAM roles
-------------------------------------------------------------------------------------------------------------

![](https://lh7-us.googleusercontent.com/HLCv2Pb9T2gYwRYNJ21mJqsgA7d_n2E2EZGKcHO-HmbsI5F_McOBspkukqWLlAQ8Bvas-GGor72xU7wRQPe3VPfC4M2tNG03LCsY675GWWhvBQxytieV2Sq5KLuIBHtf5RPp7gtZGNsQPIggoNZc6f0)

A robust [IAM strategy](https://blog.slauth.io/guide-to-cloud-identity-management) is non-negotiable at this point. Cyberattackers are getting smarter, so the least you can do is ensure you don't leave any door open to any person or machine to impact your cloud infrastructure. From increasing operational efficiency to easing secure collaboration between internal and external parties to ensuring [continuous security](https://www.jit.io/blog/ci-cd-security-tips) and regulatory compliance, the benefits of IAM are plenty.

IAM roles are an essential component of this strategy. They act like versatile access personas with specific permissions that users or services can temporarily use. Roles are designed to overcome the limitations of traditional access methods like persistent credentials, scalability, revoking issues, and context awareness. Plus, they work as needed and follow the principle of least privilege -- only providing users minimum access to complete the task.

Compared to IAM users, IAM roles do not have passwords or access keys associated with them. They only offer temporary credentials to assigned users. Hence, you can easily change the users accessing your resources while keeping the roles. [Slauth.io](http://slauth.io/) can automatically create IAM policies and roles for your organization by analyzing the real-time activity of your identities (API calls from end-to-end API tests to AWS), giving access to only what each role needs, and following the least privilege principle.

Tip! AWS recommends using IAM roles over IAM users for users and workloads accessing your AWS resources.

[](https://blog.slauth.io/terraform-iam-roles#heading-using-aws-iam-roles-with-terraform "Permalink")Using AWS IAM roles with Terraform
---------------------------------------------------------------------------------------------------------------------------------------

Manually setting up and managing IAM roles can become a blocker in scaling applications. One thing is having a team of ten needing access to resources to work. Another is having hundreds or thousands of services and resources and internal and external entities wanting to access them.

Enter Terraform - a robust Infrastructure as Code (IaC) tool that lets you automate infrastructure tasks, which is particularly useful for [multi-cloud deployments](https://controlplane.com/blog/post/best-multi-cloud-management-tools). When IAM roles combine with Terraform, developers can weave access management into Terraform configurations, creating a smooth coordination of IAM roles in cloud setups.

IAM role creation and configuration is automated, streamlining the process and ensuring consistency and repeatability across environments. This automation of provisioning, management, and deprovisioning of IAM roles mitigates the risks associated with manual errors and ensures that users only have access for the required duration. Plus, it saves your team a whole lot of time and stress.

![](https://lh7-us.googleusercontent.com/zj86klhvxoZTAkOFS6ZLOT9U6pJD-wlR-bO6swMvSPIJQ86ImF3ma77DAuUfe4bhf8lR5Fzz0eJZqEk0wpWGvoONUxV_ZQ3Pj8AZZstP_N4muioBnBqO0ibT33Tm_xvOb18JOII3y1u99CNJjn_-kjk)

From a security standpoint, Terraform's "immutable infrastructure" approach reduces the risk of unauthorized changes to [IAM access controls](https://blog.slauth.io/what-is-iam-access-analyzer-and-how-to-use-it) by encouraging developers to replace the resources rather than modify them. Because IAM roles are configured as code, they are easily traceable and trackable - helping you keep a record of all activity.

Storing detailed records of identities' activities and access controls is a general yet crucial best practice that should be adopted and promoted as part of your [security culture](https://cybeready.com/category/the-complete-guide-to-creating-a-security-culture) efforts. Plus, it proves beneficial when you need to show evidence in regulatory compliance audits.

[](https://blog.slauth.io/terraform-iam-roles#heading-5-simple-steps-to-master-terraform-iam-roles "Permalink")5 Simple steps to master Terraform IAM roles
-----------------------------------------------------------------------------------------------------------------------------------------------------------

Onto the exciting part of today's lesson: using IAM with Terraform. Before we start the tutorial, these are the prerequisites:

-   Active AWS account.

-   Terraform account.

-   Basic understanding of Terraform and the AWS IAM service.

### [](https://blog.slauth.io/terraform-iam-roles#heading-1-create-an-iam-policy "Permalink")1\. Create an IAM Policy

An [AWS IAM policy](https://blog.slauth.io/aws-iam-role-policy-issues-solutions) is a set of permissions that define what actions are allowed or denied on AWS resources. It helps developers specify who can do what within an AWS account and control the level of access granted to users, groups, and roles.

![](https://lh7-us.googleusercontent.com/nHM2G2hCeu1YYPf0Iomc69coJuVf6st9OlJJW5GuLkyQlK8fqtefnzQK78AgsP7SckRlUBaX0nqp-xU8oJ-jYBEBrLSScof5TIv1ngUabZiIQ9eC7xrlxccq-Q0tdpgudN_EmSyuC7EUoG1wbda4Ufc)

You can easily create an AWS IAM policy through AWS Management Console, AWS Command Line Interface, AWS CloudFormation, or Terraform. Since this article is specifically about Terraform, we will continue the examples using this tool.

Here is how you can create an AWS IAM policy with Terraform to allow s3:GetObject action on any S3 resource:

#### [](https://blog.slauth.io/terraform-iam-roles#heading-define-the-policy-document "Permalink")Define the Policy Document

The policy document defines the permissions and resources the policy will grant access to.

![](https://lh7-us.googleusercontent.com/83MKUw4hWxipmsMqzKd-FVG4-PJtYZFrKVEqkD5ErDPCjmkEQ7M66ngGMoLFhXJ38CBuU5CQV2u5R_Gnl1jmIQNafWRd_Y6haeqE54mW8Vp40-EefrcLr01wKGh_JFUq1sTFiVHHqLNqcAo7MhgPQ9g)

#### [](https://blog.slauth.io/terraform-iam-roles#heading-create-the-iam-policy "Permalink")Create the IAM Policy

Use the aws_iam_policy resource type and provide the policy name, description, and the policy document you defined earlier.

![](https://lh7-us.googleusercontent.com/vYrmMDkX1WyDC0bJydo4u6JY-clXossQu7TlSb3oWc0mdqwTcqXbm4VG7kn3KRKV9au0K0IfHlJMmmcGVScJPeN6FuZ6phrngTPtkZg4QTx3pzop9VPsATNPKJ8bp7XUXFT5lWg3fthdN2bwubPzX9c)

#### [](https://blog.slauth.io/terraform-iam-roles#heading-best-practices-to-follow-when-creating-an-iam-policy "Permalink")Best practices to follow when creating an IAM policy

-   Principle of least privilege: Assign only the minimum permissions required for a user. In this case, the user will only have s3:GetObject permission.

-   Use conditions: Use conditions to refine permissions. For example, you can restrict access based on conditions like IP address by modifying the policy document:

![](https://lh7-us.googleusercontent.com/cIIoKuewHoWTh2bRwub2uPO1KYHdh4Vswfvqvs0aYEk9QQVs9COIQUilpETGmTaCSisKP9cNgyHZLq8xMWXT6tfY_t7Hi1FhCJzDLdSyWA6WV7NeJR_zyV3H-dfo1FG2OvL_rtBHhW3jQLZ9VeaiGeU)

-   Version and document policies: Include a version in your policy document to track changes over time.

![](https://lh7-us.googleusercontent.com/0xvnygcKmZ7w8pmUf_jbLKV430dLQNiGAcAGrm44cof2DopmQ24coWMV31Fg9JNiJW7U2cRzF-l4kVDnj92EnQxvJ5FJwcInNLaZFVUesHImldZ8v61vrpg9bRIlsQBZPc7t-IIUTKB5el8CTZSNWJA)

### [](https://blog.slauth.io/terraform-iam-roles#heading-2-create-an-iam-role "Permalink")2\. Create an IAM Role

You can use the aws_iam_role resource to create the IAM role.

![](https://lh7-us.googleusercontent.com/f2cUDxwTZK5nbdmgbhTyEajquQozbU5ZnN0fM2m51d_JmynYYWNxJxpd-ut7b1gxK7nlsPvnCaFIPrtQTMmVVHnEpLFlSt09W5sza95-s193z6KwcysUS_T4yhapGFd4S6OSv9mAmnv-XgEHE3TN5zE)

#### [](https://blog.slauth.io/terraform-iam-roles#heading-best-practices-to-follow-when-creating-an-iam-role "Permalink")Best practices to follow when creating an IAM role

-   Define clear trust policies: The assume_role_policy within the IAM role specifies that the [ec2.amazonaws.com](http://ec2.amazonaws.com/) service can assume the role.

-   Use managed policies: Although the above example uses an inline policy, it is advised to use managed policies whenever possible.

### [](https://blog.slauth.io/terraform-iam-roles#heading-3-attach-the-policy-to-the-role "Permalink")3\. Attach the policy to the role

Use the aws_iam_policy_attachment resource to attach the policy to the role.

![](https://lh7-us.googleusercontent.com/p6wTuGRw27cz8FwsLb9GZvalYV0HWOsy4sgJuRBgT0siWZKGiFq1vVq1cjm_VgMhMlbgku-NdxxrQ9ob0EtVWUvrK62kgC0ukk7GmFRDoJf-GDy3n8SkTx7EWNYy5hbsDmxzurY-zEjwoBrhcO9fg30)

#### [](https://blog.slauth.io/terraform-iam-roles#heading-best-practices-to-follow-when-assigning-a-role-to-a-policy "Permalink")Best practices to follow when assigning a role to a policy

-   Granular and specific policies: When defining policies for IAM roles, make them granular and particular to the role's actions. In this example, the policy example_policy is limited to the s3:GetObject action, ensuring that the attached role has only the permissions to retrieve objects from Amazon S3 buckets.

-   Least common mechanism: This approach ensures that each role has only the required permissions. If different roles have different permissions needs, avoid attaching the same policy to multiple roles.

### [](https://blog.slauth.io/terraform-iam-roles#heading-4-attach-an-instance-profile-to-the-role "Permalink")4\. Attach an instance profile to the role

An instance profile in AWS is a container for an IAM role. You can use it to pass role information to an EC2 instance when the instance starts. It can also grant temporary resource permissions without exposing long-term credentials like access keys.

Instance profiles are commonly used when EC2 instances need to access other AWS services or resources. You can assign a specific set of permissions to the IAM role associated with an instance profile and control what actions an instance can perform and what resources it can access.

For example, an EC2 instance that needs to read objects from an S3 bucket can be launched with an instance profile with an associated IAM role granting it s3:GetObject permissions.

![](https://lh7-us.googleusercontent.com/IB8wCQ0y1TD6wIQF_dnFCAG6AeCnutJ1KHAdUzVC12jP7r_QUOxkubfzxqsa_BxP9vDKtm0zpm4APiXpKlrVua-8o-fbSA7s02nGA945kixq_X1FX86doayrukjVvE5ed0zUAzZEcV5FVlRyQ92L47s)

### [](https://blog.slauth.io/terraform-iam-roles#heading-5-test-if-the-iam-role-configuration-is-working-correctly "Permalink")5\. Test if the IAM role configuration is working correctly

Finally, run terraform init to initialize the Terraform configuration and terraform apply to apply the changes.

Then, you can test the IAM role configuration through AWS CLI:

-   SSH into the EC2 instance that is associated with the IAM role.

-   Run the following command to list the contents of an S3 bucket.

![](https://lh7-us.googleusercontent.com/xh-SM7PSsvH55Hhd_hntxqDEOwmr6tzEylPu8x9uG1V4JVH5TORN3BIkQ9Ns_pvlM8krI8DLi5C91u3oflD5a0TOH5l8ph3fPr44vMPxcVLkwQdkVVzI41j3nMrkRJrr77ETpWd9jXXcChAzWZrQy5c)

If the role is correctly configured, it should return a list of objects in the specified S3 bucket.

[](https://blog.slauth.io/terraform-iam-roles#heading-ready-set-role "Permalink")Ready, Set, Role
-------------------------------------------------------------------------------------------------

The above steps look straightforward, but don't get mistaken: things get much more cumbersome with the increasing number of resources, users, and conditions. Terraform isn't all the automation you can get - you can simplify the creation and management of IAM roles even more with tools like Slauth.

[Slauth.io](http://slauth.io/) is your IAM policy and role master. It tracks the activity of identities and automatically determines what access each machine identity needs to what resources. Plus, based on the analyzed permissions, it can generate custom IAM roles that match the company's needs and requirements so you can leave the error-prone guesswork behind and focus on tackling your to-do list instead. [Sign up here](https://www.slauth.io/sign-up) to join our waiting list and try it out.