-
Notifications
You must be signed in to change notification settings - Fork 602
feat: 新增 ECS ENI 安全组挂载资源 #9618
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
mir-xiong
wants to merge
1
commit into
aliyun:master
Choose a base branch
from
mir-xiong:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
feat: 新增 ECS ENI 安全组挂载资源 #9618
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -42,4 +42,8 @@ coverage.html | |
| coverage.out | ||
|
|
||
| .qwenignore | ||
| .terraflow/ | ||
| .terraflow/ | ||
|
|
||
|
|
||
| terraform-provider-alicloud* | ||
| mise.toml | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,57 @@ | ||
| package alicloud | ||
|
|
||
| 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) | ||
| } | ||
| }) | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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. | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
|
|
||
| ## 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. | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
测试需要覆盖真实的资源创建的场景,会创建真实的资源并验证结果。 可以参考其他资源的AccTest