Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Limit & KeyID Feature for Keys DataSource #2538

Merged
merged 8 commits into from
Jul 27, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 91 additions & 11 deletions ibm/data_source_ibm_kms_key.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,17 +24,27 @@ func dataSourceIBMKMSkey() *schema.Resource {
Required: true,
Description: "Key protect or hpcs instance GUID",
},
"limit": {
Type: schema.TypeInt,
Optional: true,
Description: "Limit till the keys to be fetched",
},
"key_id": {
Type: schema.TypeString,
Optional: true,
ExactlyOneOf: []string{"alias", "key_name", "key_id"},
},
"key_name": {
Type: schema.TypeString,
Optional: true,
Description: "The name of the key to be fetched",
ExactlyOneOf: []string{"alias", "key_name"},
ExactlyOneOf: []string{"alias", "key_name", "key_id"},
},
"alias": {
Type: schema.TypeString,
Optional: true,
Description: "The alias associated with the key",
ExactlyOneOf: []string{"alias", "key_name"},
ExactlyOneOf: []string{"alias", "key_name", "key_id"},
},
"endpoint_type": {
Type: schema.TypeString,
Expand Down Expand Up @@ -221,30 +231,72 @@ func dataSourceIBMKMSKeyRead(d *schema.ResourceData, meta interface{}) error {
}

api.Config.InstanceID = instanceID
var totalKeys []kp.Key

if v, ok := d.GetOk("key_name"); ok {
keys, err := api.GetKeys(context.Background(), 0, 0)
if err != nil {
return fmt.Errorf(
"Get Keys failed with error: %s", err)
limit := d.Get("limit")
limitVal := limit.(int)
offset := 0
//default page size of API is 200 as stated
pageSize := 200

// when the limit is not passed, the api works in default way to avoid backward compatibility issues

if limitVal == 0 {
keys, err := api.GetKeys(context.Background(), 0, offset)
if err != nil {
return fmt.Errorf(
"Get Keys failed with error: %s", err)
}
retreivedKeys := keys.Keys
totalKeys = append(totalKeys, retreivedKeys...)
} else {
// when the limit is passed by the user
for {
if offset < limitVal {
if (limitVal - offset) < pageSize {
keys, err := api.GetKeys(context.Background(), (limitVal - offset), offset)
if err != nil {
return fmt.Errorf(
"Get Keys failed with error: %s", err)
}
retreivedKeys := keys.Keys
totalKeys = append(totalKeys, retreivedKeys...)
break
} else {
keys, err := api.GetKeys(context.Background(), pageSize, offset)
if err != nil {
return fmt.Errorf(
"Get Keys failed with error: %s", err)
}
numOfKeysFetched := keys.Metadata.NumberOfKeys
retreivedKeys := keys.Keys
totalKeys = append(totalKeys, retreivedKeys...)
if numOfKeysFetched < pageSize || offset+pageSize == limitVal {
break
}

offset = offset + pageSize
}
}
}
}
retreivedKeys := keys.Keys
if len(retreivedKeys) == 0 {

if len(totalKeys) == 0 {
return fmt.Errorf("No keys in instance %s", instanceID)
}
var keyName string
var matchKeys []kp.Key
if v.(string) != "" {
keyName = v.(string)
for _, keyData := range retreivedKeys {
for _, keyData := range totalKeys {
if keyData.Name == keyName {
matchKeys = append(matchKeys, keyData)
}
}
} else {
matchKeys = retreivedKeys
matchKeys = totalKeys
}

if len(matchKeys) == 0 {
return fmt.Errorf("No keys with name %s in instance %s", keyName, instanceID)
}
Expand All @@ -271,6 +323,34 @@ func dataSourceIBMKMSKeyRead(d *schema.ResourceData, meta interface{}) error {
keyMap = append(keyMap, keyInstance)

}
d.SetId(instanceID)
d.Set("keys", keyMap)
d.Set("instance_id", instanceID)
} else if v, ok := d.GetOk("key_id"); ok {
key, err := api.GetKey(context.Background(), v.(string))
if err != nil {
return fmt.Errorf(
"Get Keys failed with error: %s", err)
}
keyMap := make([]map[string]interface{}, 0, 1)
keyInstance := make(map[string]interface{})
keyInstance["id"] = key.ID
keyInstance["name"] = key.Name
keyInstance["crn"] = key.CRN
keyInstance["standard_key"] = key.Extractable
keyInstance["aliases"] = key.Aliases
keyInstance["key_ring_id"] = key.KeyRingID
policies, err := api.GetPolicies(context.Background(), key.ID)
if err != nil {
return fmt.Errorf("Failed to read policies: %s", err)
}
if len(policies) == 0 {
log.Printf("No Policy Configurations read\n")
} else {
keyInstance["policies"] = flattenKeyPolicies(policies)
}
keyMap = append(keyMap, keyInstance)

d.SetId(instanceID)
d.Set("keys", keyMap)
d.Set("instance_id", instanceID)
Expand Down
74 changes: 67 additions & 7 deletions ibm/data_source_ibm_kms_key_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,28 @@ func TestAccIBMKMSKeyDataSource_basic(t *testing.T) {
},
})
}

func TestAccIBMKMSKeyDataSource_Key(t *testing.T) {
instanceName := fmt.Sprintf("kms_%d", acctest.RandIntRange(10, 100))
// bucketName := fmt.Sprintf("bucket", acctest.RandIntRange(10, 100))
keyName := fmt.Sprintf("key_%d", acctest.RandIntRange(10, 100))

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccCheckIBMKmsKeyDataSourceKeyConfig(instanceName, keyName),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("data.ibm_kms_key.test", "keys.0.name", keyName),
resource.TestCheckResourceAttr("data.ibm_kms_key.test2", "keys.0.name", keyName),
resource.TestCheckResourceAttr("data.ibm_kms_key.test2", "keys.1.name", keyName),
),
},
},
})
}

