-
Notifications
You must be signed in to change notification settings - Fork 453
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
Add dynamic data source #1103
Changes from 1 commit
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) { | ||
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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} | ||
`) | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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!