From 46da2bece4c361fb76fcdd801dabba00d89b1d48 Mon Sep 17 00:00:00 2001 From: andrewkim099 Date: Thu, 24 Sep 2026 12:30:22 -0500 Subject: [PATCH] feat(provider): add boundary_target_host_source resource (#839) * feat(provider): add boundary_target_host_source resource --------- Co-authored-by: Andrew Kim Co-authored-by: Andrew Kim --- docs/resources/target_host_source.md | 25 ++ internal/provider/provider.go | 1 + .../provider/resource_target_host_source.go | 192 +++++++++++++++ .../resource_target_host_source_test.go | 223 ++++++++++++++++++ 4 files changed, 441 insertions(+) create mode 100644 docs/resources/target_host_source.md create mode 100644 internal/provider/resource_target_host_source.go create mode 100644 internal/provider/resource_target_host_source_test.go diff --git a/docs/resources/target_host_source.md b/docs/resources/target_host_source.md new file mode 100644 index 00000000..2d043138 --- /dev/null +++ b/docs/resources/target_host_source.md @@ -0,0 +1,25 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "boundary_target_host_source Resource - terraform-provider-boundary" +subcategory: "" +description: |- + Attaches a host source to an existing Boundary target. Use this resource instead of the host_source_ids field on boundary_target when the target and its host sources are managed in separate Terraform configurations. Do not set host_source_ids on boundary_target when using this resource for the same target. +--- + +# boundary_target_host_source (Resource) + +Attaches a host source to an existing Boundary target. Use this resource instead of the `host_source_ids` field on `boundary_target` when the target and its host sources are managed in separate Terraform configurations. Do not set `host_source_ids` on `boundary_target` when using this resource for the same target. + + + + +## Schema + +### Required + +- `host_source_id` (String) The ID of the host source to attach to the target. +- `target_id` (String) The ID of the target to attach the host source to. + +### Read-Only + +- `id` (String) The ID of this resource. diff --git a/internal/provider/provider.go b/internal/provider/provider.go index b93a1fad..98b0e766 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -131,6 +131,7 @@ func New() *schema.Provider { "boundary_scope": resourceScope(), "boundary_storage_bucket": resourceStorageBucket(), "boundary_target": resourceTarget(), + "boundary_target_host_source": resourceTargetHostSource(), "boundary_user": resourceUser(), "boundary_worker": resourceWorker(), }, diff --git a/internal/provider/resource_target_host_source.go b/internal/provider/resource_target_host_source.go new file mode 100644 index 00000000..e365d290 --- /dev/null +++ b/internal/provider/resource_target_host_source.go @@ -0,0 +1,192 @@ +// Copyright IBM Corp. 2020, 2026 +// SPDX-License-Identifier: MPL-2.0 + +package provider + +import ( + "context" + "fmt" + "net/http" + "strings" + + "github.com/hashicorp/boundary/api" + "github.com/hashicorp/boundary/api/targets" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +const ( + targetHostSourceTargetIdKey = "target_id" + targetHostSourceIdKey = "host_source_id" + targetHostSourceDescription = "Attaches a host source to an existing Boundary target. " + + "Use this resource instead of the `host_source_ids` field on `boundary_target` " + + "when the target and its host sources are managed in separate Terraform configurations. " + + "Do not set `host_source_ids` on `boundary_target` when using this resource for the same target." +) + +func resourceTargetHostSource() *schema.Resource { + return &schema.Resource{ + Description: targetHostSourceDescription, + + CreateContext: resourceTargetHostSourceCreate, + ReadContext: resourceTargetHostSourceRead, + DeleteContext: resourceTargetHostSourceDelete, + + Importer: &schema.ResourceImporter{ + StateContext: schema.ImportStatePassthroughContext, + }, + + Schema: map[string]*schema.Schema{ + targetHostSourceTargetIdKey: { + Description: "The ID of the target to attach the host source to.", + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + targetHostSourceIdKey: { + Description: "The ID of the host source to attach to the target.", + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + }, + } +} + +func resourceTargetHostSourceCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + md := meta.(*metaData) + tc := targets.NewClient(md.client) + + targetId := d.Get(targetHostSourceTargetIdKey).(string) + hostSourceId := d.Get(targetHostSourceIdKey).(string) + + // Read the target to get its current host source list. + trr, err := tc.Read(ctx, targetId) + if err != nil { + return diag.Errorf("error reading target: %v", err) + } + if trr == nil { + return diag.Errorf("target nil after read") + } + + hostSourceExists := false + for _, id := range trr.Item.HostSourceIds { + if id == hostSourceId { + hostSourceExists = true + break + } + } + + if !hostSourceExists { + if _, err := tc.AddHostSources(ctx, targetId, 0, []string{hostSourceId}, targets.WithAutomaticVersioning(true)); err != nil { + return diag.Errorf("error adding host source to target: %v", err) + } + } + + d.SetId(fmt.Sprintf("%s:%s", hostSourceId, targetId)) + if err := d.Set(targetHostSourceTargetIdKey, targetId); err != nil { + return diag.FromErr(err) + } + if err := d.Set(targetHostSourceIdKey, hostSourceId); err != nil { + return diag.FromErr(err) + } + + return nil +} + +func resourceTargetHostSourceRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + md := meta.(*metaData) + tc := targets.NewClient(md.client) + + targetId, hostSourceId, err := targetAndHostSourceIdsFromResourceData(d) + if err != nil { + return diag.FromErr(err) + } + + trr, err := tc.Read(ctx, targetId) + if err != nil { + if apiErr := api.AsServerError(err); apiErr != nil && apiErr.Response().StatusCode() == http.StatusNotFound { + d.SetId("") + return nil + } + return diag.Errorf("error reading target: %v", err) + } + if trr == nil { + return diag.Errorf("target nil after read") + } + + // If this host source is no longer attached, remove from state. + for _, id := range trr.Item.HostSourceIds { + if id == hostSourceId { + if err := d.Set(targetHostSourceTargetIdKey, targetId); err != nil { + return diag.FromErr(err) + } + if err := d.Set(targetHostSourceIdKey, hostSourceId); err != nil { + return diag.FromErr(err) + } + return nil + } + } + + d.SetId("") + return nil +} + +func resourceTargetHostSourceDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + md := meta.(*metaData) + tc := targets.NewClient(md.client) + + targetId, hostSourceId, err := targetAndHostSourceIdsFromResourceData(d) + if err != nil { + return diag.FromErr(err) + } + + // Read the current list so we can remove just this one ID. + trr, err := tc.Read(ctx, targetId) + if err != nil { + if apiErr := api.AsServerError(err); apiErr != nil && apiErr.Response().StatusCode() == http.StatusNotFound { + return nil // target is already gone + } + return diag.Errorf("error reading target before detach: %v", err) + } + if trr == nil { + return nil + } + + found := false + for _, id := range trr.Item.HostSourceIds { + if id == hostSourceId { + found = true + } + } + if !found { + return nil // host source is already gone + } + + if _, err := tc.RemoveHostSources(ctx, targetId, 0, []string{hostSourceId}, targets.WithAutomaticVersioning(true)); err != nil { + return diag.Errorf("error removing host source from target: %v", err) + } + + return nil +} + +// targetAndHostSourceIdsFromResourceData returns the target ID and host source ID +// from either the resource attributes (normal CRUD) or the composite resource ID (import). +func targetAndHostSourceIdsFromResourceData(d *schema.ResourceData) (targetId, hostSourceId string, err error) { + if t, ok := d.GetOk(targetHostSourceTargetIdKey); ok { + targetId = t.(string) + } + if h, ok := d.GetOk(targetHostSourceIdKey); ok { + hostSourceId = h.(string) + } + if targetId != "" && hostSourceId != "" { + return targetId, hostSourceId, nil + } + + // Fall back to parsing the composite ID — this path is taken on import. + parts := strings.SplitN(d.Id(), ":", 2) + if len(parts) != 2 || parts[0] == "" || parts[1] == "" { + return "", "", fmt.Errorf("invalid resource ID %q: expected format :", d.Id()) + } + return parts[1], parts[0], nil +} diff --git a/internal/provider/resource_target_host_source_test.go b/internal/provider/resource_target_host_source_test.go new file mode 100644 index 00000000..4f7bd714 --- /dev/null +++ b/internal/provider/resource_target_host_source_test.go @@ -0,0 +1,223 @@ +// Copyright IBM Corp. 2020, 2026 +// SPDX-License-Identifier: MPL-2.0 + +package provider + +import ( + "context" + "fmt" + "net/http" + "testing" + + "github.com/hashicorp/boundary/api" + "github.com/hashicorp/boundary/api/targets" + "github.com/hashicorp/boundary/testing/controller" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" +) + +const fooTargetHostSourceTemplate = ` +resource "boundary_host_catalog" "foo" { + type = "static" + name = "test" + description = "test catalog" + scope_id = boundary_scope.proj1.id + depends_on = [boundary_role.proj1_admin] +} + +resource "boundary_host" "foo" { + name = "foo" + host_catalog_id = boundary_host_catalog.foo.id + type = "static" + address = "10.0.0.1" +} + +resource "boundary_host_set" "foo" { + name = "foo" + type = "static" + host_catalog_id = boundary_host_catalog.foo.id + host_ids = [ + boundary_host.foo.id, + ] +} + +resource "boundary_target" "foo" { + name = "test-target" + type = "tcp" + scope_id = boundary_scope.proj1.id + default_port = 22 + default_client_port = 1022 + depends_on = [boundary_role.proj1_admin] + lifecycle { + ignore_changes = [host_source_ids] + } +} + +%s +` + +const fooTargetHostSourceResource = `resource "boundary_target_host_source" "foo" { + target_id = boundary_target.foo.id + host_source_id = boundary_host_set.foo.id +} +` + +var ( + fooTargetHostSourceAttachment = fmt.Sprintf(fooTargetHostSourceTemplate, fooTargetHostSourceResource) + fooTargetHostSourceDetached = fmt.Sprintf(fooTargetHostSourceTemplate, "") +) + +func TestAccTargetHostSource(t *testing.T) { + tc := controller.NewTestController(t, tcConfig...) + t.Cleanup(tc.Shutdown) + + url := tc.ApiAddrs()[0] + suffix := id.UniqueId() + + var provider *schema.Provider + resource.Test(t, resource.TestCase{ + IsUnitTest: true, + ProviderFactories: providerFactories(&provider), + CheckDestroy: testAccCheckTargetHostSourceDestroy(t, provider), + Steps: []resource.TestStep{ + { + Config: testConfig(url, fooOrg(suffix), firstProjectFoo, fooTargetHostSourceAttachment), + Check: resource.ComposeTestCheckFunc( + testAccCheckTargetHostSourceExists(provider, "boundary_target_host_source.foo"), + resource.TestCheckResourceAttrSet("boundary_target_host_source.foo", targetHostSourceTargetIdKey), + resource.TestCheckResourceAttrSet("boundary_target_host_source.foo", targetHostSourceIdKey), + testAccCheckTargetHostSourceAttached(provider, "boundary_target.foo", "boundary_host_set.foo"), + ), + }, + importStep("boundary_target_host_source.foo"), + { + Config: testConfig(url, fooOrg(suffix), firstProjectFoo, fooTargetHostSourceDetached), + Check: resource.ComposeTestCheckFunc( + testAccCheckTargetResourceHostSource(provider, "boundary_target.foo", nil), + ), + }, + }, + }) +} + +func testAccCheckTargetHostSourceExists(testProvider *schema.Provider, name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[name] + if !ok { + return fmt.Errorf("target host source resource not found: %s", name) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("target host source resource ID is not set") + } + + targetID := rs.Primary.Attributes[targetHostSourceTargetIdKey] + hostSourceID := rs.Primary.Attributes[targetHostSourceIdKey] + if targetID == "" { + return fmt.Errorf("target_id is not set") + } + if hostSourceID == "" { + return fmt.Errorf("host_source_id is not set") + } + + md := testProvider.Meta().(*metaData) + targetClient := targets.NewClient(md.client) + + targetResource, err := targetClient.Read(context.Background(), targetID) + if err != nil { + return fmt.Errorf("error reading target %q: %v", targetID, err) + } + if targetResource == nil { + return fmt.Errorf("target %q nil after read", targetID) + } + + for _, id := range targetResource.Item.HostSourceIds { + if id == hostSourceID { + return nil + } + } + + return fmt.Errorf("host source %q not attached to target %q", hostSourceID, targetID) + } +} + +func testAccCheckTargetHostSourceAttached(testProvider *schema.Provider, targetName, hostSourceName string) resource.TestCheckFunc { + return func(s *terraform.State) error { + targetResource, ok := s.RootModule().Resources[targetName] + if !ok { + return fmt.Errorf("target resource not found: %s", targetName) + } + hostSourceResource, ok := s.RootModule().Resources[hostSourceName] + if !ok { + return fmt.Errorf("host source resource not found: %s", hostSourceName) + } + + targetID := targetResource.Primary.ID + hostSourceID := hostSourceResource.Primary.ID + if targetID == "" { + return fmt.Errorf("target resource ID is not set") + } + if hostSourceID == "" { + return fmt.Errorf("host source resource ID is not set") + } + + md := testProvider.Meta().(*metaData) + targetClient := targets.NewClient(md.client) + + targetResourceState, err := targetClient.Read(context.Background(), targetID) + if err != nil { + return fmt.Errorf("error reading target %q: %v", targetID, err) + } + if targetResourceState == nil { + return fmt.Errorf("target %q nil after read", targetID) + } + + for _, id := range targetResourceState.Item.HostSourceIds { + if id == hostSourceID { + return nil + } + } + + return fmt.Errorf("host source %q not attached to target %q", hostSourceID, targetID) + } +} + +func testAccCheckTargetHostSourceDestroy(t *testing.T, testProvider *schema.Provider) resource.TestCheckFunc { + return func(s *terraform.State) error { + for _, rs := range s.RootModule().Resources { + if rs.Type != "boundary_target_host_source" { + continue + } + + targetID := rs.Primary.Attributes[targetHostSourceTargetIdKey] + hostSourceID := rs.Primary.Attributes[targetHostSourceIdKey] + if targetID == "" || hostSourceID == "" { + continue + } + + md := testProvider.Meta().(*metaData) + targetClient := targets.NewClient(md.client) + + targetResource, err := targetClient.Read(context.Background(), targetID) + if err != nil { + if apiErr := api.AsServerError(err); apiErr != nil && apiErr.Response().StatusCode() == http.StatusNotFound { + continue + } + return fmt.Errorf("error reading target %q while checking destroy: %v", targetID, err) + } + if targetResource == nil { + continue + } + + for _, id := range targetResource.Item.HostSourceIds { + if id == hostSourceID { + return fmt.Errorf("host source %q still attached to target %q after destroy", hostSourceID, targetID) + } + } + } + + return nil + } +}