Is there a way to do this in terraform (12)?

resource "rancher2_project" "myproject" {
    count       = var.enable_namespace ? 1 : 0                         
    name        = "myproject"                                                                           
    ...                                                                                                                       
}                                                                               
                                                                    
resource "rancher2_namespace" "mynamespace" {                             
    count       = var.enable_namespace ? 1 : 0                         
    name        = "mynamespace"                                                        
    project_id  = rancher2_project.myproject.id
    ...
}                                                                               

So both the project and the namespace depend on var.enable_namespace, in theory this could work. But in reality if var.enable_namespace is false terraform says that rancher2_project.myproject.id is not defined.

I thought about dynamic blocks, but I guess they are just for inside a resource block. If not, I have no idea how to define it for resources.

So is there any way to do this?

You could chain the dependency like this:

resource "rancher2_project" "myproject" {
    count       = var.enable_namespace ? 1 : 0                         
    name        = "myproject"                                                                           
    ...                                                                                                                       
}  
resource "rancher2_namespace" "mynamespace" {  
    count       = length(rancher2_project.myproject[*])
    name        = "mynamespace"                                                        
    project_id  = rancher2_project.myproject[count.index].id
    ...
}

Regarding dynamic blocks, you can use for_each on resources but I’m not sure I would consider it the better fit here.

See the docs:

If you read my post that it doesn’t work: forget it, it was my fault …

Thanks, works like a charm :slight_smile:

1 Like