Skip to content
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

New Resource: alicloud_ack_one_membership_attachment #8150

Closed
Closed
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
1 change: 1 addition & 0 deletions alicloud/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -1058,6 +1058,7 @@ func Provider() terraform.ResourceProvider {
"alicloud_arms_environment": resourceAliCloudArmsEnvironment(),
"alicloud_hologram_instance": resourceAliCloudHologramInstance(),
"alicloud_ack_one_cluster": resourceAliCloudAckOneCluster(),
"alicloud_ack_one_membership_attachment": resourceAliCloudAckOneMembershipAttachment(),
"alicloud_drds_polardbx_instance": resourceAliCloudDrdsPolardbxInstance(),
"alicloud_gpdb_backup_policy": resourceAliCloudGpdbBackupPolicy(),
"alicloud_threat_detection_file_upload_limit": resourceAliCloudThreatDetectionFileUploadLimit(),
Expand Down
145 changes: 145 additions & 0 deletions alicloud/resource_alicloud_ack_one_membership_attachment.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
package alicloud

import (
"log"
"time"

util "github.com/alibabacloud-go/tea-utils/service"
"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 resourceAliCloudAckOneMembershipAttachment() *schema.Resource {
return &schema.Resource{
Schema: map[string]*schema.Schema{
"cluster_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "ID of the ACK One fleet cluster",
},
"sub_cluster_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "ID of the ACK cluster that needs to be managed by ACK One fleet",
},
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(25 * time.Minute),
Delete: schema.DefaultTimeout(25 * time.Minute),
},
Create: resourceAliCloudAckOneMembershipAttachmentCreate,
Read: resourceAliCloudAckOneMembershipAttachmentRead,
Delete: resourceAliCloudAckOneMembershipAttachmentDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
}
}

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

action := "AttachClusterToHub"
var request map[string]interface{}
var response map[string]interface{}
conn, err := client.NewAckoneClient()
if err != nil {
return WrapError(err)
}
request = make(map[string]interface{})
request["ClusterId"] = d.Get("cluster_id")
request["ClusterIds"] = "[\"" + d.Get("sub_cluster_id").(string) + "\"]"

runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2022-01-01"), StringPointer("AK"), nil, request, &runtime)

if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)

if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ack_one_membership_attachment", action, AlibabaCloudSdkGoERROR)
}

managedClusterIds := response["ManagedClusterIds"].([]interface{})
if len(managedClusterIds) != 1 {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ack_one_membership_attachment", action, AlibabaCloudSdkGoERROR)
}

managedClusterId := managedClusterIds[0].(string)
d.SetId(response["ClusterId"].(string) + ":" + managedClusterId)

return nil
}

func resourceAliCloudAckOneMembershipAttachmentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ackOneServiceV2 := AckOneServiceV2{client}

objectRaw, err := ackOneServiceV2.DescribeAckOneMembershipAttachment(d.Id())
if err != nil {
if !d.IsNewResource() && NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ack_one_membership_attachment DescribeAckOneMembershipAttachment Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}

d.Set("cluster_id", objectRaw["cluster_id"])
d.Set("sub_cluster_id", objectRaw["sub_cluster_id"])
return nil
}

func resourceAliCloudAckOneMembershipAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DetachClusterFromHub"
var request map[string]interface{}
var response map[string]interface{}
conn, err := client.NewAckoneClient()
if err != nil {
return WrapError(err)
}
request = make(map[string]interface{})
request["ClusterId"] = d.Get("cluster_id")
request["ClusterIds"] = "[\"" + d.Get("sub_cluster_id").(string) + "\"]"

runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2022-01-01"), StringPointer("AK"), nil, request, &runtime)

if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)

if err != nil {
if NotFoundError(err) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}

return nil
}
184 changes: 184 additions & 0 deletions alicloud/resource_alicloud_ack_one_membership_attachment_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
package alicloud

import (
"fmt"
"testing"

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

func TestAccAliCloudAckOneMembershipAttachment_basic(t *testing.T) {
var v map[string]interface{}
resourceId := "alicloud_ack_one_membership_attachment.default"
ra := resourceAttrInit(resourceId, AliCloudAckOneMembershipAttachmentMap)
rc := resourceCheckInitWithDescribeMethod(resourceId, &v, func() interface{} {
return &AckOneServiceV2{testAccProvider.Meta().(*connectivity.AliyunClient)}
}, "DescribeAckOneMembershipAttachment")
rac := resourceAttrCheckInit(rc, ra)
testAccCheck := rac.resourceAttrMapUpdateSet()
rand := acctest.RandInt()
name := fmt.Sprintf("tf-testAccAckOneMembershipAttachment-%d", rand)
testAccConfig := resourceTestAccConfigFunc(resourceId, name, AliCloudAckOneMembershipAttachmentBasicDependence0)
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: rac.checkResourceDestroy(),
Steps: []resource.TestStep{
{
Config: testAccConfig(map[string]interface{}{
"cluster_id": "${alicloud_ack_one_cluster.default.id}",
"sub_cluster_id": "${alicloud_cs_managed_kubernetes.default.id}",
}),
Check: resource.ComposeTestCheckFunc(
testAccCheck(
map[string]string{
"cluster_id": CHECKSET,
"sub_cluster_id": CHECKSET,
},
),
),
},
{
ResourceName: resourceId,
ImportState: true,
ImportStateVerify: true,
ImportStateVerifyIgnore: []string{},
},
},
})
}

