Skip to content

Commit

Permalink
Merge pull request #100 from yannickstruyf3/feature/cluster_datasourc…
Browse files Browse the repository at this point in the history
…e_name

Feature/cluster datasource name
  • Loading branch information
marinsalinas authored Mar 19, 2020
2 parents b69bc49 + a324e1a commit daa37e6
Show file tree
Hide file tree
Showing 4 changed files with 259 additions and 17 deletions.
79 changes: 63 additions & 16 deletions nutanix/data_source_nutanix_cluster.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,20 @@ import (
"fmt"
"strconv"

"github.com/terraform-providers/terraform-provider-nutanix/utils"

"github.com/hashicorp/terraform/helper/schema"
v3 "github.com/terraform-providers/terraform-provider-nutanix/client/v3"
"github.com/terraform-providers/terraform-provider-nutanix/utils"
)

func dataSourceNutanixCluster() *schema.Resource {
return &schema.Resource{
Read: dataSourceNutanixClusterRead,
Schema: map[string]*schema.Schema{
"cluster_id": {
Type: schema.TypeString,
Required: true,
Type: schema.TypeString,
Computed: true,
Optional: true,
ConflictsWith: []string{"name"},
},
"metadata": {
Type: schema.TypeMap,
Expand Down Expand Up @@ -99,8 +101,10 @@ func dataSourceNutanixCluster() *schema.Resource {
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
Type: schema.TypeString,
Optional: true,
Computed: true,
ConflictsWith: []string{"cluster_id"},
},

// COMPUTED
Expand Down Expand Up @@ -589,15 +593,23 @@ func dataSourceNutanixClusterRead(d *schema.ResourceData, meta interface{}) erro
conn := meta.(*Client).API

c, ok := d.GetOk("cluster_id")

if !ok {
return fmt.Errorf("please provide the cluster_id attribute")
}

// Make request to the API
v, err := conn.V3.GetCluster(c.(string))
if err != nil {
return err
var v *v3.ClusterIntentResponse
var err error
if ok {
// Make request to the API
v, err = conn.V3.GetCluster(c.(string))
if err != nil {
return err
}
} else {
n, ok := d.GetOk("name")
if !ok {
return fmt.Errorf("please provide the cluster_id or name attribute")
}
v, err = findClusterByName(conn, n.(string))
if err != nil {
return err
}
}

m, c := setRSEntityMetadata(v.Metadata)
Expand Down Expand Up @@ -1030,7 +1042,42 @@ func dataSourceNutanixClusterRead(d *schema.ResourceData, meta interface{}) erro
return err
}

d.SetId(utils.StringValue(v.Metadata.UUID))
cUUID := utils.StringValue(v.Metadata.UUID)
if err := d.Set("cluster_id", cUUID); err != nil {
return err
}

d.SetId(cUUID)
return nil
}

func findClusterByName(conn *v3.Client, name string) (*v3.ClusterIntentResponse, error) {
clusterEntitiesMetadata := &v3.DSMetadata{}
resp, err := conn.V3.ListCluster(clusterEntitiesMetadata)
if err != nil {
return nil, err
}
entities := resp.Entities

found := make([]*v3.ClusterIntentResponse, 0)
for _, v := range entities {
if *v.Status.Name == name {
found = append(found, &v3.ClusterIntentResponse{
Status: v.Status,
Spec: v.Spec,
Metadata: v.Metadata,
APIVersion: v.APIVersion,
})
}
}

if len(found) > 1 {
return nil, fmt.Errorf("your query returned more than one result. Please use cluster_id argument instead")
}

if len(found) == 0 {
return nil, fmt.Errorf("did not find cluster with name %s", name)
}

return found[0], nil
}
74 changes: 73 additions & 1 deletion nutanix/data_source_nutanix_cluster_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package nutanix

import (
"regexp"
"testing"

"github.com/hashicorp/terraform/helper/resource"
Expand All @@ -22,10 +23,81 @@ func TestAccNutanixClusterDataSource_basic(t *testing.T) {
})
}

func TestAccNutanixClusterDataSource_ByName(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccClusterDataSourceConfigByName,
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttrSet(
"data.nutanix_cluster.cluster", "id"),
resource.TestCheckResourceAttrSet(
"data.nutanix_cluster.cluster", "name"),
resource.TestCheckResourceAttrSet(
"data.nutanix_cluster.cluster", "cluster_id"),
),
},
},
})
}

func TestAccNutanixClusterDataSource_ByNameNotExisting(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccClusterDataSourceConfigByNameNotExisting,
ExpectError: regexp.MustCompile("did not find cluster with name *"),
},
},
})
}

func TestAccNutanixClusterDataSource_NameUuidConflict(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccClusterDataSourceConfigNameUUIDConflict,
ExpectError: regexp.MustCompile(" * conflicts with *"),
},
},
})
}

const testAccClusterDataSourceConfig = `
data "nutanix_clusters" "clusters" {}
data "nutanix_cluster" "cluster" {
cluster_id = data.nutanix_clusters.clusters.entities.1.metadata.uuid
cluster_id = data.nutanix_clusters.clusters.entities.0.metadata.uuid
}`

const testAccClusterDataSourceConfigByName = `
data "nutanix_clusters" "clusters" {}
data "nutanix_cluster" "cluster" {
name = data.nutanix_clusters.clusters.entities.0.name
}`

const testAccClusterDataSourceConfigByNameNotExisting = `
data "nutanix_clusters" "clusters" {}
data "nutanix_cluster" "cluster" {
name = "ThisDoesNotExist"
}`

