Monday, November 25, 2024

Creating IAM Role and Assigning it to EC2 Instance requires four steps

locals {
region = "us-west-2"
owner = "<name>"
ami = "ami-XXXXXX"
}

# Setup ECR Roles for EC2
resource "aws_iam_policy" "ecr_policy" {
name = "MyECRPolicy"

policy = jsonencode({
Version : "2012-10-17",
Statement : [
{
Effect : "Allow",
Action : [
"ecr:CompleteLayerUpload",
"ecr:UploadLayerPart",
"ecr:InitiateLayerUpload",
"ecr:BatchCheckLayerAvailability",
"ecr:PutImage",
"ecr:BatchGetImage"
],
Resource : "arn:aws:ecr:us-west-2:#############:repository/<name>/myweb"
},
{
Effect : "Allow",
Action : "ecr:GetAuthorizationToken",
Resource : "*"
}
]
})

tags = {
Name = "ECR Policy"
Owner = local.owner
}
}

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

tags = {
Name = "ECR Role"
Owner = local.owner
}
}

resource "aws_iam_role_policy_attachment" "ecr_policy_attach" {
role = aws_iam_role.ecr_role.name
policy_arn = aws_iam_policy.ecr_policy.arn
}

# Critical Definition
# When you use the AWS Dashboard to create a role, this will automatically
# create an instance profile. But using TF, this field "Instance profile ARN"
# doesn't appear in UI until this is defined.
#
# "An instance profile in AWS is a container for an IAM role that passes role
# information to an EC2 instance when it starts."
#
# "Instance profiles act as a bridge for IAM roles, which define a collection
# of permissions. An EC2 instance profile defines "who" the instance is, and
# then "assumes" the IAM role to gain the necessary permissions"
#
# It is then possible to select the MyECRRole and assign it to the instance
resource "aws_iam_instance_profile" "ecr_instance_profile" {
name = "MyECRInstanceProfile"
role = aws_iam_role.ecr_role.name
}