Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,8 @@ coverage.html
coverage.out

.qwenignore
.terraflow/
.terraflow/


terraform-provider-alicloud*
mise.toml
1 change: 1 addition & 0 deletions alicloud/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -1644,6 +1644,7 @@ func Provider() terraform.ResourceProvider {
"alicloud_slb_load_balancer": resourceAlicloudSlbLoadBalancer(),
"alicloud_ecs_network_interface": resourceAliCloudEcsNetworkInterface(),
"alicloud_ecs_network_interface_attachment": resourceAliCloudEcsNetworkInterfaceAttachment(),
"alicloud_ecs_eni_sg_attachment": resourceAliCloudEcsEniSgAttachment(),
"alicloud_config_aggregator": resourceAliCloudConfigAggregator(),
"alicloud_config_aggregate_config_rule": resourceAliCloudConfigAggregateConfigRule(),
"alicloud_config_aggregate_compliance_pack": resourceAliCloudConfigAggregateCompliancePack(),
Expand Down
241 changes: 241 additions & 0 deletions alicloud/resource_alicloud_ecs_eni_sg_attachment.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,241 @@
package alicloud

import (
"fmt"
"log"
"time"

"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)

func resourceAliCloudEcsEniSgAttachment() *schema.Resource {
return &schema.Resource{
Create: resourceAliCloudEcsEniSgAttachmentCreate,
Read: resourceAliCloudEcsEniSgAttachmentRead,
Delete: resourceAliCloudEcsEniSgAttachmentDelete,
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(2 * time.Minute),
Delete: schema.DefaultTimeout(2 * time.Minute),
},
Schema: map[string]*schema.Schema{
"network_interface_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"attach_security_group_ids": {
Type: schema.TypeList,
Required: true,
ForceNew: true,
MinItems: 1,
Elem: &schema.Schema{Type: schema.TypeString},
},
"original_security_group_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"effective_security_group_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
}
}

func resourceAliCloudEcsEniSgAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}

networkInterfaceId := d.Get("network_interface_id").(string)
object, err := ecsService.DescribeEcsNetworkInterface(networkInterfaceId)
if err != nil {
return WrapError(err)
}

originalSgIds := flattenEniSecurityGroupIds(object)
attachSgIds := expandStringList(d.Get("attach_security_group_ids").([]interface{}))
targetSgIds := mergeSecurityGroupsWithAttach(attachSgIds, originalSgIds)

if err := modifyEniSecurityGroups(client, d.Timeout(schema.TimeoutCreate), networkInterfaceId, targetSgIds); err != nil {
return WrapError(err)
}
if err := waitForEniSecurityGroups(ecsService, d.Timeout(schema.TimeoutCreate), networkInterfaceId, targetSgIds); err != nil {
return WrapError(err)
}

d.SetId(networkInterfaceId)
d.Set("original_security_group_ids", originalSgIds)
d.Set("effective_security_group_ids", targetSgIds)

return resourceAliCloudEcsEniSgAttachmentRead(d, meta)
}

func resourceAliCloudEcsEniSgAttachmentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}

object, err := ecsService.DescribeEcsNetworkInterface(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ecs_eni_sg_attachment ecsService.DescribeEcsNetworkInterface Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}

d.Set("network_interface_id", d.Id())
d.Set("effective_security_group_ids", flattenEniSecurityGroupIds(object))

return nil
}

func resourceAliCloudEcsEniSgAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}

networkInterfaceId := d.Get("network_interface_id").(string)
originalSgIds := expandStringList(d.Get("original_security_group_ids").([]interface{}))
if len(originalSgIds) == 0 {
return nil
}

if err := modifyEniSecurityGroups(client, d.Timeout(schema.TimeoutDelete), networkInterfaceId, originalSgIds); err != nil {
return WrapError(err)
}
if err := waitForEniSecurityGroups(ecsService, d.Timeout(schema.TimeoutDelete), networkInterfaceId, originalSgIds); err != nil {
return WrapError(err)
}

return nil
}

func flattenEniSecurityGroupIds(object map[string]interface{}) []string {
result := make([]string, 0)
ids, ok := object["SecurityGroupIds"].(map[string]interface{})
if !ok {
return result
}
sgs, ok := ids["SecurityGroupId"].([]interface{})
if !ok {
return result
}
for _, sg := range sgs {
result = append(result, fmt.Sprint(sg))
}
return result
}

func mergeSecurityGroupsWithAttach(attach []string, existing []string) []string {
seen := make(map[string]struct{})
result := make([]string, 0, len(attach)+len(existing))
for _, sg := range attach {
if _, ok := seen[sg]; ok {
continue
}
seen[sg] = struct{}{}
result = append(result, sg)
}
for _, sg := range existing {
if _, ok := seen[sg]; ok {
continue
}
seen[sg] = struct{}{}
result = append(result, sg)
}
return result
}

