Creating and attaching an AWS IAM role, with a policy to an EC2 instance using Terraform scripts

This is an infrastructure as a code, which is equivalent to the AWS CloudFormation, that allows the user to create, update, and version any of the Amazon Web Services (AWS) infrastructure.

Why Terraform?

Terraform utilizes the cloud provider APIs (Application programming interfaces) to provision infrastructure, hence there’re no authentication techniques after, what the customer is using with the cloud provider already. This could be considered as one of the best option, in terms of maintainability, security and ease-of-use.

  1. creating an IAM policy using terraform.
  2. attaching the policy to the role using terraform.
  3. creating the IAM instance profile using terraform.
  4. Assigning the IAM role, to an EC2 instance on the fly using terraform.

1. Creating an AWS IAM role using Terraform:

This is where, the IAM role creation will be done. The assume_role_policy parameter is a must to be given within the resource block, and there are other optional parameters as well such as name, path, description etc.

resource "aws_iam_instance_profile" "test_profile" {                             name  = "test_profile"                         
roles = ["${aws_iam_role.ec2_s3_access_role.name}"]
}

2. Creating an AWS IAM policy using Terraform:

This is where we need to define the required policy (i.e. permissions) according to the necessities. For example, allowing the IAM role to access all the S3 buckets within the region. Providing the policy is a required parameter, where as there are other parameters as well such as arn, path, id etc.

3. Attaching the policy to the role using Terraform:

This is where, we’ll be attaching the policy which we wrote above, to the role we created in the first step.

4. Creating the IAM instance profile using terraform:

This is the resource, which must be used to tag the IAM role to the EC2 instance. As in, when we are creating the resource block for an EC2 instance, in order for us to assign the role to that instance, it expects the aws_iam_instance_profile to be given as a parameter.

5. Assigning the IAM role, to an EC2 instance on the fly using terraform:

Here we will be creating a basic free tier EC2 instance and attaching the iam instance profile which we created above in the step 4.

terraform init
terraform plan
terraform validate
terraform apply

Machine Learning has kept me thriving…https://about.me/kulasangar

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store