packerlabs/lab0/role.tf

69 lines
1.8 KiB
Terraform
Raw Normal View History

2024-12-02 20:32:48 +00:00
# Create an IAM role
resource "aws_iam_role" "ec2_ami_role" {
name = "ec2-ami-role"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Action = "sts:AssumeRole"
Principal = {
Service = "ec2.amazonaws.com"
}
Effect = "Allow"
Sid = ""
},
]
})
}
# Attach the policy that allows creating AMIs
resource "aws_iam_policy" "ec2_ami_policy" {
name = "ec2-ami-policy"
description = "Policy to allow EC2 instances to create AMIs"
policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Effect = "Allow"
Action = [
"ec2:DescribeRegions",
"ec2:DescribeImages",
"ec2:DescribeInstances",
"ec2:DescribeVolumes",
"ec2:DescribeTags",
"ec2:CreateTags",
"ec2:CreateKeyPair",
"ec2:DeleteKeyPair",
"ec2:CreateImage",
"ec2:ModifyImageAttribute",
"ec2:DeregisterImage",
"ec2:DeleteSnapshot",
"ec2:RunInstances",
"ec2:StopInstances",
"ec2:TerminateInstances",
"ec2:CreateSecurityGroup",
"ec2:DescribeSecurityGroups",
"ec2:AuthorizeSecurityGroupIngress",
"ec2:AuthorizeSecurityGroupEgress",
"ec2:DeleteSecurityGroup",
]
Resource = "*"
},
]
})
}
# Attach the policy to the role
resource "aws_iam_role_policy_attachment" "ec2_ami_role_policy_attachment" {
role = aws_iam_role.ec2_ami_role.name
policy_arn = aws_iam_policy.ec2_ami_policy.arn
}
# Create an IAM instance profile to associate the role with the EC2 instance
resource "aws_iam_instance_profile" "ec2_ami_instance_profile" {
name = "ec2-ami-instance-profile"
role = aws_iam_role.ec2_ami_role.name
}