やりたいこと
- Terraform を使ってS3を作成する
- S3バケットの用途はALBのログ用
- S3のバケットポリシーのPrincipal をリージョン毎に動的変更したい
やってみた
main.tf
data "aws_caller_identity" "current" {}
data "aws_region" "current" {}
resource "aws_s3_bucket" "awslogs" {
bucket = "${data.aws_caller_identity.current.account_id}-${var.env}-awslogs"
}
resource "aws_s3_bucket_acl" "awslogs" {
bucket = aws_s3_bucket.awslogs.id
acl = "log-delivery-write"
}
resource "aws_s3_bucket_policy" "awslogs" {
bucket = aws_s3_bucket.awslogs.id
policy = templatefile(
"../../module/s3_logs/files/elblogs_bucket_policy_template.json",
{
account_id = data.aws_caller_identity.current.account_id,
policy_elb_accout = lookup(var.elb_account_id, data.aws_region.current.name),
bucket_name = aws_s3_bucket.awslogs.id
}
)
}
variables.tf
variable "elb_account_id" {
type = map(any)
default = {
us-east-1 = "127311923021"
us-east-2 = "033677994240"
us-west-1 = "027434742980"
us-west-2 = "797873946194"
ca-central-1 = "985666609251"
eu-central-1 = "054676820928"
eu-west-1 = "156460612806"
eu-west-2 = "652711504416"
eu-west-3 = "009996457667"
eu-north-1 = "897822967062"
ap-east-1 = "754344448648"
ap-northeast-1 = "582318560864"
ap-northeast-2 = "600734575887"
ap-northeast-3 = "383597477331"
ap-southeast-1 = "114774131450"
ap-southeast-2 = "783225319266"
ap-south-1 = "718504428378"
sa-east-1 = "507241528517"
us-gov-west-1 = "048591011584"
us-gov-east-1 = "190560391635"
cn-north-1 = "638102146993"
cn-northwest-1 = "037604701340"
}
}
# 環境名
variable "env" {}
./files/elblogs_bucket_policy_template.json
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::${policy_elb_accout}:root"
},
"Action": "s3:PutObject",
"Resource": "arn:aws:s3:::${bucket_name}/AWSLogs/${account_id}/*"
},
{
"Sid": "AWSLogDeliveryWrite",
"Effect": "Allow",
"Principal": {
"Service": "delivery.logs.amazonaws.com"
},
"Action": "s3:PutObject",
"Resource": "arn:aws:s3:::${bucket_name}/AWSLogs/${account_id}/*",
"Condition": {
"StringEquals": {
"s3:x-amz-acl": "bucket-owner-full-control"
}
}
},
{
"Sid": "AWSLogDeliveryAclCheck",
"Effect": "Allow",
"Principal": {
"Service": "delivery.logs.amazonaws.com"
},
"Action": "s3:GetBucketAcl",
"Resource": "arn:aws:s3:::${bucket_name}"
}
]
}
解説
- main.tf
-
lookup
を用いて、変数elb_account_id
より、現在のリージョンに適したAWSアカウントを見つける -
templatefile
を用いて、別ファイルに切り出したバケットポリシー(JSONファイル)の変数を置き換える
-
- variables.tf
- リージョン名とアカウントのマップを記載