AdSense

網頁

2022/5/9

Terraform 設定S3 bucket的Access Point

Terraform設定AWS S3 bucket的access point。


事前要求

參考「Terraform 建立S3 bucket範例」建立S3 bucket terraform-demo-bucket-202205052200並上傳hello.txt


設定Access Point

使用resource aws_s3_access_point來設定bucket的access point。

  • bucket - 要建立access point的bucket名稱。必填。
  • name - Access point的名稱。必填。

至於access point的存取權限policy則使用resource aws_s3control_access_point_policy來設定。


例如下面設定所有AWS principle皆禁止取得access point terraform-demo-bucket中的object內容。policy的值為jsonencode轉成的JSON字串。

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_access_point" "demo_bucket_access_point" {
  bucket = aws_s3_bucket.demo_bucket.id
  name   = "terraform-demo-bucket"
}

resource "aws_s3control_access_point_policy" "demo_bucket_access_point_policy" {
  access_point_arn = aws_s3_access_point.demo_bucket_access_point.arn

  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Sid = "DenyAllGetObject"
      Effect = "Deny"
      Principal = {
        AWS = "*"
      }
      Action = "s3:GetObject"
      Resource = "${aws_s3_access_point.demo_bucket_access_point.arn}/object/*"
    }]
  })
}

github


套用設定

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




AWS CLI測試

在AWS CLI輸入aws s3api get-object --bucket <access_point_arn> --key <key> <outfile>測試取得object內容。

  • <access_point_arn> - access point的ARN
  • <key> - object的key
  • <outfile> - 取得object要存成的檔案名稱。

所以是aws s3api get-object --bucket arn:aws:s3:ap-northeast-1:400361196721:accesspoint/terraform-demo-bucket --key hello.txt hello.txt。結果因為policy設定所以access denied無法取得object內容。

$ aws s3api get-object --bucket arn:aws:s3:ap-northeast-1:400361196721:accesspoint/terraform-demo-bucket --key hello.txt hello.txt

An error occurred (AccessDenied) when calling the GetObject operation: Access Denied


沒有留言:

AdSense