How to Create an IAM Role with Ec2 Full Permissions Using Terraform
Introduction :-
AWS Identity and Access Management (IAM) is a powerful tool that allows you to control access to your AWS resources. IAM roles are a type of IAM entity that enables you to grant permissions to users, applications, or services to access AWS resources without the need for long-term access keys. In this blog post, we will show you how to create an IAM role with full S3 permission using #Terraform, assign it to an EC2 instance, and access S3 using command line.
Prerequisites :-
An AWS account
AWS CLI installed and configured
#Terraform installed on your machine
Step-1 :- Configure AWS CLI Make sure that you have configured your AWS CLI with the necessary access keys and secrets. You can check this by running the following command in your terminal:
aws configure
If you haven’t configured AWS CLI yet, you can follow the official AWS documentation to set it up.
Step-2 :- Create a folder named iam-ec2 within the folder create #Terraform configuration file main.tf and copy the below content.
provider "aws" {
region = "us-east-1"
}
resource "aws_iam_role" "ec2_role" {
name = var.name
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Effect = "Allow"
Principal = {
Service = "ec2.amazonaws.com"
}
Action = "sts:AssumeRole"
}
]
})
}
resource "aws_iam_role_policy_attachment" "ec2_role_attachment" {
policy_arn = "arn:aws:iam::aws:policy/AmazonS3FullAccess"
role = aws_iam_role.ec2_role.name
}
In this file, we first define the AWS provider and specify the region we want to use (in this case, us-east-1). Then, we create an AWS IAM role with the name “ec2-role” and define the policy that allows EC2 instances to assume this role.
- Create a variable.tf file in your iam-ec2 folder to define the variables
variable "name" {
type = string
default = "ec2-role"
}
- Define the required outputs in outputs.tf file as shown below.
output "ec2_role_arn" {
value = aws_iam_role.ec2_role.arn
}
Step 3: Initialize #Terraform In your terminal, navigate to the directory where you saved the #Terraform file and run the following command:
terraform init
This command will download the necessary #Terraform plugins and modules.
Step 4: Apply the #Terraform Configuration Run the following command to apply the #Terraform configuration:
terraform apply
This command will show you a summary of the changes that #Terraform is going to make. If everything looks good, type “yes” to confirm and proceed with the changes.
conclusion:-
creating an IAM role with full S3 permission using #Terraform and assigning it to an EC2 instance is a straightforward process that can be accomplished in just a few steps. Once the role is assigned to the instance, you can use the AWS CLI to access S3 resources without the need for long-term access keys. By using IAM roles, you can ensure that your resources are accessed only by authorized entities and maintain the security and integrity of your AWS environment.