Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add dynamic data source #1103

Merged
merged 4 commits into from
Jun 11, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
113 changes: 113 additions & 0 deletions vsphere/data_source_vsphere_dynamic.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
package vsphere

import (
"context"
"fmt"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/vmware/govmomi/object"
"github.com/vmware/govmomi/vapi/tags"
"log"
"regexp"
)

func dataSourceVSphereDynamic() *schema.Resource {
return &schema.Resource{
Read: dataSourceVSphereDynamicRead,

Schema: map[string]*schema.Schema{
"filter": {
Type: schema.TypeSet,
Required: true,
Description: "List of tag IDs to match target.",
Elem: &schema.Schema{Type: schema.TypeString},
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
Description: "A regular expression used to match against managed object names.",
},
"type": {
Type: schema.TypeString,
Optional: true,
Description: "The type of managed object to return.",
},
},
}
}

func dataSourceVSphereDynamicRead(d *schema.ResourceData, meta interface{}) error {
log.Printf("[DEBUG] dataSourceDynamic: Beggining dynamic data source read.")
tm, err := meta.(*VSphereClient).TagsManager()
if err != nil {
return err
}
tagIds := d.Get("filter").(*schema.Set).List()
matches, err := filterObjectsByTag(tm, tagIds)
if err != nil {
return err
}
id, err := filterObjectsByName(d, meta, matches)
if err != nil {
return err
}
d.SetId(id)
log.Printf("[DEBUG] dataSourceDynamic: Read complete. Resource located: %s", id)
return nil
}

func filterObjectsByName(d *schema.ResourceData, meta interface{}, matches []tags.AttachedObjects) (string, error) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Doing a quick scan of this code. This function appears to return the first regex match. But because it is a regex, couldn't it match more than one object? Should the function collect all the matches and emit an error if more than one is matched?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It could. It was actually purposeful at first, but after your comment and talking to @koikonom, I realized it was a very bad idea. Thank you for bringing me to my senses!

log.Printf("[DEBUG] dataSourceDynamic: Filtering objects by name.")
re, err := regexp.Compile(d.Get("name_regex").(string))
if err != nil {
return "", err
}
for _, match := range matches[0].ObjectIDs {
mtype := d.Get("type").(string)
if mtype != "" && match.Reference().Type != mtype {
// Skip this object because the type does not match
continue
}
attachedObject := object.NewCommon(meta.(*VSphereClient).vimClient.Client, match.Reference())
name, err := attachedObject.ObjectName(context.TODO())
if err != nil {
return "", err
}
if re.Match([]byte(name)) {
log.Printf("[DEBUG] dataSourceDynamic: Match found: %s", name)
return match.Reference().Value, nil
}
}
return "", fmt.Errorf("no matching resources found")
}

func filterObjectsByTag(tm *tags.Manager, t []interface{}) ([]tags.AttachedObjects, error) {
log.Printf("[DEBUG] dataSourceDynamic: Filtering objects by tags.")
var tagIds []string
for _, ti := range t {
tagIds = append(tagIds, ti.(string))
}
matches, err := tm.GetAttachedObjectsOnTags(context.TODO(), tagIds)
if err != nil {
return nil, err
}
for _, match := range matches {
matches[0] = attachedObjectsIntersection(matches[0], match)
}
if len(matches[0].ObjectIDs) < 1 {
return nil, fmt.Errorf("no resources match filter")
}
log.Printf("[DEBUG] dataSourceDynamic: Objects filtered.")
return matches, nil
}

func attachedObjectsIntersection(a, b tags.AttachedObjects) tags.AttachedObjects {
var inter tags.AttachedObjects
for _, aval := range a.ObjectIDs {
for _, bval := range b.ObjectIDs {
if aval == bval {
inter.ObjectIDs = append(inter.ObjectIDs, aval)
}
}
}
return inter
}
269 changes: 269 additions & 0 deletions vsphere/data_source_vsphere_dynamic_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,269 @@
package vsphere

import (
"fmt"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/terraform"
"regexp"
"testing"
)

func TestAccDataSourceVSphereDynamic_regexAndTag(t *testing.T) {
t.Cleanup(RunSweepers)
resource.Test(t, resource.TestCase{
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccDataSourceVSphereDynamicConfigBase(),
},
{
Config: testAccDataSourceVSphereDynamicConfig(),
Check: resource.ComposeTestCheckFunc(
testMatchDatacenterIds("vsphere_datacenter.dc2", "data.vsphere_dynamic.dyn1"),
),
},
{
Config: testAccDataSourceVSphereDynamicConfigBase(),
},
},
})
}

func TestAccDataSourceVSphereDynamic_multiTag(t *testing.T) {
t.Cleanup(RunSweepers)
resource.Test(t, resource.TestCase{
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccDataSourceVSphereDynamicConfigBase(),
},
{
Config: testAccDataSourceVSphereDynamicConfig(),
Check: resource.ComposeTestCheckFunc(
testMatchDatacenterIds("vsphere_datacenter.dc1", "data.vsphere_dynamic.dyn2"),
),
},
{
Config: testAccDataSourceVSphereDynamicConfigBase(),
},
},
})
}

