Skip to content

Commit a639325

Browse files
Add compute_machine_types datasource (#9819) (#17107)
* Add compute_machine_types datasource * Add documentation for compute_machine_types datasource [upstream:7a789b657e3de8471a629c449d043255980bbc3f] Signed-off-by: Modular Magician <[email protected]>
1 parent dacf3f9 commit a639325

File tree

5 files changed

+408
-0
lines changed

5 files changed

+408
-0
lines changed

.changelog/9819.txt

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
```release-note:new-datasource
2+
`google_compute_machine_types`
3+
```

google/provider/provider_mmv1_resources.go

+1
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,7 @@ var handwrittenDatasources = map[string]*schema.Resource{
172172
"google_compute_instance_serial_port": compute.DataSourceGoogleComputeInstanceSerialPort(),
173173
"google_compute_instance_template": compute.DataSourceGoogleComputeInstanceTemplate(),
174174
"google_compute_lb_ip_ranges": compute.DataSourceGoogleComputeLbIpRanges(),
175+
"google_compute_machine_types": compute.DataSourceGoogleComputeMachineTypes(),
175176
"google_compute_network": compute.DataSourceGoogleComputeNetwork(),
176177
"google_compute_networks": compute.DataSourceGoogleComputeNetworks(),
177178
"google_compute_network_endpoint_group": compute.DataSourceGoogleComputeNetworkEndpointGroup(),
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,214 @@
1+
// Copyright (c) HashiCorp, Inc.
2+
// SPDX-License-Identifier: MPL-2.0
3+
package compute
4+
5+
import (
6+
"context"
7+
"fmt"
8+
9+
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
10+
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
11+
"github.com/hashicorp/terraform-provider-google/google/tpgresource"
12+
transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport"
13+
"google.golang.org/api/compute/v1"
14+
)
15+
16+
func DataSourceGoogleComputeMachineTypes() *schema.Resource {
17+
return &schema.Resource{
18+
ReadContext: dataSourceGoogleComputeMachineTypesRead,
19+
20+
Schema: map[string]*schema.Schema{
21+
"filter": {
22+
Type: schema.TypeString,
23+
Optional: true,
24+
},
25+
26+
"machine_types": {
27+
Type: schema.TypeList,
28+
Computed: true,
29+
Description: `The list of machine types`,
30+
Elem: &schema.Resource{
31+
Schema: map[string]*schema.Schema{
32+
"name": {
33+
Type: schema.TypeString,
34+
Computed: true,
35+
Description: `The name of the machine type.`,
36+
},
37+
"guest_cpus": {
38+
Type: schema.TypeInt,
39+
Computed: true,
40+
Description: `The number of virtual CPUs that are available to the instance.`,
41+
},
42+
"memory_mb": {
43+
Type: schema.TypeInt,
44+
Computed: true,
45+
Description: `The amount of physical memory available to the instance, defined in MB.`,
46+
},
47+
"deprecated": {
48+
Type: schema.TypeSet,
49+
Computed: true,
50+
Description: `The deprecation status associated with this machine type. Only applicable if the machine type is unavailable.`,
51+
Elem: &schema.Resource{
52+
Schema: map[string]*schema.Schema{
53+
"replacement": {
54+
Type: schema.TypeString,
55+
Computed: true,
56+
Description: `The URL of the suggested replacement for a deprecated machine type.`,
57+
},
58+
"state": {
59+
Type: schema.TypeString,
60+
Computed: true,
61+
Description: `The deprecation state of this resource. This can be ACTIVE, DEPRECATED, OBSOLETE, or DELETED.`,
62+
},
63+
},
64+
},
65+
},
66+
"maximum_persistent_disks": {
67+
Type: schema.TypeInt,
68+
Computed: true,
69+
Description: `The maximum persistent disks allowed.`,
70+
},
71+
"maximum_persistent_disks_size_gb": {
72+
Type: schema.TypeInt,
73+
Computed: true,
74+
Description: `The maximum total persistent disks size (GB) allowed.`,
75+
},
76+
"description": {
77+
Type: schema.TypeString,
78+
Computed: true,
79+
Description: `A textual description of the machine type.`,
80+
},
81+
"is_shared_cpus": {
82+
Type: schema.TypeBool,
83+
Computed: true,
84+
Description: `Whether this machine type has a shared CPU.`,
85+
},
86+
"accelerators": {
87+
Type: schema.TypeList,
88+
Computed: true,
89+
Description: `A list of accelerator configurations assigned to this machine type.`,
90+
Elem: &schema.Resource{
91+
Schema: map[string]*schema.Schema{
92+
"guest_accelerator_type": {
93+
Type: schema.TypeString,
94+
Computed: true,
95+
Description: `The accelerator type resource name, not a full URL, e.g. nvidia-tesla-t4.`,
96+
},
97+
"guest_accelerator_count": {
98+
Type: schema.TypeInt,
99+
Computed: true,
100+
Description: `Number of accelerator cards exposed to the guest.`,
101+
},
102+
},
103+
},
104+
},
105+
"self_link": {
106+
Type: schema.TypeString,
107+
Computed: true,
108+
Description: `The server-defined URL for the machine type.`,
109+
},
110+
},
111+
},
112+
},
113+
"zone": {
114+
Type: schema.TypeString,
115+
Computed: true,
116+
Description: `The name of the zone for this request.`,
117+
Optional: true,
118+
},
119+
120+
"project": {
121+
Type: schema.TypeString,
122+
Computed: true,
123+
Description: `Project ID for this request.`,
124+
Optional: true,
125+
},
126+
},
127+
}
128+
}
129+
130+
func dataSourceGoogleComputeMachineTypesRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
131+
config := meta.(*transport_tpg.Config)
132+
userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent)
133+
if err != nil {
134+
return diag.FromErr(err)
135+
}
136+
137+
project, err := tpgresource.GetProject(d, config)
138+
if err != nil {
139+
return diag.FromErr(err)
140+
}
141+
142+
filter := d.Get("filter").(string)
143+
zone := d.Get("zone").(string)
144+
145+
machineTypes := make([]map[string]interface{}, 0)
146+
token := ""
147+
148+
for paginate := true; paginate; {
149+
resp, err := config.NewComputeClient(userAgent).MachineTypes.List(project, zone).Context(ctx).Filter(filter).PageToken(token).Do()
150+
if err != nil {
151+
return diag.FromErr(fmt.Errorf("Error retrieving machine types: %w", err))
152+
153+
}
154+
pageMachineTypes := flattenDatasourceGoogleComputeMachineTypesList(ctx, resp.Items)
155+
machineTypes = append(machineTypes, pageMachineTypes...)
156+
157+
token = resp.NextPageToken
158+
paginate = token != ""
159+
}
160+
161+
if err := d.Set("machine_types", machineTypes); err != nil {
162+
return diag.FromErr(fmt.Errorf("Error setting machine_types: %w", err))
163+
}
164+
165+
if err := d.Set("project", project); err != nil {
166+
return diag.FromErr(fmt.Errorf("Error setting project: %w", err))
167+
}
168+
if err := d.Set("zone", zone); err != nil {
169+
return diag.FromErr(fmt.Errorf("Error setting zone: %w", err))
170+
}
171+
172+
id := fmt.Sprintf("projects/%s/zones/%s/machineTypes/filters/%s", project, zone, filter)
173+
d.SetId(id)
174+
175+
return diag.Diagnostics{}
176+
}
177+
178+
func flattenDatasourceGoogleComputeMachineTypesList(ctx context.Context, v []*compute.MachineType) []map[string]interface{} {
179+
if v == nil {
180+
return make([]map[string]interface{}, 0)
181+
}
182+
183+
machineTypes := make([]map[string]interface{}, 0, len(v))
184+
for _, mt := range v {
185+
accelerators := make([]map[string]interface{}, len(mt.Accelerators))
186+
for i, a := range mt.Accelerators {
187+
accelerators[i] = map[string]interface{}{
188+
"guest_accelerator_type": a.GuestAcceleratorType,
189+
"guest_accelerator_count": a.GuestAcceleratorCount,
190+
}
191+
}
192+
machineType := map[string]interface{}{
193+
"name": mt.Name,
194+
"guest_cpus": mt.GuestCpus,
195+
"memory_mb": mt.MemoryMb,
196+
"maximum_persistent_disks": mt.MaximumPersistentDisks,
197+
"maximum_persistent_disks_size_gb": mt.MaximumPersistentDisksSizeGb,
198+
"description": mt.Description,
199+
"is_shared_cpus": mt.IsSharedCpu,
200+
"accelerators": accelerators,
201+
"self_link": mt.SelfLink,
202+
}
203+
if dep := mt.Deprecated; dep != nil {
204+
d := map[string]interface{}{
205+
"replacement": dep.Replacement,
206+
"state": dep.State,
207+
}
208+
machineType["deprecated"] = []map[string]interface{}{d}
209+
}
210+
machineTypes = append(machineTypes, machineType)
211+
}
212+
213+
return machineTypes
214+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// Copyright (c) HashiCorp, Inc.
2+
// SPDX-License-Identifier: MPL-2.0
3+
// Copyright (c) HashiCorp, Inc.
4+
// SPDX-License-Identifier: MPL-2.0
5+
package compute_test
6+
7+
import (
8+
"regexp"
9+
"testing"
10+
11+
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
12+
"github.com/hashicorp/terraform-provider-google/google/acctest"
13+
)
14+
15+
func TestAccDataSourceGoogleComputeMachineTypes_basic(t *testing.T) {
16+
t.Parallel()
17+
18+
acctest.VcrTest(t, resource.TestCase{
19+
PreCheck: func() { acctest.AccTestPreCheck(t) },
20+
ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t),
21+
Steps: []resource.TestStep{
22+
{
23+
Config: testAccComputeMachineTypes,
24+
Check: resource.ComposeTestCheckFunc(
25+
// We can't guarantee machine type availability in a given project and zone, so we'll check set-ness rather than correctness
26+
resource.TestMatchResourceAttr("data.google_compute_machine_types.test", "machine_types.0.name", regexp.MustCompile(`^[a-z0-9-]+$`)),
27+
resource.TestMatchResourceAttr("data.google_compute_machine_types.test", "machine_types.0.guest_cpus", regexp.MustCompile(`^\d+$`)),
28+
resource.TestMatchResourceAttr("data.google_compute_machine_types.test", "machine_types.0.memory_mb", regexp.MustCompile(`^\d+$`)),
29+
resource.TestMatchResourceAttr("data.google_compute_machine_types.test", "machine_types.0.maximum_persistent_disks", regexp.MustCompile(`^\d+$`)),
30+
resource.TestMatchResourceAttr("data.google_compute_machine_types.test", "machine_types.0.maximum_persistent_disks_size_gb", regexp.MustCompile(`^\d+$`)),
31+
resource.TestMatchResourceAttr("data.google_compute_machine_types.test", "machine_types.0.description", regexp.MustCompile(`.+`)),
32+
resource.TestMatchResourceAttr("data.google_compute_machine_types.test", "machine_types.0.is_shared_cpus", regexp.MustCompile(`^true|false$`)),
33+
resource.TestMatchResourceAttr("data.google_compute_machine_types.test", "machine_types.0.self_link", regexp.MustCompile(`.+`)),
34+
),
35+
},
36+
},
37+
})
38+
}
39+
40+
const testAccComputeMachineTypes = `
41+
data "google_compute_zones" "available" {}
42+
43+
data "google_compute_machine_types" "test" {
44+
filter = "guest_cpus > 0"
45+
zone = data.google_compute_zones.available.names[0]
46+
}
47+
`

0 commit comments

Comments
 (0)