IT/Terraform

[Terraform] AWS S3 Bucket Policy 규칙 추가 방법

반응형

Intro

오늘은 테라폼을 이용하여 S3 Bucket policy 규칙을 추가해보도록 하겠습니다. S3 Bucket policy는 json 형태로 되어있으며 이는 IAM policy와 매우 유사하기 때문에 향 후 IAM policy에 규칙을 추가하는데에도 동일하게 적용이 가능합니다.

참고로 아래 URL에서와 같이 cloudwatch logs에 데이터를 s3 bucket에 넣기 위해 필요한 policy를 추가 하는 예제로 설명드리겠습니다.

https://docs.aws.amazon.com/ko_kr/AmazonCloudWatch/latest/logs/S3ExportTasksConsole.html

Bucket policy 추가 하는 2가지 방법

테라폼 소스로 Bucket policy를 추가하는 방법은 2가지가 있습니다.

방법1: policy를 json 형태 그대로 넣는 방법

다음과 같이 <<EOT 를 사용해서 직접 json 형태를 그대로 가져올 수 있기 때문에 쉽게 코딩이 가능하지만 가시성이 떨어진다는 단점이 있어서 지속적으로 소스코드를 운영하기가 수월하지 않을 수 있습니다.

resource "aws_s3_bucket_policy" "s3_example_bucket_policy" {
     bucket = aws_s3_bucket.s3_example_bucket.id
   policy = <<EOT
     {
         "Version": "2012-10-17",
        "Statement": [
           {
               "Action": "s3:GetBucketAcl",
               "Effect": "Allow",
               "Resource": "${aws_s3_bucket.s3_example_bucket.arn}",
               "Principal": { "Service": "logs.ap-northeast-2.amazonaws.com" }
           },
           {
               "Action": "s3:PutObject" ,
               "Effect": "Allow",
               "Resource": "${aws_s3_bucket.s3_example_bucket.arn}/*",
               "Condition": { "StringEquals": { "s3:x-amz-acl": "bucket-owner-full-control" } },
               "Principal": { "Service": "logs.ap-northeast-2.amazonaws.com" }
          }
         ]
     }
 EOT
}

}

방법2: json을 data형태로 만들어서 넣는 방법

다음과 같이 json을 data로 만들어서 사용할 수 있습니다. 이렇게 되면 data내부에서 각 필드별로 정리를 쉽게할 수 있어서 가시성이 좋아지면 소스 코드를 유지 보수하는데 수월하다는 장점이 있습니다. 하지만 data 에 파라미터 값들이 json형태로 어떻게 설정되는지 알아야하기 때문에 terraform document나 예제소스를 많이 참고해야한다는 단점이 있겠네요.

resource "aws_s3_bucket_policy" "s3_example_bucket_policy" {
     bucket = aws_s3_bucket.s3_example_bucket.id
   policy = data.aws_iam_policy_document.s3_example_bucket_policy_data.json
}

data "aws_iam_policy_document" ""s3_example_bucket_policy_data" {

  statement {
    actions = [
      "s3:GetBucketAcl",
    ]

    effect = "Allow"

    resources = [
      "${aws_s3_bucket.s3_example_bucket.arn}",
    ]

    principals {
      type        = "Service"
      identifiers = ["logs.ap-northeast-2.amazonaws.com"]
    }
  }

  statement {
    actions = [
      "s3:PutObject",
    ]

    effect = "Allow"

    resources = [
      "${aws_s3_bucket.s3_example_bucket.arn}/*",
    ]

    condition {
      test     = "StringEquals"
      variable = "s3:x-amz-acl"

      values = [
        "bucket-owner-full-control",
      ]
    }

    principals {
      type        = "Service"
      identifiers = ["logs.ap-northeast-2.amazonaws.com"]
    }
  }
}
반응형