Convert an existing s3 bucket policy into a terraform-managed policy?



  • 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



  • 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",
        ]
      }
    }
    




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2