-
Notifications
You must be signed in to change notification settings - Fork 7
/
resource_hcs_nat_gateway.go
298 lines (271 loc) · 9.17 KB
/
resource_hcs_nat_gateway.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
package nat
import (
"context"
"fmt"
"log"
"regexp"
"time"
"github.com/hashicorp/go-multierror"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
golangsdk "github.com/huaweicloud/terraform-provider-hcs/huaweicloudstack/sdk/huaweicloud"
"github.com/huaweicloud/terraform-provider-hcs/huaweicloudstack/sdk/huaweicloud/openstack/common/tags"
"github.com/huaweicloud/terraform-provider-hcs/huaweicloudstack/sdk/huaweicloud/openstack/nat/v2/gateways"
"github.com/huaweicloud/terraform-provider-hcs/huaweicloudstack/common"
"github.com/huaweicloud/terraform-provider-hcs/huaweicloudstack/config"
"github.com/huaweicloud/terraform-provider-hcs/huaweicloudstack/utils"
)
type (
PublicSpecType string
)
const (
PublicSpecTypeSmall PublicSpecType = "1"
PublicSpecTypeMedium PublicSpecType = "2"
PublicSpecTypeLarge PublicSpecType = "3"
PublicSpecTypeExtraLarge PublicSpecType = "4"
)
func ResourcePublicGateway() *schema.Resource {
return &schema.Resource{
CreateContext: resourcePublicGatewayCreate,
ReadContext: resourcePublicGatewayRead,
UpdateContext: resourcePublicGatewayUpdate,
DeleteContext: resourcePublicGatewayDelete,
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(5 * time.Minute),
Update: schema.DefaultTimeout(5 * time.Minute),
Delete: schema.DefaultTimeout(5 * time.Minute),
},
Importer: &schema.ResourceImporter{
StateContext: schema.ImportStatePassthroughContext,
},
Schema: map[string]*schema.Schema{
"region": {
Type: schema.TypeString,
Computed: true,
Description: "The region where the NAT gateway is located.",
},
"vpc_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "The ID of the VPC to which the NAT gateway belongs.",
},
"subnet_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "The network ID of the downstream interface (the next hop of the DVR) " +
"of the NAT gateway.",
},
"name": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.All(
validation.StringMatch(regexp.MustCompile(`[\w-]*`),
"Only letters, digits, hyphens (-) and underscores (_) are allowed."),
validation.StringLenBetween(1, 64),
),
Description: "The NAT gateway name.",
},
"spec": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{
string(PublicSpecTypeSmall),
string(PublicSpecTypeMedium),
string(PublicSpecTypeLarge),
string(PublicSpecTypeExtraLarge),
}, false),
Description: "The specification of the NAT gateway.",
},
"description": {
Type: schema.TypeString,
Optional: true,
Description: "The description of the NAT gateway.",
},
"enterprise_project_id": {
Type: schema.TypeString,
Computed: true,
Description: "The enterprise project ID of the NAT gateway.",
},
"tags": common.TagsSchema(),
"status": {
Type: schema.TypeString,
Computed: true,
Description: "The current status of the NAT gateway.",
},
},
}
}
func publicGatewayStateRefreshFunc(client *golangsdk.ServiceClient, gatewayId string,
targets []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
resp, err := gateways.Get(client, gatewayId)
if err != nil {
if _, ok := err.(golangsdk.ErrDefault404); ok {
return resp, "COMPLETED", nil
}
return resp, "", err
}
if utils.StrSliceContains([]string{"INACTIVE"}, resp.Status) {
return resp, "", fmt.Errorf("unexpect status (%s)", resp.Status)
}
if utils.StrSliceContains(targets, resp.Status) {
return resp, "COMPLETED", nil
}
return resp, "PENDING", nil
}
}
func resourcePublicGatewayCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
cfg := config.GetHcsConfig(meta)
region := cfg.GetRegion(d)
client, err := cfg.NatGatewayClient(region)
if err != nil {
return diag.Errorf("error creating NAT v2 client: %s", err)
}
opts := gateways.CreateOpts{
Name: d.Get("name").(string),
VpcId: d.Get("vpc_id").(string),
InternalNetworkId: d.Get("subnet_id").(string),
Spec: d.Get("spec").(string),
Description: d.Get("description").(string),
EnterpriseProjectId: cfg.GetEnterpriseProjectID(d),
}
resp, err := gateways.Create(client, opts)
if err != nil {
return diag.Errorf("error creating NAT gateway: %s", err)
}
d.SetId(resp.ID)
stateConf := &resource.StateChangeConf{
Pending: []string{"PENDING"},
Target: []string{"COMPLETED"},
Refresh: publicGatewayStateRefreshFunc(client, d.Id(), []string{"ACTIVE"}),
Timeout: d.Timeout(schema.TimeoutCreate),
Delay: 5 * time.Second,
PollInterval: 10 * time.Second,
}
_, err = stateConf.WaitForStateContext(ctx)
if err != nil {
return diag.FromErr(err)
}
if gatewayTags, ok := d.GetOk("tags"); ok {
networkClient, err := cfg.NetworkingV2Client(region)
if err != nil {
return diag.Errorf("error creating VPC v2.0 client: %s", err)
}
taglist := utils.ExpandResourceTags(gatewayTags.(map[string]interface{}))
err = tags.Create(networkClient, "nat_gateways", d.Id(), taglist).ExtractErr()
if err != nil {
return diag.Errorf("error setting tags to the NAT gateway: %s", err)
}
}
return resourcePublicGatewayRead(ctx, d, meta)
}
func resourcePublicGatewayRead(_ context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
cfg := config.GetHcsConfig(meta)
region := cfg.GetRegion(d)
client, err := cfg.NatGatewayClient(region)
if err != nil {
return diag.Errorf("error creating NAT v2 client: %s", err)
}
networkClient, err := cfg.NetworkingV2Client(region)
if err != nil {
return diag.Errorf("error creating VPC v2.0 client: %s", err)
}
gatewayId := d.Id()
resp, err := gateways.Get(client, gatewayId)
if err != nil {
return common.CheckDeletedDiag(d, err, "NAT Gateway")
}
mErr := multierror.Append(nil,
d.Set("region", region),
d.Set("name", resp.Name),
d.Set("spec", resp.Spec),
d.Set("vpc_id", resp.RouterId),
d.Set("subnet_id", resp.InternalNetworkId),
d.Set("description", resp.Description),
d.Set("enterprise_project_id", resp.EnterpriseProjectId),
d.Set("status", resp.Status),
)
gatewayTags, err := tags.Get(networkClient, "nat_gateways", gatewayId).Extract()
if err != nil {
log.Printf("[WARN] Error getting gateway tags: %s", err)
} else {
mErr = multierror.Append(mErr, d.Set("tags", utils.TagsToMap(gatewayTags.Tags)))
}
if err = mErr.ErrorOrNil(); err != nil {
return diag.Errorf("error saving NAT gateway fields: %s", err)
}
return nil
}
func resourcePublicGatewayUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
var (
cfg = config.GetHcsConfig(meta)
region = cfg.GetRegion(d)
gatewayId = d.Id()
)
if d.HasChangeExcept("tags") {
client, err := cfg.NatGatewayClient(region)
if err != nil {
return diag.Errorf("error creating NAT v2 client: %s", err)
}
opts := gateways.UpdateOpts{
Name: d.Get("name").(string),
Spec: d.Get("spec").(string),
Description: utils.String(d.Get("description").(string)),
}
_, err = gateways.Update(client, gatewayId, opts)
if err != nil {
return diag.Errorf("error updating NAT gateway (%s): %s", gatewayId, err)
}
stateConf := &resource.StateChangeConf{
Pending: []string{"PENDING"},
Target: []string{"COMPLETED"},
Refresh: publicGatewayStateRefreshFunc(client, gatewayId, []string{"ACTIVE"}),
Timeout: d.Timeout(schema.TimeoutUpdate),
Delay: 5 * time.Second,
PollInterval: 10 * time.Second,
}
_, err = stateConf.WaitForStateContext(ctx)
if err != nil {
return diag.FromErr(err)
}
}
if d.HasChange("tags") {
networkClient, err := cfg.NetworkingV2Client(region)
if err != nil {
return diag.Errorf("error creating VPC v2.0 client: %s", err)
}
err = utils.UpdateResourceTags(networkClient, d, "nat_gateways", gatewayId)
if err != nil {
return diag.Errorf("error updating tags of the NAT gateway: %s", err)
}
}
return resourcePublicGatewayRead(ctx, d, meta)
}
func resourcePublicGatewayDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
cfg := config.GetHcsConfig(meta)
client, err := cfg.NatGatewayClient(cfg.GetRegion(d))
if err != nil {
return diag.Errorf("error creating NAT v2 client: %s", err)
}
gatewayId := d.Id()
if err = gateways.Delete(client, gatewayId); err != nil {
return diag.Errorf("unable to delete NAT gateway (%s): %s", gatewayId, err)
}
stateConf := &resource.StateChangeConf{
Pending: []string{"PENDING"},
Target: []string{"COMPLETED"},
Refresh: publicGatewayStateRefreshFunc(client, gatewayId, nil),
Timeout: d.Timeout(schema.TimeoutDelete),
Delay: 5 * time.Second,
PollInterval: 10 * time.Second,
}
_, err = stateConf.WaitForStateContext(ctx)
if err != nil {
return diag.FromErr(err)
}
return nil
}