How to Create and Attach IAM Role in AWS using Terraform

In this article we are going to cover How to create and attach IAM role in AWS using Terraform | attach S3 bucket full access to IAM role using Terraform | Attach IAM role to aws_instance_profile | attach aws_instance_profile to EC2 using Terraform

In AWS, Identity and Access Management (IAM) roles are used to grant permissions to entities (such as AWS services, applications, or users) to access AWS resources. Terraform is a popular Infrastructure as Code (IaC) tool that allows you to define and provision infrastructure resources, including IAM roles, in a declarative manner.

Table of Contents

Scenarios where we attach S3 bucket to AWS EC2 Instance:

Below are some real time where we attach S3 bucket to AWS EC2 Instance

  • Downloading and uploading files/images from EC2 to S3
  • Suppose you have done setup of Web Sever on EC2 and you want to serve images/videos from S3 bucket(Not to store images/videos in source code).

Prerequisites:

Before creating an IAM role using Terraform in AWS, you need to have a few prerequisites in place. Here are the essential steps:

1. AWS Account Setup:

Ensure you have an AWS account and appropriate access to create IAM roles.

2. AWS CLI Configuration:

Please install AWS CLI if not installed using below articles

How to Install and Configure AWS CLI on Windows [2 Steps]

How to Install AWS CLI on Amazon Linux 2

Configure the AWS Command Line Interface (CLI) with the necessary credentials. You can use the following command to set up your credentials:

aws configure

Enter your AWS Access Key ID, Secret Access Key, preferred region, and output format (JSON, text, etc.) as prompted.

step 1

3. Install Terraform:

Make sure Terraform is installed on your local machine. You can download it from the official Terraform website and follow the installation instructions for your operating system using below articles

How to Install Terraform on Amazon Linux 2

How To Install Terraform On Windows [2 Steps]

4. IAM Permissions:

Ensure that the AWS account you’re using has the necessary permissions to create IAM roles. The user or role you are using to execute Terraform should have IAM permissions.

5. IAM Policy for Terraform:

It’s a good practice to create an IAM policy that grants only the necessary permissions for Terraform. Here’s an example policy that you can attach to your IAM user or role:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "iam:CreateRole",
        "iam:AttachRolePolicy",
        "iam:PutRolePolicy"
      ],
      "Resource": "*"
    }
  ]
}

This policy allows the creation of IAM roles, attaching policies to roles, and putting policies to roles.

6. IAM Trust Relationship:

Define the trust relationship policy. This policy specifies which entities (such as AWS services or accounts) are allowed to assume the IAM role. Ensure that you have the correct Principal section in the assume_role_policy attribute of your Terraform aws_iam_role resource.

7. Customize Terraform Configuration:

Modify the Terraform configuration file (as shown in the previous example) to match your requirements, specifying the region, role name, policies, etc.

Create and Attach IAM Role in AWS using Terraform

Here’s a basic example of how you can create an IAM role in AWS and attach S3 bucket full access to IAM role using Terraform | Attach IAM role to aws_instance_profile | attach aws_instance_profile to EC2.

Create a new folder and save the code in a file with a .tf extension (e.g., demo.tf).

demo.tf

paste the below code

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 4.0"
    }
  }
}
provider "aws" {
  region = "ap-south-1"
}
resource "aws_iam_role" "demo_role" {
  name = "demo_role"

  assume_role_policy = jsonencode({
    Version = "2012-10-17",
    Statement = [
      {
        Action = "sts:AssumeRole",
        Effect = "Allow",
        Principal = {
          Service = "ec2.amazonaws.com"
        }
      }
    ]
  })
}


resource "aws_iam_role_policy_attachment" "example_attachment" {
  policy_arn = "arn:aws:iam::aws:policy/AmazonS3FullAccess"
  role       = aws_iam_role.demo_role.name
}


resource "aws_iam_instance_profile" "demo_profile" {
  name = "demo_profile"
  role = aws_iam_role.demo_role.name
}

resource "aws_instance" "demo_instance" {
  ami           = "ami-02a2af70a66af6dfb"
  instance_type = "t2.micro"

  iam_instance_profile = aws_iam_instance_profile.demo_profile.name

  tags = {
    Name = "demo_instance"
  }
}

Let’s break down the code:

  1. Provider Configuration: Specifies the AWS region you want to use.
  2. IAM Role Resource: Creates an IAM role named “example-role” with a trust policy allowing the EC2 service to assume the role. The assume_role_policy attribute contains a JSON policy document.
  3. IAM Role Policy Attachment Resource: Attaches an AWS managed policy (AmazonS3FullAccess in this example) to the IAM role. Adjust the policy_arn attribute to attach the policies you need.

Make sure you have the AWS CLI configured with the necessary credentials before running Terraform.

To use this Terraform configuration, run following set of command :

1.Terraform format

the terraform fmt command is a valuable tool for maintaining code consistency, readability, and collaboration in Terraform projects. It is part of best practices for writing maintainable and scalable infrastructure as code (IaC).

terraform fmt

2. Terraform Initialization:

Run the following commands to initialize your working directory :

terraform init
step 2

3. Terraform Plan:

After initializing, plan the Terraform configuration:

terraform plan
step3.1
step3.2

4. Terraform Apply:

After initializing,Run terraform apply to create the resources :

terraform apply

Confirm the changes when prompted. Terraform will create the IAM role based on your configuration.

step4.2

Verifying the above created aws resources

When you create resources in AWS using Terraform, you can view those resources through the AWS Management Console, AWS CLI, or AWS SDKs.

step 5 1
step 6 1

By following these steps, you can set up the prerequisites and create an IAM role using Terraform in your AWS environment. Adjust the IAM policies and trust relationships based on your specific use case and security requirements.

Terraform destroy

The primary purpose of terraform destroy is to remove all the resources that were created by the Terraform configuration. This includes deleting instances, networks, storage, IAM roles, and any other resources defined in your Terraform configuration.

terraform destroy

How to Create and Attach IAM Role in AWS using Terraform Interview Questions and Answers

1. What is an IAM Role in AWS?

  • Answer: An IAM Role is an AWS Identity and Access Management entity that defines a set of permissions for making AWS service requests. It is not associated with a specific user or group but can be assumed by users, services, or AWS resources.

2. How is an IAM Role different from an IAM User?

  • Answer: An IAM User represents a person or service with unique security credentials, while an IAM Role is an entity that defines a set of permissions and can be assumed by users, services, or resources. Users have fixed credentials, whereas roles are assumed dynamically.

3. Why would you use IAM Roles?

  • Answer: IAM Roles are used for delegating permissions to entities without the need to share long-term credentials. They are often used in scenarios where temporary access is needed, such as granting permissions to AWS services, federated users, or cross-account access.

4. How do you assume an IAM Role?

  • Answer: IAM Roles can be assumed using AWS Identity and Access Management (IAM) temporary security credentials. Users or services can assume a role by making a call to the AWS Security Token Service (STS) AssumeRole API, which returns temporary credentials to be used for subsequent requests.

5. What is the purpose of IAM Role Trust Relationships?

  • Answer: Trust relationships define which entities (e.g., users, accounts, services) are allowed to assume a particular IAM Role. It is specified in a JSON policy document attached to the role and outlines the conditions under which the role can be assumed.

6. Explain the concept of Cross-Account IAM Roles.

  • Answer: Cross-Account IAM Roles allow access to resources in one AWS account from another account. By establishing trust relationships between accounts, a role in one account can be assumed by a user or resource in another account, facilitating secure access across accounts.

7. How do you restrict access to an IAM Role to specific IP addresses?

  • Answer: IAM Roles themselves do not have a direct mechanism for IP-based restrictions. However, you can implement such restrictions by using IAM policies in conjunction with other AWS services, like AWS Identity and Access Management (IAM) condition keys, Amazon Virtual Private Cloud (VPC), or AWS WAF.

8. What is the purpose of IAM Role Session Policies?

  • Answer: IAM Role Session Policies are inline policies that can be attached directly to a role. They define what actions and resources are allowed or denied during the duration of a role’s temporary security credentials. Session policies are often used to further limit permissions for assumed roles.

9. How do you rotate IAM Role credentials?

  • Answer: IAM Role credentials can be rotated by updating the role’s policies or by rotating the credentials of the AWS service or entity that assumes the role. For example, if an EC2 instance assumes a role, you can update the instance profile or terminate and relaunch the instance to obtain new temporary credentials.

10. What is the difference between IAM Role and IAM Group?

Answer: An IAM Role is an entity that defines a set of permissions and can be assumed by users, services, or resources. On the other hand, an IAM Group is a collection of IAM users. Roles are not tied to specific users but are assumed dynamically, while groups are used to simplify the management of user permissions.

11.What is the difference between instance profile and role

Role:

Represents a set of permissions that you can apply to users, groups, or AWS resources.

Provides temporary security credentials.

Can be assumed by AWS services, IAM users, or other resources.

Instance Profile:

Specifically used to grant IAM roles to EC2 instances.

Eliminates the need to store long-term credentials on EC2 instances.

Associated with EC2 instances at launch time.

12.Can an instance profile assume a role ?

No, an instance profile itself cannot assume a role. Instead, an instance profile is a container for an IAM role, and it allows an AWS resource, such as an EC2 instance, to assume that role. The role, not the instance profile, is the entity that can be assumed by other AWS entities.

