Hi @Sanjoy1995
google_sql_database_instance.default[*].name
is a tuple
Given the below (to simulate:
locals {
name = [ "testdb1", "testdb2" ]
}
Then local.name[*]
is equivalent to local.name
:
PS C:\Development\discuss\67582> terraform console
> local.name[*]
[
"testdb1",
"testdb2",
]
> type(local.name[*])
tuple([
string,
string,
])
> type(local.name)
tuple([
string,
string,
])
> local.name
[
"testdb1",
"testdb2",
]
Remember that you need to create each database as a resource. Just because you have a database of the same name across different database_instances does not mean that they are the same database (They are different databases with the same name.)
Therefore the for_each is required to create the multiple database instances, and a database can only belong to one database_instance.
Using a splat in the instance reference is the same as saying ‘associate this database to all of the database instances contained in the tuple’ which you can’t do due to a database only being able to be associated to one instance.
Extending this example
If the requirement is to create the same named databases in the list for each database instance then you will need to create a new map containing every combination of database x instance:
|
instance A |
instance B |
db 1 |
A1 |
B1 |
db 2 |
A2 |
B2 |
Therefore you would create 4x database resources (A1,B1,A2,B2)
The below code has two lists and creates a local
which contains maps of the above. It then creates a terraform_data
resource (to simulate the database resource) for each combination via a for_each
against local.combinations
locals {
instances = ["instance_a", "instance_b"]
databases = ["db_1", "db_2"]
# create a cartesian product of instances and databases as maps with a composite key
combinations = merge([
for instance in local.instances : {
for database in local.databases : "${instance}-${database}" => {
instance = instance
database = database
}
}
]...)
}
# create a data resource for each combination (Simulates the database resource)
resource "terraform_data" "databases" {
for_each = local.combinations
input = {
instance = each.value.instance
databases_name = each.value.database
}
}
output "combinations" {
value = local.combinations
}
Place this code into a main.tf in an empty directory and run terraform plan/apply to see the outcome and to experiment.
HTH
Happy Terraforming