Infrastructure guards to prevent accidental destruction

Using the bucket policy of S3 buckets to prevent accidental deletion

Table Of Contents

Today I Explained

It isn’t always desirable for the lifecycles of resources to be fully managed with single execution within infrastructure as code. The possibility of accidently deleting a database or storage bucket containing product data, or immediately revoking a secret that grants access to resources is less than ideal. These kind of events can cause frustrating production incidents.

To avoid these kind of situations, you’ll sometimes see infrastructure guards within infrastructure as code like Terraform. These are configurations or policies that disallow the deletion or revocation of resources unless certain conditions have been met. You’ve likely encountered one of these if you have ever attempted to delete an S3 bucket that still contains files.

A common type of infrastructure guard is preventing the deletion of an AWS S3 bucket, it’s bucket policy or any of it’s contents. As long as the bucket policy is configured with the guard, it isn’t possible for objects of the bucket to be deleted within the AWS account.

You can see an example of such a policy below:

data "aws_iam_policy_document" "primary" {
  # ...
  dynamic "statement" {
    for_each = range(module.features.flags["guard"])
    content {
      sid    = "DenyDeleteOfBucket"
      effect = "Deny"

      principals {
        type        = "AWS"
        identifiers = ["*"]
      }

      actions = [
        "s3:DeleteBucket",
      ]

      resources = [
        aws_s3_bucket.primary.arn,
      ]
    }
  }

  dynamic "statement" {
    for_each = range(module.features.flags["guard"])
    content {
      sid    = "DenyDeleteOfBucketPolicy"
      effect = "Deny"

      principals {
        type        = "AWS"
        identifiers = ["*"]
      }

      actions = [
        "s3:DeleteBucketPolicy",
      ]

      resources = [
        aws_s3_bucket.primary.arn,
      ]
    }
  }
}

For the removal of the bucket policy to occur, it first requires an update to revoke the infrastructure guard. When the update has been performed, it will then become possible to destroy the infrastructure using something like terraform destroy.