AdSense

網頁

2022/5/6

Terraform 設定S3 bucket policy

Terraform設定AWS S3 bucket的bucket policy。


事前要求

參考「Terraform 建立S3 bucket範例」建立S3 bucket terraform-demo-bucket-202205052200


設定Bucket policy

使用resource aws_s3_bucket_policy來設定bucket的policy。


例如下面設定所有AWS principle皆禁止取得bucket terraform-demo-bucket-202205052200中的object內容,相當於「AWS 設定S3 bucket policy不可讀取檔案物件」的設定。policy的值為JSON字串(heredoc)。

main.tf

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 4.12"
    }
  }

  required_version = ">= 1.1.9"
}

provider "aws" {
  profile = "default"
  region  = "ap-northeast-1" // Tokyo
}

resource "aws_s3_bucket" "demo_bucket" {
  bucket = "terraform-demo-bucket-202205052200"
}

resource "aws_s3_bucket_policy" "deny_all_get_object" {
  bucket = aws_s3_bucket.demo_bucket.id
  policy = <<POLICY
  {
    "Version": "2012-10-17",
    "Statement": [
      {
        "Sid": "DenyAllGetObject",
        "Effect": "Deny",
        "Principal": {
          "AWS": "*"
        },
        "Action": "s3:GetObject",
        "Resource": "${aws_s3_bucket.demo_bucket.arn}/*"
      }
    ]
  }
  POLICY
}

policy的值參考data source aws_iam_policy_document,效果同上。

main.tf

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 4.12"
    }
  }

  required_version = ">= 1.1.9"
}

provider "aws" {
  profile = "default"
  region  = "ap-northeast-1" // Tokyo
}

resource "aws_s3_bucket" "demo_bucket" {
  bucket = "terraform-demo-bucket-202205052200"
}

resource "aws_s3_bucket_policy" "deny_all_get_object" {
  bucket = aws_s3_bucket.demo_bucket.id
  policy = data.aws_iam_policy_document.deny_all_get_object_document.json
}

data "aws_iam_policy_document" "deny_all_get_object_document" {
  statement {
    sid    = "DenyAllGetObject"
    effect = "Deny"
    principals {
      type        = "AWS"
      identifiers = ["*"]
    }
    actions   = ["s3:GetObject"]
    resources = ["${aws_s3_bucket.demo_bucket.arn}/*"]
  }
}

github


套用policy

執行terraform apply可在AWS console S3 bucket policy看到設定的policy。




沒有留言:

AdSense