Skip to content

Commit

Permalink
Merge pull request #1319 from hashicorp/f-aws-asg-tags-support
Browse files Browse the repository at this point in the history
Add tagging support for AWS ASG (cont. 1080)
  • Loading branch information
catsby committed Mar 26, 2015
2 parents e0df2a9 + deda59b commit affdd1f
Show file tree
Hide file tree
Showing 5 changed files with 400 additions and 9 deletions.
170 changes: 170 additions & 0 deletions builtin/providers/aws/autoscaling_tags.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
package aws

import (
"bytes"
"fmt"
"log"

"github.com/hashicorp/aws-sdk-go/aws"
"github.com/hashicorp/aws-sdk-go/gen/autoscaling"
"github.com/hashicorp/terraform/helper/hashcode"
"github.com/hashicorp/terraform/helper/schema"
)

// tagsSchema returns the schema to use for tags.
func autoscalingTagsSchema() *schema.Schema {
return &schema.Schema{
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"key": &schema.Schema{
Type: schema.TypeString,
Required: true,
},

"value": &schema.Schema{
Type: schema.TypeString,
Required: true,
},

"propagate_at_launch": &schema.Schema{
Type: schema.TypeBool,
Required: true,
},
},
},
Set: autoscalingTagsToHash,
}
}

func autoscalingTagsToHash(v interface{}) int {
var buf bytes.Buffer
m := v.(map[string]interface{})
buf.WriteString(fmt.Sprintf("%s-", m["key"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["value"].(string)))
buf.WriteString(fmt.Sprintf("%t-", m["propagate_at_launch"].(bool)))

return hashcode.String(buf.String())
}

// setTags is a helper to set the tags for a resource. It expects the
// tags field to be named "tag"
func setAutoscalingTags(conn *autoscaling.AutoScaling, d *schema.ResourceData) error {
if d.HasChange("tag") {
oraw, nraw := d.GetChange("tag")
o := setToMapByKey(oraw.(*schema.Set), "key")
n := setToMapByKey(nraw.(*schema.Set), "key")

resourceID := d.Get("name").(string)
c, r := diffAutoscalingTags(
autoscalingTagsFromMap(o, resourceID),
autoscalingTagsFromMap(n, resourceID),
resourceID)
create := autoscaling.CreateOrUpdateTagsType{
Tags: c,
}
remove := autoscaling.DeleteTagsType{
Tags: r,
}

// Set tags
if len(r) > 0 {
log.Printf("[DEBUG] Removing autoscaling tags: %#v", r)
if err := conn.DeleteTags(&remove); err != nil {
return err
}
}
if len(c) > 0 {
log.Printf("[DEBUG] Creating autoscaling tags: %#v", c)
if err := conn.CreateOrUpdateTags(&create); 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 diffAutoscalingTags(oldTags, newTags []autoscaling.Tag, resourceID string) ([]autoscaling.Tag, []autoscaling.Tag) {
// First, we're creating everything we have
create := make(map[string]interface{})
for _, t := range newTags {
tag := map[string]interface{}{
"value": *t.Value,
"propagate_at_launch": *t.PropagateAtLaunch,
}
create[*t.Key] = tag
}

// Build the list of what to remove
var remove []autoscaling.Tag
for _, t := range oldTags {
old, ok := create[*t.Key].(map[string]interface{})

if !ok || old["value"] != *t.Value || old["propagate_at_launch"] != *t.PropagateAtLaunch {
// Delete it!
remove = append(remove, t)
}
}

return autoscalingTagsFromMap(create, resourceID), remove
}

// tagsFromMap returns the tags for the given map of data.
func autoscalingTagsFromMap(m map[string]interface{}, resourceID string) []autoscaling.Tag {
result := make([]autoscaling.Tag, 0, len(m))
for k, v := range m {
attr := v.(map[string]interface{})
result = append(result, autoscaling.Tag{
Key: aws.String(k),
Value: aws.String(attr["value"].(string)),
PropagateAtLaunch: aws.Boolean(attr["propagate_at_launch"].(bool)),
ResourceID: aws.String(resourceID),
ResourceType: aws.String("auto-scaling-group"),
})
}

return result
}

// autoscalingTagsToMap turns the list of tags into a map.
func autoscalingTagsToMap(ts []autoscaling.Tag) map[string]interface{} {
tags := make(map[string]interface{})
for _, t := range ts {
tag := map[string]interface{}{
"value": *t.Value,
"propagate_at_launch": *t.PropagateAtLaunch,
}
tags[*t.Key] = tag
}

return tags
}

// autoscalingTagDescriptionsToMap turns the list of tags into a map.
func autoscalingTagDescriptionsToMap(ts []autoscaling.TagDescription) map[string]map[string]interface{} {
tags := make(map[string]map[string]interface{})
for _, t := range ts {
tag := map[string]interface{}{
"value": *t.Value,
"propagate_at_launch": *t.PropagateAtLaunch,
}
tags[*t.Key] = tag
}

return tags
}

func setToMapByKey(s *schema.Set, key string) map[string]interface{} {
result := make(map[string]interface{})
for _, rawData := range s.List() {
data := rawData.(map[string]interface{})
result[data[key].(string)] = data
}

return result
}
122 changes: 122 additions & 0 deletions builtin/providers/aws/autoscaling_tags_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
package aws

import (
"fmt"
"reflect"
"testing"

"github.com/hashicorp/aws-sdk-go/gen/autoscaling"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"
)

func TestDiffAutoscalingTags(t *testing.T) {
cases := []struct {
Old, New map[string]interface{}
Create, Remove map[string]interface{}
}{
// Basic add/remove
{
Old: map[string]interface{}{
"Name": map[string]interface{}{
"value": "bar",
"propagate_at_launch": true,
},
},
New: map[string]interface{}{
"DifferentTag": map[string]interface{}{
"value": "baz",
"propagate_at_launch": true,
},
},
Create: map[string]interface{}{
"DifferentTag": map[string]interface{}{
"value": "baz",
"propagate_at_launch": true,
},
},
Remove: map[string]interface{}{
"Name": map[string]interface{}{
"value": "bar",
"propagate_at_launch": true,
},
},
},

// Modify
{
Old: map[string]interface{}{
"Name": map[string]interface{}{
"value": "bar",
"propagate_at_launch": true,
},
},
New: map[string]interface{}{
"Name": map[string]interface{}{
"value": "baz",
"propagate_at_launch": false,
},
},
Create: map[string]interface{}{
"Name": map[string]interface{}{
"value": "baz",
"propagate_at_launch": false,
},
},
Remove: map[string]interface{}{
"Name": map[string]interface{}{
"value": "bar",
"propagate_at_launch": true,
},
},
},
}

var resourceID = "sample"

for i, tc := range cases {
awsTagsOld := autoscalingTagsFromMap(tc.Old, resourceID)
awsTagsNew := autoscalingTagsFromMap(tc.New, resourceID)

c, r := diffAutoscalingTags(awsTagsOld, awsTagsNew, resourceID)

cm := autoscalingTagsToMap(c)
rm := autoscalingTagsToMap(r)
if !reflect.DeepEqual(cm, tc.Create) {
t.Fatalf("%d: bad create: \n%#v\n%#v", i, cm, tc.Create)
}
if !reflect.DeepEqual(rm, tc.Remove) {
t.Fatalf("%d: bad remove: \n%#v\n%#v", i, rm, tc.Remove)
}
}
}

// testAccCheckTags can be used to check the tags on a resource.
func testAccCheckAutoscalingTags(
ts *[]autoscaling.TagDescription, key string, expected map[string]interface{}) resource.TestCheckFunc {
return func(s *terraform.State) error {
m := autoscalingTagDescriptionsToMap(*ts)
v, ok := m[key]
if !ok {
return fmt.Errorf("Missing tag: %s", key)
}

if v["value"] != expected["value"].(string) ||
v["propagate_at_launch"] != expected["propagate_at_launch"].(bool) {
return fmt.Errorf("%s: bad value: %s", key, v)
}

return nil
}
}

func testAccCheckAutoscalingTagNotExists(ts *[]autoscaling.TagDescription, key string) resource.TestCheckFunc {
return func(s *terraform.State) error {
m := autoscalingTagDescriptionsToMap(*ts)
if _, ok := m[key]; ok {
return fmt.Errorf("Tag exists when it should not: %s", key)
}

return nil
}
}
30 changes: 22 additions & 8 deletions builtin/providers/aws/resource_aws_autoscaling_group.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,8 @@ func resourceAwsAutoscalingGroup() *schema.Resource {
return hashcode.String(v.(string))
},
},

"tag": autoscalingTagsSchema(),
},
}
}
Expand All @@ -133,6 +135,11 @@ func resourceAwsAutoscalingGroupCreate(d *schema.ResourceData, meta interface{})
autoScalingGroupOpts.AvailabilityZones = expandStringList(
d.Get("availability_zones").(*schema.Set).List())

