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 Compute Flavors Data source support #609

Merged
merged 2 commits into from
Oct 28, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
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
44 changes: 44 additions & 0 deletions docs/data-sources/compute_flavors.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
---
subcategory: "Elastic Cloud Server (ECS)"
---

# huaweicloud\_compute\_flavors

Use this data source to get the ID of the available Compute Flavors.

## Example Usage

```hcl
data "huaweicloud_compute_flavors" "flavors" {
performance_type = "normal"
cpu_core_count = 2
memory_size = 4096
}

# Create ECS instance with the first matched flavor

resource "huaweicloud_compute_instance" "instance" {
flavor_id = data.huaweicloud_compute_flavors.flavors.ids[0]

# Other properties...
}
```

## Argument Reference

* `availability_zone` - (Optional) Specifies the AZ name.

* `performance_type` - (Optional) Specifies the ECS flavor type.

* `generation` - (Optional) Specifies the generation of an ECS type.

* `cpu_core_count` - (Optional) Specifies the number of vCPUs in the ECS flavor.

* `memory_size` - (Optional) Specifies the memory size(MB) in the ECS flavor.


## Attributes Reference

`id` is set to the ID of the found flavors. In addition, the following attributes are exported:

* `ids` - A list of flavor IDs.
107 changes: 107 additions & 0 deletions huaweicloud/data_source_huaweicloud_compute_flavors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
package huaweicloud

import (
"fmt"
"strconv"

"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/huaweicloud/golangsdk/openstack/ecs/v1/flavors"
)

func DataSourceEcsFlavors() *schema.Resource {
return &schema.Resource{
Read: dataSourceEcsFlavorsRead,

Schema: map[string]*schema.Schema{
"availability_zone": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"performance_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"generation": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"cpu_core_count": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
},
"memory_size": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
}
}

func dataSourceEcsFlavorsRead(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
ecsClient, err := config.computeV1Client(GetRegion(d, config))
if err != nil {
return fmt.Errorf("Error creating HuaweiCloud ECS client: %s", err)
}

listOpts := &flavors.ListOpts{
AvailabilityZone: d.Get("availability_zone").(string),
}

pages, err := flavors.List(ecsClient, listOpts).AllPages()
if err != nil {
return err
}

allFlavors, err := flavors.ExtractFlavors(pages)
if err != nil {
return fmt.Errorf("Unable to retrieve flavors: %s ", err)
}

cpu := d.Get("cpu_core_count").(int)
mem := int64(d.Get("memory_size").(int))
pType := d.Get("performance_type").(string)
gen := d.Get("generation").(string)

var ids []string
for _, flavor := range allFlavors {
vCpu, _ := strconv.Atoi(flavor.Vcpus)
if cpu > 0 && vCpu != cpu {
continue
}

if mem > 0 && flavor.Ram != mem {
continue
}

if pType != "" && flavor.OsExtraSpecs.PerformanceType != pType {
continue
}

if gen != "" && flavor.OsExtraSpecs.Generation != gen {
continue
}

ids = append(ids, flavor.ID)
}

if len(ids) < 1 {
return fmt.Errorf("Your query returned no results. " +
"Please change your search criteria and try again.")
}

d.SetId(dataResourceIdHash(ids))
d.Set("ids", ids)

return nil
}
47 changes: 47 additions & 0 deletions huaweicloud/data_source_huaweicloud_compute_flavors_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package huaweicloud

import (
"fmt"
"testing"

"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/terraform"
)

func TestAccEcsFlavorsDataSource_basic(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccEcsFlavorsDataSource_basic,
Check: resource.ComposeTestCheckFunc(
testAccCheckEcsFlavorDataSourceID("data.huaweicloud_compute_flavors.this"),
),
},
},
})
}

func testAccCheckEcsFlavorDataSourceID(n string) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("Can't find compute flavors data source: %s", n)
}

if rs.Primary.ID == "" {
return fmt.Errorf("Compute Flavors data source ID not set")
}

return nil
}
}

const testAccEcsFlavorsDataSource_basic = `
data "huaweicloud_compute_flavors" "this" {
performance_type = "normal"
cpu_core_count = 2
memory_size = 4096
}
`
1 change: 1 addition & 0 deletions huaweicloud/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,7 @@ func Provider() terraform.ResourceProvider {
"huaweicloud_cce_cluster": dataSourceCCEClusterV3(),
"huaweicloud_cce_node": dataSourceCCENodeV3(),
"huaweicloud_cdm_flavors": dataSourceCdmFlavorV1(),
"huaweicloud_compute_flavors": DataSourceEcsFlavors(),
"huaweicloud_csbs_backup": dataSourceCSBSBackupV1(),
"huaweicloud_csbs_backup_policy": dataSourceCSBSBackupPolicyV1(),
"huaweicloud_cts_tracker": dataSourceCTSTrackerV1(),
Expand Down
12 changes: 12 additions & 0 deletions huaweicloud/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"strings"
"time"

"github.com/hashicorp/terraform-plugin-sdk/helper/hashcode"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/huaweicloud/golangsdk"
Expand Down Expand Up @@ -185,3 +186,14 @@ func jsonMarshal(t interface{}) ([]byte, error) {
err := enc.Encode(t)
return buffer.Bytes(), err
}

// Generates a hash for the set hash function used by the ID
func dataResourceIdHash(ids []string) string {
var buf bytes.Buffer

for _, id := range ids {
buf.WriteString(fmt.Sprintf("%s-", id))
}

return fmt.Sprintf("%d", hashcode.String(buf.String()))
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading