-
Notifications
You must be signed in to change notification settings - Fork 7
/
resource_hcs_nat_snat_rule.go
309 lines (277 loc) · 9.34 KB
/
resource_hcs_nat_snat_rule.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
299
300
301
302
303
304
305
306
307
308
309
package nat
import (
"context"
"fmt"
"log"
"strings"
"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/nat/v2/snats"
"github.com/huaweicloud/terraform-provider-hcs/huaweicloudstack/sdk/huaweicloud/openstack/networking/v1/eips"
"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 SourceType int
const (
SourceTypeVpc SourceType = 0
)
func ResourcePublicSnatRule() *schema.Resource {
return &schema.Resource{
CreateContext: resourcePublicSnatRuleCreate,
ReadContext: resourcePublicSnatRuleRead,
DeleteContext: resourcePublicSnatRuleDelete,
Importer: &schema.ResourceImporter{
StateContext: schema.ImportStatePassthroughContext,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(5 * time.Minute),
Update: schema.DefaultTimeout(5 * time.Minute),
Delete: schema.DefaultTimeout(5 * time.Minute),
},
Schema: map[string]*schema.Schema{
"region": {
Type: schema.TypeString,
Computed: true,
Description: "The region where the SNAT rule is located.",
},
"floating_ip_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
DiffSuppressFunc: utils.SuppressSnatFiplistDiffs,
Description: "The IDs of floating IPs connected by SNAT rule.",
},
"nat_gateway_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "schema: Required; The ID of the gateway to which the SNAT rule belongs.",
},
"source_type": {
Type: schema.TypeInt,
ValidateFunc: validation.IntInSlice([]int{
int(SourceTypeVpc),
}),
Optional: true,
ForceNew: true,
Description: "The resource type of the SNAT rule.",
},
"subnet_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
Description: "The network IDs of subnet connected by SNAT rule (VPC side).",
},
"cidr": {
Type: schema.TypeString,
Computed: true,
Description: "The CIDR block connected by SNAT rule (DC side).",
},
"description": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
Description: "The description of the SNAT rule.",
},
"floating_ip_address": {
Type: schema.TypeString,
Computed: true,
Description: "The floating IP addresses (separated by commas) connected by SNAT rule.",
},
"status": {
Type: schema.TypeString,
Computed: true,
Description: "The status of the SNAT rule.",
},
// deprecated
"network_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Deprecated: "schema: Deprecated; Use 'subnet_id' instead.",
},
},
}
}
func buildPublicSnatRuleCreateOpts(d *schema.ResourceData) (snats.CreateOpts, error) {
result := snats.CreateOpts{
GatewayId: d.Get("nat_gateway_id").(string),
FloatingIpId: d.Get("floating_ip_id").(string),
Cidr: d.Get("cidr").(string),
Description: d.Get("description").(string),
}
var subnetId string
if v, ok := d.GetOk("subnet_id"); ok {
subnetId = v.(string)
} else {
subnetId = d.Get("network_id").(string)
}
result.NetworkId = subnetId
sourceType := d.Get("source_type").(int)
if sourceType == 1 && subnetId != "" {
return result, fmt.Errorf("In the DC (Direct Connect) scenario (source_type is 1), only the parameter 'cidr' " +
"is valid, and the parameter 'subnet_id' must be empty")
}
result.SourceType = sourceType
return result, nil
}
func publicSnatRuleStateRefreshFunc(client *golangsdk.ServiceClient, ruleId string,
targets []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
resp, err := snats.Get(client, ruleId)
if err != nil {
if _, ok := err.(golangsdk.ErrDefault404); ok {
return resp, "COMPLETED", nil
}
return resp, "", err
}
if utils.StrSliceContains([]string{"INACTIVE", "EIP_FREEZED"}, 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 resourcePublicSnatRuleCreate(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)
}
opts, err := buildPublicSnatRuleCreateOpts(d)
if err != nil {
return diag.FromErr(err)
}
log.Printf("[DEBUG] The create options of the public SNAT rule is: %#v", opts)
resp, err := snats.Create(client, opts)
if err != nil {
return diag.Errorf("error creating public SNAT rule: %s", err)
}
d.SetId(resp.ID)
stateConf := &resource.StateChangeConf{
Pending: []string{"PENDING"},
Target: []string{"COMPLETED"},
Refresh: publicSnatRuleStateRefreshFunc(client, d.Id(), []string{"ACTIVE"}),
Timeout: d.Timeout(schema.TimeoutCreate),
Delay: 3 * time.Second,
PollInterval: 10 * time.Second,
}
_, err = stateConf.WaitForStateContext(ctx)
if err != nil {
return diag.FromErr(err)
}
return resourcePublicSnatRuleRead(ctx, d, meta)
}
func resourcePublicSnatRuleRead(_ context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
cfg := config.GetHcsConfig(meta)
region := cfg.GetRegion(d)
natClient, err := cfg.NatGatewayClient(region)
if err != nil {
return diag.Errorf("error creating NAT v2 client: %s", err)
}
resp, err := snats.Get(natClient, d.Id())
if err != nil {
return common.CheckDeletedDiag(d, err, "Public SNAT rule")
}
mErr := multierror.Append(nil,
d.Set("region", region),
d.Set("nat_gateway_id", resp.GatewayId),
d.Set("floating_ip_id", resp.FloatingIpId),
d.Set("floating_ip_address", resp.FloatingIpAddress),
d.Set("source_type", resp.SourceType),
d.Set("subnet_id", resp.NetworkId),
d.Set("cidr", resp.Cidr),
d.Set("status", resp.Status),
d.Set("description", resp.Description),
)
if err = mErr.ErrorOrNil(); err != nil {
return diag.Errorf("error saving public SNAT rule fields: %s", err)
}
return nil
}
func resourcePublicSnatRuleUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
cfg := config.GetHcsConfig(meta)
region := cfg.GetRegion(d)
natClient, err := cfg.NatGatewayClient(region)
if err != nil {
return diag.Errorf("error creating NAT v2 client: %s", err)
}
ruleId := d.Id()
opts := snats.UpdateOpts{
GatewayId: d.Get("nat_gateway_id").(string),
Description: utils.String(d.Get("description").(string)),
}
if d.HasChange("floating_ip_id") {
eipClient, err := cfg.NetworkingV1Client(region)
if err != nil {
return diag.Errorf("error creating VPC v1 client: %s", err)
}
eipIds := d.Get("floating_ip_id").(string)
eipList := strings.Split(eipIds, ",")
eipAddrs := make([]string, len(eipList))
// get EIP address from ID
for i, eipId := range eipList {
eIP, err := eips.Get(eipClient, eipId).Extract()
if err != nil {
return diag.Errorf("error fetching EIP (%s): %s", eipId, err)
}
eipAddrs[i] = eIP.PublicAddress
}
opts.FloatingIpAddress = strings.Join(eipAddrs, ",")
}
log.Printf("[DEBUG] The update options of the public SNAT rule is: %#v", opts)
_, err = snats.Update(natClient, ruleId, opts)
if err != nil {
return diag.Errorf("error updating public SNAT rule: %s", err)
}
log.Printf("[DEBUG] waiting for public SNAT rule (%s) to become available", ruleId)
stateConf := &resource.StateChangeConf{
Pending: []string{"PENDING"},
Target: []string{"COMPLETED"},
Refresh: publicSnatRuleStateRefreshFunc(natClient, ruleId, []string{"ACTIVE"}),
Timeout: d.Timeout(schema.TimeoutUpdate),
Delay: 3 * time.Second,
PollInterval: 10 * time.Second,
}
_, err = stateConf.WaitForStateContext(ctx)
if err != nil {
return diag.FromErr(err)
}
return resourcePublicSnatRuleRead(ctx, d, meta)
}
func resourcePublicSnatRuleDelete(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)
}
ruleId := d.Id()
gatewayId := d.Get("nat_gateway_id").(string)
err = snats.Delete(client, gatewayId, ruleId)
if err != nil {
return diag.Errorf("error deleting public SNAT rule (%s): %s", ruleId, err)
}
stateConf := &resource.StateChangeConf{
Pending: []string{"PENDING"},
Target: []string{"COMPLETED"},
Refresh: publicSnatRuleStateRefreshFunc(client, ruleId, nil),
Timeout: d.Timeout(schema.TimeoutDelete),
Delay: 3 * time.Second,
PollInterval: 10 * time.Second,
}
_, err = stateConf.WaitForStateContext(ctx)
if err != nil {
return diag.FromErr(err)
}
return nil
}