Skip to content

Commit

Permalink
Add support for tags on Directory Service (hashicorp#1398)
Browse files Browse the repository at this point in the history
* add support for tags on Directory Service

* update doc for directory service tags argument

* add acceptance test for tags on directory service

* Add tests for the diff function
  • Loading branch information
pablo-ruth authored and radeksimko committed Aug 23, 2017
1 parent b7f9caf commit b976976
Show file tree
Hide file tree
Showing 4 changed files with 238 additions and 0 deletions.
13 changes: 13 additions & 0 deletions aws/resource_aws_directory_service_directory.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ func resourceAwsDirectoryServiceDirectory() *schema.Resource {
Computed: true,
ForceNew: true,
},
"tags": tagsSchema(),
"vpc_settings": &schema.Schema{
Type: schema.TypeList,
Optional: true,
Expand Down Expand Up @@ -391,6 +392,10 @@ func resourceAwsDirectoryServiceDirectoryUpdate(d *schema.ResourceData, meta int
}
}

if err := setTagsDS(dsconn, d, d.Id()); err != nil {
return err
}

return resourceAwsDirectoryServiceDirectoryRead(d, meta)
}

Expand Down Expand Up @@ -438,6 +443,14 @@ func resourceAwsDirectoryServiceDirectoryRead(d *schema.ResourceData, meta inter
d.Set("connect_settings", flattenDSConnectSettings(dir.DnsIpAddrs, dir.ConnectSettings))
d.Set("enable_sso", *dir.SsoEnabled)

tagList, err := dsconn.ListTagsForResource(&directoryservice.ListTagsForResourceInput{
ResourceId: aws.String(d.Id()),
})
if err != nil {
return fmt.Errorf("Failed to get Directory service tags (id: %s): %s", d.Id(), err)
}
d.Set("tags", tagsToMapDS(tagList.Tags))

return nil
}

Expand Down
105 changes: 105 additions & 0 deletions aws/resource_aws_directory_service_directory_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package aws

import (
"fmt"
"reflect"
"testing"

"github.com/aws/aws-sdk-go/aws"
Expand All @@ -13,6 +14,57 @@ import (
"github.com/hashicorp/terraform/terraform"
)

func TestDiffTagsDirectoryService(t *testing.T) {
cases := []struct {
Old, New map[string]interface{}
Create, Remove map[string]string
}{
// Basic add/remove
{
Old: map[string]interface{}{
"foo": "bar",
},
New: map[string]interface{}{
"bar": "baz",
},
Create: map[string]string{
"bar": "baz",
},
Remove: map[string]string{
"foo": "bar",
},
},

// Modify
{
Old: map[string]interface{}{
"foo": "bar",
},
New: map[string]interface{}{
"foo": "baz",
},
Create: map[string]string{
"foo": "baz",
},
Remove: map[string]string{
"foo": "bar",
},
},
}

for i, tc := range cases {
c, r := diffTagsDS(tagsFromMapDS(tc.Old), tagsFromMapDS(tc.New))
cm := tagsToMapDS(c)
rm := tagsToMapDS(r)
if !reflect.DeepEqual(cm, tc.Create) {
t.Fatalf("%d: bad create: %#v", i, cm)
}
if !reflect.DeepEqual(rm, tc.Remove) {
t.Fatalf("%d: bad remove: %#v", i, rm)
}
}
}

func TestAccAWSDirectoryServiceDirectory_basic(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Expand All @@ -29,6 +81,23 @@ func TestAccAWSDirectoryServiceDirectory_basic(t *testing.T) {
})
}

func TestAccAWSDirectoryServiceDirectory_tags(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckDirectoryServiceDirectoryDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccDirectoryServiceDirectoryTagsConfig,
Check: resource.ComposeTestCheckFunc(
testAccCheckServiceDirectoryExists("aws_directory_service_directory.bar"),
resource.TestCheckResourceAttr("aws_directory_service_directory.bar", "tags.%", "2"),
),
},
},
})
}