const testAccClusterDataSourceConfigNameUUIDConflict = `
data "nutanix_clusters" "clusters" {}
data "nutanix_cluster" "cluster" {
cluster_id = data.nutanix_clusters.clusters.entities.0.metadata.uuid
name = data.nutanix_clusters.clusters.entities.0.name
}`
25 changes: 25 additions & 0 deletions nutanix/resource_nutanix_virtual_machine.go
Original file line number Diff line number Diff line change
Expand Up @@ -1182,9 +1182,20 @@ func resourceNutanixVirtualMachineUpdate(d *schema.ResourceData, meta interface{
}

if d.HasChange("disk_list") {
preCdromCount, err := CountDiskListCdrom(res.DiskList)
if err != nil {
return err
}
if res.DiskList, err = expandDiskList(d, false); err != nil {
return err
}
postCdromCount, err := CountDiskListCdrom(res.DiskList)
if err != nil {
return err
}
if preCdromCount != postCdromCount {
hotPlugChange = false
}
}

if d.HasChange("serial_port_list") {
Expand Down Expand Up @@ -1546,6 +1557,10 @@ func getVMResources(d *schema.ResourceData, vm *v3.VMResources) error {
vm.VgaConsoleEnabled = utils.BoolPtr(v.(bool))
}
if v, ok := d.GetOk("power_state_mechanism"); ok {
if vm.PowerStateMechanism == nil {
log.Printf("m.PowerStateMechanism was nil, setting correct value!")
vm.PowerStateMechanism = &v3.VMPowerStateMechanism{}
}
vm.PowerStateMechanism.Mechanism = utils.StringPtr(v.(string))
}
if v, ok := d.GetOk("should_fail_on_script_failure"); ok {
Expand Down Expand Up @@ -1913,3 +1928,13 @@ func waitForIPRefreshFunc(client *v3.Client, vmUUID string) resource.StateRefres
return resp, WAITING, nil
}
}

func CountDiskListCdrom(dl []*v3.VMDisk) (int, error) {
counter := 0
for _, v := range dl {
if *v.DeviceProperties.DeviceType == "CDROM" {
counter++
}
}
return counter, nil
}
98 changes: 98 additions & 0 deletions nutanix/resource_nutanix_virtual_machine_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,62 @@ func TestAccNutanixVirtualMachine_WithSerialPortList(t *testing.T) {
})
}

func TestAccNutanixVirtualMachine_PowerStateMechanism(t *testing.T) {
r := acctest.RandInt()
resourceName := "nutanix_virtual_machine.vm6"
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckNutanixVirtualMachineDestroy,
Steps: []resource.TestStep{
{
Config: testAccNutanixVMConfigPowerStateMechanism(r),
Check: resource.ComposeTestCheckFunc(
testAccCheckNutanixVirtualMachineExists(resourceName),
resource.TestCheckResourceAttr(resourceName, "power_state_mechanism", "ACPI"),
),
},
{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
ImportStateVerifyIgnore: []string{"disk_list"},
},
},
})
}

func TestAccNutanixVirtualMachine_CdromGuestCustomisationReboot(t *testing.T) {
r := acctest.RandInt()
resourceName := "nutanix_virtual_machine.vm7"
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckNutanixVirtualMachineDestroy,
Steps: []resource.TestStep{
{
Config: testAccNutanixVMConfigCdromGuestCustomisationReboot(r),
Check: resource.ComposeTestCheckFunc(
testAccCheckNutanixVirtualMachineExists(resourceName),
),
ExpectNonEmptyPlan: true,
},
{
Config: testAccNutanixVMConfigCdromGuestCustomisationReboot(r),
Check: resource.ComposeTestCheckFunc(
testAccCheckNutanixVirtualMachineExists(resourceName),
),
},
{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
ImportStateVerifyIgnore: []string{"disk_list"},
},
},
})
}

func testAccCheckNutanixVirtualMachineExists(n string) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
Expand Down Expand Up @@ -531,3 +587,45 @@ resource "nutanix_virtual_machine" "vm5" {
}
`, r)
}

func testAccNutanixVMConfigPowerStateMechanism(r int) string {
return fmt.Sprintf(`
data "nutanix_clusters" "clusters" {}
locals {
cluster1 = "${data.nutanix_clusters.clusters.entities.0.service_list.0 == "PRISM_CENTRAL"
? data.nutanix_clusters.clusters.entities.1.metadata.uuid : data.nutanix_clusters.clusters.entities.0.metadata.uuid}"
}
resource "nutanix_virtual_machine" "vm6" {
name = "test-dou-%d"
cluster_uuid = "${local.cluster1}"
num_vcpus_per_socket = 1
num_sockets = 1
memory_size_mib = 186
power_state_mechanism = "ACPI"
}
`, r)
}

func testAccNutanixVMConfigCdromGuestCustomisationReboot(r int) string {
return fmt.Sprintf(`
data "nutanix_clusters" "clusters" {}
locals {
cluster1 = "${data.nutanix_clusters.clusters.entities.0.service_list.0 == "PRISM_CENTRAL"
? data.nutanix_clusters.clusters.entities.1.metadata.uuid : data.nutanix_clusters.clusters.entities.0.metadata.uuid}"
}
resource "nutanix_virtual_machine" "vm7" {
name = "test-dou-%d"
cluster_uuid = "${local.cluster1}"
num_vcpus_per_socket = 1
num_sockets = 1
memory_size_mib = 186
guest_customization_cloud_init_user_data = base64encode("#cloud-config\nfqdn: test.domain.local")
}
`, r)
}

0 comments on commit daa37e6

Please sign in to comment.