I have multiple Terraform projects, in project A I create a bucket like this:
resource "aws_s3_bucket" "s3_bucket" {
bucket_prefix = "s3-bucket-"
}
this create a bucket with a random characters in the ends:
s3-bucket-20230927170795326300000001
Now I want to refer the name of this bucket in another project B, so I create:
data "aws_s3_bucket" "s3_bucket" {
bucket = "s3-bucket-"
}
But this will not work because the name is random, is there any trick to solve this?
You could store the bucket name in SSM Parameter Store (or Secrets Manager, if you prefer; however, SSM is more cost-effective, and I assume that this data is not highly security-sensitive).
Here’s an example:
resource "aws_ssm_parameter" "bucket-prod" {
name = "/bucket-names/prod"
type = "String"
value = var.bucket-name
}
Afterwards, you can retrieve it in another module:
data "aws_ssm_parameter" "bucket-prod" {
name = "/bucket-names/prod"
}
data "aws_s3_bucket" "s3_bucket" {
bucket = data.aws_ssm_parameter.bucket-prod.value
}
You can also find more info on how to use SSM resources in the official Terraform docs here.