I have created s3 bucket using terraform. I am using random id for uniqueness.
resource "random_id" "s3_suffix-example" {
byte_length = 4
}
resource "aws_s3_bucket" "s3_suffix-example-bucket" {
bucket = "s3_suffix-example-bucket-${lower(random_id.s3_suffix-dev.id)}"
tags = {
Name = "s3_suffix-example-bucket-${lower(random_id.s3_suffix-dev.id)}"
Owner = "[email protected]"
}
}
I found two problems with this approach though-
1- How do i modifying previously creating S3 bucket? e.g. I would like to add a policy to the s3 bucket created in first run. The first time tf apply ran it created bucket- s3_suffix-example-bucket-8hvg1g. When I run tf apply second time Terraform creates another bucket s3_suffix-example-bucket-rhwert. How do modify the bucket that was created in first run i.e.s3_suffix-example-bucket-8hvg1g?
2- I saw this is leaving behind dangling S3 buckets, if tf apply is run multiple times.
How can I solve these two problems?
CodePudding user response:
I don't know what you are doing to cause this behavior, but the behavior you're describing is not how this tool works. Consider the following:
resource "random_id" "this" {
byte_length = 1
}
output "id" {
value = random_id.this.id
}
When one applies this, you get an output. For me id = "sQ"
. Then, if I apply again, id = "sQ"
. And again ad infinitum.
So if defining a bucket in the same state:
resource "aws_s3_bucket" "this" {
bucket = "my-bucket-${random_id.this.id}"
}
That bucket now has the name my-bucket-sQ
. And when applied again, No changes. Your infrastructure matches the configuration.
And you can still modify as you see fit, or attach resources to it.
resource "aws_s3_bucket_acl" "this" {
bucket = aws_s3_bucket.this.id
acl = "private"
}
As an aside, you should consider using the bucket_prefix argument if your goal is bucket name uniqueness. That is exactly for what it is designed, and doesn't require any other consideration.
resource "aws_s3_bucket" "this" {
bucket_prefix = "my-bucket"
}