func modifyEniSecurityGroups(client *connectivity.AliyunClient, timeout time.Duration, networkInterfaceId string, securityGroupIds []string) error {
action := "ModifyNetworkInterfaceAttribute"
request := map[string]interface{}{
"RegionId": client.RegionId,
"NetworkInterfaceId": networkInterfaceId,
"SecurityGroupId": stringSliceToInterfaceSlice(securityGroupIds),
}
var response map[string]interface{}
var err error
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(timeout, func() *resource.RetryError {
response, err = client.RpcPost("Ecs", "2014-05-26", action, nil, request, false)
if err != nil {
if NeedRetry(err) || IsExpectedErrors(err, []string{"OperationConflict", "InvalidOperation.InvalidEniState", "ServiceUnavailable"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, networkInterfaceId, action, AlibabaCloudSdkGoERROR)
}
return nil
}

func waitForEniSecurityGroups(ecsService EcsService, timeout time.Duration, networkInterfaceId string, expected []string) error {
stateConf := &resource.StateChangeConf{
Pending: []string{"Pending"},
Target: []string{"Applied"},
Refresh: func() (interface{}, string, error) {
object, err := ecsService.DescribeEcsNetworkInterface(networkInterfaceId)
if err != nil {
return nil, "", err
}
current := flattenEniSecurityGroupIds(object)
if equalStringSet(current, expected) {
return object, "Applied", nil
}
return object, "Pending", nil
},
Timeout: timeout,
MinTimeout: 3 * time.Second,
PollInterval: 5 * time.Second,
}
_, err := stateConf.WaitForState()
return err
}

func equalStringSet(a []string, b []string) bool {
uniqA := uniqueStrings(a)
uniqB := uniqueStrings(b)
if len(uniqA) != len(uniqB) {
return false
}
set := make(map[string]struct{}, len(uniqA))
for _, item := range uniqA {
set[item] = struct{}{}
}
for _, item := range uniqB {
if _, ok := set[item]; !ok {
return false
}
}
return true
}

func uniqueStrings(items []string) []string {
result := make([]string, 0, len(items))
seen := make(map[string]struct{}, len(items))
for _, item := range items {
if _, ok := seen[item]; ok {
continue
}
seen[item] = struct{}{}
result = append(result, item)
}
return result
}

func stringSliceToInterfaceSlice(v []string) []interface{} {
result := make([]interface{}, 0, len(v))
for _, item := range v {
result = append(result, item)
}
return result
}
57 changes: 57 additions & 0 deletions alicloud/resource_alicloud_ecs_eni_sg_attachment_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package alicloud
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

测试需要覆盖真实的资源创建的场景,会创建真实的资源并验证结果。 可以参考其他资源的AccTest


import "testing"

func TestMergeSecurityGroupsWithAttach(t *testing.T) {
attach := []string{"sg-4", "sg-3", "sg-4"}
existing := []string{"sg-1", "sg-2", "sg-3"}

got := mergeSecurityGroupsWithAttach(attach, existing)
want := []string{"sg-4", "sg-3", "sg-1", "sg-2"}

if len(got) != len(want) {
t.Fatalf("unexpected length, got=%v want=%v", got, want)
}
for i := range got {
if got[i] != want[i] {
t.Fatalf("unexpected merge result, got=%v want=%v", got, want)
}
}
}

func TestEqualStringSet(t *testing.T) {
tests := []struct {
name string
a []string
b []string
want bool
}{
{
name: "same members different order",
a: []string{"sg-1", "sg-2", "sg-3"},
b: []string{"sg-3", "sg-1", "sg-2"},
want: true,
},
{
name: "duplicates are ignored",
a: []string{"sg-1", "sg-2", "sg-2"},
b: []string{"sg-2", "sg-1"},
want: true,
},
{
name: "different members",
a: []string{"sg-1", "sg-2"},
b: []string{"sg-1", "sg-3"},
want: false,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := equalStringSet(tt.a, tt.b)
if got != tt.want {
t.Fatalf("equalStringSet()=%v, want=%v, a=%v, b=%v", got, tt.want, tt.a, tt.b)
}
})
}
}
49 changes: 49 additions & 0 deletions website/docs/r/ecs_eni_sg_attachment.html.markdown
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
---
subcategory: "ECS"
layout: "alicloud"
page_title: "Alicloud: alicloud_ecs_eni_sg_attachment"
sidebar_current: "docs-alicloud-resource-ecs-eni-sg-attachment"
description: |-
Provides an Alicloud ECS ENI Security Group attachment resource.
---

# alicloud_ecs_eni_sg_attachment

Provides an ECS ENI security group attachment resource.

This resource merges `attach_security_group_ids` into the current ENI security group relationship and preserves existing groups that are not explicitly attached.
Because ECS API may not preserve list order in responses, this resource treats security group relationships as a set for state convergence.

When this resource is destroyed, it restores the ENI security groups to the original list captured at creation time.

## Example Usage

Basic Usage

```terraform
resource "alicloud_ecs_eni_sg_attachment" "default" {
network_interface_id = "eni-xxxxxxxxxxxx"

# Current ENI security groups: [sg-1, sg-2, sg-3]
# attach_security_group_ids: [sg-4, sg-3]
# Effective relationship after apply contains: sg-1, sg-2, sg-3, sg-4
# (order is not guaranteed by ECS API)
attach_security_group_ids = ["sg-4", "sg-3"]
}
```

## Argument Reference

The following arguments are supported:

* `network_interface_id` - (Required, ForceNew) The ID of the network interface.
* `attach_security_group_ids` - (Required, ForceNew, List) Security group IDs to merge into the network interface's existing security group relationship.
**NOTE:** The final relationship is guaranteed, but returned order from ECS may differ.
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. 告警框没有高亮显示。 需要前后都隔一样才能正确渲染。可以通过 https://registry.terraform.io/tools/doc-preview 预览下。
  2. 如果 attach_security_group_ids 存在服务端返回和本地配置顺序不一致的情况,在schema定义中需要压制下diff ,不然用户创建之后会出现diff, 需压多次改动配置


## Attributes Reference

The following attributes are exported:

* `id` - The resource ID, same as `network_interface_id`.
* `original_security_group_ids` - The original security group IDs captured before attachment apply.
* `effective_security_group_ids` - The effective security group IDs currently observed on the network interface.