func TestAccDataSourceVSphereDynamic_multiResult(t *testing.T) {
t.Cleanup(RunSweepers)
resource.Test(t, resource.TestCase{
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccDataSourceVSphereDynamicConfigBase(),
},
{
Config: testAccDataSourceVSphereDynamicConfig(),
Check: resource.ComposeTestCheckFunc(
resource.TestMatchResourceAttr("data.vsphere_dynamic.dyn3", "id", regexp.MustCompile("datacenter-")),
),
},
{
Config: testAccDataSourceVSphereDynamicConfigBase(),
},
},
})
}

func TestAccDataSourceVSphereDynamic_sameTagNames(t *testing.T) {
t.Cleanup(RunSweepers)
resource.Test(t, resource.TestCase{
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccDataSourceVSphereDynamicConfigBase(),
},
{
Config: testAccDataSourceVSphereDynamicConfig(),
Check: resource.ComposeTestCheckFunc(
testMatchDatacenterIds("vsphere_datacenter.dc2", "data.vsphere_dynamic.dyn4"),
),
},
{
Config: testAccDataSourceVSphereDynamicConfigBase(),
},
},
})
}

func TestAccDataSourceVSphereDynamic_typeFilter(t *testing.T) {
t.Cleanup(RunSweepers)
resource.Test(t, resource.TestCase{
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccDataSourceVSphereDynamicConfigBase(),
},
{
Config: testAccDataSourceVSphereDynamicConfig(),
Check: resource.ComposeTestCheckFunc(
testMatchDatacenterIds("vsphere_datacenter.dc1", "data.vsphere_dynamic.dyn5"),
),
},
{
Config: testAccDataSourceVSphereDynamicConfigBase(),
},
},
})
}

func testMatchDatacenterIds(a, b string) resource.TestCheckFunc {
return func(s *terraform.State) error {
ida := s.RootModule().Resources[a].Primary.Attributes["moid"]
idb := s.RootModule().Resources[b].Primary.ID
if ida != idb {
return fmt.Errorf("unexpected ID. Expected: %s, Got: %s", idb, ida)
}
return nil
}
}

func init() {
resource.AddTestSweepers("tags", &resource.Sweeper{
Name: "tag_cleanup",
Dependencies: nil,
F: tagSweep,
})
resource.AddTestSweepers("datacenters", &resource.Sweeper{
Name: "datacenter_cleanup",
Dependencies: nil,
F: dcSweep,
})
}

func testAccDataSourceVSphereDynamicConfigBase() string {
return fmt.Sprintf(`
resource "vsphere_datacenter" "dc1" {
name = "testdc1"
tags = [vsphere_tag.tag1.id, vsphere_tag.tag2.id]
}

resource "vsphere_datacenter" "dc2" {
name = "testdc2"
tags = [ vsphere_tag.tag1.id, vsphere_tag.tag3.id ]
}

resource "vsphere_tag_category" "category1" {
name = "cat1"
description = "cat1"
cardinality = "MULTIPLE"

associable_types = [
"Datacenter"
]
}

resource "vsphere_tag_category" "category2" {
name = "cat2"
description = "cat2"
cardinality = "MULTIPLE"

associable_types = [
"Datacenter"
]
}

resource "vsphere_tag" "tag1" {
name = "tag1"
category_id = vsphere_tag_category.category1.id
}

resource "vsphere_tag" "tag2" {
name = "tag2"
category_id = vsphere_tag_category.category2.id
}

resource "vsphere_tag" "tag3" {
name = "tag2"
category_id = vsphere_tag_category.category1.id
}`)
}

func testAccDataSourceVSphereDynamicConfig() string {
return fmt.Sprintf(`
resource "vsphere_datacenter" "dc1" {
name = "testdc1"
tags = [vsphere_tag.tag1.id, vsphere_tag.tag2.id]
}

resource "vsphere_datacenter" "dc2" {
name = "testdc2"
tags = [ vsphere_tag.tag1.id, vsphere_tag.tag3.id ]
}

resource "vsphere_tag_category" "category1" {
name = "cat1"
description = "cat1"
cardinality = "MULTIPLE"

associable_types = [
"Datacenter"
]
}

resource "vsphere_tag_category" "category2" {
name = "cat2"
description = "cat2"
cardinality = "MULTIPLE"

associable_types = [
"Datacenter"
]
}

resource "vsphere_tag" "tag1" {
name = "tag1"
category_id = vsphere_tag_category.category1.id
}

resource "vsphere_tag" "tag2" {
name = "tag2"
category_id = vsphere_tag_category.category2.id
}

resource "vsphere_tag" "tag3" {
name = "tag2"
category_id = vsphere_tag_category.category1.id
}

data "vsphere_dynamic" "dyn1" {
filter = [ vsphere_tag.tag1.id ]
name_regex = "dc2"
}

data "vsphere_dynamic" "dyn2" {
filter = [ vsphere_tag.tag1.id, vsphere_tag.tag2.id ]
name_regex = ""
}

data "vsphere_dynamic" "dyn3" {
filter = [ vsphere_tag.tag1.id ]
name_regex = ""
}

data "vsphere_dynamic" "dyn4" {
filter = [ vsphere_tag.tag3.id ]
name_regex = ""
}

data "vsphere_dynamic" "dyn5" {
filter = [ vsphere_tag.tag1.id, vsphere_tag.tag2.id ]
name_regex = ""
type = "Datacenter"
}

data "vsphere_datacenter" "dc1" {
name = vsphere_datacenter.dc1.name
}

data "vsphere_datacenter" "dc2" {
name = vsphere_datacenter.dc2.name
}
`)
}
Loading