func TestAccIBMKMSKeyDataSourceHPCS_basic(t *testing.T) {
// bucketName := fmt.Sprintf("bucket", acctest.RandIntRange(10, 100))
keyName := fmt.Sprintf("key_%d", acctest.RandIntRange(10, 100))
Expand Down Expand Up @@ -69,6 +91,44 @@ func TestAccIBMKmsDataSourceKeyPolicy_basic(t *testing.T) {
})
}

func testAccCheckIBMKmsKeyDataSourceKeyConfig(instanceName, keyName string) string {
return fmt.Sprintf(`
resource "ibm_resource_instance" "kms_instance" {
name = "%s"
service = "kms"
plan = "tiered-pricing"
location = "us-south"
}
resource "ibm_kms_key" "test" {
instance_id = "${ibm_resource_instance.kms_instance.guid}"
key_name = "%s"
standard_key = true
force_delete = true
}
resource "ibm_kms_key" "test2" {
instance_id = "${ibm_resource_instance.kms_instance.guid}"
key_name = "${ibm_kms_key.test.key_name}"
standard_key = true
force_delete = true
}
resource "ibm_kms_key" "test3" {
instance_id = "${ibm_resource_instance.kms_instance.guid}"
key_name = "${ibm_kms_key.test.key_name}"
standard_key = true
force_delete = true
}
data "ibm_kms_key" "test" {
instance_id = "${ibm_kms_key.test3.instance_id}"
key_id = "${ibm_kms_key.test.key_id}"
}
data "ibm_kms_key" "test2" {
instance_id = "${ibm_kms_key.test3.instance_id}"
limit = 2
key_name = "${ibm_kms_key.test.key_name}"
}
`, instanceName, keyName)
}

func testAccCheckIBMKmsKeyDataSourceConfig(instanceName, keyName string) string {
return fmt.Sprintf(`
resource "ibm_resource_instance" "kms_instance" {
Expand All @@ -84,8 +144,8 @@ func testAccCheckIBMKmsKeyDataSourceConfig(instanceName, keyName string) string
force_delete = true
}
data "ibm_kms_key" "test" {
instance_id = "${ibm_kms_key.test.instance_id}"
key_name = "${ibm_kms_key.test.key_name}"
instance_id = "${ibm_kms_key.test.instance_id}"
key_name = "${ibm_kms_key.test.key_name}"
}
`, instanceName, keyName)
}
Expand All @@ -99,10 +159,10 @@ func testAccCheckIBMKmsKeyDataSourceHpcsConfig(hpcsInstanceID, KeyName string) s
force_delete = true
}
data "ibm_kms_key" "test" {
instance_id = "${ibm_kms_key.test.instance_id}"
key_name = "${ibm_kms_key.test.key_name}"
instance_id = "${ibm_kms_key.test.instance_id}"
key_name = "${ibm_kms_key.test.key_name}"
}

`, hpcsInstanceID, KeyName)
}

Expand All @@ -114,7 +174,7 @@ func testAccCheckIBMKmsDataSourceKeyPolicyConfig(instanceName, keyName string, i
plan = "tiered-pricing"
location = "us-south"
}

resource "ibm_kms_key" "test" {
instance_id = ibm_resource_instance.kp_instance.guid
key_name = "%s"
Expand All @@ -130,7 +190,7 @@ func testAccCheckIBMKmsDataSourceKeyPolicyConfig(instanceName, keyName string, i
}
data "ibm_kms_key" "test" {
instance_id = "${ibm_kms_key.test.instance_id}"
key_name = "${ibm_kms_key.test.key_name}"
key_name = "${ibm_kms_key.test.key_name}"
}
`, instanceName, keyName, interval_month, enabled)
}
Loading