diff --git a/alicloud/resource_alicloud_kms_key.go b/alicloud/resource_alicloud_kms_key.go index 60890ec1a4dd..e0565ecff92f 100644 --- a/alicloud/resource_alicloud_kms_key.go +++ b/alicloud/resource_alicloud_kms_key.go @@ -1,3 +1,4 @@ +// Package alicloud. This file is generated automatically. Please do not modify it manually, thank you! package alicloud import ( @@ -27,26 +28,25 @@ func resourceAliCloudKmsKey() *schema.Resource { Delete: schema.DefaultTimeout(5 * time.Minute), }, Schema: map[string]*schema.Schema{ - "key_usage": { + "automatic_rotation": { Type: schema.TypeString, Optional: true, - ForceNew: true, Computed: true, - ValidateFunc: StringInSlice([]string{"ENCRYPT/DECRYPT", "SIGN/VERIFY"}, false), + ValidateFunc: StringInSlice([]string{"Enabled", "Disabled"}, false), }, - "origin": { + "deletion_protection": { Type: schema.TypeString, Optional: true, - ForceNew: true, Computed: true, - ValidateFunc: StringInSlice([]string{"Aliyun_KMS", "EXTERNAL"}, false), + ValidateFunc: StringInSlice([]string{"Enabled", "Disabled"}, false), }, - "key_spec": { - Type: schema.TypeString, - Optional: true, - ForceNew: true, - Computed: true, - ValidateFunc: StringInSlice([]string{"Aliyun_AES_256", "Aliyun_AES_128", "Aliyun_AES_192", "Aliyun_SM4", "RSA_2048", "RSA_3072", "EC_P256", "EC_P256K", "EC_SM2"}, false), + "deletion_protection_description": { + Type: schema.TypeString, + Optional: true, + }, + "description": { + Type: schema.TypeString, + Optional: true, }, "dkms_instance_id": { Type: schema.TypeString, @@ -54,22 +54,32 @@ func resourceAliCloudKmsKey() *schema.Resource { Computed: true, ForceNew: true, }, - "protection_level": { + "key_spec": { Type: schema.TypeString, Optional: true, + Computed: true, ForceNew: true, - Default: "SOFTWARE", - ValidateFunc: StringInSlice([]string{"SOFTWARE", "HSM"}, false), + ValidateFunc: StringInSlice([]string{"Aliyun_AES_256", "Aliyun_AES_128", "Aliyun_AES_192", "Aliyun_SM4", "RSA_2048", "RSA_3072", "EC_P256", "EC_P256K", "EC_SM2"}, false), }, - "automatic_rotation": { + "key_usage": { Type: schema.TypeString, Optional: true, Computed: true, - ValidateFunc: StringInSlice([]string{"Enabled", "Disabled"}, false), + ForceNew: true, + ValidateFunc: StringInSlice([]string{"ENCRYPT/DECRYPT", "SIGN/VERIFY"}, false), }, - "rotation_interval": { - Type: schema.TypeString, - Optional: true, + "origin": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + ValidateFunc: StringInSlice([]string{"Aliyun_KMS", "EXTERNAL"}, false), + }, + "pending_window_in_days": { + Type: schema.TypeInt, + Optional: true, + ValidateFunc: IntBetween(7, 366), + ConflictsWith: []string{"deletion_window_in_days"}, }, "policy": { Type: schema.TypeString, @@ -80,7 +90,14 @@ func resourceAliCloudKmsKey() *schema.Resource { return equal }, }, - "description": { + "protection_level": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + Default: "SOFTWARE", + ValidateFunc: StringInSlice([]string{"SOFTWARE", "HSM"}, false), + }, + "rotation_interval": { Type: schema.TypeString, Optional: true, }, @@ -91,12 +108,6 @@ func resourceAliCloudKmsKey() *schema.Resource { ValidateFunc: StringInSlice([]string{"Enabled", "Disabled", "PendingDeletion"}, false), ConflictsWith: []string{"key_state"}, }, - "pending_window_in_days": { - Type: schema.TypeInt, - Optional: true, - ValidateFunc: IntBetween(7, 366), - ConflictsWith: []string{"deletion_window_in_days"}, - }, "tags": tagsSchema(), "arn": { Type: schema.TypeString, @@ -141,7 +152,6 @@ func resourceAliCloudKmsKey() *schema.Resource { Type: schema.TypeString, Optional: true, Computed: true, - ValidateFunc: StringInSlice([]string{"Enabled", "Disabled", "PendingDeletion"}, false), ConflictsWith: []string{"status"}, Deprecated: "Field `key_state` has been deprecated from provider version 1.123.1. New field `status` instead.", }, @@ -156,49 +166,45 @@ func resourceAliCloudKmsKey() *schema.Resource { } func resourceAliCloudKmsKeyCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*connectivity.AliyunClient) - var response map[string]interface{} + action := "CreateKey" - request := make(map[string]interface{}) + var request map[string]interface{} + var response map[string]interface{} + query := make(map[string]interface{}) conn, err := client.NewKmsClient() if err != nil { return WrapError(err) } + request = make(map[string]interface{}) + if v, ok := d.GetOk("description"); ok { + request["Description"] = v + } if v, ok := d.GetOk("key_usage"); ok { request["KeyUsage"] = v } - if v, ok := d.GetOk("origin"); ok { request["Origin"] = v } - - if v, ok := d.GetOk("key_spec"); ok { - request["KeySpec"] = v - } - - if v, ok := d.GetOk("dkms_instance_id"); ok { - request["DKMSInstanceId"] = v - } - if v, ok := d.GetOk("protection_level"); ok { request["ProtectionLevel"] = v } - - if v, ok := d.GetOk("automatic_rotation"); ok { - request["EnableAutomaticRotation"] = convertKmsKeyAutomaticRotationRequest(v.(string)) - } - if v, ok := d.GetOk("rotation_interval"); ok { request["RotationInterval"] = v } - + if v, ok := d.GetOk("key_spec"); ok { + request["KeySpec"] = v + } if v, ok := d.GetOk("policy"); ok { request["Policy"] = v } - - if v, ok := d.GetOk("description"); ok { - request["Description"] = v + if v, ok := d.GetOk("automatic_rotation"); ok { + request["EnableAutomaticRotation"] = convertKmsKeyAutomaticRotationRequest(v.(string)) + } + if v, ok := d.GetOk("dkms_instance_id"); ok { + request["DKMSInstanceId"] = v } if v, ok := d.GetOk("tags"); ok { @@ -210,14 +216,13 @@ func resourceAliCloudKmsKeyCreate(d *schema.ResourceData, meta interface{}) erro request["Tags"] = tagsJson } - 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("2016-01-20"), 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("2016-01-20"), StringPointer("AK"), query, request, &runtime) if err != nil { - if NeedRetry(err) { + if IsExpectedErrors(err, []string{"Forbidden.DKMSInstanceStateInvalid"}) || NeedRetry(err) { wait() return resource.RetryableError(err) } @@ -243,42 +248,34 @@ func resourceAliCloudKmsKeyCreate(d *schema.ResourceData, meta interface{}) erro func resourceAliCloudKmsKeyRead(d *schema.ResourceData, meta interface{}) error { client := meta.(*connectivity.AliyunClient) - kmsService := KmsService{client} + kmsServiceV2 := KmsServiceV2{client} - object, err := kmsService.DescribeKmsKey(d.Id()) + objectRaw, err := kmsServiceV2.DescribeKmsKey(d.Id()) if err != nil { if !d.IsNewResource() && NotFoundError(err) { - log.Printf("[DEBUG] Resource alicloud_kms_key kmsService.DescribeKmsKey Failed!!! %s", err) + log.Printf("[DEBUG] Resource alicloud_kms_key DescribeKmsKey Failed!!! %s", err) d.SetId("") return nil } return WrapError(err) } - d.Set("key_usage", object["KeyUsage"]) - d.Set("origin", object["Origin"]) - d.Set("key_spec", object["KeySpec"]) - d.Set("protection_level", object["ProtectionLevel"]) - d.Set("automatic_rotation", object["AutomaticRotation"]) - d.Set("rotation_interval", object["RotationInterval"]) - d.Set("description", object["Description"]) - d.Set("status", object["KeyState"]) - d.Set("arn", object["Arn"]) - d.Set("primary_key_version", object["PrimaryKeyVersion"]) - d.Set("last_rotation_date", object["LastRotationDate"]) - d.Set("next_rotation_date", object["NextRotationDate"]) - d.Set("material_expire_time", object["MaterialExpireTime"]) - d.Set("creator", object["Creator"]) - d.Set("creation_date", object["CreationDate"]) - d.Set("delete_date", object["DeleteDate"]) - d.Set("key_state", object["KeyState"]) - d.Set("is_enabled", convertKmsKeyIsEnabledResponse(object["KeyState"])) - - if dkmsInstanceId, ok := object["DKMSInstanceId"].(string); ok { + if objectRaw["AutomaticRotation"] != nil { + d.Set("automatic_rotation", objectRaw["AutomaticRotation"]) + } + if objectRaw["DeletionProtection"] != nil { + d.Set("deletion_protection", objectRaw["DeletionProtection"]) + } + d.Set("deletion_protection_description", objectRaw["DeletionProtectionDescription"]) + if objectRaw["Description"] != nil { + d.Set("description", objectRaw["Description"]) + } + + if dkmsInstanceId, ok := objectRaw["DKMSInstanceId"].(string); ok { d.Set("dkms_instance_id", dkmsInstanceId) if dkmsInstanceId != "" { - policy, err := kmsService.DescribeKmsKeyPolicy(d.Id()) + policy, err := kmsServiceV2.DescribeKmsKeyPolicy(d.Id()) if err != nil { return WrapError(err) } @@ -289,157 +286,67 @@ func resourceAliCloudKmsKeyRead(d *schema.ResourceData, meta interface{}) error } } - listTagResourcesObject, err := kmsService.ListTagResources(d.Id(), "key") - if err != nil { - return WrapError(err) + if objectRaw["KeySpec"] != nil { + d.Set("key_spec", objectRaw["KeySpec"]) } - - d.Set("tags", tagsToMap(listTagResourcesObject)) - - return nil -} - -func resourceAliCloudKmsKeyUpdate(d *schema.ResourceData, meta interface{}) error { - client := meta.(*connectivity.AliyunClient) - kmsService := KmsService{client} - var response map[string]interface{} - d.Partial(true) - - update := false - updateRotationPolicyReq := map[string]interface{}{ - "KeyId": d.Id(), + if objectRaw["KeyUsage"] != nil { + d.Set("key_usage", objectRaw["KeyUsage"]) } - - if !d.IsNewResource() && d.HasChange("automatic_rotation") { - update = true + if objectRaw["Origin"] != nil { + d.Set("origin", objectRaw["Origin"]) } - if v, ok := d.GetOk("automatic_rotation"); ok { - updateRotationPolicyReq["EnableAutomaticRotation"] = convertKmsKeyAutomaticRotationRequest(v) + if objectRaw["ProtectionLevel"] != nil { + d.Set("protection_level", objectRaw["ProtectionLevel"]) } - - if !d.IsNewResource() && d.HasChange("rotation_interval") { - update = true + d.Set("rotation_interval", objectRaw["RotationInterval"]) + if objectRaw["KeyState"] != nil { + d.Set("status", objectRaw["KeyState"]) + d.Set("key_state", objectRaw["KeyState"]) + d.Set("is_enabled", convertKmsKeyIsEnabledResponse(objectRaw["KeyState"])) } - if v, ok := d.GetOk("rotation_interval"); ok { - updateRotationPolicyReq["RotationInterval"] = v + if objectRaw["Arn"] != nil { + d.Set("arn", objectRaw["Arn"]) } - - if update { - action := "UpdateRotationPolicy" - conn, err := client.NewKmsClient() - if err != nil { - return WrapError(err) - } - - 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("2016-01-20"), StringPointer("AK"), nil, updateRotationPolicyReq, &runtime) - if err != nil { - if NeedRetry(err) { - wait() - return resource.RetryableError(err) - } - return resource.NonRetryableError(err) - } - return nil - }) - addDebug(action, response, updateRotationPolicyReq) - - if err != nil { - return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR) - } - - d.SetPartial("automatic_rotation") - d.SetPartial("rotation_interval") + if objectRaw["PrimaryKeyVersion"] != nil { + d.Set("primary_key_version", objectRaw["PrimaryKeyVersion"]) } - - update = false - setKeyPolicyReq := map[string]interface{}{ - "KeyId": d.Id(), + if objectRaw["LastRotationDate"] != nil { + d.Set("last_rotation_date", objectRaw["LastRotationDate"]) } - - if !d.IsNewResource() && d.HasChange("policy") { - update = true + d.Set("next_rotation_date", objectRaw["NextRotationDate"]) + if objectRaw["MaterialExpireTime"] != nil { + d.Set("material_expire_time", objectRaw["MaterialExpireTime"]) } - if v, ok := d.GetOk("policy"); ok { - setKeyPolicyReq["Policy"] = v + if objectRaw["Creator"] != nil { + d.Set("creator", objectRaw["Creator"]) } - - if update { - action := "SetKeyPolicy" - conn, err := client.NewKmsClient() - if err != nil { - return WrapError(err) - } - - 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("2016-01-20"), StringPointer("AK"), nil, setKeyPolicyReq, &runtime) - if err != nil { - if NeedRetry(err) { - wait() - return resource.RetryableError(err) - } - return resource.NonRetryableError(err) - } - return nil - }) - addDebug(action, response, setKeyPolicyReq) - - if err != nil { - return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR) - } - - d.SetPartial("policy") + if objectRaw["CreationDate"] != nil { + d.Set("creation_date", objectRaw["CreationDate"]) } - - update = false - updateKeyDescriptionReq := map[string]interface{}{ - "KeyId": d.Id(), + if objectRaw["DeleteDate"] != nil { + d.Set("delete_date", objectRaw["DeleteDate"]) } - if !d.IsNewResource() && d.HasChange("description") { - update = true - } - if v, ok := d.GetOk("description"); ok { - updateKeyDescriptionReq["Description"] = v + listTagResourcesObject, err := kmsServiceV2.ListTagResources(d.Id(), "key") + if err != nil { + return WrapError(err) } - if update { - action := "UpdateKeyDescription" - conn, err := client.NewKmsClient() - if err != nil { - return WrapError(err) - } + d.Set("tags", tagsToMap(listTagResourcesObject)) - 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("2016-01-20"), StringPointer("AK"), nil, updateKeyDescriptionReq, &runtime) - if err != nil { - if NeedRetry(err) { - wait() - return resource.RetryableError(err) - } - return resource.NonRetryableError(err) - } - return nil - }) - addDebug(action, response, updateKeyDescriptionReq) + return nil +} - if err != nil { - return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR) - } +func resourceAliCloudKmsKeyUpdate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*connectivity.AliyunClient) + kmsServiceV2 := KmsServiceV2{client} - d.SetPartial("description") - } + var request map[string]interface{} + var response map[string]interface{} + var query map[string]interface{} + update := false + d.Partial(true) - update = false var statusTarget string if d.HasChange("status") { @@ -467,28 +374,27 @@ func resourceAliCloudKmsKeyUpdate(d *schema.ResourceData, meta interface{}) erro } if update { - object, err := kmsService.DescribeKmsKey(d.Id()) + object, err := kmsServiceV2.DescribeKmsKey(d.Id()) if err != nil { return WrapError(err) } if object["KeyState"].(string) != statusTarget { if statusTarget == "Disabled" { - request := map[string]interface{}{ - "KeyId": d.Id(), - } - action := "DisableKey" conn, err := client.NewKmsClient() if err != nil { return WrapError(err) } + request = make(map[string]interface{}) + query = make(map[string]interface{}) + request["KeyId"] = d.Id() 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("2016-01-20"), StringPointer("AK"), nil, request, &runtime) + response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-01-20"), StringPointer("AK"), query, request, &runtime) if err != nil { if NeedRetry(err) { wait() @@ -504,28 +410,27 @@ func resourceAliCloudKmsKeyUpdate(d *schema.ResourceData, meta interface{}) erro return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR) } - stateConf := BuildStateConf([]string{}, []string{"Disabled"}, d.Timeout(schema.TimeoutUpdate), 10*time.Second, kmsService.KmsKeyStateRefreshFunc(d.Id(), []string{})) + stateConf := BuildStateConf([]string{}, []string{"Disabled"}, d.Timeout(schema.TimeoutUpdate), 10*time.Second, kmsServiceV2.KmsKeyStateRefreshFunc(d.Id(), "KeyState", []string{})) if _, err := stateConf.WaitForState(); err != nil { return WrapErrorf(err, IdMsg, d.Id()) } } if statusTarget == "Enabled" { - request := map[string]interface{}{ - "KeyId": d.Id(), - } - action := "EnableKey" conn, err := client.NewKmsClient() if err != nil { return WrapError(err) } + request = make(map[string]interface{}) + query = make(map[string]interface{}) + request["KeyId"] = d.Id() 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("2016-01-20"), StringPointer("AK"), nil, request, &runtime) + response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-01-20"), StringPointer("AK"), query, request, &runtime) if err != nil { if NeedRetry(err) { wait() @@ -541,28 +446,185 @@ func resourceAliCloudKmsKeyUpdate(d *schema.ResourceData, meta interface{}) erro return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR) } - stateConf := BuildStateConf([]string{}, []string{"Enabled"}, d.Timeout(schema.TimeoutUpdate), 10*time.Second, kmsService.KmsKeyStateRefreshFunc(d.Id(), []string{})) + stateConf := BuildStateConf([]string{}, []string{"Enabled"}, d.Timeout(schema.TimeoutUpdate), 10*time.Second, kmsServiceV2.KmsKeyStateRefreshFunc(d.Id(), "KeyState", []string{})) if _, err := stateConf.WaitForState(); err != nil { return WrapErrorf(err, IdMsg, d.Id()) } } + } + } + update = false + action := "UpdateKeyDescription" + conn, err := client.NewKmsClient() + if err != nil { + return WrapError(err) + } + request = make(map[string]interface{}) + query = make(map[string]interface{}) + request["KeyId"] = d.Id() - d.SetPartial("status") - d.SetPartial("key_state") - d.SetPartial("is_enabled") + if !d.IsNewResource() && d.HasChange("description") { + update = true + } + if v, ok := d.GetOk("description"); ok { + request["Description"] = v + } + 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("2016-01-20"), StringPointer("AK"), query, request, &runtime) + if err != nil { + if NeedRetry(err) { + wait() + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + addDebug(action, response, request) + if err != nil { + return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR) } } + update = false + action = "UpdateRotationPolicy" + conn, err = client.NewKmsClient() + if err != nil { + return WrapError(err) + } + request = make(map[string]interface{}) + query = make(map[string]interface{}) + request["KeyId"] = d.Id() - if !d.IsNewResource() && d.HasChange("tags") { - if err := kmsService.SetResourceTags(d, "key"); err != nil { + if !d.IsNewResource() && d.HasChange("automatic_rotation") { + update = true + } + if v, ok := d.GetOk("automatic_rotation"); ok { + request["EnableAutomaticRotation"] = convertKmsKeyAutomaticRotationRequest(v) + } + + if !d.IsNewResource() && d.HasChange("rotation_interval") { + update = true + } + if v, ok := d.GetOk("rotation_interval"); ok { + request["RotationInterval"] = v + } + + 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("2016-01-20"), StringPointer("AK"), query, request, &runtime) + if err != nil { + if NeedRetry(err) { + wait() + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + addDebug(action, response, request) + if err != nil { + return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR) + } + } + update = false + action = "SetDeletionProtection" + conn, err = client.NewKmsClient() + if err != nil { + return WrapError(err) + } + request = make(map[string]interface{}) + query = make(map[string]interface{}) + request["KeyId"] = d.Id() + + if d.HasChange("deletion_protection_description") { + update = true + } + if v, ok := d.GetOk("deletion_protection_description"); ok { + request["DeletionProtectionDescription"] = v + } + + if d.HasChange("deletion_protection") { + update = true + } + if v, ok := d.GetOk("deletion_protection"); ok { + request["EnableDeletionProtection"] = convertKmsKeyDeletionProtectionRequest(v) + } + + 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("2016-01-20"), StringPointer("AK"), query, request, &runtime) + if err != nil { + if NeedRetry(err) { + wait() + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + addDebug(action, response, request) + if err != nil { + return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR) + } + } + + update = false + setKeyPolicyReq := map[string]interface{}{ + "KeyId": d.Id(), + } + + if !d.IsNewResource() && d.HasChange("policy") { + update = true + } + if v, ok := d.GetOk("policy"); ok { + setKeyPolicyReq["Policy"] = v + } + + if update { + action := "SetKeyPolicy" + conn, err := client.NewKmsClient() + if err != nil { return WrapError(err) } - d.SetPartial("tags") + 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("2016-01-20"), StringPointer("AK"), nil, setKeyPolicyReq, &runtime) + if err != nil { + if NeedRetry(err) { + wait() + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + addDebug(action, response, setKeyPolicyReq) + + if err != nil { + return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR) + } } - d.Partial(false) + if !d.IsNewResource() && d.HasChange("tags") { + if err := kmsServiceV2.SetResourceTags(d, "key"); err != nil { + return WrapError(err) + } + } + d.Partial(false) return resourceAliCloudKmsKeyRead(d, meta) } @@ -642,3 +704,15 @@ func convertKmsKeyIsEnabledResponse(source interface{}) interface{} { return false } + +func convertKmsKeyDeletionProtectionRequest(source interface{}) interface{} { + source = fmt.Sprint(source) + switch source { + case "Enabled": + return true + case "Disabled": + return false + } + + return false +} diff --git a/alicloud/resource_alicloud_kms_key_test.go b/alicloud/resource_alicloud_kms_key_test.go index ebdda6abb24f..98b2fcdae6fa 100644 --- a/alicloud/resource_alicloud_kms_key_test.go +++ b/alicloud/resource_alicloud_kms_key_test.go @@ -119,7 +119,9 @@ func testSweepKmsKey(region string) error { return nil } -func TestAccAliCloudKmsKey_basic0(t *testing.T) { +// Test Kms Key. >>> Resource test cases, automatically generated. +// Case 全生命周期 8855 +func TestAccAliCloudKmsKey_basic8855(t *testing.T) { var v map[string]interface{} resourceId := "alicloud_kms_key.default" ra := resourceAttrInit(resourceId, AliCloudKmsKeyMap0) @@ -130,7 +132,7 @@ func TestAccAliCloudKmsKey_basic0(t *testing.T) { testAccCheck := rac.resourceAttrMapUpdateSet() rand := acctest.RandIntRange(1000000, 9999999) name := fmt.Sprintf("tf-testAcc%sKmsKey%d", defaultRegionToTest, rand) - testAccConfig := resourceTestAccConfigFunc(resourceId, name, AliCloudKmsKeyBasicDependence0) + testAccConfig := resourceTestAccConfigFunc(resourceId, name, AliCloudKmsKeyBasicDependence8855) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) @@ -175,11 +177,33 @@ func TestAccAliCloudKmsKey_basic0(t *testing.T) { }, { Config: testAccConfig(map[string]interface{}{ - "description": name, + "deletion_protection": "Enabled", }), Check: resource.ComposeTestCheckFunc( testAccCheck(map[string]string{ - "description": name, + "deletion_protection": "Enabled", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "deletion_protection_description": name, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "deletion_protection_description": name, + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "deletion_protection": "Disabled", + "deletion_protection_description": REMOVEKEY, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "deletion_protection": "Disabled", + "deletion_protection_description": REMOVEKEY, }), ), }, @@ -207,14 +231,41 @@ func TestAccAliCloudKmsKey_basic0(t *testing.T) { Config: testAccConfig(map[string]interface{}{ "tags": map[string]string{ "Created": "TF", - "For": "Key", + "For": "Test", }, }), Check: resource.ComposeTestCheckFunc( testAccCheck(map[string]string{ "tags.%": "2", "tags.Created": "TF", - "tags.For": "Key", + "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, }), ), }, @@ -228,7 +279,7 @@ func TestAccAliCloudKmsKey_basic0(t *testing.T) { }) } -func TestAccAliCloudKmsKey_basic0_twin(t *testing.T) { +func TestAccAliCloudKmsKey_basic8855_twin(t *testing.T) { var v map[string]interface{} resourceId := "alicloud_kms_key.default" ra := resourceAttrInit(resourceId, AliCloudKmsKeyMap0) @@ -239,7 +290,7 @@ func TestAccAliCloudKmsKey_basic0_twin(t *testing.T) { testAccCheck := rac.resourceAttrMapUpdateSet() rand := acctest.RandIntRange(1000000, 9999999) name := fmt.Sprintf("tf-testAcc%sKmsKey%d", defaultRegionToTest, rand) - testAccConfig := resourceTestAccConfigFunc(resourceId, name, AliCloudKmsKeyBasicDependence0) + testAccConfig := resourceTestAccConfigFunc(resourceId, name, AliCloudKmsKeyBasicDependence8855) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) @@ -250,33 +301,49 @@ func TestAccAliCloudKmsKey_basic0_twin(t *testing.T) { Steps: []resource.TestStep{ { Config: testAccConfig(map[string]interface{}{ - "key_usage": "ENCRYPT/DECRYPT", - "origin": "Aliyun_KMS", - "key_spec": "Aliyun_AES_256", - "protection_level": "SOFTWARE", - "automatic_rotation": "Enabled", - "rotation_interval": "605800s", - "description": name, - "status": "Enabled", - "pending_window_in_days": "7", + "key_usage": "ENCRYPT/DECRYPT", + "origin": "Aliyun_KMS", + "key_spec": "Aliyun_AES_256", + "protection_level": "SOFTWARE", + "automatic_rotation": "Enabled", + "rotation_interval": "605800s", + "description": name, + "status": "Enabled", + "deletion_protection": "Enabled", + "deletion_protection_description": name, + "pending_window_in_days": "7", "tags": map[string]string{ "Created": "TF", - "For": "Key", + "For": "Test", }, }), Check: resource.ComposeTestCheckFunc( testAccCheck(map[string]string{ - "key_usage": "ENCRYPT/DECRYPT", - "origin": "Aliyun_KMS", - "key_spec": "Aliyun_AES_256", - "protection_level": "SOFTWARE", - "automatic_rotation": "Enabled", - "rotation_interval": "605800s", - "description": name, - "status": "Enabled", - "tags.%": "2", - "tags.Created": "TF", - "tags.For": "Key", + "key_usage": "ENCRYPT/DECRYPT", + "origin": "Aliyun_KMS", + "key_spec": "Aliyun_AES_256", + "protection_level": "SOFTWARE", + "automatic_rotation": "Enabled", + "rotation_interval": "605800s", + "description": name, + "status": "Enabled", + "deletion_protection": "Enabled", + "deletion_protection_description": name, + "tags.%": "2", + "tags.Created": "TF", + "tags.For": "Test", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "deletion_protection": "Disabled", + "deletion_protection_description": REMOVEKEY, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "deletion_protection": "Disabled", + "deletion_protection_description": REMOVEKEY, }), ), }, @@ -290,7 +357,8 @@ func TestAccAliCloudKmsKey_basic0_twin(t *testing.T) { }) } -func TestAccAliCloudKmsKey_basic1(t *testing.T) { +// Case 全生命周期dkms_instance_id, policy 8856 +func TestAccAliCloudKmsKey_basic8856(t *testing.T) { var v map[string]interface{} resourceId := "alicloud_kms_key.default" ra := resourceAttrInit(resourceId, AliCloudKmsKeyMap1) @@ -301,7 +369,7 @@ func TestAccAliCloudKmsKey_basic1(t *testing.T) { testAccCheck := rac.resourceAttrMapUpdateSet() rand := acctest.RandIntRange(1000000, 9999999) name := fmt.Sprintf("tf-testAcc%sKmsKey%d", defaultRegionToTest, rand) - testAccConfig := resourceTestAccConfigFunc(resourceId, name, AliCloudKmsKeyBasicDependence1) + testAccConfig := resourceTestAccConfigFunc(resourceId, name, AliCloudKmsKeyBasicDependence8856) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) @@ -346,6 +414,38 @@ func TestAccAliCloudKmsKey_basic1(t *testing.T) { }), ), }, + { + Config: testAccConfig(map[string]interface{}{ + "deletion_protection": "Enabled", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "deletion_protection": "Enabled", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "deletion_protection_description": name, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "deletion_protection_description": name, + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "deletion_protection": "Disabled", + "deletion_protection_description": REMOVEKEY, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "deletion_protection": "Disabled", + "deletion_protection_description": REMOVEKEY, + }), + ), + }, { Config: testAccConfig(map[string]interface{}{ "policy": `{\"Statement\": [{\"Action\": [\"kms:*\"],\"Effect\": \"Allow\",\"Principal\": {\"RAM\": [\"acs:ram::` + "${data.alicloud_account.default.id}" + `:*\"]},\"Resource\": [\"*\"],\"Sid\": \"Key\"}],\"Version\": \"1\"}`, @@ -390,14 +490,41 @@ func TestAccAliCloudKmsKey_basic1(t *testing.T) { Config: testAccConfig(map[string]interface{}{ "tags": map[string]string{ "Created": "TF", - "For": "Key", + "For": "Test", }, }), Check: resource.ComposeTestCheckFunc( testAccCheck(map[string]string{ "tags.%": "2", "tags.Created": "TF", - "tags.For": "Key", + "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, }), ), }, @@ -411,7 +538,7 @@ func TestAccAliCloudKmsKey_basic1(t *testing.T) { }) } -func TestAccAliCloudKmsKey_basic1_twin(t *testing.T) { +func TestAccAliCloudKmsKey_basic8856_twin(t *testing.T) { var v map[string]interface{} resourceId := "alicloud_kms_key.default" ra := resourceAttrInit(resourceId, AliCloudKmsKeyMap1) @@ -422,7 +549,7 @@ func TestAccAliCloudKmsKey_basic1_twin(t *testing.T) { testAccCheck := rac.resourceAttrMapUpdateSet() rand := acctest.RandIntRange(1000000, 9999999) name := fmt.Sprintf("tf-testAcc%sKmsKey%d", defaultRegionToTest, rand) - testAccConfig := resourceTestAccConfigFunc(resourceId, name, AliCloudKmsKeyBasicDependence1) + testAccConfig := resourceTestAccConfigFunc(resourceId, name, AliCloudKmsKeyBasicDependence8856) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) @@ -433,37 +560,53 @@ func TestAccAliCloudKmsKey_basic1_twin(t *testing.T) { Steps: []resource.TestStep{ { Config: testAccConfig(map[string]interface{}{ - "key_usage": "ENCRYPT/DECRYPT", - "origin": "Aliyun_KMS", - "key_spec": "Aliyun_AES_256", - "dkms_instance_id": "${alicloud_kms_instance.default.id}", - "protection_level": "SOFTWARE", - "automatic_rotation": "Enabled", - "rotation_interval": "605800s", - "policy": `{\"Statement\": [{\"Action\": [\"kms:*\"],\"Effect\": \"Allow\",\"Principal\": {\"RAM\": [\"acs:ram::` + "${data.alicloud_account.default.id}" + `:*\"]},\"Resource\": [\"*\"],\"Sid\": \"Key\"}],\"Version\": \"1\"}`, - "description": name, - "status": "Enabled", - "pending_window_in_days": "7", + "key_usage": "ENCRYPT/DECRYPT", + "origin": "Aliyun_KMS", + "key_spec": "Aliyun_AES_256", + "dkms_instance_id": "${alicloud_kms_instance.default.id}", + "protection_level": "SOFTWARE", + "automatic_rotation": "Enabled", + "rotation_interval": "605800s", + "policy": `{\"Statement\": [{\"Action\": [\"kms:*\"],\"Effect\": \"Allow\",\"Principal\": {\"RAM\": [\"acs:ram::` + "${data.alicloud_account.default.id}" + `:*\"]},\"Resource\": [\"*\"],\"Sid\": \"Key\"}],\"Version\": \"1\"}`, + "description": name, + "deletion_protection": "Enabled", + "deletion_protection_description": name, + "status": "Enabled", + "pending_window_in_days": "7", "tags": map[string]string{ "Created": "TF", - "For": "Key", + "For": "Test", }, }), Check: resource.ComposeTestCheckFunc( testAccCheck(map[string]string{ - "key_usage": "ENCRYPT/DECRYPT", - "origin": "Aliyun_KMS", - "key_spec": "Aliyun_AES_256", - "dkms_instance_id": CHECKSET, - "protection_level": "SOFTWARE", - "automatic_rotation": "Enabled", - "rotation_interval": "605800s", - "policy": CHECKSET, - "description": name, - "status": "Enabled", - "tags.%": "2", - "tags.Created": "TF", - "tags.For": "Key", + "key_usage": "ENCRYPT/DECRYPT", + "origin": "Aliyun_KMS", + "key_spec": "Aliyun_AES_256", + "dkms_instance_id": CHECKSET, + "protection_level": "SOFTWARE", + "automatic_rotation": "Enabled", + "rotation_interval": "605800s", + "policy": CHECKSET, + "description": name, + "deletion_protection": "Enabled", + "deletion_protection_description": name, + "status": "Enabled", + "tags.%": "2", + "tags.Created": "TF", + "tags.For": "Test", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "deletion_protection": "Disabled", + "deletion_protection_description": REMOVEKEY, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "deletion_protection": "Disabled", + "deletion_protection_description": REMOVEKEY, }), ), }, @@ -477,7 +620,8 @@ func TestAccAliCloudKmsKey_basic1_twin(t *testing.T) { }) } -func TestAccAliCloudKmsKey_basic2(t *testing.T) { +// Case 全生命周期, 适配废弃字段key_state 8857 +func TestAccAliCloudKmsKey_basic8857(t *testing.T) { var v map[string]interface{} resourceId := "alicloud_kms_key.default" ra := resourceAttrInit(resourceId, AliCloudKmsKeyMap0) @@ -488,7 +632,7 @@ func TestAccAliCloudKmsKey_basic2(t *testing.T) { testAccCheck := rac.resourceAttrMapUpdateSet() rand := acctest.RandIntRange(1000000, 9999999) name := fmt.Sprintf("tf-testAcc%sKmsKey%d", defaultRegionToTest, rand) - testAccConfig := resourceTestAccConfigFunc(resourceId, name, AliCloudKmsKeyBasicDependence0) + testAccConfig := resourceTestAccConfigFunc(resourceId, name, AliCloudKmsKeyBasicDependence8855) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) @@ -531,6 +675,38 @@ func TestAccAliCloudKmsKey_basic2(t *testing.T) { }), ), }, + { + Config: testAccConfig(map[string]interface{}{ + "deletion_protection": "Enabled", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "deletion_protection": "Enabled", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "deletion_protection_description": name, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "deletion_protection_description": name, + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "deletion_protection": "Disabled", + "deletion_protection_description": REMOVEKEY, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "deletion_protection": "Disabled", + "deletion_protection_description": REMOVEKEY, + }), + ), + }, { Config: testAccConfig(map[string]interface{}{ "description": name, @@ -565,14 +741,41 @@ func TestAccAliCloudKmsKey_basic2(t *testing.T) { Config: testAccConfig(map[string]interface{}{ "tags": map[string]string{ "Created": "TF", - "For": "Key", + "For": "Test", }, }), Check: resource.ComposeTestCheckFunc( testAccCheck(map[string]string{ "tags.%": "2", "tags.Created": "TF", - "tags.For": "Key", + "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, }), ), }, @@ -586,7 +789,7 @@ func TestAccAliCloudKmsKey_basic2(t *testing.T) { }) } -func TestAccAliCloudKmsKey_basic2_twin(t *testing.T) { +func TestAccAliCloudKmsKey_basic8857_twin(t *testing.T) { var v map[string]interface{} resourceId := "alicloud_kms_key.default" ra := resourceAttrInit(resourceId, AliCloudKmsKeyMap0) @@ -597,7 +800,7 @@ func TestAccAliCloudKmsKey_basic2_twin(t *testing.T) { testAccCheck := rac.resourceAttrMapUpdateSet() rand := acctest.RandIntRange(1000000, 9999999) name := fmt.Sprintf("tf-testAcc%sKmsKey%d", defaultRegionToTest, rand) - testAccConfig := resourceTestAccConfigFunc(resourceId, name, AliCloudKmsKeyBasicDependence0) + testAccConfig := resourceTestAccConfigFunc(resourceId, name, AliCloudKmsKeyBasicDependence8855) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) @@ -608,33 +811,49 @@ func TestAccAliCloudKmsKey_basic2_twin(t *testing.T) { Steps: []resource.TestStep{ { Config: testAccConfig(map[string]interface{}{ - "key_usage": "ENCRYPT/DECRYPT", - "origin": "Aliyun_KMS", - "key_spec": "Aliyun_AES_256", - "protection_level": "SOFTWARE", - "automatic_rotation": "Enabled", - "rotation_interval": "605800s", - "description": name, - "key_state": "Enabled", - "pending_window_in_days": "7", + "key_usage": "ENCRYPT/DECRYPT", + "origin": "Aliyun_KMS", + "key_spec": "Aliyun_AES_256", + "protection_level": "SOFTWARE", + "automatic_rotation": "Enabled", + "rotation_interval": "605800s", + "description": name, + "key_state": "Enabled", + "deletion_protection": "Enabled", + "deletion_protection_description": name, + "pending_window_in_days": "7", "tags": map[string]string{ "Created": "TF", - "For": "Key", + "For": "Test", }, }), Check: resource.ComposeTestCheckFunc( testAccCheck(map[string]string{ - "key_usage": "ENCRYPT/DECRYPT", - "origin": "Aliyun_KMS", - "key_spec": "Aliyun_AES_256", - "protection_level": "SOFTWARE", - "automatic_rotation": "Enabled", - "rotation_interval": "605800s", - "description": name, - "key_state": "Enabled", - "tags.%": "2", - "tags.Created": "TF", - "tags.For": "Key", + "key_usage": "ENCRYPT/DECRYPT", + "origin": "Aliyun_KMS", + "key_spec": "Aliyun_AES_256", + "protection_level": "SOFTWARE", + "automatic_rotation": "Enabled", + "rotation_interval": "605800s", + "description": name, + "key_state": "Enabled", + "deletion_protection": "Enabled", + "deletion_protection_description": name, + "tags.%": "2", + "tags.Created": "TF", + "tags.For": "Test", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "deletion_protection": "Disabled", + "deletion_protection_description": REMOVEKEY, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "deletion_protection": "Disabled", + "deletion_protection_description": REMOVEKEY, }), ), }, @@ -648,7 +867,8 @@ func TestAccAliCloudKmsKey_basic2_twin(t *testing.T) { }) } -func TestAccAliCloudKmsKey_basic3(t *testing.T) { +// Case 全生命周期, 适配废弃字段deletion_window_in_days, is_enabled 8858 +func TestAccAliCloudKmsKey_basic8858(t *testing.T) { var v map[string]interface{} resourceId := "alicloud_kms_key.default" ra := resourceAttrInit(resourceId, AliCloudKmsKeyMap0) @@ -659,7 +879,7 @@ func TestAccAliCloudKmsKey_basic3(t *testing.T) { testAccCheck := rac.resourceAttrMapUpdateSet() rand := acctest.RandIntRange(1000000, 9999999) name := fmt.Sprintf("tf-testAcc%sKmsKey%d", defaultRegionToTest, rand) - testAccConfig := resourceTestAccConfigFunc(resourceId, name, AliCloudKmsKeyBasicDependence0) + testAccConfig := resourceTestAccConfigFunc(resourceId, name, AliCloudKmsKeyBasicDependence8855) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) @@ -702,6 +922,38 @@ func TestAccAliCloudKmsKey_basic3(t *testing.T) { }), ), }, + { + Config: testAccConfig(map[string]interface{}{ + "deletion_protection": "Enabled", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "deletion_protection": "Enabled", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "deletion_protection_description": name, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "deletion_protection_description": name, + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "deletion_protection": "Disabled", + "deletion_protection_description": REMOVEKEY, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "deletion_protection": "Disabled", + "deletion_protection_description": REMOVEKEY, + }), + ), + }, { Config: testAccConfig(map[string]interface{}{ "description": name, @@ -736,14 +988,41 @@ func TestAccAliCloudKmsKey_basic3(t *testing.T) { Config: testAccConfig(map[string]interface{}{ "tags": map[string]string{ "Created": "TF", - "For": "Key", + "For": "Test", }, }), Check: resource.ComposeTestCheckFunc( testAccCheck(map[string]string{ "tags.%": "2", "tags.Created": "TF", - "tags.For": "Key", + "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, }), ), }, @@ -757,7 +1036,7 @@ func TestAccAliCloudKmsKey_basic3(t *testing.T) { }) } -func TestAccAliCloudKmsKey_basic3_twin(t *testing.T) { +func TestAccAliCloudKmsKey_basic8858_twin(t *testing.T) { var v map[string]interface{} resourceId := "alicloud_kms_key.default" ra := resourceAttrInit(resourceId, AliCloudKmsKeyMap0) @@ -768,7 +1047,7 @@ func TestAccAliCloudKmsKey_basic3_twin(t *testing.T) { testAccCheck := rac.resourceAttrMapUpdateSet() rand := acctest.RandIntRange(1000000, 9999999) name := fmt.Sprintf("tf-testAcc%sKmsKey%d", defaultRegionToTest, rand) - testAccConfig := resourceTestAccConfigFunc(resourceId, name, AliCloudKmsKeyBasicDependence0) + testAccConfig := resourceTestAccConfigFunc(resourceId, name, AliCloudKmsKeyBasicDependence8855) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) @@ -779,33 +1058,49 @@ func TestAccAliCloudKmsKey_basic3_twin(t *testing.T) { Steps: []resource.TestStep{ { Config: testAccConfig(map[string]interface{}{ - "key_usage": "ENCRYPT/DECRYPT", - "origin": "Aliyun_KMS", - "key_spec": "Aliyun_AES_256", - "protection_level": "SOFTWARE", - "automatic_rotation": "Enabled", - "rotation_interval": "605800s", - "description": name, - "is_enabled": "true", - "deletion_window_in_days": "7", + "key_usage": "ENCRYPT/DECRYPT", + "origin": "Aliyun_KMS", + "key_spec": "Aliyun_AES_256", + "protection_level": "SOFTWARE", + "automatic_rotation": "Enabled", + "rotation_interval": "605800s", + "description": name, + "is_enabled": "true", + "deletion_protection": "Enabled", + "deletion_protection_description": name, + "deletion_window_in_days": "7", "tags": map[string]string{ "Created": "TF", - "For": "Key", + "For": "Test", }, }), Check: resource.ComposeTestCheckFunc( testAccCheck(map[string]string{ - "key_usage": "ENCRYPT/DECRYPT", - "origin": "Aliyun_KMS", - "key_spec": "Aliyun_AES_256", - "protection_level": "SOFTWARE", - "automatic_rotation": "Enabled", - "rotation_interval": "605800s", - "description": name, - "is_enabled": "true", - "tags.%": "2", - "tags.Created": "TF", - "tags.For": "Key", + "key_usage": "ENCRYPT/DECRYPT", + "origin": "Aliyun_KMS", + "key_spec": "Aliyun_AES_256", + "protection_level": "SOFTWARE", + "automatic_rotation": "Enabled", + "rotation_interval": "605800s", + "description": name, + "is_enabled": "true", + "deletion_protection": "Enabled", + "deletion_protection_description": name, + "tags.%": "2", + "tags.Created": "TF", + "tags.For": "Test", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "deletion_protection": "Disabled", + "deletion_protection_description": REMOVEKEY, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "deletion_protection": "Disabled", + "deletion_protection_description": REMOVEKEY, }), ), }, @@ -850,11 +1145,11 @@ var AliCloudKmsKeyMap1 = map[string]string{ "is_enabled": CHECKSET, } -func AliCloudKmsKeyBasicDependence0(name string) string { +func AliCloudKmsKeyBasicDependence8855(name string) string { return "" } -func AliCloudKmsKeyBasicDependence1(name string) string { +func AliCloudKmsKeyBasicDependence8856(name string) string { return fmt.Sprintf(` variable "name" { default = "%s" @@ -889,6 +1184,9 @@ func AliCloudKmsKeyBasicDependence1(name string) string { data.alicloud_zones.default.zones.0.id, data.alicloud_zones.default.zones.1.id ] + timeouts { + delete = "60m" + } } `, name) } @@ -1412,3 +1710,5 @@ func TestUnitAliCloudKmsKey(t *testing.T) { assert.NotNil(t, err) }) } + +// Test Ecs SecurityGroup. <<< Resource test cases, automatically generated. diff --git a/alicloud/service_alicloud_kms_v2.go b/alicloud/service_alicloud_kms_v2.go index 5a5b4a350948..1368c56f973e 100644 --- a/alicloud/service_alicloud_kms_v2.go +++ b/alicloud/service_alicloud_kms_v2.go @@ -2,12 +2,15 @@ package alicloud import ( "fmt" + "log" + "strings" "time" "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" ) type KmsServiceV2 struct { @@ -342,3 +345,311 @@ func (s *KmsServiceV2) KmsApplicationAccessPointStateRefreshFunc(id string, fiel } // DescribeKmsApplicationAccessPoint >>> Encapsulated. + +// DescribeKmsKey <<< Encapsulated get interface for Kms Key. + +func (s *KmsServiceV2) DescribeKmsKey(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 := "DescribeKey" + conn, err := client.NewKmsClient() + if err != nil { + return object, WrapError(err) + } + request = make(map[string]interface{}) + query = make(map[string]interface{}) + request["KeyId"] = id + + 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("2016-01-20"), StringPointer("AK"), query, request, &runtime) + + if err != nil { + if NeedRetry(err) { + wait() + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + addDebug(action, response, request) + if err != nil { + if IsExpectedErrors(err, []string{"Forbidden.AliasNotFound", "Forbidden.KeyNotFound"}) { + return object, WrapErrorf(Error(GetNotFoundMessage("Kms:Key", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"])) + } + return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR) + } + + v, err := jsonpath.Get("$.KeyMetadata", response) + if err != nil { + return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.KeyMetadata", response) + } + + if object["KeyState"] == "PendingDeletion" { + log.Printf("[WARN] Removing Kms:Key %s because it's already gone", id) + return object, WrapErrorf(Error(GetNotFoundMessage("Kms:Key", id)), NotFoundMsg, ProviderERROR) + } + + return v.(map[string]interface{}), nil +} + +func (s *KmsServiceV2) KmsKeyStateRefreshFunc(id string, field string, failStates []string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + object, err := s.DescribeKmsKey(id) + if err != nil { + if NotFoundError(err) { + return object, "", nil + } + return nil, "", WrapError(err) + } + + v, err := jsonpath.Get(field, object) + currentStatus := fmt.Sprint(v) + + if strings.HasPrefix(field, "#") { + v, _ := jsonpath.Get(strings.TrimPrefix(field, "#"), object) + if v != nil { + currentStatus = "#CHECKSET" + } + } + + for _, failState := range failStates { + if currentStatus == failState { + return object, currentStatus, WrapError(Error(FailedToReachTargetStatus, currentStatus)) + } + } + return object, currentStatus, nil + } +} + +func (s *KmsServiceV2) DescribeKmsKeyPolicy(id string) (object map[string]interface{}, err error) { + var response map[string]interface{} + action := "GetKeyPolicy" + + conn, err := s.client.NewKmsClient() + if err != nil { + return nil, WrapError(err) + } + + request := map[string]interface{}{ + "KeyId": id, + } + + runtime := util.RuntimeOptions{} + runtime.SetAutoretry(true) + wait := incrementalWait(3*time.Second, 3*time.Second) + err = resource.Retry(5*time.Minute, func() *resource.RetryError { + response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-01-20"), StringPointer("AK"), nil, request, &runtime) + if err != nil { + if NeedRetry(err) { + wait() + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + addDebug(action, response, request) + + if err != nil { + if IsExpectedErrors(err, []string{"Forbidden.ResourceNotFound"}) { + return object, nil + } + return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR) + } + + v, err := jsonpath.Get("$", response) + if err != nil { + return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response) + } + + object = v.(map[string]interface{}) + + return object, nil +} + +// DescribeKmsKey >>> Encapsulated. + +func (s *KmsServiceV2) ListTagResources(id string, resourceType string) (object interface{}, err error) { + conn, err := s.client.NewKmsClient() + if err != nil { + return nil, WrapError(err) + } + action := "ListTagResources" + + request := map[string]interface{}{ + "RegionId": s.client.RegionId, + "ResourceType": resourceType, + } + + resourceIdNum := strings.Count(id, ":") + + switch resourceIdNum { + case 0: + request["ResourceId.1"] = id + case 1: + parts, err := ParseResourceId(id, 2) + if err != nil { + return object, WrapError(err) + } + request["ResourceId.1"] = parts[resourceIdNum] + } + + tags := make([]interface{}, 0) + var response map[string]interface{} + + for { + runtime := util.RuntimeOptions{} + runtime.SetAutoretry(true) + wait := incrementalWait(3*time.Second, 3*time.Second) + err = resource.Retry(5*time.Minute, func() *resource.RetryError { + response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-01-20"), StringPointer("AK"), nil, request, &runtime) + if err != nil { + if NeedRetry(err) { + wait() + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + addDebug(action, response, request) + v, err := jsonpath.Get("$.TagResources.TagResource", response) + if err != nil { + return resource.NonRetryableError(WrapErrorf(err, FailedGetAttributeMsg, id, "$.TagResources.TagResource", response)) + } + + if v != nil { + tags = append(tags, v.([]interface{})...) + } + + return nil + }) + if err != nil { + err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR) + return + } + + if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" { + request["NextToken"] = nextToken + } else { + break + } + } + + return tags, nil +} + +func (s *KmsServiceV2) SetResourceTags(d *schema.ResourceData, resourceType string) error { + + resourceIdNum := strings.Count(d.Id(), ":") + + if d.HasChange("tags") { + added, removed := parsingTags(d) + conn, err := s.client.NewKmsClient() + if err != nil { + return WrapError(err) + } + + removedTagKeys := make([]string, 0) + for _, v := range removed { + if !ignoredTags(v, "") { + removedTagKeys = append(removedTagKeys, v) + } + } + + if len(removedTagKeys) > 0 { + action := "UntagResources" + request := map[string]interface{}{ + "RegionId": s.client.RegionId, + "ResourceType": resourceType, + } + + switch resourceIdNum { + case 0: + request["ResourceId.1"] = d.Id() + case 1: + parts, err := ParseResourceId(d.Id(), 2) + if err != nil { + return WrapError(err) + } + request["ResourceId.1"] = parts[resourceIdNum] + } + + for i, key := range removedTagKeys { + request[fmt.Sprintf("TagKey.%d", i+1)] = key + } + + runtime := util.RuntimeOptions{} + runtime.SetAutoretry(true) + wait := incrementalWait(2*time.Second, 1*time.Second) + err := resource.Retry(10*time.Minute, func() *resource.RetryError { + response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-01-20"), StringPointer("AK"), nil, 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 WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR) + } + } + + if len(added) > 0 { + action := "TagResources" + request := map[string]interface{}{ + "RegionId": s.client.RegionId, + "ResourceType": resourceType, + } + + switch resourceIdNum { + case 0: + request["ResourceId.1"] = d.Id() + case 1: + parts, err := ParseResourceId(d.Id(), 2) + if err != nil { + return WrapError(err) + } + request["ResourceId.1"] = parts[resourceIdNum] + } + + count := 1 + for key, value := range added { + request[fmt.Sprintf("Tag.%d.Key", count)] = key + request[fmt.Sprintf("Tag.%d.Value", count)] = value + count++ + } + + runtime := util.RuntimeOptions{} + runtime.SetAutoretry(true) + wait := incrementalWait(2*time.Second, 1*time.Second) + err := resource.Retry(10*time.Minute, func() *resource.RetryError { + response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-01-20"), StringPointer("AK"), nil, 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 WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR) + } + } + d.SetPartial("tags") + } + return nil +} diff --git a/website/docs/r/kms_key.html.markdown b/website/docs/r/kms_key.html.markdown index d7dd3bcc9b79..d4f89ecd3355 100644 --- a/website/docs/r/kms_key.html.markdown +++ b/website/docs/r/kms_key.html.markdown @@ -2,7 +2,6 @@ subcategory: "KMS" layout: "alicloud" page_title: "Alicloud: alicloud_kms_key" -sidebar_current: "docs-alicloud-resource-kms-key" description: |- Provides a Alicloud KMS Key resource. --- @@ -11,6 +10,8 @@ description: |- Provides a KMS Key resource. + + For information about KMS Key and how to use it, see [What is Key](https://www.alibabacloud.com/help/en/kms/developer-reference/api-createkey). -> **NOTE:** Available since v1.85.0. @@ -36,22 +37,21 @@ resource "alicloud_kms_key" "default" { ## Argument Reference The following arguments are supported: - +* `automatic_rotation` - (Optional) Specifies whether to enable automatic key rotation. Default value: `Disabled`. Valid values: `Enabled`, `Disabled`. +* `deletion_protection` - (Optional, Available since v1.240.0) Specifies whether to enable deletion protection. Default value: `Disabled`. Valid values: `Enabled`, `Disabled`. +* `deletion_protection_description` - (Optional, Available since v1.240.0) The description of deletion protection. **NOTE:** `deletion_protection_description` takes effect only if `deletion_protection` is set to `Enabled`. +* `description` - (Optional) The description of the key. +* `dkms_instance_id` - (Optional, ForceNew, Available since v1.183.0) The ID of the KMS instance. +* `key_spec` - (Optional, ForceNew) The specification of the key. Default value: `Aliyun_AES_256`. Valid values: `Aliyun_AES_256`, `Aliyun_AES_128`, `Aliyun_AES_192`, `Aliyun_SM4`, `RSA_2048`, `RSA_3072`, `EC_P256`, `EC_P256K`, `EC_SM2`. * `key_usage` - (Optional, ForceNew) The usage of the key. Default value: `ENCRYPT/DECRYPT`. Valid values: - `ENCRYPT/DECRYPT`: Encrypts or decrypts data. - `SIGN/VERIFY`: Generates or verifies a digital signature. * `origin` - (Optional, ForceNew) The key material origin. Default value: `Aliyun_KMS`. Valid values: `Aliyun_KMS`, `EXTERNAL`. -* `key_spec` - (Optional, ForceNew) The specification of the key. Default value: `Aliyun_AES_256`. Valid values: `Aliyun_AES_256`, `Aliyun_AES_128`, `Aliyun_AES_192`, `Aliyun_SM4`, `RSA_2048`, `RSA_3072`, `EC_P256`, `EC_P256K`, `EC_SM2`. -* `dkms_instance_id` - (Optional, Computed, ForceNew, Available since v1.183.0) The ID of the KMS instance. -* `protection_level` - (Optional, ForceNew) The protection level of the key. Default value: `SOFTWARE`. Valid values: `SOFTWARE`, `HSM`. -* `automatic_rotation` - (Optional) Specifies whether to enable automatic key rotation. Default value: `Disabled`. Valid values: `Enabled`, `Disabled`. -* `rotation_interval` - (Optional) The period of automatic key rotation. The following units are supported: d (day), h (hour), m (minute), and s (second). For example, you can use either 7d or 604800s to specify a seven-day interval. -**NOTE**: If `automatic_rotation` is set to `Enabled`, `rotation_interval` is required. +* `pending_window_in_days` - (Optional, Int) The number of days before the CMK is deleted. During this period, the CMK is in the PendingDeletion state. After this period ends, you cannot cancel the deletion. Unit: days. Valid values: `7` to `366`. **NOTE:** From version 1.184.0, `pending_window_in_days` can be set to `366`. * `policy` - (Optional, Available since v1.224.0) The content of the key policy. The value is in the JSON format. The value can be up to 32,768 bytes in length. For more information, see [How to use it](https://www.alibabacloud.com/help/en/kms/developer-reference/api-setkeypolicy). -* `description` - (Optional) The description of the key. +* `protection_level` - (Optional, ForceNew) The protection level of the key. Default value: `SOFTWARE`. Valid values: `SOFTWARE`, `HSM`. +* `rotation_interval` - (Optional) The period of automatic key rotation. The following units are supported: d (day), h (hour), m (minute), and s (second). For example, you can use either 7d or 604800s to specify a seven-day interval. **NOTE**: If `automatic_rotation` is set to `Enabled`, `rotation_interval` is required. * `status` - (Optional, Available since v1.123.1) The status of key. Default value: `Enabled`. Valid values: `Enabled`, `Disabled`, `PendingDeletion`. -* `pending_window_in_days` - (Optional, Int) The number of days before the CMK is deleted. During this period, the CMK is in the PendingDeletion state. After this period ends, you cannot cancel the deletion. Unit: days. Valid values: `7` to `366`. -**NOTE:** From version 1.184.0, `pending_window_in_days` can be set to `366`. * `tags` - (Optional, Available since v1.207.0) A mapping of tags to assign to the resource. * `deletion_window_in_days` - (Optional, Int, Deprecated since v1.85.0) Field `deletion_window_in_days` has been deprecated from provider version 1.85.0. New field `pending_window_in_days` instead. * `key_state` - (Deprecated since v1.123.1) Field `key_state` has been deprecated from provider version 1.123.1. New field `status` instead. @@ -80,7 +80,6 @@ The following arguments are supported: -> **NOTE:** Available since v1.224.0. 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 5 mins) Used when create the Key. * `update` - (Defaults to 5 mins) Used when update the Key. * `delete` - (Defaults to 5 mins) Used when delete the Key.