func TestAccAWSDirectoryServiceDirectory_microsoft(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Expand Down Expand Up @@ -250,6 +319,42 @@ resource "aws_subnet" "bar" {
}
`

const testAccDirectoryServiceDirectoryTagsConfig = `
resource "aws_directory_service_directory" "bar" {
name = "corp.notexample.com"
password = "SuperSecretPassw0rd"
size = "Small"
vpc_settings {
vpc_id = "${aws_vpc.main.id}"
subnet_ids = ["${aws_subnet.foo.id}", "${aws_subnet.bar.id}"]
}
tags {
foo = "bar"
project = "test"
}
}
resource "aws_vpc" "main" {
cidr_block = "10.0.0.0/16"
tags {
Name = "testAccDirectoryServiceDirectoryConfig"
}
}
resource "aws_subnet" "foo" {
vpc_id = "${aws_vpc.main.id}"
availability_zone = "us-west-2a"
cidr_block = "10.0.1.0/24"
}
resource "aws_subnet" "bar" {
vpc_id = "${aws_vpc.main.id}"
availability_zone = "us-west-2b"
cidr_block = "10.0.2.0/24"
}
`

const testAccDirectoryServiceDirectoryConfig_connector = `
resource "aws_directory_service_directory" "bar" {
name = "corp.notexample.com"
Expand Down
115 changes: 115 additions & 0 deletions aws/tagsDS.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
package aws

import (
"log"
"regexp"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/directoryservice"
"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 setTagsDS(conn *directoryservice.DirectoryService, d *schema.ResourceData, resourceId string) error {
if d.HasChange("tags") {
oraw, nraw := d.GetChange("tags")
o := oraw.(map[string]interface{})
n := nraw.(map[string]interface{})
create, remove := diffTagsDS(tagsFromMapDS(o), tagsFromMapDS(n))

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

_, err := conn.RemoveTagsFromResource(&directoryservice.RemoveTagsFromResourceInput{
ResourceId: aws.String(resourceId),
TagKeys: k,
})
if err != nil {
return err
}
}
if len(create) > 0 {
log.Printf("[DEBUG] Creating tags: %s", create)
_, err := conn.AddTagsToResource(&directoryservice.AddTagsToResourceInput{
ResourceId: aws.String(resourceId),
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 diffTagsDS(oldTags, newTags []*directoryservice.Tag) ([]*directoryservice.Tag, []*directoryservice.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 []*directoryservice.Tag
for _, t := range oldTags {
old, ok := create[*t.Key]
if !ok || old != *t.Value {
// Delete it!
remove = append(remove, t)
}
}

return tagsFromMapDS(create), remove
}

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

return result
}

// tagsToMap turns the list of tags into a map.
func tagsToMapDS(ts []*directoryservice.Tag) map[string]string {
result := make(map[string]string)
for _, t := range ts {
if !tagIgnoredDS(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 tagIgnoredDS(t *directoryservice.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
}
5 changes: 5 additions & 0 deletions website/docs/r/directory_service_directory.html.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ resource "aws_directory_service_directory" "bar" {
vpc_id = "${aws_vpc.main.id}"
subnet_ids = ["${aws_subnet.foo.id}", "${aws_subnet.bar.id}"]
}
tags {
Project = "foo"
}
}
resource "aws_vpc" "main" {
Expand Down Expand Up @@ -58,6 +62,7 @@ The following arguments are supported:
* `short_name` - (Optional) The short name of the directory, such as `CORP`.
* `enable_sso` - (Optional) Whether to enable single-sign on for the directory. Requires `alias`. Defaults to `false`.
* `type` (Optional) - The directory type (`SimpleAD` or `MicrosoftAD` are accepted values). Defaults to `SimpleAD`.
* `tags` - (Optional) A mapping of tags to assign to the resource.

**vpc\_settings** supports the following:

Expand Down

0 comments on commit b976976

Please sign in to comment.