0

I have a large bucket policy historically maintained by hand.

I'd like to move it into CI/terraform (for the policy maintenance), but I don't want TF to own the bucket itself.

Is there any way to have TF "import" the huge existing policy and generate the TF file for it? https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/s3_bucket_policy

1 Answer 1

1

Try this, since the bucket is already there with the policy you can run the below command to get the policy inside the tf state

$ terraform import aws_s3_bucket_policy.allow_access_from_another_account my-s3-bucket-name

Once the policy is there in the TF, run the below code in main.tf

So that it will match with the policy in the state and in the plan it will display if it matches with the state or not.

//resource "aws_s3_bucket" "example" { // bucket = "my-tf-test-bucket" //}

    resource "aws_s3_bucket_policy" "allow_access_from_another_account" {
      bucket = "enter the bucket ID from the portal"
      policy = data.aws_iam_policy_document.allow_access_from_another_account.json
    }
    
    data "aws_iam_policy_document" "allow_access_from_another_account" {
      statement {
        principals {
          type        = "AWS"
          identifiers = ["123456789012"]
        }
    
        actions = [
          "s3:GetObject",
          "s3:ListBucket",
        ]
    
        resources = [
          "arn for aws bucket",
        ]
      }
    }
1
  • 1
    Thanks accepting as this is the right TF answer. Also though, I found this CLI command is an easy way there from CI (not as good, but quick to implement). aws s3api put-bucket-policy --bucket <bucket> --policy file://<local-file>.json Commented Aug 24, 2022 at 22:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.