/
data_source_huaweicloud_vpc_subnet_ids.go
70 lines (55 loc) · 1.62 KB
/
data_source_huaweicloud_vpc_subnet_ids.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package vpc
import (
"context"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/chnsz/golangsdk/openstack/networking/v1/subnets"
"github.com/huaweicloud/terraform-provider-huaweicloud/huaweicloud/config"
)
// @API VPC GET /v1/{project_id}/subnets
func DataSourceVpcSubnetIdsV1() *schema.Resource {
return &schema.Resource{
ReadContext: dataSourceVpcSubnetIdsV1Read,
Schema: map[string]*schema.Schema{
"region": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Required: true,
},
"ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
}
}
func dataSourceVpcSubnetIdsV1Read(_ context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
config := meta.(*config.Config)
subnetClient, err := config.NetworkingV1Client(config.GetRegion(d))
if err != nil {
return diag.Errorf("error creating Vpc client: %s", err)
}
listOpts := subnets.ListOpts{
VPC_ID: d.Get("vpc_id").(string),
}
refinedSubnets, err := subnets.List(subnetClient, listOpts)
if err != nil {
return diag.Errorf("unable to retrieve subnets: %s", err)
}
if len(refinedSubnets) == 0 {
return diag.Errorf("no matching subnet found for vpc with id %s", d.Get("vpc_id").(string))
}
Subnets := make([]string, 0)
for _, subnet := range refinedSubnets {
Subnets = append(Subnets, subnet.ID)
}
d.SetId(d.Get("vpc_id").(string))
d.Set("ids", Subnets)
d.Set("region", config.GetRegion(d))
return nil
}