forked from aliyun/terraform-provider-alicloud
-
Notifications
You must be signed in to change notification settings - Fork 0
/
resource_alicloud_security_group_rule.go
354 lines (307 loc) · 10.6 KB
/
resource_alicloud_security_group_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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
package alicloud
import (
"fmt"
"strconv"
"strings"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ecs"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
"github.com/terraform-providers/terraform-provider-alicloud/alicloud/connectivity"
)
func resourceAliyunSecurityGroupRule() *schema.Resource {
return &schema.Resource{
Create: resourceAliyunSecurityGroupRuleCreate,
Read: resourceAliyunSecurityGroupRuleRead,
Delete: resourceAliyunSecurityGroupRuleDelete,
Schema: map[string]*schema.Schema{
"type": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validateSecurityRuleType,
Description: "Type of rule, ingress (inbound) or egress (outbound).",
},
"ip_protocol": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validateSecurityRuleIpProtocol,
},
"nic_type": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
ValidateFunc: validateSecurityRuleNicType,
},
"policy": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: GroupRulePolicyAccept,
ValidateFunc: validateSecurityRulePolicy,
},
"port_range": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: AllPortRange,
DiffSuppressFunc: ecsSecurityGroupRulePortRangeDiffSuppressFunc,
},
"priority": &schema.Schema{
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
Default: 1,
ValidateFunc: validateSecurityPriority,
},
"security_group_id": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"cidr_ip": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"source_security_group_id": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ConflictsWith: []string{"cidr_ip"},
},
"source_group_owner_account": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
},
}
}
func resourceAliyunSecurityGroupRuleCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
direction := d.Get("type").(string)
sgId := d.Get("security_group_id").(string)
ptl := d.Get("ip_protocol").(string)
port := d.Get("port_range").(string)
if port == "" {
return fmt.Errorf("'port_range': required field is not set or invalid.")
}
nicType := d.Get("nic_type").(string)
policy := d.Get("policy").(string)
priority := d.Get("priority").(int)
if _, ok := d.GetOk("cidr_ip"); !ok {
if _, ok := d.GetOk("source_security_group_id"); !ok {
return fmt.Errorf("Either 'cidr_ip' or 'source_security_group_id' must be specified.")
}
}
request, err := buildAliyunSGRuleRequest(d, meta)
if err != nil {
return err
}
if direction == string(DirectionIngress) {
request.ApiName = "AuthorizeSecurityGroup"
_, err = client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.ProcessCommonRequest(request)
})
} else {
request.ApiName = "AuthorizeSecurityGroupEgress"
_, err = client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.ProcessCommonRequest(request)
})
}
if err != nil {
return fmt.Errorf("Error authorizing security group rule type %s: %s", direction, err)
}
var cidr_ip string
if ip, ok := d.GetOk("cidr_ip"); ok {
cidr_ip = ip.(string)
} else {
cidr_ip = d.Get("source_security_group_id").(string)
}
d.SetId(sgId + ":" + direction + ":" + ptl + ":" + port + ":" + nicType + ":" + cidr_ip + ":" + policy + ":" + strconv.Itoa(priority))
return resourceAliyunSecurityGroupRuleRead(d, meta)
}
func resourceAliyunSecurityGroupRuleRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
parts := strings.Split(d.Id(), ":")
policy := parseSecurityRuleId(d, meta, 6)
strPriority := parseSecurityRuleId(d, meta, 7)
var priority int
if policy == "" || strPriority == "" {
policy = d.Get("policy").(string)
priority = d.Get("priority").(int)
d.SetId(d.Id() + ":" + policy + ":" + strconv.Itoa(priority))
} else {
prior, err := strconv.Atoi(strPriority)
if err != nil {
return fmt.Errorf("SecrityGroupRuleRead parse rule id gets an error: %#v", err)
}
priority = prior
}
sgId := parts[0]
direction := parts[1]
rule, err := ecsService.DescribeSecurityGroupRule(sgId, direction, parts[2], parts[3], parts[4], parts[5], policy, priority)
if err != nil {
if NotFoundError(err) || IsExceptedError(err, InvalidSecurityGroupIdNotFound) {
d.SetId("")
return nil
}
return fmt.Errorf("Error describing security group rule: %#v", err)
}
d.Set("type", rule.Direction)
d.Set("ip_protocol", strings.ToLower(string(rule.IpProtocol)))
d.Set("nic_type", rule.NicType)
d.Set("policy", strings.ToLower(string(rule.Policy)))
d.Set("port_range", rule.PortRange)
if pri, err := strconv.Atoi(rule.Priority); err != nil {
return fmt.Errorf("Converting rule priority %s got an error: %#v.", rule.Priority, err)
} else {
d.Set("priority", pri)
}
d.Set("security_group_id", sgId)
//support source and desc by type
if direction == string(DirectionIngress) {
d.Set("cidr_ip", rule.SourceCidrIp)
d.Set("source_security_group_id", rule.SourceGroupId)
d.Set("source_group_owner_account", rule.SourceGroupOwnerAccount)
} else {
d.Set("cidr_ip", rule.DestCidrIp)
d.Set("source_security_group_id", rule.DestGroupId)
d.Set("source_group_owner_account", rule.DestGroupOwnerAccount)
}
return nil
}
func deleteSecurityGroupRule(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ruleType := d.Get("type").(string)
request, err := buildAliyunSGRuleRequest(d, meta)
if err != nil {
return err
}
if ruleType == string(DirectionIngress) {
request.ApiName = "RevokeSecurityGroup"
_, err = client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.ProcessCommonRequest(request)
})
} else {
request.ApiName = "RevokeSecurityGroupEgress"
_, err = client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.ProcessCommonRequest(request)
})
}
return err
}
func resourceAliyunSecurityGroupRuleDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
parts := strings.Split(d.Id(), ":")
policy := parseSecurityRuleId(d, meta, 6)
strPriority := parseSecurityRuleId(d, meta, 7)
var priority int
if policy == "" || strPriority == "" {
policy = d.Get("policy").(string)
priority = d.Get("priority").(int)
d.SetId(d.Id() + ":" + policy + ":" + strconv.Itoa(priority))
} else {
prior, err := strconv.Atoi(strPriority)
if err != nil {
return fmt.Errorf("SecrityGroupRuleRead parse rule id gets an error: %#v", err)
}
priority = prior
}
return resource.Retry(5*time.Minute, func() *resource.RetryError {
err := deleteSecurityGroupRule(d, meta)
if err != nil {
if NotFoundError(err) || IsExceptedError(err, InvalidSecurityGroupIdNotFound) {
return nil
}
resource.RetryableError(fmt.Errorf("Delete security group rule timeout and got an error: %#v", err))
}
_, err = ecsService.DescribeSecurityGroupRule(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], policy, priority)
if err != nil {
if NotFoundError(err) || IsExceptedError(err, InvalidSecurityGroupIdNotFound) {
return nil
}
return resource.NonRetryableError(err)
}
return resource.RetryableError(fmt.Errorf("Delete security group rule timeout and got an error: %#v", err))
})
}
func buildAliyunSGRuleRequest(d *schema.ResourceData, meta interface{}) (*requests.CommonRequest, error) {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
request := client.NewCommonRequest(connectivity.ECSCode, connectivity.ApiVersion20140526)
direction := d.Get("type").(string)
port_range := d.Get("port_range").(string)
request.QueryParams["PortRange"] = port_range
if v, ok := d.GetOk("ip_protocol"); ok {
request.QueryParams["IpProtocol"] = v.(string)
if v.(string) == string(Tcp) || v.(string) == string(Udp) {
if port_range == AllPortRange {
return nil, fmt.Errorf("'tcp' and 'udp' can support port range: [1, 65535]. Please correct it and try again.")
}
} else if port_range != AllPortRange {
return nil, fmt.Errorf("'icmp', 'gre' and 'all' only support port range '-1/-1'. Please correct it and try again.")
}
}
if v, ok := d.GetOk("policy"); ok {
request.QueryParams["Policy"] = v.(string)
}
if v, ok := d.GetOk("priority"); ok {
request.QueryParams["Priority"] = strconv.Itoa(v.(int))
}
if v, ok := d.GetOk("cidr_ip"); ok {
if direction == string(DirectionIngress) {
request.QueryParams["SourceCidrIp"] = v.(string)
} else {
request.QueryParams["DestCidrIp"] = v.(string)
}
}
var targetGroupId string
if v, ok := d.GetOk("source_security_group_id"); ok {
targetGroupId = v.(string)
if direction == string(DirectionIngress) {
request.QueryParams["SourceGroupId"] = targetGroupId
} else {
request.QueryParams["DestGroupId"] = targetGroupId
}
}
if v, ok := d.GetOk("source_group_owner_account"); ok {
if direction == string(DirectionIngress) {
request.QueryParams["SourceGroupOwnerAccount"] = v.(string)
} else {
request.QueryParams["DestGroupOwnerAccount"] = v.(string)
}
}
sgId := d.Get("security_group_id").(string)
group, err := ecsService.DescribeSecurityGroupAttribute(sgId)
if err != nil {
return nil, fmt.Errorf("Error get security group %s error: %#v", sgId, err)
}
if v, ok := d.GetOk("nic_type"); ok {
if group.VpcId != "" || targetGroupId != "" {
if GroupRuleNicType(v.(string)) != GroupRuleIntranet {
return nil, fmt.Errorf("When security group in the vpc or authorizing permission for source/destination security group, " +
"the nic_type must be 'intranet'.")
}
}
request.QueryParams["NicType"] = v.(string)
}
request.QueryParams["SecurityGroupId"] = sgId
return request, nil
}
func parseSecurityRuleId(d *schema.ResourceData, meta interface{}, index int) (result string) {
parts := strings.Split(d.Id(), ":")
defer func() {
if e := recover(); e != nil {
fmt.Printf("Panicing %s\r\n", e)
result = ""
}
}()
return parts[index]
}