var AliCloudAckOneMembershipAttachmentMap = map[string]string{
"cluster_id": CHECKSET,
"sub_cluster_id": CHECKSET,
}

func AliCloudAckOneMembershipAttachmentBasicDependence0(name string) string {
return fmt.Sprintf(`
variable "name" {
default = "%s"
}

provider "alicloud" {
region = "cn-hangzhou"
}

data "alicloud_zones" "default" {
available_resource_creation = "VSwitch"
}

resource "alicloud_vpc" "defaultVpc" {
cidr_block = "172.16.0.0/12"
}

resource "alicloud_vswitch" "defaultyVSwitch" {
vpc_id = alicloud_vpc.defaultVpc.id
cidr_block = "172.16.2.0/24"
zone_id = data.alicloud_zones.default.zones.0.id
}

resource "alicloud_ack_one_cluster" "default" {
network {
vpc_id = alicloud_vpc.defaultVpc.id
vswitches = ["${alicloud_vswitch.defaultyVSwitch.id}"]
}
}

# leave it to empty would create a new one
variable "vpc_id" {
description = "Existing vpc id used to create several vswitches and other resources."
default = ""
}

variable "vpc_cidr" {
description = "The cidr block used to launch a new vpc when 'vpc_id' is not specified."
default = "10.0.0.0/8"
}

# leave it to empty then terraform will create several vswitches
variable "vswitch_ids" {
description = "List of existing vswitch id."
type = list(string)
default = []
}

variable "vswitch_cidrs" {
description = "List of cidr blocks used to create several new vswitches when 'vswitch_ids' is not specified."
type = list(string)
default = ["10.1.0.0/16", "10.2.0.0/16"]
}

# options: between 24-28
variable "node_cidr_mask" {
description = "The node cidr block to specific how many pods can run on single node."
default = 24
}

# options: ipvs|iptables
variable "proxy_mode" {
description = "Proxy mode is option of kube-proxy."
default = "ipvs"
}

variable "service_cidr" {
description = "The kubernetes service cidr block. It cannot be equals to vpc's or vswitch's or pod's and cannot be in them."
default = "192.168.0.0/16"
}

variable "terway_vswitch_ids" {
description = "List of existing vswitch ids for terway."
type = list(string)
default = []
}

variable "terway_vswitch_cidrs" {
description = "List of cidr blocks used to create several new vswitches when 'terway_vswitch_cidrs' is not specified."
type = list(string)
default = ["10.4.0.0/16", "10.5.0.0/16"]
}

data "alicloud_enhanced_nat_available_zones" "enhanced" {}

# If there is not specifying vpc_id, the module will launch a new vpc
resource "alicloud_vpc" "vpc" {
count = var.vpc_id == "" ? 1 : 0
cidr_block = var.vpc_cidr
}

# According to the vswitch cidr blocks to launch several vswitches
resource "alicloud_vswitch" "vswitches" {
count = length(var.vswitch_ids) > 0 ? 0 : length(var.vswitch_cidrs)
vpc_id = var.vpc_id == "" ? join("", alicloud_vpc.vpc.*.id) : var.vpc_id
cidr_block = element(var.vswitch_cidrs, count.index)
zone_id = data.alicloud_enhanced_nat_available_zones.enhanced.zones[count.index].zone_id
}

# According to the vswitch cidr blocks to launch several vswitches
resource "alicloud_vswitch" "terway_vswitches" {
count = length(var.terway_vswitch_ids) > 0 ? 0 : length(var.terway_vswitch_cidrs)
vpc_id = var.vpc_id == "" ? join("", alicloud_vpc.vpc.*.id) : var.vpc_id
cidr_block = element(var.terway_vswitch_cidrs, count.index)
zone_id = data.alicloud_enhanced_nat_available_zones.enhanced.zones[count.index].zone_id
}

resource "alicloud_cs_managed_kubernetes" "default" {
cluster_spec = "ack.pro.small"
# version can not be defined in variables.tf.
# version = "1.26.3-aliyun.1"
vswitch_ids = length(var.vswitch_ids) > 0 ? split(",", join(",", var.vswitch_ids)) : length(var.vswitch_cidrs) < 1 ? [] : split(",", join(",", alicloud_vswitch.vswitches.*.id))
pod_vswitch_ids = length(var.terway_vswitch_ids) > 0 ? split(",", join(",", var.terway_vswitch_ids)) : length(var.terway_vswitch_cidrs) < 1 ? [] : split(",", join(",", alicloud_vswitch.terway_vswitches.*.id))
new_nat_gateway = true
node_cidr_mask = var.node_cidr_mask
proxy_mode = var.proxy_mode
service_cidr = var.service_cidr

is_enterprise_security_group = true

addons {
name = "terway-eniip"
}
}
`, name)
}
Loading
Loading