diff --git a/alicloud/provider.go b/alicloud/provider.go index 2d3a63556f26..bd683ad2bad4 100644 --- a/alicloud/provider.go +++ b/alicloud/provider.go @@ -1568,7 +1568,7 @@ func Provider() terraform.ResourceProvider { "alicloud_vpc_ipv4_cidr_block": resourceAliCloudVpcIpv4CidrBlock(), "alicloud_vpc_public_ip_address_pool": resourceAliCloudVpcPublicIpAddressPool(), "alicloud_dcdn_waf_policy_domain_attachment": resourceAlicloudDcdnWafPolicyDomainAttachment(), - "alicloud_nlb_server_group": resourceAlicloudNlbServerGroup(), + "alicloud_nlb_server_group": resourceAliCloudNlbServerGroup(), "alicloud_vpc_peer_connection": resourceAliCloudVpcPeerConnection(), "alicloud_ga_access_log": resourceAlicloudGaAccessLog(), "alicloud_ebs_disk_replica_group": resourceAlicloudEbsDiskReplicaGroup(), diff --git a/alicloud/resource_alicloud_nlb_server_group.go b/alicloud/resource_alicloud_nlb_server_group.go index e6cd5b594c56..c135a8a8b0c8 100644 --- a/alicloud/resource_alicloud_nlb_server_group.go +++ b/alicloud/resource_alicloud_nlb_server_group.go @@ -1,32 +1,31 @@ +// Package alicloud. This file is generated automatically. Please do not modify it manually, thank you! package alicloud import ( "fmt" "log" - "regexp" "time" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" - + "github.com/PaesslerAG/jsonpath" 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 resourceAlicloudNlbServerGroup() *schema.Resource { +func resourceAliCloudNlbServerGroup() *schema.Resource { return &schema.Resource{ - Create: resourceAlicloudNlbServerGroupCreate, - Read: resourceAlicloudNlbServerGroupRead, - Update: resourceAlicloudNlbServerGroupUpdate, - Delete: resourceAlicloudNlbServerGroupDelete, + Create: resourceAliCloudNlbServerGroupCreate, + Read: resourceAliCloudNlbServerGroupRead, + Update: resourceAliCloudNlbServerGroupUpdate, + Delete: resourceAliCloudNlbServerGroupDelete, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, }, Timeouts: &schema.ResourceTimeout{ - Create: schema.DefaultTimeout(1 * time.Minute), - Delete: schema.DefaultTimeout(1 * time.Minute), - Update: schema.DefaultTimeout(1 * time.Minute), + Create: schema.DefaultTimeout(5 * time.Minute), + Update: schema.DefaultTimeout(5 * time.Minute), + Delete: schema.DefaultTimeout(5 * time.Minute), }, Schema: map[string]*schema.Schema{ "address_ip_version": { @@ -34,81 +33,82 @@ func resourceAlicloudNlbServerGroup() *schema.Resource { Optional: true, Computed: true, ForceNew: true, - ValidateFunc: validation.StringInSlice([]string{"Ipv4", "DualStack"}, false), + ValidateFunc: StringInSlice([]string{"DualStack", "Ipv4"}, false), }, - "connection_drain": { + "any_port_enabled": { Type: schema.TypeBool, Optional: true, Computed: true, + ForceNew: true, + }, + "connection_drain_enabled": { + Type: schema.TypeBool, + Optional: true, + Computed: true, + ConflictsWith: []string{"connection_drain"}, }, "connection_drain_timeout": { Type: schema.TypeInt, Optional: true, Computed: true, - ValidateFunc: validation.IntBetween(10, 900), + ValidateFunc: IntBetween(10, 900), }, "health_check": { Type: schema.TypeList, - Required: true, + Optional: true, + Computed: true, + ForceNew: true, MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - "health_check_connect_port": { + "health_check_interval": { Type: schema.TypeInt, Optional: true, Computed: true, - ValidateFunc: validation.IntBetween(0, 65535), + ValidateFunc: IntBetween(1, 50), }, - "health_check_connect_timeout": { + "health_check_connect_port": { Type: schema.TypeInt, Optional: true, Computed: true, - ValidateFunc: validation.IntBetween(1, 300), + ValidateFunc: IntBetween(0, 65535), }, - "health_check_domain": { + "health_check_url": { Type: schema.TypeString, Optional: true, Computed: true, }, - "health_check_enabled": { - Type: schema.TypeBool, - Optional: true, - }, - "health_check_interval": { + "unhealthy_threshold": { Type: schema.TypeInt, Optional: true, Computed: true, - ValidateFunc: IntBetween(5, 40), + ValidateFunc: IntBetween(2, 10), }, - "health_check_type": { - Type: schema.TypeString, + "healthy_threshold": { + Type: schema.TypeInt, Optional: true, Computed: true, - ValidateFunc: validation.StringInSlice([]string{"TCP", "HTTP"}, false), + ValidateFunc: IntBetween(2, 10), }, - "health_check_url": { + "http_check_method": { Type: schema.TypeString, Optional: true, - Computed: true, - ValidateFunc: validation.StringLenBetween(1, 80), + ValidateFunc: StringInSlice([]string{"GET", "HEAD"}, false), }, - "healthy_threshold": { + "health_check_connect_timeout": { Type: schema.TypeInt, Optional: true, Computed: true, - ValidateFunc: IntBetween(2, 10), + ValidateFunc: IntBetween(1, 300), }, - "unhealthy_threshold": { - Type: schema.TypeInt, - Optional: true, - Computed: true, - ValidateFunc: IntBetween(2, 10), + "health_check_domain": { + Type: schema.TypeString, + Optional: true, + Computed: true, }, - "http_check_method": { - Type: schema.TypeString, - Optional: true, - Computed: true, - ValidateFunc: validation.StringInSlice([]string{"HEAD", "GET"}, false), + "health_check_enabled": { + Type: schema.TypeBool, + Optional: true, }, "health_check_http_code": { Type: schema.TypeList, @@ -116,44 +116,48 @@ func resourceAlicloudNlbServerGroup() *schema.Resource { Computed: true, Elem: &schema.Schema{Type: schema.TypeString}, }, + "health_check_type": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ValidateFunc: StringInSlice([]string{"TCP", "HTTP"}, false), + }, }, }, }, + "preserve_client_ip_enabled": { + Type: schema.TypeBool, + Optional: true, + Computed: true, + }, "protocol": { Type: schema.TypeString, Optional: true, Computed: true, ForceNew: true, - ValidateFunc: validation.StringInSlice([]string{"TCP", "UDP", "TCPSSL"}, false), + ValidateFunc: StringInSlice([]string{"TCP", "UDP", "TCPSSL"}, false), }, "resource_group_id": { Type: schema.TypeString, Optional: true, Computed: true, - ForceNew: true, }, "scheduler": { Type: schema.TypeString, Optional: true, Computed: true, - ValidateFunc: validation.StringInSlice([]string{"Wrr", "Rr", "Sch", "Tch", "Qch"}, false), + ValidateFunc: StringInSlice([]string{"Wrr", "Rr", "Qch", "Tch"}, false), }, "server_group_name": { - Type: schema.TypeString, - Required: true, - ValidateFunc: validation.StringMatch(regexp.MustCompile(`^[a-zA-Z][a-zA-Z0-9-._]{1,127}$`), "The name must be 2 to 128 characters in length, and can contain letters, digits, periods (.), underscores (_), and hyphens (-). The name must start with a letter."), + Type: schema.TypeString, + Required: true, }, "server_group_type": { Type: schema.TypeString, Optional: true, Computed: true, ForceNew: true, - ValidateFunc: validation.StringInSlice([]string{"Instance", "Ip"}, false), - }, - "preserve_client_ip_enabled": { - Type: schema.TypeBool, - Optional: true, - Computed: true, + ValidateFunc: StringInSlice([]string{"Instance", "Ip"}, false), }, "status": { Type: schema.TypeString, @@ -165,78 +169,123 @@ func resourceAlicloudNlbServerGroup() *schema.Resource { Required: true, ForceNew: true, }, + "connection_drain": { + Type: schema.TypeBool, + Optional: true, + Computed: true, + Deprecated: "Field 'connection_drain' has been deprecated since provider version 1.214.0. New field 'connection_drain_enabled' instead.", + }, }, } } -func resourceAlicloudNlbServerGroupCreate(d *schema.ResourceData, meta interface{}) error { +func resourceAliCloudNlbServerGroupCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*connectivity.AliyunClient) - var response map[string]interface{} + action := "CreateServerGroup" - request := make(map[string]interface{}) + var request map[string]interface{} + var response map[string]interface{} + query := make(map[string]interface{}) conn, err := client.NewNlbClient() if err != nil { return WrapError(err) } - if v, ok := d.GetOk("address_ip_version"); ok { - request["AddressIPVersion"] = v + request = make(map[string]interface{}) + request["RegionId"] = client.RegionId + request["ClientToken"] = buildClientToken(action) + + if v, ok := d.GetOk("server_group_type"); ok { + request["ServerGroupType"] = v + } + request["ServerGroupName"] = d.Get("server_group_name") + if v, ok := d.GetOk("protocol"); ok { + request["Protocol"] = v + } + request["VpcId"] = d.Get("vpc_id") + if v, ok := d.GetOkExists("any_port_enabled"); ok { + request["AnyPortEnabled"] = v } if v, ok := d.GetOkExists("connection_drain"); ok { request["ConnectionDrainEnabled"] = v } + + if v, ok := d.GetOkExists("connection_drain_enabled"); ok { + request["ConnectionDrainEnabled"] = v + } if v, ok := d.GetOk("connection_drain_timeout"); ok { request["ConnectionDrainTimeout"] = v } - if v, ok := d.GetOk("protocol"); ok { - request["Protocol"] = v - } - request["RegionId"] = client.RegionId - if v, ok := d.GetOk("resource_group_id"); ok { - request["ResourceGroupId"] = v - } if v, ok := d.GetOk("scheduler"); ok { request["Scheduler"] = v } - request["ServerGroupName"] = d.Get("server_group_name") - if v, ok := d.GetOk("server_group_type"); ok { - request["ServerGroupType"] = v - } if v, ok := d.GetOkExists("preserve_client_ip_enabled"); ok { request["PreserveClientIpEnabled"] = v } - if v, ok := d.GetOk("health_check"); ok { - healthCheckConfig := make(map[string]interface{}) - for _, healthCheckConfigArgs := range v.([]interface{}) { - healthCheckConfigArg := healthCheckConfigArgs.(map[string]interface{}) - healthCheckConfig["HealthCheckEnabled"] = healthCheckConfigArg["health_check_enabled"] - if healthCheckConfig["HealthCheckEnabled"] == true { - healthCheckConfig["HealthCheckConnectPort"] = healthCheckConfigArg["health_check_connect_port"] - healthCheckConfig["HealthCheckType"] = healthCheckConfigArg["health_check_type"] - healthCheckConfig["HealthyThreshold"] = healthCheckConfigArg["healthy_threshold"] - healthCheckConfig["UnhealthyThreshold"] = healthCheckConfigArg["unhealthy_threshold"] - healthCheckConfig["HealthCheckConnectTimeout"] = healthCheckConfigArg["health_check_connect_timeout"] - healthCheckConfig["HealthCheckInterval"] = healthCheckConfigArg["health_check_interval"] - if v, ok := healthCheckConfigArg["health_check_domain"]; ok && fmt.Sprint(v) != "" { - healthCheckConfig["HealthCheckDomain"] = v - } - if v, ok := healthCheckConfigArg["health_check_url"]; ok && fmt.Sprint(v) != "" { - healthCheckConfig["HealthCheckUrl"] = v - } - if v, ok := healthCheckConfigArg["http_check_method"]; ok && fmt.Sprint(v) != "" { - healthCheckConfig["HttpCheckMethod"] = v - } - healthCheckConfig["HealthCheckHttpCode"] = healthCheckConfigArg["health_check_http_code"] + if v, ok := d.GetOk("resource_group_id"); ok { + request["ResourceGroupId"] = v + } + if v, ok := d.GetOk("address_ip_version"); ok { + request["AddressIPVersion"] = v + } + objectDataLocalMap := make(map[string]interface{}) + if v := d.Get("health_check"); !IsNil(v) { + nodeNative, _ := jsonpath.Get("$[0].health_check_enabled", v) + if nodeNative != "" { + objectDataLocalMap["HealthCheckEnabled"] = nodeNative + } + if objectDataLocalMap["HealthCheckEnabled"] == true { + nodeNative1, _ := jsonpath.Get("$[0].health_check_type", v) + if nodeNative1 != "" { + objectDataLocalMap["HealthCheckType"] = nodeNative1 + } + nodeNative2, _ := jsonpath.Get("$[0].health_check_connect_port", v) + if nodeNative2 != "" { + objectDataLocalMap["HealthCheckConnectPort"] = nodeNative2 + } + nodeNative3, _ := jsonpath.Get("$[0].healthy_threshold", v) + if nodeNative3 != "" { + objectDataLocalMap["HealthyThreshold"] = nodeNative3 + } + nodeNative4, _ := jsonpath.Get("$[0].unhealthy_threshold", v) + if nodeNative4 != "" { + objectDataLocalMap["UnhealthyThreshold"] = nodeNative4 + } + nodeNative5, _ := jsonpath.Get("$[0].health_check_connect_timeout", v) + if nodeNative5 != "" { + objectDataLocalMap["HealthCheckConnectTimeout"] = nodeNative5 + } + nodeNative6, _ := jsonpath.Get("$[0].health_check_interval", v) + if nodeNative6 != "" { + objectDataLocalMap["HealthCheckInterval"] = nodeNative6 + } + nodeNative7, _ := jsonpath.Get("$[0].health_check_domain", v) + if nodeNative7 != "" { + objectDataLocalMap["HealthCheckDomain"] = nodeNative7 + } + nodeNative8, _ := jsonpath.Get("$[0].health_check_url", v) + if nodeNative8 != "" { + objectDataLocalMap["HealthCheckUrl"] = nodeNative8 + } + nodeNative9, _ := jsonpath.Get("$[0].http_check_method", v) + if nodeNative9 != "" { + objectDataLocalMap["HttpCheckMethod"] = nodeNative9 + } + nodeNative10, _ := jsonpath.Get("$[0].health_check_http_code", v) + if nodeNative10 != "" { + objectDataLocalMap["HealthCheckHttpCode"] = nodeNative10 } } - request["HealthCheckConfig"] = healthCheckConfig } - request["VpcId"] = d.Get("vpc_id") - request["ClientToken"] = buildClientToken("CreateServerGroup") + request["HealthCheckConfig"] = objectDataLocalMap + runtime := util.RuntimeOptions{} runtime.SetAutoretry(true) - wait := incrementalWait(3*time.Second, 3*time.Second) - err = resource.Retry(client.GetRetryTimeout(d.Timeout(schema.TimeoutCreate)), func() *resource.RetryError { - response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2022-04-30"), StringPointer("AK"), nil, request, &runtime) + 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-04-30"), StringPointer("AK"), query, request, &runtime) + request["ClientToken"] = buildClientToken(action) + if err != nil { if NeedRetry(err) { wait() @@ -244,153 +293,191 @@ func resourceAlicloudNlbServerGroupCreate(d *schema.ResourceData, meta interface } return resource.NonRetryableError(err) } + addDebug(action, response, request) return nil }) - addDebug(action, response, request) + if err != nil { return WrapErrorf(err, DefaultErrorMsg, "alicloud_nlb_server_group", action, AlibabaCloudSdkGoERROR) } - if fmt.Sprint(response["Success"]) == "false" { - return WrapError(fmt.Errorf("%s failed, response: %v", action, response)) - } d.SetId(fmt.Sprint(response["ServerGroupId"])) - nlbService := NlbService{client} - stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, nlbService.NlbServerGroupStateRefreshFunc(d.Id(), []string{})) + nlbServiceV2 := NlbServiceV2{client} + stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, nlbServiceV2.NlbServerGroupStateRefreshFunc(d.Id(), "ServerGroupStatus", []string{})) if _, err := stateConf.WaitForState(); err != nil { return WrapErrorf(err, IdMsg, d.Id()) } - return resourceAlicloudNlbServerGroupUpdate(d, meta) + + return resourceAliCloudNlbServerGroupUpdate(d, meta) } -func resourceAlicloudNlbServerGroupRead(d *schema.ResourceData, meta interface{}) error { + +func resourceAliCloudNlbServerGroupRead(d *schema.ResourceData, meta interface{}) error { client := meta.(*connectivity.AliyunClient) - nlbService := NlbService{client} - object, err := nlbService.DescribeNlbServerGroup(d.Id()) + nlbServiceV2 := NlbServiceV2{client} + + objectRaw, err := nlbServiceV2.DescribeNlbServerGroup(d.Id()) if err != nil { - if NotFoundError(err) { - log.Printf("[DEBUG] Resource alicloud_nlb_server_group nlbService.DescribeNlbServerGroup Failed!!! %s", err) + if !d.IsNewResource() && NotFoundError(err) { + log.Printf("[DEBUG] Resource alicloud_nlb_server_group DescribeNlbServerGroup Failed!!! %s", err) d.SetId("") return nil } return WrapError(err) } - d.Set("address_ip_version", object["AddressIPVersion"]) - d.Set("connection_drain", object["ConnectionDrainEnabled"]) - if v, ok := object["ConnectionDrainTimeout"]; ok && fmt.Sprint(v) != "0" { - d.Set("connection_drain_timeout", formatInt(v)) - } - - healthCheckSli := make([]map[string]interface{}, 0) - if v, ok := object["HealthCheck"]; ok { - if len(v.(map[string]interface{})) > 0 { - healthCheck := v.(map[string]interface{}) - healthCheckMap := make(map[string]interface{}) - healthCheckMap["health_check_connect_port"] = healthCheck["HealthCheckConnectPort"] - healthCheckMap["health_check_connect_timeout"] = healthCheck["HealthCheckConnectTimeout"] - healthCheckMap["health_check_domain"] = healthCheck["HealthCheckDomain"] - healthCheckMap["health_check_enabled"] = healthCheck["HealthCheckEnabled"] - healthCheckMap["health_check_interval"] = healthCheck["HealthCheckInterval"] - healthCheckMap["health_check_type"] = healthCheck["HealthCheckType"] - healthCheckMap["health_check_url"] = healthCheck["HealthCheckUrl"] - healthCheckMap["healthy_threshold"] = healthCheck["HealthyThreshold"] - healthCheckMap["unhealthy_threshold"] = healthCheck["UnhealthyThreshold"] - healthCheckMap["http_check_method"] = healthCheck["HttpCheckMethod"] - healthCheckMap["health_check_http_code"] = healthCheck["HealthCheckHttpCode"] - healthCheckSli = append(healthCheckSli, healthCheckMap) + d.Set("address_ip_version", objectRaw["AddressIPVersion"]) + d.Set("any_port_enabled", objectRaw["AnyPortEnabled"]) + d.Set("connection_drain_enabled", objectRaw["ConnectionDrainEnabled"]) + d.Set("connection_drain_timeout", objectRaw["ConnectionDrainTimeout"]) + d.Set("preserve_client_ip_enabled", objectRaw["PreserveClientIpEnabled"]) + d.Set("protocol", objectRaw["Protocol"]) + d.Set("resource_group_id", objectRaw["ResourceGroupId"]) + d.Set("scheduler", objectRaw["Scheduler"]) + d.Set("server_group_name", objectRaw["ServerGroupName"]) + d.Set("server_group_type", objectRaw["ServerGroupType"]) + d.Set("status", objectRaw["ServerGroupStatus"]) + d.Set("vpc_id", objectRaw["VpcId"]) + + healthCheckMaps := make([]map[string]interface{}, 0) + healthCheckMap := make(map[string]interface{}) + healthCheck1Raw := make(map[string]interface{}) + if objectRaw["HealthCheck"] != nil { + healthCheck1Raw = objectRaw["HealthCheck"].(map[string]interface{}) + } + if len(healthCheck1Raw) > 0 { + healthCheckMap["health_check_connect_port"] = healthCheck1Raw["HealthCheckConnectPort"] + healthCheckMap["health_check_connect_timeout"] = healthCheck1Raw["HealthCheckConnectTimeout"] + healthCheckMap["health_check_domain"] = healthCheck1Raw["HealthCheckDomain"] + healthCheckMap["health_check_enabled"] = healthCheck1Raw["HealthCheckEnabled"] + healthCheckMap["health_check_interval"] = healthCheck1Raw["HealthCheckInterval"] + healthCheckMap["health_check_type"] = healthCheck1Raw["HealthCheckType"] + healthCheckMap["health_check_url"] = healthCheck1Raw["HealthCheckUrl"] + healthCheckMap["healthy_threshold"] = healthCheck1Raw["HealthyThreshold"] + healthCheckMap["http_check_method"] = healthCheck1Raw["HttpCheckMethod"] + healthCheckMap["unhealthy_threshold"] = healthCheck1Raw["UnhealthyThreshold"] + + healthCheckHttpCode1Raw := make([]interface{}, 0) + if healthCheck1Raw["HealthCheckHttpCode"] != nil { + healthCheckHttpCode1Raw = healthCheck1Raw["HealthCheckHttpCode"].([]interface{}) } + + healthCheckMap["health_check_http_code"] = healthCheckHttpCode1Raw + healthCheckMaps = append(healthCheckMaps, healthCheckMap) } - d.Set("health_check", healthCheckSli) - d.Set("protocol", object["Protocol"]) - d.Set("scheduler", object["Scheduler"]) - d.Set("server_group_name", object["ServerGroupName"]) - d.Set("server_group_type", object["ServerGroupType"]) - d.Set("status", object["ServerGroupStatus"]) - d.Set("vpc_id", object["VpcId"]) - d.Set("resource_group_id", object["ResourceGroupId"]) - d.Set("preserve_client_ip_enabled", object["PreserveClientIpEnabled"]) - if v, ok := object["Tags"]; ok && len(v.([]interface{})) > 0 { - d.Set("tags", tagsToMap(v)) - } + d.Set("health_check", healthCheckMaps) + tagsMaps := objectRaw["Tags"] + d.Set("tags", tagsToMap(tagsMaps)) + d.Set("connection_drain", d.Get("connection_drain_enabled")) return nil } -func resourceAlicloudNlbServerGroupUpdate(d *schema.ResourceData, meta interface{}) error { + +func resourceAliCloudNlbServerGroupUpdate(d *schema.ResourceData, meta interface{}) error { client := meta.(*connectivity.AliyunClient) - nlbService := NlbService{client} + var request map[string]interface{} var response map[string]interface{} + var query map[string]interface{} + update := false + d.Partial(true) + action := "UpdateServerGroupAttribute" conn, err := client.NewNlbClient() if err != nil { return WrapError(err) } - d.Partial(true) - - if d.HasChange("tags") { - if err := nlbService.SetResourceTags(d, "servergroup"); err != nil { - return WrapError(err) - } - d.SetPartial("tags") - } - update := false - request := map[string]interface{}{ - "ServerGroupId": d.Id(), - } + request = make(map[string]interface{}) + query = make(map[string]interface{}) + request["ServerGroupId"] = d.Id() + request["RegionId"] = client.RegionId + request["ClientToken"] = buildClientToken(action) if !d.IsNewResource() && d.HasChange("connection_drain") { update = true - if v, ok := d.GetOkExists("connection_drain"); ok { - request["ConnectionDrainEnabled"] = v - } + request["ConnectionDrainEnabled"] = d.Get("connection_drain") + } + + if !d.IsNewResource() && d.HasChange("connection_drain_enabled") { + update = true + request["ConnectionDrainEnabled"] = d.Get("connection_drain_enabled") } + if !d.IsNewResource() && d.HasChange("connection_drain_timeout") { update = true - if v, ok := d.GetOk("connection_drain_timeout"); ok { - request["ConnectionDrainTimeout"] = v - } + request["ConnectionDrainTimeout"] = d.Get("connection_drain_timeout") } - request["RegionId"] = client.RegionId + if !d.IsNewResource() && d.HasChange("scheduler") { update = true - if v, ok := d.GetOk("scheduler"); ok { - request["Scheduler"] = v - } + request["Scheduler"] = d.Get("scheduler") + } + + if !d.IsNewResource() && d.HasChange("preserve_client_ip_enabled") { + update = true + request["PreserveClientIpEnabled"] = d.Get("preserve_client_ip_enabled") } if !d.IsNewResource() && d.HasChange("health_check") { update = true - if v, ok := d.GetOk("health_check"); ok { - healthCheckConfig := make(map[string]interface{}) - for _, healthCheckConfigArgs := range v.([]interface{}) { - healthCheckConfigArg := healthCheckConfigArgs.(map[string]interface{}) - healthCheckConfig["HealthCheckEnabled"] = healthCheckConfigArg["health_check_enabled"] - if healthCheckConfig["HealthCheckEnabled"] == true { - healthCheckConfig["HealthCheckConnectPort"] = healthCheckConfigArg["health_check_connect_port"] - healthCheckConfig["HealthCheckType"] = healthCheckConfigArg["health_check_type"] - healthCheckConfig["HealthyThreshold"] = healthCheckConfigArg["healthy_threshold"] - healthCheckConfig["UnhealthyThreshold"] = healthCheckConfigArg["unhealthy_threshold"] - healthCheckConfig["HealthCheckConnectTimeout"] = healthCheckConfigArg["health_check_connect_timeout"] - healthCheckConfig["HealthCheckInterval"] = healthCheckConfigArg["health_check_interval"] - if v, ok := healthCheckConfigArg["health_check_domain"]; ok && fmt.Sprint(v) != "" { - healthCheckConfig["HealthCheckDomain"] = v - } - if v, ok := healthCheckConfigArg["health_check_url"]; ok && fmt.Sprint(v) != "" { - healthCheckConfig["HealthCheckUrl"] = v - } - healthCheckConfig["HttpCheckMethod"] = healthCheckConfigArg["http_check_method"] - healthCheckConfig["HealthCheckHttpCode"] = healthCheckConfigArg["health_check_http_code"] + objectDataLocalMap := make(map[string]interface{}) + if v := d.Get("health_check"); !IsNil(v) { + nodeNative, _ := jsonpath.Get("$[0].health_check_enabled", v) + if nodeNative != "" { + objectDataLocalMap["HealthCheckEnabled"] = nodeNative + } + if objectDataLocalMap["HealthCheckEnabled"] == true { + + nodeNative1, _ := jsonpath.Get("$[0].health_check_type", v) + if nodeNative1 != "" { + objectDataLocalMap["HealthCheckType"] = nodeNative1 + } + nodeNative2, _ := jsonpath.Get("$[0].health_check_connect_port", v) + if nodeNative2 != "" { + objectDataLocalMap["HealthCheckConnectPort"] = nodeNative2 + } + nodeNative3, _ := jsonpath.Get("$[0].healthy_threshold", v) + if nodeNative3 != "" { + objectDataLocalMap["HealthyThreshold"] = nodeNative3 + } + nodeNative4, _ := jsonpath.Get("$[0].unhealthy_threshold", v) + if nodeNative4 != "" { + objectDataLocalMap["UnhealthyThreshold"] = nodeNative4 + } + nodeNative5, _ := jsonpath.Get("$[0].health_check_connect_timeout", v) + if nodeNative5 != "" { + objectDataLocalMap["HealthCheckConnectTimeout"] = nodeNative5 + } + nodeNative6, _ := jsonpath.Get("$[0].health_check_interval", v) + if nodeNative6 != "" { + objectDataLocalMap["HealthCheckInterval"] = nodeNative6 + } + nodeNative7, _ := jsonpath.Get("$[0].health_check_domain", v) + if nodeNative7 != "" { + objectDataLocalMap["HealthCheckDomain"] = nodeNative7 + } + nodeNative8, _ := jsonpath.Get("$[0].health_check_url", v) + if nodeNative8 != "" { + objectDataLocalMap["HealthCheckUrl"] = nodeNative8 + } + nodeNative9, _ := jsonpath.Get("$[0].http_check_method", v) + if nodeNative9 != "" { + objectDataLocalMap["HttpCheckMethod"] = nodeNative9 + } + nodeNative10, _ := jsonpath.Get("$[0].health_check_http_code", v) + if nodeNative10 != "" { + objectDataLocalMap["HealthCheckHttpCode"] = nodeNative10 } } - request["HealthCheckConfig"] = healthCheckConfig } + request["HealthCheckConfig"] = objectDataLocalMap } + if update { - action := "UpdateServerGroupAttribute" - request["ClientToken"] = buildClientToken("UpdateServerGroupAttribute") runtime := util.RuntimeOptions{} runtime.SetAutoretry(true) - wait := incrementalWait(3*time.Second, 3*time.Second) - err = resource.Retry(client.GetRetryTimeout(d.Timeout(schema.TimeoutUpdate)), func() *resource.RetryError { - response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2022-04-30"), StringPointer("AK"), nil, request, &runtime) + wait := incrementalWait(3*time.Second, 5*time.Second) + err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError { + response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2022-04-30"), StringPointer("AK"), query, request, &runtime) + request["ClientToken"] = buildClientToken(action) + if err != nil { if NeedRetry(err) { wait() @@ -398,39 +485,55 @@ func resourceAlicloudNlbServerGroupUpdate(d *schema.ResourceData, meta interface } return resource.NonRetryableError(err) } + addDebug(action, response, request) return nil }) - addDebug(action, response, request) if err != nil { return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR) } - if fmt.Sprint(response["Success"]) == "false" { - return WrapError(fmt.Errorf("%s failed, response: %v", action, response)) - } - stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, nlbService.NlbServerGroupStateRefreshFunc(d.Id(), []string{})) + nlbServiceV2 := NlbServiceV2{client} + stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, nlbServiceV2.NlbServerGroupStateRefreshFunc(d.Id(), "ServerGroupStatus", []string{})) if _, err := stateConf.WaitForState(); err != nil { return WrapErrorf(err, IdMsg, d.Id()) } - d.SetPartial("connection_drain") + d.SetPartial("connection_drain_enabled") d.SetPartial("connection_drain_timeout") d.SetPartial("scheduler") + d.SetPartial("preserve_client_ip_enabled") + d.SetPartial("health_check_enabled") + d.SetPartial("health_check_type") + d.SetPartial("health_check_connect_port") + d.SetPartial("healthy_threshold") + d.SetPartial("unhealthy_threshold") + d.SetPartial("health_check_connect_timeout") + d.SetPartial("health_check_interval") + d.SetPartial("health_check_domain") + d.SetPartial("health_check_url") + d.SetPartial("http_check_method") } update = false - addServersToServerGroupReq := map[string]interface{}{ - "ServerGroupId": d.Id(), + action = "UpdateServerGroupAttribute" + conn, err = client.NewNlbClient() + if err != nil { + return WrapError(err) } + request = make(map[string]interface{}) + query = make(map[string]interface{}) + request["ServerGroupId"] = d.Id() + request["RegionId"] = client.RegionId + request["ClientToken"] = buildClientToken(action) if !d.IsNewResource() && d.HasChange("server_group_name") { update = true - addServersToServerGroupReq["ServerGroupName"] = d.Get("server_group_name") } + request["ServerGroupName"] = d.Get("server_group_name") if update { - action := "UpdateServerGroupAttribute" - addServersToServerGroupReq["ClientToken"] = buildClientToken("UpdateServerGroupAttribute") runtime := util.RuntimeOptions{} runtime.SetAutoretry(true) - wait := incrementalWait(3*time.Second, 3*time.Second) - err = resource.Retry(client.GetRetryTimeout(d.Timeout(schema.TimeoutUpdate)), func() *resource.RetryError { - response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2022-04-30"), StringPointer("AK"), nil, addServersToServerGroupReq, &runtime) + wait := incrementalWait(3*time.Second, 5*time.Second) + err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError { + response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2022-04-30"), StringPointer("AK"), query, request, &runtime) + request["ClientToken"] = buildClientToken(action) + if err != nil { if NeedRetry(err) { wait() @@ -438,57 +541,112 @@ func resourceAlicloudNlbServerGroupUpdate(d *schema.ResourceData, meta interface } return resource.NonRetryableError(err) } + addDebug(action, response, request) return nil }) - addDebug(action, response, addServersToServerGroupReq) if err != nil { return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR) } - if fmt.Sprint(response["Success"]) == "false" { - return WrapError(fmt.Errorf("%s failed, response: %v", action, response)) + nlbServiceV2 := NlbServiceV2{client} + stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, nlbServiceV2.NlbServerGroupStateRefreshFunc(d.Id(), "ServerGroupStatus", []string{})) + if _, err := stateConf.WaitForState(); err != nil { + return WrapErrorf(err, IdMsg, d.Id()) } d.SetPartial("server_group_name") } + update = false + action = "MoveResourceGroup" + conn, err = client.NewNlbClient() + if err != nil { + return WrapError(err) + } + request = make(map[string]interface{}) + query = make(map[string]interface{}) + request["ResourceId"] = d.Id() + request["RegionId"] = client.RegionId + request["ClientToken"] = buildClientToken(action) + if _, ok := d.GetOk("resource_group_id"); ok && !d.IsNewResource() && d.HasChange("resource_group_id") { + update = true + request["NewResourceGroupId"] = d.Get("resource_group_id") + } + + request["ResourceType"] = "servergroup" + if update { + runtime := util.RuntimeOptions{} + runtime.SetAutoretry(true) + wait := incrementalWait(3*time.Second, 5*time.Second) + err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError { + response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2022-04-30"), StringPointer("AK"), query, request, &runtime) + request["ClientToken"] = buildClientToken(action) + + if err != nil { + if NeedRetry(err) { + wait() + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + addDebug(action, response, request) + return nil + }) + if err != nil { + return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR) + } + d.SetPartial("resource_group_id") + } + + if d.HasChange("tags") { + nlbServiceV2 := NlbServiceV2{client} + if err := nlbServiceV2.SetResourceTags(d, "servergroup"); err != nil { + return WrapError(err) + } + d.SetPartial("tags") + } d.Partial(false) - return resourceAlicloudNlbServerGroupRead(d, meta) + return resourceAliCloudNlbServerGroupRead(d, meta) } -func resourceAlicloudNlbServerGroupDelete(d *schema.ResourceData, meta interface{}) error { + +func resourceAliCloudNlbServerGroupDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*connectivity.AliyunClient) action := "DeleteServerGroup" + var request map[string]interface{} var response map[string]interface{} + query := make(map[string]interface{}) conn, err := client.NewNlbClient() if err != nil { return WrapError(err) } - request := map[string]interface{}{ - "ServerGroupId": d.Id(), - } - + request = make(map[string]interface{}) + request["ServerGroupId"] = d.Id() request["RegionId"] = client.RegionId - request["ClientToken"] = buildClientToken("DeleteServerGroup") + + request["ClientToken"] = buildClientToken(action) + runtime := util.RuntimeOptions{} runtime.SetAutoretry(true) - wait := incrementalWait(3*time.Second, 3*time.Second) - err = resource.Retry(client.GetRetryTimeout(d.Timeout(schema.TimeoutDelete)), func() *resource.RetryError { - response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2022-04-30"), StringPointer("AK"), nil, request, &runtime) + 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-04-30"), StringPointer("AK"), query, request, &runtime) + request["ClientToken"] = buildClientToken(action) + if err != nil { - if NeedRetry(err) || IsExpectedErrors(err, []string{"SystemBusy"}) { + if NeedRetry(err) { wait() return resource.RetryableError(err) } return resource.NonRetryableError(err) } + addDebug(action, response, request) return nil }) - addDebug(action, response, request) + if err != nil { return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR) } - if fmt.Sprint(response["Success"]) == "false" { - return WrapError(fmt.Errorf("%s failed, response: %v", action, response)) - } - nlbService := NlbService{client} - stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutDelete), 5*time.Second, nlbService.NlbServerGroupStateRefreshFunc(d.Id(), []string{})) + + nlbServiceV2 := NlbServiceV2{client} + stateConf := BuildStateConf([]string{}, []string{"Succeeded"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, nlbServiceV2.DescribeAsyncNlbServerGroupStateRefreshFunc(d, response, "$.Status", []string{})) if _, err := stateConf.WaitForState(); err != nil { return WrapErrorf(err, IdMsg, d.Id()) } diff --git a/alicloud/resource_alicloud_nlb_server_group_test.go b/alicloud/resource_alicloud_nlb_server_group_test.go index 2641f7845c84..7d9a7e0d4a3e 100644 --- a/alicloud/resource_alicloud_nlb_server_group_test.go +++ b/alicloud/resource_alicloud_nlb_server_group_test.go @@ -113,7 +113,7 @@ func testSweepNlbServerGroup(region string) error { return nil } -func TestAccAlicloudNLBServerGroup_basic0(t *testing.T) { +func TestAccAliCloudNLBServerGroup_basic0(t *testing.T) { var v map[string]interface{} resourceId := "alicloud_nlb_server_group.default" ra := resourceAttrInit(resourceId, AlicloudNLBServerGroupMap0) @@ -217,7 +217,7 @@ data "alicloud_resource_manager_resource_groups" "default" {} `, name) } -func TestAccAlicloudNLBServerGroup_basic1(t *testing.T) { +func TestAccAliCloudNLBServerGroup_basic1(t *testing.T) { var v map[string]interface{} resourceId := "alicloud_nlb_server_group.default" ra := resourceAttrInit(resourceId, AlicloudNLBServerGroupMap0) @@ -467,7 +467,7 @@ func TestUnitAccAlicloudNlbServerGroup(t *testing.T) { StatusCode: tea.Int(400), } }) - err = resourceAlicloudNlbServerGroupCreate(dInit, rawClient) + err = resourceAliCloudNlbServerGroupCreate(dInit, rawClient) patches.Reset() assert.NotNil(t, err) ReadMockResponseDiff := map[string]interface{}{} @@ -490,7 +490,7 @@ func TestUnitAccAlicloudNlbServerGroup(t *testing.T) { } return ReadMockResponse, nil }) - err := resourceAlicloudNlbServerGroupCreate(dInit, rawClient) + err := resourceAliCloudNlbServerGroupCreate(dInit, rawClient) patches.Reset() switch errorCode { case "NonRetryableError": @@ -517,7 +517,7 @@ func TestUnitAccAlicloudNlbServerGroup(t *testing.T) { StatusCode: tea.Int(400), } }) - err = resourceAlicloudNlbServerGroupUpdate(dExisted, rawClient) + err = resourceAliCloudNlbServerGroupUpdate(dExisted, rawClient) patches.Reset() assert.NotNil(t, err) attributesDiff := map[string]interface{}{ @@ -585,7 +585,7 @@ func TestUnitAccAlicloudNlbServerGroup(t *testing.T) { } return ReadMockResponse, nil }) - err := resourceAlicloudNlbServerGroupUpdate(dExisted, rawClient) + err := resourceAliCloudNlbServerGroupUpdate(dExisted, rawClient) patches.Reset() switch errorCode { case "NonRetryableError": @@ -637,7 +637,7 @@ func TestUnitAccAlicloudNlbServerGroup(t *testing.T) { } return ReadMockResponse, nil }) - err := resourceAlicloudNlbServerGroupUpdate(dExisted, rawClient) + err := resourceAliCloudNlbServerGroupUpdate(dExisted, rawClient) patches.Reset() switch errorCode { case "NonRetryableError": @@ -701,7 +701,7 @@ func TestUnitAccAlicloudNlbServerGroup(t *testing.T) { } return ReadMockResponse, nil }) - err := resourceAlicloudNlbServerGroupUpdate(dExisted, rawClient) + err := resourceAliCloudNlbServerGroupUpdate(dExisted, rawClient) patches.Reset() switch errorCode { case "NonRetryableError": @@ -765,7 +765,7 @@ func TestUnitAccAlicloudNlbServerGroup(t *testing.T) { } return ReadMockResponse, nil }) - err := resourceAlicloudNlbServerGroupUpdate(dExisted, rawClient) + err := resourceAliCloudNlbServerGroupUpdate(dExisted, rawClient) patches.Reset() switch errorCode { case "NonRetryableError": @@ -809,7 +809,7 @@ func TestUnitAccAlicloudNlbServerGroup(t *testing.T) { } return ReadMockResponse, nil }) - err := resourceAlicloudNlbServerGroupRead(dExisted, rawClient) + err := resourceAliCloudNlbServerGroupRead(dExisted, rawClient) patches.Reset() switch errorCode { case "NonRetryableError": @@ -828,7 +828,7 @@ func TestUnitAccAlicloudNlbServerGroup(t *testing.T) { StatusCode: tea.Int(400), } }) - err = resourceAlicloudNlbServerGroupDelete(dExisted, rawClient) + err = resourceAliCloudNlbServerGroupDelete(dExisted, rawClient) patches.Reset() assert.NotNil(t, err) attributesDiff = map[string]interface{}{} @@ -859,7 +859,7 @@ func TestUnitAccAlicloudNlbServerGroup(t *testing.T) { } return ReadMockResponse, nil }) - err := resourceAlicloudNlbServerGroupDelete(dExisted, rawClient) + err := resourceAliCloudNlbServerGroupDelete(dExisted, rawClient) patches.Reset() switch errorCode { case "NonRetryableError": @@ -869,3 +869,1565 @@ func TestUnitAccAlicloudNlbServerGroup(t *testing.T) { } } } + +// Test Nlb ServerGroup. >>> Resource test cases, automatically generated. +// Case 3734 +func TestAccAliCloudNlbServerGroup_basic3734(t *testing.T) { + var v map[string]interface{} + resourceId := "alicloud_nlb_server_group.default" + ra := resourceAttrInit(resourceId, AlicloudNlbServerGroupMap3734) + rc := resourceCheckInitWithDescribeMethod(resourceId, &v, func() interface{} { + return &NlbServiceV2{testAccProvider.Meta().(*connectivity.AliyunClient)} + }, "DescribeNlbServerGroup") + rac := resourceAttrCheckInit(rc, ra) + testAccCheck := rac.resourceAttrMapUpdateSet() + rand := acctest.RandIntRange(10000, 99999) + name := fmt.Sprintf("tf-testacc%snlbservergroup%d", defaultRegionToTest, rand) + testAccConfig := resourceTestAccConfigFunc(resourceId, name, AlicloudNlbServerGroupBasicDependence3734) + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + }, + IDRefreshName: resourceId, + Providers: testAccProviders, + CheckDestroy: rac.checkResourceDestroy(), + Steps: []resource.TestStep{ + { + Config: testAccConfig(map[string]interface{}{ + "server_group_name": name, + "vpc_id": "${alicloud_vpc.defaultxDhVj6.id}", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "server_group_name": name, + "vpc_id": CHECKSET, + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{}), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{}), + ), + }, + { + Config: testAccConfig(map[string]interface{}{}), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{}), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "server_group_name": name + "_update", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "server_group_name": name + "_update", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "preserve_client_ip_enabled": "true", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "preserve_client_ip_enabled": "true", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "protocol": "TCP", + "server_group_type": "Instance", + "server_group_name": name + "_update", + "vpc_id": "${alicloud_vpc.defaultxDhVj6.id}", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "protocol": "TCP", + "server_group_type": "Instance", + "server_group_name": name + "_update", + "vpc_id": CHECKSET, + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "tags": map[string]string{ + "Created": "TF", + "For": "Test", + }, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "tags.%": "2", + "tags.Created": "TF", + "tags.For": "Test", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "tags": map[string]string{ + "Created": "TF-update", + "For": "Test-update", + }, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "tags.%": "2", + "tags.Created": "TF-update", + "tags.For": "Test-update", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "tags": REMOVEKEY, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "tags.%": "0", + "tags.Created": REMOVEKEY, + "tags.For": REMOVEKEY, + }), + ), + }, + { + ResourceName: resourceId, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{}, + }, + }, + }) +} + +var AlicloudNlbServerGroupMap3734 = map[string]string{ + "status": CHECKSET, + "address_ip_version": CHECKSET, + "scheduler": CHECKSET, + "health_check.#": CHECKSET, + "server_group_type": CHECKSET, + "preserve_client_ip_enabled": CHECKSET, + "connection_drain_enabled": CHECKSET, + "connection_drain_timeout": CHECKSET, + "any_port_enabled": CHECKSET, + "protocol": CHECKSET, +} + +func AlicloudNlbServerGroupBasicDependence3734(name string) string { + return fmt.Sprintf(` +variable "name" { + default = "%s" +} + +resource "alicloud_vpc" "defaultxDhVj6" { + description = "ceshi" + vpc_name = var.name + + cidr_block = "10.0.0.0/8" +} + + +`, name) +} + +// Case 4668 +func TestAccAliCloudNlbServerGroup_basic4668(t *testing.T) { + var v map[string]interface{} + resourceId := "alicloud_nlb_server_group.default" + ra := resourceAttrInit(resourceId, AlicloudNlbServerGroupMap4668) + rc := resourceCheckInitWithDescribeMethod(resourceId, &v, func() interface{} { + return &NlbServiceV2{testAccProvider.Meta().(*connectivity.AliyunClient)} + }, "DescribeNlbServerGroup") + rac := resourceAttrCheckInit(rc, ra) + testAccCheck := rac.resourceAttrMapUpdateSet() + rand := acctest.RandIntRange(10000, 99999) + name := fmt.Sprintf("tf-testacc%snlbservergroup%d", defaultRegionToTest, rand) + testAccConfig := resourceTestAccConfigFunc(resourceId, name, AlicloudNlbServerGroupBasicDependence4668) + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + }, + IDRefreshName: resourceId, + Providers: testAccProviders, + CheckDestroy: rac.checkResourceDestroy(), + Steps: []resource.TestStep{ + { + Config: testAccConfig(map[string]interface{}{ + "any_port_enabled": "false", + "protocol": "UDP", + "server_group_type": "Instance", + "server_group_name": name, + "vpc_id": "${alicloud_vpc.defaultEyoN1M.id}", + "health_check": []map[string]interface{}{ + { + "health_check_type": "HTTP", + "health_check_connect_port": "0", + "healthy_threshold": "2", + "unhealthy_threshold": "2", + "health_check_enabled": "true", + "health_check_connect_timeout": "20", + "health_check_interval": "10", + "health_check_domain": "example.com", + "health_check_url": "/rdk", + "health_check_http_code": []string{ + "http_2xx", "http_3xx", "http_4xx"}, + "http_check_method": "HEAD", + }, + }, + "scheduler": "Qch", + "connection_drain_timeout": "20", + "connection_drain_enabled": "true", + "address_ip_version": "Ipv4", + "tags": map[string]string{ + "Created": "TF", + "For": "Test", + }, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "any_port_enabled": "false", + "protocol": "UDP", + "server_group_type": "Instance", + "server_group_name": name, + "vpc_id": CHECKSET, + "scheduler": "Qch", + "connection_drain_timeout": "20", + "connection_drain_enabled": "true", + "address_ip_version": "Ipv4", + "tags.%": "2", + "tags.Created": "TF", + "tags.For": "Test", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "preserve_client_ip_enabled": "true", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "preserve_client_ip_enabled": "true", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "connection_drain_enabled": "true", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "connection_drain_enabled": "true", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "scheduler": "Qch", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "scheduler": "Qch", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "connection_drain_timeout": "10", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "connection_drain_timeout": "10", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{}), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{}), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "connection_drain_timeout": "20", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "connection_drain_timeout": "20", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{}), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{}), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "health_check": []map[string]interface{}{ + { + "health_check_enabled": "true", + "health_check_connect_port": "0", + "health_check_connect_timeout": "20", + "health_check_interval": "10", + "health_check_domain": "example.com", + "health_check_http_code": []string{"http_4xx"}, + "http_check_method": "HEAD", + }, + }, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{}), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "preserve_client_ip_enabled": "true", + "connection_drain_enabled": "true", + "any_port_enabled": "true", + "protocol": "UDP", + "server_group_type": "Instance", + "server_group_name": name + "_update", + "vpc_id": "${alicloud_vpc.defaultEyoN1M.id}", + "health_check": []map[string]interface{}{ + { + "health_check_enabled": "true", + "health_check_type": "TCP", + "health_check_connect_port": "1", + "healthy_threshold": "2", + "unhealthy_threshold": "2", + "health_check_connect_timeout": "1", + "health_check_interval": "5", + "health_check_domain": "$SERVER_IP", + "health_check_url": "/rdktest", + "health_check_http_code": []string{ + "http_2xx"}, + "http_check_method": "HEAD", + }, + }, + "scheduler": "Qch", + "connection_drain_timeout": "10", + "address_ip_version": "Ipv4", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "preserve_client_ip_enabled": "true", + "connection_drain_enabled": "true", + "any_port_enabled": "true", + "protocol": "UDP", + "server_group_type": "Instance", + "server_group_name": name + "_update", + "vpc_id": CHECKSET, + "scheduler": "Qch", + "connection_drain_timeout": "10", + "address_ip_version": "Ipv4", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "tags": map[string]string{ + "Created": "TF", + "For": "Test", + }, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "tags.%": "2", + "tags.Created": "TF", + "tags.For": "Test", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "tags": map[string]string{ + "Created": "TF-update", + "For": "Test-update", + }, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "tags.%": "2", + "tags.Created": "TF-update", + "tags.For": "Test-update", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "tags": REMOVEKEY, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "tags.%": "0", + "tags.Created": REMOVEKEY, + "tags.For": REMOVEKEY, + }), + ), + }, + { + ResourceName: resourceId, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{}, + }, + }, + }) +} + +var AlicloudNlbServerGroupMap4668 = map[string]string{ + "status": CHECKSET, + "address_ip_version": CHECKSET, + "scheduler": CHECKSET, + "health_check.#": CHECKSET, + "server_group_type": CHECKSET, + "preserve_client_ip_enabled": CHECKSET, + "connection_drain_enabled": CHECKSET, + "connection_drain_timeout": CHECKSET, + "any_port_enabled": CHECKSET, + "protocol": CHECKSET, +} + +func AlicloudNlbServerGroupBasicDependence4668(name string) string { + return fmt.Sprintf(` +variable "name" { + default = "%s" +} + +resource "alicloud_vpc" "defaultEyoN1M" { + cidr_block = "172.16.0.0/12" + vpc_name = var.name + +} + + +`, name) +} + +// Case 4639 +func TestAccAliCloudNlbServerGroup_basic4639(t *testing.T) { + var v map[string]interface{} + resourceId := "alicloud_nlb_server_group.default" + ra := resourceAttrInit(resourceId, AlicloudNlbServerGroupMap4639) + rc := resourceCheckInitWithDescribeMethod(resourceId, &v, func() interface{} { + return &NlbServiceV2{testAccProvider.Meta().(*connectivity.AliyunClient)} + }, "DescribeNlbServerGroup") + rac := resourceAttrCheckInit(rc, ra) + testAccCheck := rac.resourceAttrMapUpdateSet() + rand := acctest.RandIntRange(10000, 99999) + name := fmt.Sprintf("tf-testacc%snlbservergroup%d", defaultRegionToTest, rand) + testAccConfig := resourceTestAccConfigFunc(resourceId, name, AlicloudNlbServerGroupBasicDependence4639) + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + }, + IDRefreshName: resourceId, + Providers: testAccProviders, + CheckDestroy: rac.checkResourceDestroy(), + Steps: []resource.TestStep{ + { + Config: testAccConfig(map[string]interface{}{ + "server_group_name": name, + "vpc_id": "${alicloud_vpc.testsr.id}", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "server_group_name": name, + "vpc_id": CHECKSET, + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "preserve_client_ip_enabled": "true", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "preserve_client_ip_enabled": "true", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "connection_drain_enabled": "true", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "connection_drain_enabled": "true", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "scheduler": "Wrr", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "scheduler": "Wrr", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "connection_drain_timeout": "10", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "connection_drain_timeout": "10", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "server_group_name": name + "_update", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "server_group_name": name + "_update", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{}), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{}), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "server_group_name": name + "_update", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "server_group_name": name + "_update", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "scheduler": "Rr", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "scheduler": "Rr", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "connection_drain_timeout": "20", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "connection_drain_timeout": "20", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{}), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{}), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "server_group_name": name + "_update", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "server_group_name": name + "_update", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "scheduler": "Wrr", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "scheduler": "Wrr", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "scheduler": "Tch", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "scheduler": "Tch", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "preserve_client_ip_enabled": "true", + "connection_drain_enabled": "true", + "any_port_enabled": "true", + "protocol": "TCP", + "server_group_type": "Instance", + "server_group_name": name + "_update", + "vpc_id": "${alicloud_vpc.testsr.id}", + "health_check": []map[string]interface{}{ + { + "health_check_enabled": "true", + "health_check_type": "TCP", + "health_check_connect_port": "1", + "healthy_threshold": "2", + "unhealthy_threshold": "2", + "health_check_connect_timeout": "1", + "health_check_interval": "5", + "health_check_domain": "$SERVER_IP", + "health_check_url": "/rdktest", + "health_check_http_code": []string{ + "http_2xx"}, + "http_check_method": "HEAD", + }, + }, + "scheduler": "Wrr", + "connection_drain_timeout": "10", + "address_ip_version": "Ipv4", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "preserve_client_ip_enabled": "true", + "connection_drain_enabled": "true", + "any_port_enabled": "true", + "protocol": "TCP", + "server_group_type": "Instance", + "server_group_name": name + "_update", + "vpc_id": CHECKSET, + "scheduler": "Wrr", + "connection_drain_timeout": "10", + "address_ip_version": "Ipv4", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "tags": map[string]string{ + "Created": "TF", + "For": "Test", + }, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "tags.%": "2", + "tags.Created": "TF", + "tags.For": "Test", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "tags": map[string]string{ + "Created": "TF-update", + "For": "Test-update", + }, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "tags.%": "2", + "tags.Created": "TF-update", + "tags.For": "Test-update", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "tags": REMOVEKEY, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "tags.%": "0", + "tags.Created": REMOVEKEY, + "tags.For": REMOVEKEY, + }), + ), + }, + { + ResourceName: resourceId, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{}, + }, + }, + }) +} + +var AlicloudNlbServerGroupMap4639 = map[string]string{ + "status": CHECKSET, + "address_ip_version": CHECKSET, + "scheduler": CHECKSET, + "health_check.#": CHECKSET, + "server_group_type": CHECKSET, + "preserve_client_ip_enabled": CHECKSET, + "connection_drain_enabled": CHECKSET, + "connection_drain_timeout": CHECKSET, + "any_port_enabled": CHECKSET, + "protocol": CHECKSET, +} + +func AlicloudNlbServerGroupBasicDependence4639(name string) string { + return fmt.Sprintf(` +variable "name" { + default = "%s" +} + +resource "alicloud_vpc" "testsr" { + cidr_block = "172.16.0.0/12" + vpc_name = var.name + +} + + +`, name) +} + +// Case 4662 +func TestAccAliCloudNlbServerGroup_basic4662(t *testing.T) { + var v map[string]interface{} + resourceId := "alicloud_nlb_server_group.default" + ra := resourceAttrInit(resourceId, AlicloudNlbServerGroupMap4662) + rc := resourceCheckInitWithDescribeMethod(resourceId, &v, func() interface{} { + return &NlbServiceV2{testAccProvider.Meta().(*connectivity.AliyunClient)} + }, "DescribeNlbServerGroup") + rac := resourceAttrCheckInit(rc, ra) + testAccCheck := rac.resourceAttrMapUpdateSet() + rand := acctest.RandIntRange(10000, 99999) + name := fmt.Sprintf("tf-testacc%snlbservergroup%d", defaultRegionToTest, rand) + testAccConfig := resourceTestAccConfigFunc(resourceId, name, AlicloudNlbServerGroupBasicDependence4662) + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + }, + IDRefreshName: resourceId, + Providers: testAccProviders, + CheckDestroy: rac.checkResourceDestroy(), + Steps: []resource.TestStep{ + { + Config: testAccConfig(map[string]interface{}{ + "server_group_name": name, + "vpc_id": "${alicloud_vpc.defaultEyoN1M.id}", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "server_group_name": name, + "vpc_id": CHECKSET, + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "preserve_client_ip_enabled": "true", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "preserve_client_ip_enabled": "true", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "connection_drain_enabled": "true", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "connection_drain_enabled": "true", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "scheduler": "Wrr", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "scheduler": "Wrr", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "connection_drain_timeout": "10", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "connection_drain_timeout": "10", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "resource_group_id": "${data.alicloud_resource_manager_resource_groups.default.ids.0}", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "resource_group_id": CHECKSET, + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "server_group_name": name + "_update", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "server_group_name": name + "_update", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{}), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{}), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "server_group_name": name + "_update", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "server_group_name": name + "_update", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "connection_drain_timeout": "20", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "connection_drain_timeout": "20", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{}), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{}), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "server_group_name": name + "_update", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "server_group_name": name + "_update", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "resource_group_id": "${data.alicloud_resource_manager_resource_groups.default.ids.1}", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "resource_group_id": CHECKSET, + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "preserve_client_ip_enabled": "true", + "connection_drain_enabled": "true", + "any_port_enabled": "true", + "protocol": "TCPSSL", + "server_group_type": "Instance", + "server_group_name": name + "_update", + "vpc_id": "${alicloud_vpc.defaultEyoN1M.id}", + "health_check": []map[string]interface{}{ + { + "health_check_enabled": "true", + "health_check_type": "TCP", + "health_check_connect_port": "1", + "healthy_threshold": "2", + "unhealthy_threshold": "2", + "health_check_connect_timeout": "1", + "health_check_interval": "5", + "health_check_domain": "$SERVER_IP", + "health_check_url": "/rdktest", + "health_check_http_code": []string{ + "http_2xx", "http_4xx"}, + "http_check_method": "HEAD", + }, + }, + "scheduler": "Wrr", + "connection_drain_timeout": "10", + "address_ip_version": "DualStack", + "resource_group_id": "${data.alicloud_resource_manager_resource_groups.default.ids.0}", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "preserve_client_ip_enabled": "true", + "connection_drain_enabled": "true", + "any_port_enabled": "true", + "protocol": "TCPSSL", + "server_group_type": "Instance", + "server_group_name": name + "_update", + "vpc_id": CHECKSET, + "scheduler": "Wrr", + "connection_drain_timeout": "10", + "address_ip_version": "DualStack", + "resource_group_id": CHECKSET, + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "tags": map[string]string{ + "Created": "TF", + "For": "Test", + }, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "tags.%": "2", + "tags.Created": "TF", + "tags.For": "Test", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "tags": map[string]string{ + "Created": "TF-update", + "For": "Test-update", + }, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "tags.%": "2", + "tags.Created": "TF-update", + "tags.For": "Test-update", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "tags": REMOVEKEY, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "tags.%": "0", + "tags.Created": REMOVEKEY, + "tags.For": REMOVEKEY, + }), + ), + }, + { + ResourceName: resourceId, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{}, + }, + }, + }) +} + +var AlicloudNlbServerGroupMap4662 = map[string]string{ + "status": CHECKSET, + "address_ip_version": CHECKSET, + "scheduler": CHECKSET, + "health_check.#": CHECKSET, + "server_group_type": CHECKSET, + "preserve_client_ip_enabled": CHECKSET, + "connection_drain_enabled": CHECKSET, + "connection_drain_timeout": CHECKSET, + "any_port_enabled": CHECKSET, + "protocol": CHECKSET, +} + +func AlicloudNlbServerGroupBasicDependence4662(name string) string { + return fmt.Sprintf(` +variable "name" { + default = "%s" +} + +resource "alicloud_vpc" "defaultEyoN1M" { + cidr_block = "172.16.0.0/12" + vpc_name = var.name + + enable_ipv6 = true +} + +data "alicloud_resource_manager_resource_groups" "default"{ + status = "OK" +} + +`, name) +} + +// Case 5353 +func TestAccAliCloudNlbServerGroup_basic5353(t *testing.T) { + var v map[string]interface{} + resourceId := "alicloud_nlb_server_group.default" + ra := resourceAttrInit(resourceId, AlicloudNlbServerGroupMap5353) + rc := resourceCheckInitWithDescribeMethod(resourceId, &v, func() interface{} { + return &NlbServiceV2{testAccProvider.Meta().(*connectivity.AliyunClient)} + }, "DescribeNlbServerGroup") + rac := resourceAttrCheckInit(rc, ra) + testAccCheck := rac.resourceAttrMapUpdateSet() + rand := acctest.RandIntRange(10000, 99999) + name := fmt.Sprintf("tf-testacc%snlbservergroup%d", defaultRegionToTest, rand) + testAccConfig := resourceTestAccConfigFunc(resourceId, name, AlicloudNlbServerGroupBasicDependence5353) + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + }, + IDRefreshName: resourceId, + Providers: testAccProviders, + CheckDestroy: rac.checkResourceDestroy(), + Steps: []resource.TestStep{ + { + Config: testAccConfig(map[string]interface{}{ + "server_group_name": name, + "vpc_id": "${alicloud_vpc.sgtestnlb.id}", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "server_group_name": name, + "vpc_id": CHECKSET, + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{}), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{}), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "connection_drain_enabled": "true", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "connection_drain_enabled": "true", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "connection_drain_timeout": "10", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "connection_drain_timeout": "10", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "server_group_name": name + "_update", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "server_group_name": name + "_update", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "connection_drain_enabled": "true", + "any_port_enabled": "true", + "protocol": "TCP", + "server_group_type": "Ip", + "server_group_name": name + "_update", + "vpc_id": "${alicloud_vpc.sgtestnlb.id}", + "health_check": []map[string]interface{}{ + { + "health_check_enabled": "true", + "health_check_type": "HTTP", + "health_check_connect_port": "1", + "healthy_threshold": "2", + "unhealthy_threshold": "2", + "health_check_connect_timeout": "1", + "health_check_interval": "5", + "health_check_domain": "$SERVER_IP", + "health_check_url": "/rdktest", + "health_check_http_code": []string{ + "http_2xx"}, + "http_check_method": "HEAD", + }, + }, + "connection_drain_timeout": "10", + "address_ip_version": "Ipv4", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "connection_drain_enabled": "true", + "any_port_enabled": "true", + "protocol": "TCP", + "server_group_type": "Ip", + "server_group_name": name + "_update", + "vpc_id": CHECKSET, + "connection_drain_timeout": "10", + "address_ip_version": "Ipv4", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "tags": map[string]string{ + "Created": "TF", + "For": "Test", + }, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "tags.%": "2", + "tags.Created": "TF", + "tags.For": "Test", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "tags": map[string]string{ + "Created": "TF-update", + "For": "Test-update", + }, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "tags.%": "2", + "tags.Created": "TF-update", + "tags.For": "Test-update", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "tags": REMOVEKEY, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "tags.%": "0", + "tags.Created": REMOVEKEY, + "tags.For": REMOVEKEY, + }), + ), + }, + { + ResourceName: resourceId, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{}, + }, + }, + }) +} + +var AlicloudNlbServerGroupMap5353 = map[string]string{ + "status": CHECKSET, + "address_ip_version": CHECKSET, + "scheduler": CHECKSET, + "health_check.#": CHECKSET, + "server_group_type": CHECKSET, + "preserve_client_ip_enabled": CHECKSET, + "connection_drain_enabled": CHECKSET, + "connection_drain_timeout": CHECKSET, + "any_port_enabled": CHECKSET, + "protocol": CHECKSET, +} + +func AlicloudNlbServerGroupBasicDependence5353(name string) string { + return fmt.Sprintf(` +variable "name" { + default = "%s" +} + +resource "alicloud_vpc" "sgtestnlb" { + description = "nlb tf用例测试" + cidr_block = "172.16.0.0/12" + vpc_name = var.name + +} + + +`, name) +} + +// Case 3734 twin +func TestAccAliCloudNlbServerGroup_basic3734_twin(t *testing.T) { + var v map[string]interface{} + resourceId := "alicloud_nlb_server_group.default" + ra := resourceAttrInit(resourceId, AlicloudNlbServerGroupMap3734) + rc := resourceCheckInitWithDescribeMethod(resourceId, &v, func() interface{} { + return &NlbServiceV2{testAccProvider.Meta().(*connectivity.AliyunClient)} + }, "DescribeNlbServerGroup") + rac := resourceAttrCheckInit(rc, ra) + testAccCheck := rac.resourceAttrMapUpdateSet() + rand := acctest.RandIntRange(10000, 99999) + name := fmt.Sprintf("tf-testacc%snlbservergroup%d", defaultRegionToTest, rand) + testAccConfig := resourceTestAccConfigFunc(resourceId, name, AlicloudNlbServerGroupBasicDependence3734) + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + }, + IDRefreshName: resourceId, + Providers: testAccProviders, + CheckDestroy: rac.checkResourceDestroy(), + Steps: []resource.TestStep{ + { + Config: testAccConfig(map[string]interface{}{ + "preserve_client_ip_enabled": "true", + "protocol": "TCP", + "server_group_type": "Instance", + "server_group_name": name, + "vpc_id": "${alicloud_vpc.defaultxDhVj6.id}", + "tags": map[string]string{ + "Created": "TF", + "For": "Test", + }, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "preserve_client_ip_enabled": "true", + "protocol": "TCP", + "server_group_type": "Instance", + "server_group_name": name, + "vpc_id": CHECKSET, + "tags.%": "2", + "tags.Created": "TF", + "tags.For": "Test", + }), + ), + }, + { + ResourceName: resourceId, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{}, + }, + }, + }) +} + +// Case 4668 twin +func TestAccAliCloudNlbServerGroup_basic4668_twin(t *testing.T) { + var v map[string]interface{} + resourceId := "alicloud_nlb_server_group.default" + ra := resourceAttrInit(resourceId, AlicloudNlbServerGroupMap4668) + rc := resourceCheckInitWithDescribeMethod(resourceId, &v, func() interface{} { + return &NlbServiceV2{testAccProvider.Meta().(*connectivity.AliyunClient)} + }, "DescribeNlbServerGroup") + rac := resourceAttrCheckInit(rc, ra) + testAccCheck := rac.resourceAttrMapUpdateSet() + rand := acctest.RandIntRange(10000, 99999) + name := fmt.Sprintf("tf-testacc%snlbservergroup%d", defaultRegionToTest, rand) + testAccConfig := resourceTestAccConfigFunc(resourceId, name, AlicloudNlbServerGroupBasicDependence4668) + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + }, + IDRefreshName: resourceId, + Providers: testAccProviders, + CheckDestroy: rac.checkResourceDestroy(), + Steps: []resource.TestStep{ + { + Config: testAccConfig(map[string]interface{}{ + "any_port_enabled": "false", + "protocol": "UDP", + "server_group_type": "Instance", + "server_group_name": name, + "vpc_id": "${alicloud_vpc.defaultEyoN1M.id}", + "health_check": []map[string]interface{}{ + { + "health_check_type": "HTTP", + "health_check_connect_port": "0", + "healthy_threshold": "2", + "unhealthy_threshold": "2", + "health_check_enabled": "true", + "health_check_connect_timeout": "20", + "health_check_interval": "10", + "health_check_domain": "example.com", + "health_check_url": "/rdk", + "health_check_http_code": []string{ + "http_2xx", "http_3xx", "http_4xx"}, + "http_check_method": "HEAD", + }, + }, + "scheduler": "Qch", + "connection_drain_timeout": "20", + "connection_drain_enabled": "true", + "address_ip_version": "Ipv4", + "tags": map[string]string{ + "Created": "TF", + "For": "Test", + }, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "any_port_enabled": "false", + "protocol": "UDP", + "server_group_type": "Instance", + "server_group_name": name, + "vpc_id": CHECKSET, + "scheduler": "Qch", + "connection_drain_timeout": "20", + "connection_drain_enabled": "true", + "address_ip_version": "Ipv4", + "tags.%": "2", + "tags.Created": "TF", + "tags.For": "Test", + }), + ), + }, + { + ResourceName: resourceId, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{}, + }, + }, + }) +} + +// Case 4639 twin +func TestAccAliCloudNlbServerGroup_basic4639_twin(t *testing.T) { + var v map[string]interface{} + resourceId := "alicloud_nlb_server_group.default" + ra := resourceAttrInit(resourceId, AlicloudNlbServerGroupMap4639) + rc := resourceCheckInitWithDescribeMethod(resourceId, &v, func() interface{} { + return &NlbServiceV2{testAccProvider.Meta().(*connectivity.AliyunClient)} + }, "DescribeNlbServerGroup") + rac := resourceAttrCheckInit(rc, ra) + testAccCheck := rac.resourceAttrMapUpdateSet() + rand := acctest.RandIntRange(10000, 99999) + name := fmt.Sprintf("tf-testacc%snlbservergroup%d", defaultRegionToTest, rand) + testAccConfig := resourceTestAccConfigFunc(resourceId, name, AlicloudNlbServerGroupBasicDependence4639) + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + }, + IDRefreshName: resourceId, + Providers: testAccProviders, + CheckDestroy: rac.checkResourceDestroy(), + Steps: []resource.TestStep{ + { + Config: testAccConfig(map[string]interface{}{ + "any_port_enabled": "false", + "protocol": "TCP", + "server_group_type": "Instance", + "server_group_name": name, + "vpc_id": "${alicloud_vpc.testsr.id}", + "health_check": []map[string]interface{}{ + { + "health_check_enabled": "true", + "health_check_type": "HTTP", + "health_check_connect_port": "0", + "healthy_threshold": "2", + "unhealthy_threshold": "2", + "health_check_connect_timeout": "20", + "health_check_interval": "10", + "health_check_domain": "example.com", + "health_check_url": "/rdk", + "health_check_http_code": []string{ + "http_2xx", "http_3xx", "http_4xx"}, + "http_check_method": "HEAD", + }, + }, + "scheduler": "Tch", + "connection_drain_timeout": "20", + "connection_drain_enabled": "true", + "address_ip_version": "Ipv4", + "tags": map[string]string{ + "Created": "TF", + "For": "Test", + }, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "any_port_enabled": "false", + "protocol": "TCP", + "server_group_type": "Instance", + "server_group_name": name, + "vpc_id": CHECKSET, + "scheduler": "Tch", + "connection_drain_timeout": "20", + "address_ip_version": "Ipv4", + "tags.%": "2", + "tags.Created": "TF", + "tags.For": "Test", + }), + ), + }, + { + ResourceName: resourceId, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{}, + }, + }, + }) +} + +// Case 4662 twin +func TestAccAliCloudNlbServerGroup_basic4662_twin(t *testing.T) { + var v map[string]interface{} + resourceId := "alicloud_nlb_server_group.default" + ra := resourceAttrInit(resourceId, AlicloudNlbServerGroupMap4662) + rc := resourceCheckInitWithDescribeMethod(resourceId, &v, func() interface{} { + return &NlbServiceV2{testAccProvider.Meta().(*connectivity.AliyunClient)} + }, "DescribeNlbServerGroup") + rac := resourceAttrCheckInit(rc, ra) + testAccCheck := rac.resourceAttrMapUpdateSet() + rand := acctest.RandIntRange(10000, 99999) + name := fmt.Sprintf("tf-testacc%snlbservergroup%d", defaultRegionToTest, rand) + testAccConfig := resourceTestAccConfigFunc(resourceId, name, AlicloudNlbServerGroupBasicDependence4662) + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + }, + IDRefreshName: resourceId, + Providers: testAccProviders, + CheckDestroy: rac.checkResourceDestroy(), + Steps: []resource.TestStep{ + { + Config: testAccConfig(map[string]interface{}{ + "any_port_enabled": "false", + "protocol": "TCPSSL", + "server_group_type": "Instance", + "server_group_name": name, + "vpc_id": "${alicloud_vpc.defaultEyoN1M.id}", + "health_check": []map[string]interface{}{ + { + "health_check_enabled": "true", + "health_check_type": "HTTP", + "health_check_connect_port": "0", + "healthy_threshold": "2", + "unhealthy_threshold": "2", + "health_check_connect_timeout": "20", + "health_check_interval": "10", + "health_check_domain": "example.com", + "health_check_url": "/rdk", + "health_check_http_code": []string{ + "http_2xx", "http_3xx", "http_4xx"}, + "http_check_method": "HEAD", + }, + }, + "scheduler": "Wrr", + "connection_drain_enabled": "true", + "connection_drain_timeout": "20", + "address_ip_version": "DualStack", + "resource_group_id": "${data.alicloud_resource_manager_resource_groups.default.ids.0}", + "tags": map[string]string{ + "Created": "TF", + "For": "Test", + }, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "any_port_enabled": "false", + "protocol": "TCPSSL", + "server_group_type": "Instance", + "server_group_name": name, + "vpc_id": CHECKSET, + "scheduler": "Wrr", + "connection_drain_timeout": "20", + "address_ip_version": "DualStack", + "resource_group_id": CHECKSET, + "tags.%": "2", + "tags.Created": "TF", + "tags.For": "Test", + }), + ), + }, + { + ResourceName: resourceId, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{}, + }, + }, + }) +} + +// Case 5353 twin +func TestAccAliCloudNlbServerGroup_basic5353_twin(t *testing.T) { + var v map[string]interface{} + resourceId := "alicloud_nlb_server_group.default" + ra := resourceAttrInit(resourceId, AlicloudNlbServerGroupMap5353) + rc := resourceCheckInitWithDescribeMethod(resourceId, &v, func() interface{} { + return &NlbServiceV2{testAccProvider.Meta().(*connectivity.AliyunClient)} + }, "DescribeNlbServerGroup") + rac := resourceAttrCheckInit(rc, ra) + testAccCheck := rac.resourceAttrMapUpdateSet() + rand := acctest.RandIntRange(10000, 99999) + name := fmt.Sprintf("tf-testacc%snlbservergroup%d", defaultRegionToTest, rand) + testAccConfig := resourceTestAccConfigFunc(resourceId, name, AlicloudNlbServerGroupBasicDependence5353) + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + }, + IDRefreshName: resourceId, + Providers: testAccProviders, + CheckDestroy: rac.checkResourceDestroy(), + Steps: []resource.TestStep{ + { + Config: testAccConfig(map[string]interface{}{ + "connection_drain_enabled": "true", + "any_port_enabled": "true", + "protocol": "TCP", + "server_group_type": "Ip", + "server_group_name": name, + "vpc_id": "${alicloud_vpc.sgtestnlb.id}", + "health_check": []map[string]interface{}{ + { + "health_check_enabled": "true", + "health_check_type": "HTTP", + "health_check_connect_port": "1", + "healthy_threshold": "2", + "unhealthy_threshold": "2", + "health_check_connect_timeout": "1", + "health_check_interval": "5", + "health_check_domain": "$SERVER_IP", + "health_check_url": "/rdktest", + "health_check_http_code": []string{ + "http_2xx"}, + "http_check_method": "HEAD", + }, + }, + "connection_drain_timeout": "10", + "address_ip_version": "Ipv4", + "tags": map[string]string{ + "Created": "TF", + "For": "Test", + }, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "connection_drain_enabled": "true", + "any_port_enabled": "true", + "protocol": "TCP", + "server_group_type": "Ip", + "server_group_name": name, + "vpc_id": CHECKSET, + "connection_drain_timeout": "10", + "address_ip_version": "Ipv4", + "tags.%": "2", + "tags.Created": "TF", + "tags.For": "Test", + }), + ), + }, + { + ResourceName: resourceId, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{}, + }, + }, + }) +} + +// Test Nlb ServerGroup. <<< Resource test cases, automatically generated. diff --git a/alicloud/service_alicloud_nlb_v2.go b/alicloud/service_alicloud_nlb_v2.go index 2b49fba17d6d..4004fc4bdb5a 100644 --- a/alicloud/service_alicloud_nlb_v2.go +++ b/alicloud/service_alicloud_nlb_v2.go @@ -6,9 +6,12 @@ import ( "time" "github.com/PaesslerAG/jsonpath" + rpc "github.com/alibabacloud-go/tea-rpc/client" util "github.com/alibabacloud-go/tea-utils/service" "github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity" + "github.com/blues/jsonata-go" "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" ) type NlbServiceV2 struct { @@ -18,7 +21,6 @@ type NlbServiceV2 struct { // DescribeNlbLoadbalancerCommonBandwidthPackageAttachment <<< Encapsulated get interface for Nlb LoadbalancerCommonBandwidthPackageAttachment. func (s *NlbServiceV2) DescribeNlbLoadbalancerCommonBandwidthPackageAttachment(id string) (object map[string]interface{}, err error) { - client := s.client var request map[string]interface{} var response map[string]interface{} @@ -38,9 +40,11 @@ func (s *NlbServiceV2) DescribeNlbLoadbalancerCommonBandwidthPackageAttachment(i request["RegionId"] = client.RegionId request["ClientToken"] = buildClientToken(action) + runtime := util.RuntimeOptions{} + runtime.SetAutoretry(true) wait := incrementalWait(3*time.Second, 5*time.Second) err = resource.Retry(1*time.Minute, func() *resource.RetryError { - response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2022-04-30"), StringPointer("AK"), query, request, &util.RuntimeOptions{}) + response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2022-04-30"), StringPointer("AK"), query, request, &runtime) request["ClientToken"] = buildClientToken(action) if err != nil { @@ -55,9 +59,6 @@ func (s *NlbServiceV2) DescribeNlbLoadbalancerCommonBandwidthPackageAttachment(i }) if err != nil { - if IsExpectedErrors(err, []string{}) { - return object, WrapErrorf(Error(GetNotFoundMessage("LoadbalancerCommonBandwidthPackageAttachment", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"])) - } return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR) } @@ -79,7 +80,9 @@ func (s *NlbServiceV2) NlbLoadbalancerCommonBandwidthPackageAttachmentStateRefre return nil, "", WrapError(err) } - currentStatus := fmt.Sprint(object[field]) + v, err := jsonpath.Get(field, object) + currentStatus := fmt.Sprint(v) + for _, failState := range failStates { if currentStatus == failState { return object, currentStatus, WrapError(Error(FailedToReachTargetStatus, currentStatus)) @@ -94,7 +97,6 @@ func (s *NlbServiceV2) NlbLoadbalancerCommonBandwidthPackageAttachmentStateRefre // DescribeNlbListenerAdditionalCertificateAttachment <<< Encapsulated get interface for Nlb ListenerAdditionalCertificateAttachment. func (s *NlbServiceV2) DescribeNlbListenerAdditionalCertificateAttachment(id string) (object map[string]interface{}, err error) { - client := s.client var request map[string]interface{} var response map[string]interface{} @@ -113,9 +115,11 @@ func (s *NlbServiceV2) DescribeNlbListenerAdditionalCertificateAttachment(id str request["ListenerId"] = parts[0] request["RegionId"] = client.RegionId + runtime := util.RuntimeOptions{} + runtime.SetAutoretry(true) wait := incrementalWait(3*time.Second, 5*time.Second) err = resource.Retry(1*time.Minute, func() *resource.RetryError { - response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2022-04-30"), StringPointer("AK"), query, request, &util.RuntimeOptions{}) + response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2022-04-30"), StringPointer("AK"), query, request, &runtime) if err != nil { if NeedRetry(err) { @@ -129,9 +133,6 @@ func (s *NlbServiceV2) DescribeNlbListenerAdditionalCertificateAttachment(id str }) if err != nil { - if IsExpectedErrors(err, []string{}) { - return object, WrapErrorf(Error(GetNotFoundMessage("ListenerAdditionalCertificateAttachment", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"])) - } return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR) } @@ -141,16 +142,18 @@ func (s *NlbServiceV2) DescribeNlbListenerAdditionalCertificateAttachment(id str } if len(v.([]interface{})) == 0 { - return object, WrapErrorf(Error(GetNotFoundMessage("ListenerAdditionalCertificateAttachment", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"])) + return object, WrapErrorf(Error(GetNotFoundMessage("ListenerAdditionalCertificateAttachment", id)), NotFoundMsg, response) } result, _ := v.([]interface{}) for _, v := range result { item := v.(map[string]interface{}) + if item["CertificateId"] != parts[1] { + continue + } return item, nil } - - return v.([]interface{})[0].(map[string]interface{}), nil + return object, WrapErrorf(Error(GetNotFoundMessage("ListenerAdditionalCertificateAttachment", id)), NotFoundMsg, response) } func (s *NlbServiceV2) NlbListenerAdditionalCertificateAttachmentStateRefreshFunc(id string, field string, failStates []string) resource.StateRefreshFunc { @@ -163,7 +166,78 @@ func (s *NlbServiceV2) NlbListenerAdditionalCertificateAttachmentStateRefreshFun return nil, "", WrapError(err) } - currentStatus := fmt.Sprint(object[field]) + v, err := jsonpath.Get(field, object) + currentStatus := fmt.Sprint(v) + + for _, failState := range failStates { + if currentStatus == failState { + return object, currentStatus, WrapError(Error(FailedToReachTargetStatus, currentStatus)) + } + } + return object, currentStatus, nil + } +} + +func (s *NlbServiceV2) DescribeAsyncGetJobStatus(d *schema.ResourceData, res map[string]interface{}) (object map[string]interface{}, err error) { + client := s.client + id := d.Id() + taskId, err := jsonpath.Get("$.JobId", res) + var request map[string]interface{} + var response map[string]interface{} + var query map[string]interface{} + parts := strings.Split(id, ":") + if len(parts) != 2 { + err = WrapError(fmt.Errorf("invalid Resource Id %s. Expected parts' length %d, got %d", id, 2, len(parts))) + } + action := "GetJobStatus" + conn, err := client.NewNlbClient() + if err != nil { + return object, WrapError(err) + } + request = make(map[string]interface{}) + query = make(map[string]interface{}) + + request["ClientToken"] = buildClientToken(action) + request["JobId"] = taskId + + runtime := util.RuntimeOptions{} + runtime.SetAutoretry(true) + wait := incrementalWait(3*time.Second, 5*time.Second) + err = resource.Retry(1*time.Minute, func() *resource.RetryError { + response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2022-04-30"), StringPointer("AK"), query, request, &runtime) + request["ClientToken"] = buildClientToken(action) + + if err != nil { + if NeedRetry(err) { + wait() + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + addDebug(action, response, request) + return nil + }) + + if err != nil { + return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR) + } + + return response, nil +} + +func (s *NlbServiceV2) DescribeAsyncNlbListenerAdditionalCertificateAttachmentStateRefreshFunc(d *schema.ResourceData, res map[string]interface{}, field string, failStates []string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + object, err := s.DescribeAsyncGetJobStatus(d, res) + if err != nil { + if NotFoundError(err) { + return object, "", nil + } + return nil, "", WrapError(err) + } + + v, err := jsonpath.Get(field, object) + currentStatus := fmt.Sprint(v) + for _, failState := range failStates { if currentStatus == failState { return object, currentStatus, WrapError(Error(FailedToReachTargetStatus, currentStatus)) @@ -174,3 +248,706 @@ func (s *NlbServiceV2) NlbListenerAdditionalCertificateAttachmentStateRefreshFun } // DescribeNlbListenerAdditionalCertificateAttachment >>> Encapsulated. +// DescribeNlbLoadBalancerSecurityGroupAttachment <<< Encapsulated get interface for Nlb LoadBalancerSecurityGroupAttachment. + +func (s *NlbServiceV2) DescribeNlbLoadBalancerSecurityGroupAttachment(id string) (object map[string]interface{}, err error) { + client := s.client + var request map[string]interface{} + var response map[string]interface{} + var query map[string]interface{} + parts := strings.Split(id, ":") + if len(parts) != 2 { + err = WrapError(fmt.Errorf("invalid Resource Id %s. Expected parts' length %d, got %d", id, 2, len(parts))) + } + action := "GetLoadBalancerAttribute" + conn, err := client.NewNlbClient() + if err != nil { + return object, WrapError(err) + } + request = make(map[string]interface{}) + query = make(map[string]interface{}) + query["LoadBalancerId"] = parts[0] + request["RegionId"] = client.RegionId + request["ClientToken"] = buildClientToken(action) + + runtime := util.RuntimeOptions{} + runtime.SetAutoretry(true) + wait := incrementalWait(3*time.Second, 5*time.Second) + err = resource.Retry(1*time.Minute, func() *resource.RetryError { + response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2022-04-30"), StringPointer("AK"), query, request, &runtime) + request["ClientToken"] = buildClientToken(action) + + if err != nil { + if NeedRetry(err) { + wait() + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + addDebug(action, response, request) + return nil + }) + + if err != nil { + return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR) + } + + result, _ := response["SecurityGroupIds"].([]interface{}) + for _, v := range result { + if v != parts[1] { + continue + } + return response, nil + } + return object, WrapErrorf(Error(GetNotFoundMessage("LoadBalancerSecurityGroupAttachment", id)), NotFoundMsg, response) +} + +func (s *NlbServiceV2) NlbLoadBalancerSecurityGroupAttachmentStateRefreshFunc(id string, field string, failStates []string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + object, err := s.DescribeNlbLoadBalancerSecurityGroupAttachment(id) + if err != nil { + if NotFoundError(err) { + return object, "", nil + } + return nil, "", WrapError(err) + } + + v, err := jsonpath.Get(field, object) + currentStatus := fmt.Sprint(v) + + for _, failState := range failStates { + if currentStatus == failState { + return object, currentStatus, WrapError(Error(FailedToReachTargetStatus, currentStatus)) + } + } + return object, currentStatus, nil + } +} + +func (s *NlbServiceV2) DescribeAsyncNlbLoadBalancerSecurityGroupAttachmentStateRefreshFunc(d *schema.ResourceData, res map[string]interface{}, field string, failStates []string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + object, err := s.DescribeAsyncGetJobStatus(d, res) + if err != nil { + if NotFoundError(err) { + return object, "", nil + } + return nil, "", WrapError(err) + } + + v, err := jsonpath.Get(field, object) + currentStatus := fmt.Sprint(v) + + for _, failState := range failStates { + if currentStatus == failState { + return object, currentStatus, WrapError(Error(FailedToReachTargetStatus, currentStatus)) + } + } + return object, currentStatus, nil + } +} + +// DescribeNlbLoadBalancerSecurityGroupAttachment >>> Encapsulated. +// DescribeNlbSecurityPolicy <<< Encapsulated get interface for Nlb SecurityPolicy. + +func (s *NlbServiceV2) DescribeNlbSecurityPolicy(id string) (object map[string]interface{}, err error) { + client := s.client + var request map[string]interface{} + var response map[string]interface{} + var query map[string]interface{} + action := "ListSecurityPolicy" + conn, err := client.NewNlbClient() + if err != nil { + return object, WrapError(err) + } + request = make(map[string]interface{}) + query = make(map[string]interface{}) + request["SecurityPolicyIds.1"] = id + request["RegionId"] = client.RegionId + + runtime := util.RuntimeOptions{} + runtime.SetAutoretry(true) + wait := incrementalWait(3*time.Second, 5*time.Second) + err = resource.Retry(1*time.Minute, func() *resource.RetryError { + response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2022-04-30"), StringPointer("AK"), query, request, &runtime) + + if err != nil { + if NeedRetry(err) { + wait() + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + addDebug(action, response, request) + return nil + }) + + if err != nil { + return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR) + } + + v, err := jsonpath.Get("$.SecurityPolicies[*]", response) + if err != nil { + return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.SecurityPolicies[*]", response) + } + + if len(v.([]interface{})) == 0 { + return object, WrapErrorf(Error(GetNotFoundMessage("SecurityPolicy", id)), NotFoundMsg, response) + } + + return v.([]interface{})[0].(map[string]interface{}), nil +} + +func (s *NlbServiceV2) NlbSecurityPolicyStateRefreshFunc(id string, field string, failStates []string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + object, err := s.DescribeNlbSecurityPolicy(id) + if err != nil { + if NotFoundError(err) { + return nil, "", nil + } + return nil, "", WrapError(err) + } + + v, err := jsonpath.Get(field, object) + currentStatus := fmt.Sprint(v) + if field == "$.Ciphers" { + e := jsonata.MustCompile("$split($.Ciphers, \",\")") + v, _ = e.Eval(object) + currentStatus = fmt.Sprint(v) + } + if field == "$.TlsVersion" { + e := jsonata.MustCompile("$split($.TlsVersion, \",\")") + v, _ = e.Eval(object) + currentStatus = fmt.Sprint(v) + } + + for _, failState := range failStates { + if currentStatus == failState { + return object, currentStatus, WrapError(Error(FailedToReachTargetStatus, currentStatus)) + } + } + return object, currentStatus, nil + } +} + +// DescribeNlbSecurityPolicy >>> Encapsulated. + +// SetResourceTags <<< Encapsulated tag function for Nlb. +func (s *NlbServiceV2) SetResourceTags(d *schema.ResourceData, resourceType string) error { + if d.HasChange("tags") { + var err error + var action string + var conn *rpc.Client + client := s.client + var request map[string]interface{} + var response map[string]interface{} + query := make(map[string]interface{}) + + added, removed := parsingTags(d) + removedTagKeys := make([]string, 0) + for _, v := range removed { + if !ignoredTags(v, "") { + removedTagKeys = append(removedTagKeys, v) + } + } + if len(removedTagKeys) > 0 { + action = "UntagResources" + conn, err = client.NewNlbClient() + if err != nil { + return WrapError(err) + } + request = make(map[string]interface{}) + query = make(map[string]interface{}) + request["ResourceId.1"] = d.Id() + request["RegionId"] = client.RegionId + request["ClientToken"] = buildClientToken(action) + for i, key := range removedTagKeys { + request[fmt.Sprintf("TagKey.%d", i+1)] = key + } + + request["ResourceType"] = resourceType + runtime := util.RuntimeOptions{} + runtime.SetAutoretry(true) + wait := incrementalWait(3*time.Second, 5*time.Second) + err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError { + response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2022-04-30"), StringPointer("AK"), query, request, &runtime) + request["ClientToken"] = buildClientToken(action) + + if err != nil { + if NeedRetry(err) { + wait() + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + addDebug(action, response, request) + return nil + }) + if err != nil { + return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR) + } + + } + + if len(added) > 0 { + action = "TagResources" + conn, err = client.NewNlbClient() + if err != nil { + return WrapError(err) + } + request = make(map[string]interface{}) + query = make(map[string]interface{}) + request["ResourceId.1"] = d.Id() + request["RegionId"] = client.RegionId + request["ClientToken"] = buildClientToken(action) + count := 1 + for key, value := range added { + request[fmt.Sprintf("Tag.%d.Key", count)] = key + request[fmt.Sprintf("Tag.%d.Value", count)] = value + count++ + } + + request["ResourceType"] = resourceType + runtime := util.RuntimeOptions{} + runtime.SetAutoretry(true) + wait := incrementalWait(3*time.Second, 5*time.Second) + err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError { + response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2022-04-30"), StringPointer("AK"), query, request, &runtime) + request["ClientToken"] = buildClientToken(action) + + if err != nil { + if NeedRetry(err) { + wait() + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + addDebug(action, response, request) + return nil + }) + if err != nil { + return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR) + } + + } + d.SetPartial("tags") + } + + return nil +} + +// SetResourceTags >>> tag function encapsulated. +// DescribeNlbServerGroup <<< Encapsulated get interface for Nlb ServerGroup. + +func (s *NlbServiceV2) DescribeNlbServerGroup(id string) (object map[string]interface{}, err error) { + client := s.client + var request map[string]interface{} + var response map[string]interface{} + var query map[string]interface{} + action := "ListServerGroups" + conn, err := client.NewNlbClient() + if err != nil { + return object, WrapError(err) + } + request = make(map[string]interface{}) + query = make(map[string]interface{}) + request["ServerGroupIds.1"] = id + request["RegionId"] = client.RegionId + + runtime := util.RuntimeOptions{} + runtime.SetAutoretry(true) + wait := incrementalWait(3*time.Second, 5*time.Second) + err = resource.Retry(1*time.Minute, func() *resource.RetryError { + response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2022-04-30"), StringPointer("AK"), query, request, &runtime) + + if err != nil { + if NeedRetry(err) { + wait() + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + addDebug(action, response, request) + return nil + }) + + if err != nil { + return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR) + } + + v, err := jsonpath.Get("$.ServerGroups[*]", response) + if err != nil { + return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.ServerGroups[*]", response) + } + + if len(v.([]interface{})) == 0 { + return object, WrapErrorf(Error(GetNotFoundMessage("ServerGroup", id)), NotFoundMsg, response) + } + + return v.([]interface{})[0].(map[string]interface{}), nil +} + +func (s *NlbServiceV2) NlbServerGroupStateRefreshFunc(id string, field string, failStates []string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + object, err := s.DescribeNlbServerGroup(id) + if err != nil { + if NotFoundError(err) { + return object, "", nil + } + return nil, "", WrapError(err) + } + + v, err := jsonpath.Get(field, object) + currentStatus := fmt.Sprint(v) + + for _, failState := range failStates { + if currentStatus == failState { + return object, currentStatus, WrapError(Error(FailedToReachTargetStatus, currentStatus)) + } + } + return object, currentStatus, nil + } +} + +func (s *NlbServiceV2) DescribeAsyncNlbServerGroupStateRefreshFunc(d *schema.ResourceData, res map[string]interface{}, field string, failStates []string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + object, err := s.DescribeAsyncGetJobStatus(d, res) + if err != nil { + if NotFoundError(err) { + return object, "", nil + } + return nil, "", WrapError(err) + } + + v, err := jsonpath.Get(field, object) + currentStatus := fmt.Sprint(v) + + for _, failState := range failStates { + if currentStatus == failState { + return object, currentStatus, WrapError(Error(FailedToReachTargetStatus, currentStatus)) + } + } + return object, currentStatus, nil + } +} + +// DescribeNlbServerGroup >>> Encapsulated. +// DescribeNlbServerGroupServerAttachment <<< Encapsulated get interface for Nlb ServerGroupServerAttachment. + +func (s *NlbServiceV2) DescribeNlbServerGroupServerAttachment(id string) (object map[string]interface{}, err error) { + client := s.client + var request map[string]interface{} + var response map[string]interface{} + var query map[string]interface{} + parts := strings.Split(id, ":") + if len(parts) != 4 { + err = WrapError(fmt.Errorf("invalid Resource Id %s. Expected parts' length %d, got %d", id, 4, len(parts))) + } + action := "ListServerGroupServers" + conn, err := client.NewNlbClient() + if err != nil { + return object, WrapError(err) + } + request = make(map[string]interface{}) + query = make(map[string]interface{}) + request["ServerGroupId"] = parts[0] + request["ServerIds.1"] = parts[1] + request["RegionId"] = client.RegionId + + runtime := util.RuntimeOptions{} + runtime.SetAutoretry(true) + wait := incrementalWait(3*time.Second, 5*time.Second) + err = resource.Retry(1*time.Minute, func() *resource.RetryError { + response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2022-04-30"), StringPointer("AK"), query, request, &runtime) + + if err != nil { + if NeedRetry(err) { + wait() + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + addDebug(action, response, request) + return nil + }) + + if err != nil { + return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR) + } + + v, err := jsonpath.Get("$.Servers[*]", response) + if err != nil { + return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Servers[*]", response) + } + + if len(v.([]interface{})) == 0 { + return object, WrapErrorf(Error(GetNotFoundMessage("ServerGroupServerAttachment", id)), NotFoundMsg, response) + } + + result, _ := v.([]interface{}) + for _, v := range result { + item := v.(map[string]interface{}) + if fmt.Sprint(item["Port"]) != parts[3] { + continue + } + if item["ServerGroupId"] != parts[0] { + continue + } + if item["ServerId"] != parts[1] { + continue + } + if item["ServerType"] != parts[2] { + continue + } + return item, nil + } + return object, WrapErrorf(Error(GetNotFoundMessage("ServerGroupServerAttachment", id)), NotFoundMsg, response) +} + +func (s *NlbServiceV2) NlbServerGroupServerAttachmentStateRefreshFunc(id string, field string, failStates []string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + object, err := s.DescribeNlbServerGroupServerAttachment(id) + if err != nil { + if NotFoundError(err) { + return object, "", nil + } + return nil, "", WrapError(err) + } + + v, err := jsonpath.Get(field, object) + currentStatus := fmt.Sprint(v) + + for _, failState := range failStates { + if currentStatus == failState { + return object, currentStatus, WrapError(Error(FailedToReachTargetStatus, currentStatus)) + } + } + return object, currentStatus, nil + } +} + +// DescribeNlbServerGroupServerAttachment >>> Encapsulated. +// DescribeNlbListener <<< Encapsulated get interface for Nlb Listener. + +func (s *NlbServiceV2) DescribeNlbListener(id string) (object map[string]interface{}, err error) { + client := s.client + var request map[string]interface{} + var response map[string]interface{} + var query map[string]interface{} + action := "GetListenerAttribute" + conn, err := client.NewNlbClient() + if err != nil { + return object, WrapError(err) + } + request = make(map[string]interface{}) + query = make(map[string]interface{}) + query["ListenerId"] = id + request["RegionId"] = client.RegionId + request["ClientToken"] = buildClientToken(action) + + runtime := util.RuntimeOptions{} + runtime.SetAutoretry(true) + wait := incrementalWait(3*time.Second, 5*time.Second) + err = resource.Retry(1*time.Minute, func() *resource.RetryError { + response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2022-04-30"), StringPointer("AK"), query, request, &runtime) + request["ClientToken"] = buildClientToken(action) + + if err != nil { + if NeedRetry(err) { + wait() + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + addDebug(action, response, request) + return nil + }) + + if err != nil { + if IsExpectedErrors(err, []string{"ResourceNotFound.listener"}) { + return object, WrapErrorf(Error(GetNotFoundMessage("Listener", id)), NotFoundMsg, response) + } + return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR) + } + + return response, nil +} + +func (s *NlbServiceV2) NlbListenerStateRefreshFunc(id string, field string, failStates []string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + object, err := s.DescribeNlbListener(id) + if err != nil { + if NotFoundError(err) { + return object, "", nil + } + return nil, "", WrapError(err) + } + + v, err := jsonpath.Get(field, object) + currentStatus := fmt.Sprint(v) + + for _, failState := range failStates { + if currentStatus == failState { + return object, currentStatus, WrapError(Error(FailedToReachTargetStatus, currentStatus)) + } + } + return object, currentStatus, nil + } +} + +func (s *NlbServiceV2) DescribeAsyncNlbListenerStateRefreshFunc(d *schema.ResourceData, res map[string]interface{}, field string, failStates []string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + object, err := s.DescribeAsyncGetJobStatus(d, res) + if err != nil { + if NotFoundError(err) { + return object, "", nil + } + return nil, "", WrapError(err) + } + + v, err := jsonpath.Get(field, object) + currentStatus := fmt.Sprint(v) + + for _, failState := range failStates { + if currentStatus == failState { + return object, currentStatus, WrapError(Error(FailedToReachTargetStatus, currentStatus)) + } + } + return object, currentStatus, nil + } +} + +// DescribeNlbListener >>> Encapsulated. + +// DescribeNlbLoadBalancer <<< Encapsulated get interface for Nlb LoadBalancer. + +func (s *NlbServiceV2) DescribeNlbLoadBalancer(id string) (object map[string]interface{}, err error) { + client := s.client + var request map[string]interface{} + var response map[string]interface{} + var query map[string]interface{} + action := "GetLoadBalancerAttribute" + conn, err := client.NewNlbClient() + if err != nil { + return object, WrapError(err) + } + request = make(map[string]interface{}) + query = make(map[string]interface{}) + query["LoadBalancerId"] = id + request["RegionId"] = client.RegionId + request["ClientToken"] = buildClientToken(action) + + runtime := util.RuntimeOptions{} + runtime.SetAutoretry(true) + wait := incrementalWait(3*time.Second, 5*time.Second) + err = resource.Retry(1*time.Minute, func() *resource.RetryError { + response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2022-04-30"), StringPointer("AK"), query, request, &runtime) + request["ClientToken"] = buildClientToken(action) + + if err != nil { + if NeedRetry(err) { + wait() + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + addDebug(action, response, request) + return nil + }) + + if err != nil { + if IsExpectedErrors(err, []string{"ResourceNotFound.loadBalancer"}) { + return object, WrapErrorf(Error(GetNotFoundMessage("LoadBalancer", id)), NotFoundMsg, response) + } + return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR) + } + + return response, nil +} +func (s *NlbServiceV2) DescribeListTagResources(id string) (object map[string]interface{}, err error) { + client := s.client + var request map[string]interface{} + var response map[string]interface{} + var query map[string]interface{} + action := "ListTagResources" + conn, err := client.NewNlbClient() + if err != nil { + return object, WrapError(err) + } + request = make(map[string]interface{}) + query = make(map[string]interface{}) + request["ResourceId.1"] = id + request["RegionId"] = client.RegionId + + request["ResourceType"] = "loadbalancer" + runtime := util.RuntimeOptions{} + runtime.SetAutoretry(true) + wait := incrementalWait(3*time.Second, 5*time.Second) + err = resource.Retry(1*time.Minute, func() *resource.RetryError { + response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2022-04-30"), StringPointer("AK"), query, request, &runtime) + + if err != nil { + if NeedRetry(err) { + wait() + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + addDebug(action, response, request) + return nil + }) + + if err != nil { + if IsExpectedErrors(err, []string{"ResourceNotFound.loadBalancer"}) { + return object, WrapErrorf(Error(GetNotFoundMessage("LoadBalancer", id)), NotFoundMsg, response) + } + return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR) + } + + return response, nil +} + +func (s *NlbServiceV2) NlbLoadBalancerStateRefreshFunc(id string, field string, failStates []string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + object, err := s.DescribeNlbLoadBalancer(id) + if err != nil { + if NotFoundError(err) { + return object, "", nil + } + return nil, "", WrapError(err) + } + + v, err := jsonpath.Get(field, object) + currentStatus := fmt.Sprint(v) + + for _, failState := range failStates { + if currentStatus == failState { + return object, currentStatus, WrapError(Error(FailedToReachTargetStatus, currentStatus)) + } + } + return object, currentStatus, nil + } +} + +func (s *NlbServiceV2) DescribeAsyncNlbLoadBalancerStateRefreshFunc(d *schema.ResourceData, res map[string]interface{}, field string, failStates []string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + object, err := s.DescribeAsyncGetJobStatus(d, res) + if err != nil { + if NotFoundError(err) { + return object, "", nil + } + return nil, "", WrapError(err) + } + + v, err := jsonpath.Get(field, object) + currentStatus := fmt.Sprint(v) + + for _, failState := range failStates { + if currentStatus == failState { + return object, currentStatus, WrapError(Error(FailedToReachTargetStatus, currentStatus)) + } + } + return object, currentStatus, nil + } +} + +// DescribeNlbLoadBalancer >>> Encapsulated. diff --git a/website/docs/r/nlb_server_group.html.markdown b/website/docs/r/nlb_server_group.html.markdown index 63c4f1cee1ce..c56440c4678d 100644 --- a/website/docs/r/nlb_server_group.html.markdown +++ b/website/docs/r/nlb_server_group.html.markdown @@ -2,14 +2,13 @@ subcategory: "Network Load Balancer (NLB)" layout: "alicloud" page_title: "Alicloud: alicloud_nlb_server_group" -sidebar_current: "docs-alicloud-resource-nlb-server-group" description: |- Provides a Alicloud NLB Server Group resource. --- # alicloud_nlb_server_group -Provides a NLB Server Group resource. +Provides a NLB Server Group resource. For information about NLB Server Group and how to use it, see [What is Server Group](https://www.alibabacloud.com/help/en/server-load-balancer/latest/createservergroup-nlb). @@ -59,59 +58,71 @@ resource "alicloud_nlb_server_group" "default" { ## Argument Reference The following arguments are supported: - -* `address_ip_version` - (Optional, ForceNew) The protocol version. Valid values: `Ipv4` (default), `DualStack`. -* `connection_drain` - (Optional) Specifies whether to enable connection draining. -* `connection_drain_timeout` - (Optional) The timeout period of connection draining. Unit: seconds. Valid values: 10 to 900. -* `health_check` - (Required) HealthCheck. See [`health_check`](#health_check) below. -* `protocol` - (Optional, ForceNew) The backend protocol. Valid values: `TCP` (default), `UDP`, and `TCPSSL`. -* `resource_group_id` - (Optional, ForceNew) The ID of the resource group to which the security group belongs. -* `scheduler` - (Optional) The routing algorithm. Valid values: - - `Wrr` (default): The Weighted Round Robin algorithm is used. Backend servers with higher weights receive more requests than backend servers with lower weights. - - `Rr`: The round-robin algorithm is used. Requests are forwarded to backend servers in sequence. - - `Sch`: Source IP hashing is used. Requests from the same source IP address are forwarded to the same backend server. - - `Tch`: Four-element hashing is used. It specifies consistent hashing that is based on four factors: source IP address, destination IP address, source port, and destination port. Requests that contain the same information based on the four factors are forwarded to the same backend server. - - `Qch`: QUIC ID hashing is used. Requests that contain the same QUIC ID are forwarded to the same backend server. -* `server_group_name` - (Required) The name of the server group. The name must be 2 to 128 characters in length, and can contain letters, digits, periods (.), underscores (_), and hyphens (-). The name must start with a letter. -* `server_group_type` - (Optional, ForceNew) The type of the server group. Valid values: - - `Instance` (default): allows you to specify `Ecs`, `Ens`, or `Eci`. - - `Ip`: allows you to specify IP addresses. -* `vpc_id` - (Required, ForceNew) The id of the vpc. -* `tags` - (Optional) A mapping of tags to assign to the resource. -* `preserve_client_ip_enabled` - (Optional) Indicates whether client address retention is enabled. +* `address_ip_version` - (Optional, ForceNew, Computed) Protocol version. Value: + - **ipv4**:IPv4 type. + - **DualStack**: Double Stack type. +* `any_port_enabled` - (Optional, ForceNew, Computed, Available since v1.214.0) Full port forwarding. +* `connection_drain_enabled` - (Optional, Computed, Available since v1.214.0) Whether to open the connection gracefully interrupted. Value: + - **true**: on. + - **false**: closed. +* `connection_drain_timeout` - (Optional, Computed) Set the connection elegant interrupt timeout. Unit: seconds. Valid values: **10** ~ **900**. +* `health_check` - (Optional, ForceNew, Computed) Health check configuration information. See [`health_check`](#health_check) below. +* `preserve_client_ip_enabled` - (Optional, Computed) Whether to enable the client address retention function. Value: + - **true**: on. + - **false**: closed. +-> **NOTE:** special instructions: When **AddressIPVersion** is of the **ipv4** type, the default value is **true**. **Addrestipversion** can only be **false** when the value of **ipv6** is **ipv6**, and can be **true** when supported by the underlying layer * *. +* `protocol` - (Optional, ForceNew, Computed) The backend Forwarding Protocol. Valid values: **TCP**, **UDP**, or **TCPSSL**. +* `resource_group_id` - (Optional, Computed) The ID of the resource group to which the server group belongs. +* `scheduler` - (Optional, Computed) Scheduling algorithm. Value: + - **Wrr**: Weighted polling. The higher the weight of the backend server, the higher the probability of being polled. + - **Rr**: polls external requests are distributed to backend servers in sequence according to the access order. sch: Source IP hash: The same source address is scheduled to the same backend server. + - **Tch**: Quadruple hash, based on the consistent hash of the Quad (source IP, Destination IP, source port, and destination port), the same stream is scheduled to the same backend server. + - **Qch**: a QUIC ID hash that allows you to hash requests with the same QUIC ID to the same backend server. +* `server_group_name` - (Required) The name of the server group. +* `server_group_type` - (Optional, ForceNew, Computed) Server group type. Value: + - **Instance**: The server type. You can add **Ecs**, **Ens**, and **Eci** instances to the server group. + - **Ip**: Ip address type. You can add Ip addresses to a server group of this type. +* `tags` - (Optional, Map) Label. +* `vpc_id` - (Required, ForceNew) The ID of the VPC to which the server group belongs. + +The following arguments will be discarded. Please use new fields as soon as possible: +* `connection_drain` - (Deprecated since v1.214.0). Field 'connection_drain' has been deprecated from provider version 1.214.0. New field 'connection_drain_enabled' instead. ### `health_check` -The health_check supports the following: - -* `health_check_connect_port` - (Optional) The backend port that is used for health checks. Valid values: 0 to 65535. Default value: 0. If you set the value to 0, the port of a backend server is used for health checks. -* `health_check_connect_timeout` - (Optional) The maximum timeout period of a health check response. Unit: seconds. Valid values: 1 to 300. Default value: 5. -* `health_check_domain` - (Optional) The domain name that is used for health checks. Valid values: - - `$SERVER_IP`: the private IP address of a backend server. - - `domain`: a specified domain name. The domain name must be 1 to 80 characters in length, and can contain letters, digits, hyphens (-), and periods (.). -* `health_check_enabled` - (Optional) Specifies whether to enable health checks. -* `health_check_interval` - (Optional) The interval between two consecutive health checks. Unit: seconds. Valid values: 5 to 5000. Default value: 10. -* `health_check_type` - (Optional) The protocol that is used for health checks. Valid values: `TCP` (default) and `HTTP`. -* `health_check_url` - (Optional) The path to which health check requests are sent. The path must be 1 to 80 characters in length, and can contain only letters, digits, and the following special characters: `- / . % ? # & =`. It can also contain the following extended characters: `_ ; ~ ! ( ) * [ ] @ $ ^ : ' , +`. The path must start with a forward slash (/). **Note:** This parameter takes effect only if `health_check_type` is set to `http`. -* `healthy_threshold` - (Optional) The number of times that an unhealthy backend server must consecutively pass health checks before it is declared healthy. In this case, the health status is changed from fail to success. Valid values: 2 to 10. Default value: 2. -* `unhealthy_threshold` - (Optional) The number of times that a healthy backend server must consecutively fail health checks before it is declared unhealthy. In this case, the health status is changed from success to fail. Valid values: 2 to 10. Default value: 2. -* `http_check_method` - (Optional) The HTTP method that is used for health checks. Valid values: `GET` and `HEAD`. **Note:** This parameter takes effect only if `health_check_type` is set to `http`. -* `health_check_http_code` - (Optional) The HTTP status codes to return to health checks. Separate multiple HTTP status codes with commas (,). Valid values: http_2xx (default), http_3xx, http_4xx, and http_5xx. **Note:** This parameter takes effect only if `health_check_type` is set to `http`. +The health_check supports the following: +* `health_check_connect_port` - (Optional, Computed) The port of the backend server for health checks. Valid values: **0** ~ **65535**. **0** indicates that the port of the backend server is used for health check. +* `health_check_connect_timeout` - (Optional, Computed) Maximum timeout for health check responses. Unit: seconds. Valid values: **1** ~ **300**. +* `health_check_domain` - (Optional, Computed) The domain name used for health check. Valid values: + - **$SERVER_IP**: uses the intranet IP of the backend server. + - **domain**: Specify a specific domain name. The length is limited to 1 to 80 characters. Only lowercase letters, numbers, dashes (-), and half-width periods (.) can be used. +-> **NOTE:** This parameter takes effect only when **HealthCheckType** is **HTTP**. +* `health_check_enabled` - (Optional, Computed) Whether to enable health check. Valid values: + - **true**: on. + - **false**: closed. +* `health_check_http_code` - (Optional, Computed) Health status return code. Multiple status codes are separated by commas (,). Valid values: **http\_2xx**, **http\_3xx**, **http\_4xx**, and **http\_5xx**. +-> **NOTE:** This parameter takes effect only when **HealthCheckType** is **HTTP**. +* `health_check_interval` - (Optional, Computed) Time interval of health examination. Unit: seconds.Valid values: **5** ~ **50**. +* `health_check_type` - (Optional, Computed) Health check protocol. Valid values: **TCP** or **HTTP**. +* `health_check_url` - (Optional, Computed) Health check path. +-> **NOTE:** This parameter takes effect only when **HealthCheckType** is **HTTP**. +* `healthy_threshold` - (Optional, Computed) After the health check is successful, the health check status of the backend server is determined from **failed** to **successful * *.Valid values: **2** to **10 * *. +* `http_check_method` - (Optional) The health check method. Valid values: **GET** or **HEAD**. +-> **NOTE:** This parameter takes effect only when **HealthCheckType** is **HTTP**. +* `unhealthy_threshold` - (Optional, Computed) After the health check fails for many times in a row, the health check status of the backend server is determined from **Success** to **Failure**. Valid values: **2** to **10**. ## Attributes Reference The following attributes are exported: - -* `id` - The resource ID in terraform of Server Group. -* `status` - The status of the resource. +* `id` - The ID of the resource supplied above. +* `status` - Server group status. Value: ## Timeouts The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/docs/configuration-0-11/resources.html#timeouts) for certain actions: - -* `create` - (Defaults to 1 mins) Used when create the Server Group. -* `update` - (Defaults to 1 mins) Used when update the Server Group. -* `delete` - (Defaults to 1 mins) Used when delete the Server Group. +* `create` - (Defaults to 5 mins) Used when create the Server Group. +* `delete` - (Defaults to 5 mins) Used when delete the Server Group. +* `update` - (Defaults to 5 mins) Used when update the Server Group. ## Import