spacelift-io / terraform-provider-spacelift

Terraform provider to interact with Spacelift
MIT License
74 stars 28 forks source link

Association resource for spaces #412

Open jkrzemin opened 1 year ago

jkrzemin commented 1 year ago

Currently the only method of setting one space as a child of other via terraform is to use an attribute parent_space_id.

This makes it impossible to reference the resource in single for each since terraform will report a cycle.

# variables.tf
variable "spaces" {
    description = "Map of spaces to create."
    default = {}
    type = map(object({
        name = string
        parent_key = optional(string, "root")
        description = optional(string)
        inherit_entities = optional(bool, false)
    }))
}

# main.tf
resource "spacelift_space" "space" {
  for_each = var.spaces
  name = each.value.name

  parent_space_id = spacelift_space.space[each.value.parent_key].id

  description = each.value.description
  inherit_entities = each.value.inherit_entities
}

If it would be possible to set such relation with association resource like https://registry.terraform.io/providers/spacelift-io/spacelift/latest/docs/resources/azure_integration_attachment then it enable usage of for loops in spaces creation.

Apollorion commented 1 day ago

Hey @jkrzemin, we are discusssing this use case internally. However, as a work around, this will solve your issue. Please note: the parent space must exist before using it in "parent_key". Which means if youre trying to add a new parent space and a child space at the same time, they would have to be broken apart into two separate applies.

variable "spaces" {
  description = "Map of spaces to create."
  default     = {}
  type = map(object({
    name             = string
    parent_key       = optional(string, "root")
    description      = optional(string)
    inherit_entities = optional(bool, false)
  }))
}

data "spacelift_spaces" "this" {}

locals {
  space_name_to_space = {
    for space in data.spacelift_spaces.this.spaces : space.name => space
  }
}

resource "spacelift_space" "space" {
  for_each = var.spaces
  name     = each.value.name

  parent_space_id = local.space_name_to_space[each.value.parent_key].space_id

  description      = each.value.description
  inherit_entities = each.value.inherit_entities
}