if v, ok := d.GetOk("tag"); ok {
autoScalingGroupOpts.Tags = autoscalingTagsFromMap(
setToMapByKey(v.(*schema.Set), "key"), d.Get("name").(string))
}

if v, ok := d.GetOk("default_cooldown"); ok {
autoScalingGroupOpts.DefaultCooldown = aws.Integer(v.(int))
}
Expand Down Expand Up @@ -186,15 +193,16 @@ func resourceAwsAutoscalingGroupRead(d *schema.ResourceData, meta interface{}) e
}

d.Set("availability_zones", g.AvailabilityZones)
d.Set("default_cooldown", *g.DefaultCooldown)
d.Set("desired_capacity", *g.DesiredCapacity)
d.Set("health_check_grace_period", *g.HealthCheckGracePeriod)
d.Set("health_check_type", *g.HealthCheckType)
d.Set("launch_configuration", *g.LaunchConfigurationName)
d.Set("default_cooldown", g.DefaultCooldown)
d.Set("desired_capacity", g.DesiredCapacity)
d.Set("health_check_grace_period", g.HealthCheckGracePeriod)
d.Set("health_check_type", g.HealthCheckType)
d.Set("launch_configuration", g.LaunchConfigurationName)
d.Set("load_balancers", g.LoadBalancerNames)
d.Set("min_size", *g.MinSize)
d.Set("max_size", *g.MaxSize)
d.Set("name", *g.AutoScalingGroupName)
d.Set("min_size", g.MinSize)
d.Set("max_size", g.MaxSize)
d.Set("name", g.AutoScalingGroupName)
d.Set("tag", g.Tags)
d.Set("vpc_zone_identifier", strings.Split(*g.VPCZoneIdentifier, ","))
d.Set("termination_policies", g.TerminationPolicies)

Expand Down Expand Up @@ -224,6 +232,12 @@ func resourceAwsAutoscalingGroupUpdate(d *schema.ResourceData, meta interface{})
opts.MaxSize = aws.Integer(d.Get("max_size").(int))
}

if err := setAutoscalingTags(autoscalingconn, d); err != nil {
return err
} else {
d.SetPartial("tag")
}

log.Printf("[DEBUG] AutoScaling Group update configuration: %#v", opts)
err := autoscalingconn.UpdateAutoScalingGroup(&opts)
if err != nil {
Expand Down

0 comments on commit affdd1f

Please sign in to comment.