When you associate an IAM role with an EC2 instance, you are, in essence, granting the instance the permissions defined in that role. The instance assumes the role and receives temporary security credentials that it can use to make AWS API requests.

To clarify:

You create an IAM Role.

You create an Instance Profile.

You associate the IAM Role with the Instance Profile.

You associate the Instance Profile with an EC2 instance.

This separation allows for better security practices because it ensures that permissions are not directly attached to the instance but rather to the IAM role that the instance assumes.

13.Can instance profile have more than one role?

No, an instance profile in AWS can only be associated with a single IAM role. Each instance profile is essentially a container for a single IAM role, and this association is made at the time of instance launch.

When you create an instance profile, you specify the IAM role that you want to associate with it. This association cannot be changed or updated without creating a new instance profile and associating it with a different IAM role.14.What is the difference between aws account and role?

An AWS account is a container for AWS resources and services, and each account operates independently with its own billing and configuration.

An AWS role is a set of permissions that can be assumed by users, services, or resources dynamically, providing a way to delegate permissions and enhance security.

In practice, AWS accounts are used for organizational and billing purposes, while roles are used to define and control permissions within accounts and for enabling secure access across accounts. Roles are a key component of identity and access management in AWS.

14.What is the difference between aws account and role?

  • An AWS account is a container for AWS resources and services, and each account operates independently with its own billing and configuration.
  • An AWS role is a set of permissions that can be assumed by users, services, or resources dynamically, providing a way to delegate permissions and enhance security.

In practice, AWS accounts are used for organizational and billing purposes, while roles are used to define and control permissions within accounts and for enabling secure access across accounts. Roles are a key component of identity and access management in AWS.

These questions cover a range of topics related to IAM Roles in AWS and should provide a good foundation for discussing identity and access management in AWS during an interview.

Interview Questions and Answers for IAM Role using terraform:

1. Explain the purpose of the IAM Role created in this Terraform code.

  • Answer: The IAM Role named “example-role” is created to be assumed by AWS EC2 instances ("Service": "ec2.amazonaws.com"). It has an attached policy (AmazonS3FullAccess) that grants full access to Amazon S3.

2. What is the significance of the assume_role_policy block?

  • Answer: The assume_role_policy block specifies the trust relationship for the role. In this example, it allows the EC2 service to assume the role by specifying the necessary trust policy in JSON format.

3. How can you attach policies to an IAM Role in Terraform?

  • Answer: Policies can be attached to an IAM Role in Terraform using the aws_iam_role_policy_attachment resource. In the example, the AmazonS3FullAccess policy is attached to the IAM Role named “example-role.”

4. What happens when an EC2 instance assumes this IAM Role?

  • Answer: When an EC2 instance assumes this IAM Role, it obtains temporary security credentials that allow it to perform actions defined by the attached policies. In this case, the instance would have full access to Amazon S3.

5. Explain the significance of the "Effect": "Allow" statement in the assume role policy.

  • Answer: The "Effect": "Allow" statement indicates that the specified actions are allowed. In this case, it allows the EC2 service to assume the role, as defined by the sts:AssumeRole action.

6. How would you modify this Terraform code to add more policies to the IAM Role?

  • Answer: You can add more aws_iam_role_policy_attachment blocks to attach additional policies. Each block should specify the policy_arn and the role to which the policy should be attached.

7. What is the purpose of the IAM Role’s unique name (example-role)?

  • Answer: The name is a user-defined identifier for the IAM Role. It must be unique within the AWS account. The role’s name is used in various AWS API calls and is a way to reference the role in Terraform code.

8. How would you modify this code to create IAM Roles in multiple AWS regions?

  • Answer: You can create a separate Terraform configuration file for each region, each with its own provider "aws" block specifying the desired region.

9. Explain the role of the sts:AssumeRole action in the trust policy.

  • Answer: The sts:AssumeRole action allows the specified entity (in this case, the EC2 service) to assume the IAM Role. It is a critical part of the trust policy that enables delegation of permissions.

10. How can you verify that the IAM Role has been successfully created using Terraform?

  • Answer: After running terraform apply, you can check the AWS Management Console or use the AWS CLI to verify the existence of the IAM Role. Additionally, Terraform provides outputs that can display relevant information after applying the configuration.

Feel free to adapt these questions and answers based on your specific interview context or delve deeper into IAM and Terraform concepts as needed.

Conclusion:

In this article we have covered How to create and attach IAM role in AWS using Terraform | attach S3 bucket full access to IAM role using Terraform | Attach IAM role to aws_instance_profile | attach aws_instance_profile to EC2 using Terraform.

About Monica Mahire

Working as DevOps Intern, Likes to explore new tools and share knowledge.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Share via
Copy link