Thursday, October 10, 2019

AWS IAM EC2 Instance Role using Terraform

AWS IAM EC2 Instance Role using Terraform

IAM Roles are used to granting the application access
to AWS Services without using permanent credentials.
IAM Role is one of the safer ways to give permission to
your EC2 instances.
We can attach roles to an EC2 instance, and that allows us to give
permission to EC2 instance to use other AWS Services, for example,
S3 buckets, database dynamo DB, ASG
Create an Assume role as below, assume_role_policy
(Required) The policy that grants an entity permission
to assume the role.

resource "aws_iam_role" "ec2_role" {
name = "ec2_terraform_role"

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

tags = {
    tag-key = "tag-value"
}
}
This is going to create IAM role but we can’t link this role to
EC2 Instance and for that, we need EC2 instance Profile

Create EC2 Instance Profile using below code

resource "aws_iam_instance_profile" "ec2_profile" {
name = "ec2_terraform_profile"
role = "${aws_iam_role.ec2_role.name}"
}

Now if we execute the above code, we have Role and Instance
Profile but with no permission.so lets add IAM Policies which
allows EC2 instance to execute specific commands for example:
access to S3 Bucket
Adding IAM Policies,for giving full access to S3 bucket
resource "aws_iam_role_policy" "test_policy" {
name = "ec2_terraform_policy"
role = "${aws_iam_role.ec2_role.id}"

policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
  {
    "Action": [
      "s3:*"
    ],
    "Effect": "Allow",
    "Resource": "*"
  }
]
}
EOF
}
Attach this role to EC2 instance
resource "aws_instance" "ebs_instance_example" {
  ami           = lookup(var.ami_id, var.region)
  instance_type = var.instance_type
  iam_instance_profile = aws_iam_instance_profile.ec2_profile.name
  # key name
  key_name = var.key_name
  # User data passing through template rendering

  tags = {
    Name = "Roles with Ec2"
  }
}
It’s time to execute code run


terraform init
Let you see what terraform will do before making the actual changes
terraform plan
To actually create the instance we need to run terraform apply
terraform apply

2 comments:

Ethical Hacking Techniques: Cracking WPA/WPA2 Wi-Fi Using WPS and Capturing Handshakes

In the realm of cyber security, ethical hacking plays a crucial role in identifying and addressing vulnerabilities. One of the areas where e...