From 5dd5b255a14fa44d831c588c3a9a7304275532bc Mon Sep 17 00:00:00 2001 From: Harshit-Gupta2 Date: Tue, 15 Mar 2022 22:12:11 +0530 Subject: [PATCH] Key Policies Deprecate --- ibm/service/kms/resource_ibm_kms_key.go | 189 +----------------- ibm/service/kms/resource_ibm_kms_key_test.go | 99 +-------- website/docs/r/kms_key.html.markdown | 59 +----- website/docs/r/kms_key_policies.html.markdown | 6 +- 4 files changed, 13 insertions(+), 340 deletions(-) diff --git a/ibm/service/kms/resource_ibm_kms_key.go b/ibm/service/kms/resource_ibm_kms_key.go index c4547b8977..b42a00574a 100644 --- a/ibm/service/kms/resource_ibm_kms_key.go +++ b/ibm/service/kms/resource_ibm_kms_key.go @@ -6,7 +6,6 @@ package kms import ( "context" "fmt" - "log" "net/url" "strconv" "strings" @@ -125,112 +124,6 @@ func ResourceIBMKmskey() *schema.Resource { Description: "The date the key material expires. The date format follows RFC 3339. You can set an expiration date on any key on its creation. A key moves into the Deactivated state within one hour past its expiration date, if one is assigned. If you create a key without specifying an expiration date, the key does not expire", ForceNew: true, }, - "policies": { - Type: schema.TypeList, - Deprecated: "Support for creating Policies with the key will soon be removed, Utilise the new resource for creating policies for the keys => ibm_kms_key_policies", - Optional: true, - Computed: true, - Description: "Creates or updates one or more policies for the specified key", - MinItems: 1, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "rotation": { - Type: schema.TypeList, - Optional: true, - Computed: true, - AtLeastOneOf: []string{"policies.0.rotation", "policies.0.dual_auth_delete"}, - Description: "Specifies the key rotation time interval in months, with a minimum of 1, and a maximum of 12", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "id": { - Type: schema.TypeString, - Computed: true, - Description: "The v4 UUID used to uniquely identify the policy resource, as specified by RFC 4122.", - }, - "crn": { - Type: schema.TypeString, - Computed: true, - Description: "Cloud Resource Name (CRN) that uniquely identifies your cloud resources.", - }, - "created_by": { - Type: schema.TypeString, - Computed: true, - Description: "The unique identifier for the resource that created the policy.", - }, - "creation_date": { - Type: schema.TypeString, - Computed: true, - Description: "The date the policy was created. The date format follows RFC 3339.", - }, - "updated_by": { - Type: schema.TypeString, - Computed: true, - Description: "The unique identifier for the resource that updated the policy.", - }, - "last_update_date": { - Type: schema.TypeString, - Computed: true, - Description: "Updates when the policy is replaced or modified. The date format follows RFC 3339.", - }, - "interval_month": { - Type: schema.TypeInt, - Required: true, - ValidateFunc: validate.ValidateAllowedRangeInt(1, 12), - Description: "Specifies the key rotation time interval in months", - }, - }, - }, - }, - "dual_auth_delete": { - Type: schema.TypeList, - Optional: true, - Computed: true, - AtLeastOneOf: []string{"policies.0.rotation", "policies.0.dual_auth_delete"}, - Description: "Data associated with the dual authorization delete policy.", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "id": { - Type: schema.TypeString, - Computed: true, - Description: "The v4 UUID used to uniquely identify the policy resource, as specified by RFC 4122.", - }, - "crn": { - Type: schema.TypeString, - Computed: true, - Description: "Cloud Resource Name (CRN) that uniquely identifies your cloud resources.", - }, - "created_by": { - Type: schema.TypeString, - Computed: true, - Description: "The unique identifier for the resource that created the policy.", - }, - "creation_date": { - Type: schema.TypeString, - Computed: true, - Description: "The date the policy was created. The date format follows RFC 3339.", - }, - "updated_by": { - Type: schema.TypeString, - Computed: true, - Description: "The unique identifier for the resource that updated the policy.", - }, - "last_update_date": { - Type: schema.TypeString, - Computed: true, - Description: "Updates when the policy is replaced or modified. The date format follows RFC 3339.", - }, - "enabled": { - Type: schema.TypeBool, - Required: true, - Description: "If set to true, Key Protect enables a dual authorization policy on a single key.", - }, - }, - }, - }, - }, - }, - }, "instance_crn": { Type: schema.TypeString, Computed: true, @@ -408,21 +301,11 @@ func resourceIBMKmsKeyRead(d *schema.ResourceData, meta interface{}) error { d.SetId("") return nil } - return fmt.Errorf("[ERROR] Get Key failed with error while reading policies: %s", err) + return fmt.Errorf("[ERROR] Get Key failed with error while reading Key: %s", err) } else if key.State == 5 { //Refers to Deleted state of the Key d.SetId("") return nil } - - policies, err := kpAPI.GetPolicies(context.Background(), keyid) - if err != nil && !strings.Contains(fmt.Sprint(err), "Unauthorized: The user does not have access to the specified resource") { - return fmt.Errorf("[ERROR] Failed to read policies: %s", err) - } - if len(policies) == 0 { - log.Printf("No Policy Configurations read\n") - } else { - d.Set("policies", flex.FlattenKeyPolicies(policies)) - } d.Set("instance_id", instanceID) d.Set("instance_crn", instanceCRN) d.Set("key_id", keyid) @@ -470,44 +353,6 @@ func resourceIBMKmsKeyUpdate(d *schema.ResourceData, meta interface{}) error { if d.HasChange("force_delete") { d.Set("force_delete", d.Get("force_delete").(bool)) } - if d.HasChange("policies") { - - kpAPI, err := meta.(conns.ClientSession).KeyManagementAPI() - if err != nil { - return err - } - - crn := d.Id() - crnData := strings.Split(crn, ":") - endpointType := d.Get("endpoint_type").(string) - instanceID := crnData[len(crnData)-3] - key_id := crnData[len(crnData)-1] - - rsConClient, err := meta.(conns.ClientSession).ResourceControllerV2API() - if err != nil { - return err - } - resourceInstanceGet := rc.GetResourceInstanceOptions{ - ID: &instanceID, - } - - instanceData, resp, err := rsConClient.GetResourceInstance(&resourceInstanceGet) - if err != nil || instanceData == nil { - return fmt.Errorf("[ERROR] Error retrieving resource instance: %s with resp code: %s", err, resp) - } - extensions := instanceData.Extensions - URL, err := KmsEndpointURL(kpAPI, endpointType, extensions) - if err != nil { - return err - } - kpAPI.URL = URL - kpAPI.Config.InstanceID = instanceID - - err = handlePolicies(d, kpAPI, meta, key_id) - if err != nil { - return fmt.Errorf("[ERROR] Could not update policies: %s", err) - } - } return resourceIBMKmsKeyRead(d, meta) } @@ -601,38 +446,6 @@ func resourceIBMKmsKeyExists(d *schema.ResourceData, meta interface{}) (bool, er } -func handlePolicies(d *schema.ResourceData, kpAPI *kp.Client, meta interface{}, key_id string) error { - var setRotation, setDualAuthDelete, dualAuthEnable bool - var rotationInterval int - - if policyInfo, ok := d.GetOk("policies"); ok { - - policyDataList := policyInfo.([]interface{}) - policyData := policyDataList[0].(map[string]interface{}) - - if rpd, ok := policyData["rotation"]; ok { - rpdList := rpd.([]interface{}) - if len(rpdList) != 0 { - rotationInterval = rpdList[0].(map[string]interface{})["interval_month"].(int) - setRotation = true - } - } - if dadp, ok := policyData["dual_auth_delete"]; ok { - dadpList := dadp.([]interface{}) - if len(dadpList) != 0 { - dualAuthEnable = dadpList[0].(map[string]interface{})["enabled"].(bool) - setDualAuthDelete = true - } - } - - _, err := kpAPI.SetPolicies(context.Background(), key_id, setRotation, rotationInterval, setDualAuthDelete, dualAuthEnable) - if err != nil { - return fmt.Errorf("[ERROR] Error while creating policies: %s", err) - } - } - return nil -} - //Construct KMS URL func KmsEndpointURL(kpAPI *kp.Client, endpointType string, extensions map[string]interface{}) (*url.URL, error) { diff --git a/ibm/service/kms/resource_ibm_kms_key_test.go b/ibm/service/kms/resource_ibm_kms_key_test.go index 65c161f392..c8a0d79ed2 100644 --- a/ibm/service/kms/resource_ibm_kms_key_test.go +++ b/ibm/service/kms/resource_ibm_kms_key_test.go @@ -126,91 +126,6 @@ func TestAccIBMKMSResource_InvalidExpDate(t *testing.T) { }) } -func TestAccIBMKMSKeyPolicy_basic(t *testing.T) { - instanceName := fmt.Sprintf("kms_%d", acctest.RandIntRange(10, 100)) - keyName := fmt.Sprintf("key_%d", acctest.RandIntRange(10, 100)) - rotation_interval := 3 - dual_auth_delete := false - rotation_interval_new := 5 - resource.Test(t, resource.TestCase{ - PreCheck: func() { acc.TestAccPreCheck(t) }, - Providers: acc.TestAccProviders, - Steps: []resource.TestStep{ - { - Config: testAccCheckIBMKmsKeyPolicyStandardConfig(instanceName, keyName, rotation_interval, dual_auth_delete), - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr("ibm_kms_key.test", "key_name", keyName), - resource.TestCheckResourceAttr("ibm_kms_key.test", "policies.0.rotation.0.interval_month", "3"), - resource.TestCheckResourceAttr("ibm_kms_key.test", "policies.0.dual_auth_delete.0.enabled", "false"), - ), - }, - { - Config: testAccCheckIBMKmsKeyPolicyStandardConfig(instanceName, keyName, rotation_interval_new, dual_auth_delete), - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr("ibm_kms_key.test", "key_name", keyName), - resource.TestCheckResourceAttr("ibm_kms_key.test", "policies.0.rotation.0.interval_month", "5"), - resource.TestCheckResourceAttr("ibm_kms_key.test", "policies.0.dual_auth_delete.0.enabled", "false"), - ), - }, - }, - }) -} - -func TestAccIBMKMSKeyPolicy_rotation(t *testing.T) { - instanceName := fmt.Sprintf("kms_%d", acctest.RandIntRange(10, 100)) - keyName := fmt.Sprintf("key_%d", acctest.RandIntRange(10, 100)) - rotation_interval := 3 - resource.Test(t, resource.TestCase{ - PreCheck: func() { acc.TestAccPreCheck(t) }, - Providers: acc.TestAccProviders, - Steps: []resource.TestStep{ - { - Config: testAccCheckIBMKmsKeyPolicyRotation(instanceName, keyName, rotation_interval), - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr("ibm_kms_key.test", "key_name", keyName), - resource.TestCheckResourceAttr("ibm_kms_key.test", "policies.0.rotation.0.interval_month", "3"), - ), - }, - }, - }) -} - -func TestAccIBMKMSKeyPolicy_dualAuth(t *testing.T) { - instanceName := fmt.Sprintf("kms_%d", acctest.RandIntRange(10, 100)) - keyName := fmt.Sprintf("key_%d", acctest.RandIntRange(10, 100)) - dual_auth_delete := false - resource.Test(t, resource.TestCase{ - PreCheck: func() { acc.TestAccPreCheck(t) }, - Providers: acc.TestAccProviders, - Steps: []resource.TestStep{ - { - Config: testAccCheckIBMKmsKeyPolicyDualAuth(instanceName, keyName, dual_auth_delete), - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr("ibm_kms_key.test", "key_name", keyName), - resource.TestCheckResourceAttr("ibm_kms_key.test", "policies.0.dual_auth_delete.0.enabled", "false"), - ), - }, - }, - }) -} - -func TestAccIBMKMSKeyPolicy_invalid_interval(t *testing.T) { - instanceName := fmt.Sprintf("kms_%d", acctest.RandIntRange(10, 100)) - keyName := fmt.Sprintf("key_%d", acctest.RandIntRange(10, 100)) - rotation_interval := 13 - dual_auth_delete := false - resource.Test(t, resource.TestCase{ - PreCheck: func() { acc.TestAccPreCheck(t) }, - Providers: acc.TestAccProviders, - Steps: []resource.TestStep{ - { - Config: testAccCheckIBMKmsKeyPolicyStandardConfig(instanceName, keyName, rotation_interval, dual_auth_delete), - ExpectError: regexp.MustCompile("config is invalid:"), - }, - }, - }) -} - func testAccCheckIBMKmsResourceStandardConfig(instanceName, KeyName string) string { return fmt.Sprintf(` resource "ibm_resource_instance" "kms_instance" { @@ -225,7 +140,6 @@ func testAccCheckIBMKmsResourceStandardConfig(instanceName, KeyName string) stri standard_key = true force_delete = true } - `, instanceName, KeyName) } @@ -252,7 +166,7 @@ func testAccCheckIBMKmsResourceRootkeyWithCOSConfig(instanceName, KeyName, cosIn return fmt.Sprintf(` provider "ibm" { region = "us-south" - } + } resource "ibm_resource_instance" "kms_instance1" { name = "%s" service = "kms" @@ -272,13 +186,11 @@ func testAccCheckIBMKmsResourceRootkeyWithCOSConfig(instanceName, KeyName, cosIn plan = "standard" location = "global" } - resource "ibm_iam_authorization_policy" "policy" { source_service_name = "cloud-object-storage" target_service_name = "kms" roles = ["Reader"] } - resource "ibm_cos_bucket" "smart-us-south" { depends_on = [ibm_iam_authorization_policy.policy] bucket_name = "%s" @@ -287,7 +199,6 @@ func testAccCheckIBMKmsResourceRootkeyWithCOSConfig(instanceName, KeyName, cosIn storage_class = "smart" key_protect = ibm_kms_key.test.id } - `, instanceName, KeyName, cosInstanceName, bucketName) } @@ -318,7 +229,6 @@ func testAccCheckIBMKmsCreateStandardKeyConfig(instanceName, KeyName, expiration force_delete = true expiration_date = "%s" } - `, instanceName, KeyName, expirationDate) } @@ -337,7 +247,6 @@ func testAccCheckIBMKmsCreateRootKeyConfig(instanceName, KeyName, expirationDate force_delete = true expiration_date = "%s" } - `, instanceName, KeyName, expirationDate) } @@ -349,7 +258,7 @@ func testAccCheckIBMKmsKeyPolicyStandardConfig(instanceName, KeyName string, rot plan = "tiered-pricing" location = "us-south" } - + resource "ibm_kms_key" "test" { instance_id = ibm_resource_instance.kp_instance.guid key_name = "%s" @@ -374,7 +283,7 @@ func testAccCheckIBMKmsKeyPolicyRotation(instanceName, KeyName string, rotation_ plan = "tiered-pricing" location = "us-south" } - + resource "ibm_kms_key" "test" { instance_id = ibm_resource_instance.kp_instance.guid key_name = "%s" @@ -396,7 +305,7 @@ func testAccCheckIBMKmsKeyPolicyDualAuth(instanceName, KeyName string, dual_auth plan = "tiered-pricing" location = "us-south" } - + resource "ibm_kms_key" "test" { instance_id = ibm_resource_instance.kp_instance.guid key_name = "%s" diff --git a/website/docs/r/kms_key.html.markdown b/website/docs/r/kms_key.html.markdown index ef6f69bda7..4f23a9168c 100644 --- a/website/docs/r/kms_key.html.markdown +++ b/website/docs/r/kms_key.html.markdown @@ -13,6 +13,11 @@ This resource can be used for management of keys in both Key Protect and Hyper P After creating an Hyper Protect Crypto Service instance you need to initialize the instance properly with the crypto units, in order to create, or manage Hyper Protect Crypto Service keys. For more information, about how to initialize the Hyper Protect Crypto Service instance, see [Initialize Hyper Protect Crypto](https://cloud.ibm.com/docs/hs-crypto?topic=hs-crypto-initialize-hsm) only for HPCS instance. +~> **Deprecated:** + +The ability to use the ibm_kms_key resource to create or update key policies in Terraform has been removed in favor of a dedicated ibm_kms_key_policies resource. For more information, check out [here](https://registry.terraform.io/providers/IBM-Cloud/ibm/latest/docs/resources/kms_key_policies#example-usage-to-create-a-[…]and-associate-a-key-policy) + + ## Example usage to provision Key Protect service and key management ```terraform @@ -69,60 +74,6 @@ resource "ibm_kms_key" "key" { force_delete = true } ``` -## Example usage to provision KMS key with key policies - -Set policies for a key, as an automatic rotation policy or a dual authorization policy to protect against the accidental deletion of keys. - -~> **Deprecated:** - -The ability to use the ibm_kms_key resource to create or update key policies in Terraform has been deprecated and it is scheduled to be removed soon in favor of a dedicated ibm_kms_key_policies resource. For more information, check out [here](https://registry.terraform.io/providers/IBM-Cloud/ibm/latest/docs/resources/kms_key_policies#example-usage-to-create-a-[…]and-associate-a-key-policy) - -Until the deprecation is released: -- For new key policies, start using ibm_kms_key_policies -- For existing policies already created through ibm_kms_key resource, add lifecycle ignore block to ibm_kms_key resource to ignore any state change to the policies (see example below) - -```terraform -resource "ibm_resource_instance" "kp_instance" { - name = "test_kp" - service = "kms" - plan = "tiered-pricing" - location = "us-south" -} -resource "ibm_kms_key" "key" { - instance_id = ibm_resource_instance.kp_instance.guid - key_name = "key" - standard_key = false - expiration_date = "2020-12-05T15:43:46Z" - policies { - rotation { - interval_month = 3 - } - dual_auth_delete { - enabled = false - } - } -} -``` - -## Lifecycle Ignore Block Example - -```terraform -resource "ibm_kms_key" "kms_tf_test_key1" { - instance_id = ibm_resource_instance.kms_tf_test1.guid - key_name = "kms_tf_test_key1" - standard_key = false - force_delete = true - policies { - rotation { - interval_month = 8 - } - } - lifecycle { - ignore_changes = [ - policies, - ] - } - ``` ## Example usage to provision KMS and import a key diff --git a/website/docs/r/kms_key_policies.html.markdown b/website/docs/r/kms_key_policies.html.markdown index 468cebed68..e7eab40d93 100644 --- a/website/docs/r/kms_key_policies.html.markdown +++ b/website/docs/r/kms_key_policies.html.markdown @@ -10,6 +10,9 @@ description: |- Provides a resource to manage key policies for Key Protect and Hyper Protect Crypto Service (HPCS) services. This allows key policies to be created and updated. Key policies can be created for an existing kms key resource. +**NOTE** +: `terraform destroy` does not remove the policies of the Key but only clears the state file. Key Policies get deleted when the associated key resource is destroyed. + ## Example usage to create a Key and associate a key policy. @@ -39,9 +42,6 @@ resource "ibm_kms_key_policies" "key_policy" { } ``` -**NOTE** -1) `terraform destroy` does not remove the policies of the Key but only clears the state file. Key Policies get deleted when the associated key resource is destroyed. - ## Argument reference The following arguments are supported: