hashicorp / terraform-provider-aws

The AWS Provider enables Terraform to manage AWS resources.
https://registry.terraform.io/providers/hashicorp/aws
Mozilla Public License 2.0
9.87k stars 9.21k forks source link

[Enhancement]: Check if bucket with that "name" already exists when running plan #30550

Open tomer-ds opened 1 year ago

tomer-ds commented 1 year ago

Description

Currently when creating a new S3 bucket or EC2 target group, if the name you chose already exists either in the world or in your current region, the plan will succeed and Terraform will want to create the resource, but in reality the Apply run will fail due to failed API calls to AWS due to "Name already exists" error

When creating S3 buckets or any other resource where the name cannot be reused, such as load balancers or target groups, it would be good if the Terraform Plan would fail if said name already exists. That way we could catch issues like this during the Plan and not during Apply.

I know AWS CLI has the call bucket-exists so maybe something similar could be implemented here

Affected Resource(s) and/or Data Source(s)

aws_s3_bucket

Potential Terraform Configuration

data "aws_canonical_user_id" "current" {}

data "aws_elb_service_account" "main" {}

locals {
  lb_logs_bucket_policy = <<POLICY
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::${data.aws_elb_service_account.main.id}:root"
      },
      "Action": "s3:PutObject",
      "Resource": "arn:aws:s3:::${join("-", [lower(local.full_environment_name), "lb-access-logs"])}/*"
    }
  ]
}
POLICY

  enable_lb_access_logs = var.is_root_workspace == true && (var.enable_lb_access_logs == true || var.is_production_environment == true)

  s3_buckets = {
    lb-access-logs = {
      create_bucket = local.enable_lb_access_logs
      attach_policy = true
      policy        = local.lb_logs_bucket_policy
    }
    cloudfront-logs = {
      create_bucket = var.create_cf_distributions
      acl           = "log-delivery-write"
    }
    msk-broker-logs-bucket = {
      create_bucket = var.create_msk_cluster
      acl           = "log-delivery-write"
    }
  }

}

module "s3_buckets" {
  source  = "terraform-aws-modules/s3-bucket/aws"
  version = "3.7.0"

  for_each = local.s3_buckets

  create_bucket            = each.value.create_bucket
  bucket                   = join("-", [lower(local.full_environment_name), each.key])
  acl                      = try(each.value.acl, null)
  control_object_ownership = true

  policy        = try(each.value.policy, null)
  attach_policy = try(each.value.attach_policy, false)

  force_destroy = var.force_destroy
}

References

https://github.com/hashicorp/terraform-provider-aws/issues/2187

Would you like to implement a fix?

None

github-actions[bot] commented 1 year ago

Community Note

Voting for Prioritization

Volunteering to Work on This Issue