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

add new datasource alicloud_kms_keys #357

Merged
merged 1 commit into from
Jan 22, 2018
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
IMPROVEMENTS:

- *New Resource*: _alicloud_kms_key_ ([#355](https://github.com/alibaba/terraform-provider/pull/355))
- *New DataSource*: _alicloud_kms_keys_ ([#356](https://github.com/alibaba/terraform-provider/pull/356))

## 1.6.2 (January 18, 2018)

Expand Down
167 changes: 167 additions & 0 deletions alicloud/data_source_alicloud_kms_keys.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
package alicloud

import (
"fmt"
"regexp"

"github.com/denverdino/aliyungo/kms"
"github.com/hashicorp/terraform/helper/schema"
)

func dataSourceAlicloudKmsKeys() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudKmsKeysRead,

Schema: map[string]*schema.Schema{
"ids": &schema.Schema{
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
MinItems: 1,
},

"description_regex": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validateNameRegex,
},

"status": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validateKmsKeyStatus,
},

"output_file": {
Type: schema.TypeString,
Optional: true,
},

//Computed value
"keys": &schema.Schema{
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"arn": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"creation_date": {
Type: schema.TypeString,
Computed: true,
},
"delete_date": {
Type: schema.TypeString,
Computed: true,
},
"creator": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}

func dataSourceAlicloudKmsKeysRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AliyunClient).kmsconn

args := &kms.ListKeysArgs{}

idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok && len(v.([]interface{})) > 0 {
for _, i := range v.([]interface{}) {
idsMap[i.(string)] = i.(string)
}
}

var keyIds []string
pagination := getPagination(1, 50)
for true {
args.Pagination = pagination
results, err := conn.ListKeys(args)
if err != nil {
return fmt.Errorf("Error ListKeys: %#v", err)
}
for _, key := range results.Keys.Key {
if idsMap != nil {
if _, ok := idsMap[key.KeyId]; ok {
keyIds = append(keyIds, key.KeyId)
continue
}
}
keyIds = append(keyIds, key.KeyId)
}
if len(results.Keys.Key) < pagination.PageSize {
break
}
pagination.PageNumber += 1
}

if len(keyIds) < 1 {
return fmt.Errorf("Your query kms keys returned no results. Please change your search criteria and try again.")
}

var s []map[string]interface{}
var ids []string
descriptionRegex, ok := d.GetOk("description_regex")
var r *regexp.Regexp
if ok && descriptionRegex.(string) != "" {
r = regexp.MustCompile(descriptionRegex.(string))
}
status, statusOk := d.GetOk("status")

for _, k := range keyIds {
key, err := conn.DescribeKey(k)
if err != nil {
return fmt.Errorf("DescribeKey got an error: %#v", err)
}

if r != nil && !r.MatchString(key.KeyMetadata.Description) {
continue
}
if statusOk && status != "" && status != key.KeyMetadata.KeyState {
continue
}
mapping := map[string]interface{}{
"id": key.KeyMetadata.KeyId,
"arn": key.KeyMetadata.Arn,
"description": key.KeyMetadata.Description,
"status": key.KeyMetadata.KeyState,
"creation_date": key.KeyMetadata.CreationDate,
"delete_date": key.KeyMetadata.DeleteDate,
"creator": key.KeyMetadata.Creator,
}
s = append(s, mapping)
ids = append(ids, key.KeyMetadata.KeyId)
}

d.SetId(dataResourceIdHash(ids))
if err := d.Set("keys", s); err != nil {
return err
}

// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
40 changes: 40 additions & 0 deletions alicloud/data_source_alicloud_kms_keys_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package alicloud

import (
//"regexp"
"testing"

"github.com/hashicorp/terraform/helper/resource"
)

func TestAccAlicloudKmsKeyDataSource_basic(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccCheckAlicloudKmsKeyDataSourceBasic,
Check: resource.ComposeTestCheckFunc(
testAccCheckAlicloudDataSourceID("data.alicloud_kms_keys.keys"),
resource.TestCheckResourceAttr("data.alicloud_kms_keys.keys", "keys.#", "1"),
resource.TestCheckResourceAttr("data.alicloud_kms_keys.keys", "keys.0.description", "Terraform acc test datasource"),
resource.TestCheckResourceAttr("data.alicloud_kms_keys.keys", "keys.0.status", "Enabled"),
),
},
},
})
}


