S3 iteslf has quite simple config.
resource "aws_s3_bucket" "s3_for_ec2" {
bucket = var.bucket
tags = {
Name = var.name
}
}
resource "aws_s3_bucket_ownership_controls" "s3_for_ec2_controls" {
bucket = aws_s3_bucket.s3_for_ec2.id
rule {
object_ownership = "BucketOwnerPreferred"
}
}
resource "aws_s3_bucket_acl" "s3_for_ec2" {
depends_on = [aws_s3_bucket_ownership_controls.s3_for_ec2_controls]
bucket = aws_s3_bucket.s3_for_ec2.id
acl = "private"
}
aws_s3_bucket_ownership_controls: This resource sets up S3 bucket ownership controls for the S3 bucket created by the aws_s3_bucket resource.
aws_s3_bucket_acl: This resource block configures the access control list (ACL) for the S3 bucket created by the aws_s3_bucket resource.
resource "aws_iam_role" "ec2_iam_role" {
name = "ec2_iam_role"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Effect = "Allow"
Principal = {
Service = "ec2.amazonaws.com"
}
Action = "sts:AssumeRole"
}
]
})
}
resource "aws_iam_policy" "s3_policy" {
name = "s3_policy"
description = "Allows EC2 instances to access S3"
policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Effect = "Allow"
Action = [
"s3:GetObject",
"s3:PutObject",
"s3:ListBucket"
]
Resource = [
aws_s3_bucket.s3_for_ec2.arn,
"${aws_s3_bucket.s3_for_ec2.arn}/*"
]
}
]
})
}
resource "aws_iam_role_policy_attachment" "s3_policy_attachment" {
policy_arn = aws_iam_policy.s3_policy.arn
role = aws_iam_role.ec2_iam_role.name
}
resource "aws_iam_instance_profile" "ec2_instance_profile" {
name = "ec2_instance_profile"
role = aws_iam_role.ec2_iam_role.name
}
aws_iam_role : This resource defines an IAM role named ec2_iam_role. The assume_role_policy attribute specifies that the role can be assumed by ec2.amazonaws.com service
aws_iam_policy : This resource defines an IAM policy named s3_policy. The policy grants permission to perform s3:GetObject, s3:PutObject, and s3:ListBucket actions on the S3 bucket specified by the Resource attribute.
aws_s3_bucket.s3_for_ec2.arn <- bucket itself, but not any of its contents.
${aws_s3_bucket.s3_for_ec2.arn}/* <- all objects within the S3 bucket.
aws_iam_role_policy_attachment : This resource attaches the aws_iam_policy defined to the aws_iam_role.
aws_iam_instance_profile : This resource defines an IAM instance profile named ec2_instance_profile. When an EC2 instance is launched with this instance profile, the instance can assume the IAM role and inherit its permissions.
After set these, add this to ec2
resource "aws_instance" "ec2" {
...
iam_instance_profile = var.ec2_instance_profile
Then ec2 has that role.