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

Added missing features on parameter store resource #1

Merged
merged 2 commits into from
Jul 31, 2017
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
98 changes: 67 additions & 31 deletions aws/resource_aws_ssm_parameter.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@ func resourceAwsSsmParameter() *schema.Resource {
Required: true,
ForceNew: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
Default: "",
},
"type": {
Type: schema.TypeString,
Required: true,
Expand All @@ -42,52 +47,78 @@ func resourceAwsSsmParameter() *schema.Resource {
"overwrite": {
Type: schema.TypeBool,
Optional: true,
Default: false,
// The default should be set to true, terraform lifecycle should take care of not overriding the value if it is manually set by the user.
// Otherwise, it is causing a breaking change because the first version did not allow overwrite parameter and overwrite was allowed.
Default: true,
},
"allowed_pattern": {
Type: schema.TypeString,
Optional: true,
Default: "",
},
"tags": tagsSchema(),
},
}
}

func resourceAwsSsmParameterRead(d *schema.ResourceData, meta interface{}) error {
ssmconn := meta.(*AWSClient).ssmconn
conn := meta.(*AWSClient).ssmconn

log.Printf("[DEBUG] Reading SSM Parameter: %s", d.Id())

paramInput := &ssm.GetParametersInput{
Names: []*string{
aws.String(d.Get("name").(string)),
},
if resp, err := conn.GetParameters(&ssm.GetParametersInput{
Names: []*string{aws.String(d.Get("name").(string))},
WithDecryption: aws.Bool(true),
}); err != nil {
return errwrap.Wrapf("[ERROR] Error getting SSM parameter: {{err}}", err)
} else {
if len(resp.InvalidParameters) > 0 {
log.Print("[INFO] The resource no longer exists, marking it for recreation:", d.Id())
d.MarkNewResource()
return nil
}
param := resp.Parameters[0]
d.Set("name", param.Name)
d.Set("type", param.Type)
d.Set("value", param.Value)
}

resp, err := ssmconn.GetParameters(paramInput)

if err != nil {
if resp, err := conn.DescribeParameters(&ssm.DescribeParametersInput{
Filters: []*ssm.ParametersFilter{
&ssm.ParametersFilter{
Key: aws.String("Name"),
Values: []*string{aws.String(d.Get("name").(string))},
},
},
}); err != nil {
return errwrap.Wrapf("[ERROR] Error describing SSM parameter: {{err}}", err)
} else {
param := resp.Parameters[0]
d.Set("key_id", param.KeyId)
d.Set("description", param.Description)
d.Set("allowed_pattern", param.AllowedPattern)
}

if len(resp.InvalidParameters) > 0 {
return fmt.Errorf("[ERROR] SSM Parameter %s is invalid", d.Id())
if tagList, err := conn.ListTagsForResource(&ssm.ListTagsForResourceInput{
ResourceId: aws.String(d.Get("name").(string)),
ResourceType: aws.String("Parameter"),
}); err != nil {
return fmt.Errorf("Failed to get SSM parameter tags for %s: %s", d.Get("name"), err)
} else {
d.Set("tags", tagsToMapSSM(tagList.TagList))
}

param := resp.Parameters[0]
d.Set("name", param.Name)
d.Set("type", param.Type)
d.Set("value", param.Value)

return nil
}

func resourceAwsSsmParameterDelete(d *schema.ResourceData, meta interface{}) error {
ssmconn := meta.(*AWSClient).ssmconn
conn := meta.(*AWSClient).ssmconn

log.Printf("[INFO] Deleting SSM Parameter: %s", d.Id())

paramInput := &ssm.DeleteParameterInput{
_, err := conn.DeleteParameter(&ssm.DeleteParameterInput{
Name: aws.String(d.Get("name").(string)),
}

_, err := ssmconn.DeleteParameter(paramInput)
})
if err != nil {
return err
}
Expand All @@ -98,28 +129,33 @@ func resourceAwsSsmParameterDelete(d *schema.ResourceData, meta interface{}) err
}

func resourceAwsSsmParameterPut(d *schema.ResourceData, meta interface{}) error {
ssmconn := meta.(*AWSClient).ssmconn
conn := meta.(*AWSClient).ssmconn

log.Printf("[INFO] Creating SSM Parameter: %s", d.Get("name").(string))

paramInput := &ssm.PutParameterInput{
Name: aws.String(d.Get("name").(string)),
Type: aws.String(d.Get("type").(string)),
Value: aws.String(d.Get("value").(string)),
Overwrite: aws.Bool(d.Get("overwrite").(bool)),
Name: aws.String(d.Get("name").(string)),
Description: aws.String(d.Get("description").(string)),
Type: aws.String(d.Get("type").(string)),
Value: aws.String(d.Get("value").(string)),
Overwrite: aws.Bool(d.Get("overwrite").(bool)),
AllowedPattern: aws.String(d.Get("allowed_pattern").(string)),
}

if keyID, ok := d.GetOk("key_id"); ok {
log.Printf("[DEBUG] Setting key_id for SSM Parameter %s: %s", d.Get("name").(string), keyID.(string))
log.Printf("[DEBUG] Setting key_id for SSM Parameter %v: %s", d.Get("name"), keyID)
paramInput.SetKeyId(keyID.(string))
}

log.Printf("[DEBUG] Waiting for SSM Parameter %q to be updated", d.Get("name").(string))
_, err := ssmconn.PutParameter(paramInput)

if err != nil {
log.Printf("[DEBUG] Waiting for SSM Parameter %v to be updated", d.Get("name"))
if _, err := conn.PutParameter(paramInput); err != nil {
return errwrap.Wrapf("[ERROR] Error creating SSM parameter: {{err}}", err)
}

if err := setTagsSSM(conn, d, d.Get("name").(string), "Parameter"); err != nil {
return errwrap.Wrapf("[ERROR] Error creating SSM parameter tags: {{err}}", err)
}

d.SetId(d.Get("name").(string))

return resourceAwsSsmParameterRead(d, meta)
Expand Down
3 changes: 3 additions & 0 deletions aws/resource_aws_ssm_parameter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,7 @@ func testAccAWSSSMParameterBasicConfigOverwrite(rName string, value string) stri
return fmt.Sprintf(`
resource "aws_ssm_parameter" "foo" {
name = "test_parameter-%s"
description = "description for parameter %s"
type = "String"
value = "%s"
overwrite = true
Expand All @@ -242,6 +243,7 @@ func testAccAWSSSMParameterSecureConfig(rName string, value string) string {
return fmt.Sprintf(`
resource "aws_ssm_parameter" "secret_foo" {
name = "test_secure_parameter-%s"
description = "description for parameter %s"
type = "SecureString"
value = "%s"
}
Expand All @@ -252,6 +254,7 @@ func testAccAWSSSMParameterSecureConfigWithKey(rName string, value string) strin
return fmt.Sprintf(`
resource "aws_ssm_parameter" "secret_foo" {
name = "test_secure_parameter-%s"
description = "description for parameter %s"
type = "SecureString"
value = "%s"
key_id = "${aws_kms_key.test_key.id}"
Expand Down
117 changes: 117 additions & 0 deletions aws/tagsSSM.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
package aws

import (
"log"
"regexp"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ssm"
"github.com/hashicorp/terraform/helper/schema"
)

// setTags is a helper to set the tags for a resource. It expects the
// tags field to be named "tags"
func setTagsSSM(conn *ssm.SSM, d *schema.ResourceData, id, resourceType string) error {
if d.HasChange("tags") {
oraw, nraw := d.GetChange("tags")
o := oraw.(map[string]interface{})
n := nraw.(map[string]interface{})
create, remove := diffTagsSSM(tagsFromMapSSM(o), tagsFromMapSSM(n))

// Set tags
if len(remove) > 0 {
log.Printf("[DEBUG] Removing tags: %#v", remove)
k := make([]*string, len(remove), len(remove))
for i, t := range remove {
k[i] = t.Key
}

_, err := conn.RemoveTagsFromResource(&ssm.RemoveTagsFromResourceInput{
ResourceId: aws.String(id),
ResourceType: aws.String(resourceType),
TagKeys: k,
})
if err != nil {
return err
}
}
if len(create) > 0 {
log.Printf("[DEBUG] Creating tags: %#v", create)
_, err := conn.AddTagsToResource(&ssm.AddTagsToResourceInput{
ResourceId: aws.String(id),
ResourceType: aws.String(resourceType),
Tags: create,
})
if err != nil {
return err
}
}
}

return nil
}

// diffTags takes our tags locally and the ones remotely and returns
// the set of tags that must be created, and the set of tags that must
// be destroyed.
func diffTagsSSM(oldTags, newTags []*ssm.Tag) ([]*ssm.Tag, []*ssm.Tag) {
// First, we're creating everything we have
create := make(map[string]interface{})
for _, t := range newTags {
create[*t.Key] = *t.Value
}

// Build the list of what to remove
var remove []*ssm.Tag
for _, t := range oldTags {
old, ok := create[*t.Key]
if !ok || old != *t.Value {
// Delete it!
remove = append(remove, t)
}
}

return tagsFromMapSSM(create), remove
}

// tagsFromMap returns the tags for the given map of data.
func tagsFromMapSSM(m map[string]interface{}) []*ssm.Tag {
result := make([]*ssm.Tag, 0, len(m))
for k, v := range m {
t := &ssm.Tag{
Key: aws.String(k),
Value: aws.String(v.(string)),
}
if !tagIgnoredSSM(t) {
result = append(result, t)
}
}

return result
}

// tagsToMap turns the list of tags into a map.
func tagsToMapSSM(ts []*ssm.Tag) map[string]string {
result := make(map[string]string)
for _, t := range ts {
if !tagIgnoredSSM(t) {
result[*t.Key] = *t.Value
}
}

return result
}

// compare a tag against a list of strings and checks if it should
// be ignored or not
func tagIgnoredSSM(t *ssm.Tag) bool {
filter := []string{"^aws:"}
for _, v := range filter {
log.Printf("[DEBUG] Matching %v with %v\n", v, *t.Key)
if r, _ := regexp.MatchString(v, *t.Key); r == true {
log.Printf("[DEBUG] Found AWS specific tag %s (val: %s), ignoring.\n", *t.Key, *t.Value)
return true
}
}
return false
}
Loading