const testAccCheckAlicloudKmsKeyDataSourceBasic = `
resource "alicloud_kms_key" "key" {
description = "Terraform acc test datasource"
deletion_window_in_days = 7
}

data "alicloud_kms_keys" "keys" {
description_regex = "Terraform*"
ids = ["${alicloud_kms_key.key.id}"]
status = "Enabled"
}
`
6 changes: 3 additions & 3 deletions alicloud/import_alicloud_kms_key_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@ func TestAccAlicloudKmsKey_import(t *testing.T) {
},

resource.TestStep{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
ImportStateVerifyIgnore: []string{"deletion_window_in_days"},
},
},
Expand Down
1 change: 1 addition & 0 deletions alicloud/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ func Provider() terraform.ResourceProvider {
"alicloud_instance_types": dataSourceAlicloudInstanceTypes(),
"alicloud_vpcs": dataSourceAlicloudVpcs(),
"alicloud_key_pairs": dataSourceAlicloudKeyPairs(),
"alicloud_kms_keys": dataSourceAlicloudKmsKeys(),
"alicloud_dns_domains": dataSourceAlicloudDnsDomains(),
"alicloud_dns_groups": dataSourceAlicloudDnsGroups(),
"alicloud_dns_records": dataSourceAlicloudDnsRecords(),
Expand Down
7 changes: 6 additions & 1 deletion alicloud/resource_alicloud_kms_key.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ func resourceAlicloudKmsKey() *schema.Resource {
"description": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Default: "From Terraform",
Default: "From Terraform",
ValidateFunc: validateStringLengthInRange(0, 8192),
},
"key_usage": &schema.Schema{
Expand Down Expand Up @@ -53,6 +53,10 @@ func resourceAlicloudKmsKey() *schema.Resource {
ValidateFunc: validateIntegerInRange(7, 30),
Default: 30,
},
"arn": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
},
}
}
Expand Down Expand Up @@ -98,6 +102,7 @@ func resourceAlicloudKmsKeyRead(d *schema.ResourceData, meta interface{}) error
d.Set("key_usage", key.KeyMetadata.KeyUsage)
d.Set("is_enabled", KeyState(key.KeyMetadata.KeyState) == Enabled)
d.Set("deletion_window_in_days", d.Get("deletion_window_in_days").(int))
d.Set("arn", key.KeyMetadata.Arn)

return nil
}
Expand Down
21 changes: 21 additions & 0 deletions alicloud/validators.go
Original file line number Diff line number Diff line change
Expand Up @@ -321,6 +321,17 @@ func validateInstanceChargeTypePeriodUnit(v interface{}, k string) (ws []string,
return
}

func validateInstanceStatus(v interface{}, k string) (ws []string, errors []error) {
status := ecs.InstanceStatus(v.(string))
if status != ecs.Running && status != ecs.Stopped && status != ecs.Creating &&
status != ecs.Starting && status != ecs.Stopping {
errors = append(errors, fmt.Errorf(
"%q must contain a valid status, expected %s or %s or %s or %s or %s, got %s.",
k, ecs.Creating, ecs.Starting, ecs.Running, ecs.Stopping, ecs.Stopped, status))
}
return
}

// SLB
func validateSlbName(v interface{}, k string) (ws []string, errors []error) {
if value := v.(string); value != "" {
Expand Down Expand Up @@ -1104,3 +1115,13 @@ func validateDBInstanceName(v interface{}, k string) (ws []string, errors []erro
}
return
}

func validateKmsKeyStatus(v interface{}, k string) (ws []string, errors []error) {
status := KeyState(v.(string))
if status != Enabled && status != Disabled && status != PendingDeletion {
errors = append(errors, fmt.Errorf(
"%q must contain a valid status, expected %s or %s or %s, got %s.",
k, Enabled, Disabled, PendingDeletion, status))
}
return
}