Skip to content

Commit

Permalink
Merge pull request #3453 from terraform-providers/td-aws_directory_se…
Browse files Browse the repository at this point in the history
…rvice_directory-cleanup

resource/aws_directory_service_directory: Validate size argument and various code cleanup
  • Loading branch information
bflad authored Feb 20, 2018
2 parents d78d3d9 + aacae9e commit 25777a7
Showing 1 changed file with 74 additions and 83 deletions.
157 changes: 74 additions & 83 deletions aws/resource_aws_directory_service_directory.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,11 @@ import (
"github.com/hashicorp/terraform/helper/schema"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/directoryservice"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/validation"
)

var directoryCreationFuncs = map[string]func(*directoryservice.DirectoryService, *schema.ResourceData) (string, error){
"SimpleAD": createSimpleDirectoryService,
"MicrosoftAD": createActiveDirectoryService,
"ADConnector": createDirectoryConnector,
}

func resourceAwsDirectoryServiceDirectory() *schema.Resource {
return &schema.Resource{
Create: resourceAwsDirectoryServiceDirectoryCreate,
Expand Down Expand Up @@ -47,6 +40,10 @@ func resourceAwsDirectoryServiceDirectory() *schema.Resource {
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{
directoryservice.DirectorySizeLarge,
directoryservice.DirectorySizeSmall,
}, false),
},
"alias": {
Type: schema.TypeString,
Expand All @@ -68,6 +65,7 @@ func resourceAwsDirectoryServiceDirectory() *schema.Resource {
"tags": tagsSchema(),
"vpc_settings": {
Type: schema.TypeList,
MaxItems: 1,
Optional: true,
ForceNew: true,
Elem: &schema.Resource{
Expand All @@ -89,6 +87,7 @@ func resourceAwsDirectoryServiceDirectory() *schema.Resource {
},
"connect_settings": {
Type: schema.TypeList,
MaxItems: 1,
Optional: true,
ForceNew: true,
Elem: &schema.Resource{
Expand Down Expand Up @@ -142,19 +141,13 @@ func resourceAwsDirectoryServiceDirectory() *schema.Resource {
"type": {
Type: schema.TypeString,
Optional: true,
Default: "SimpleAD",
Default: directoryservice.DirectoryTypeSimpleAd,
ForceNew: true,
ValidateFunc: func(v interface{}, k string) (ws []string, es []error) {
validTypes := []string{"SimpleAD", "MicrosoftAD"}
value := v.(string)
for validType, _ := range directoryCreationFuncs {
if validType == value {
return
}
}
es = append(es, fmt.Errorf("%q must be one of %q", k, validTypes))
return
},
ValidateFunc: validation.StringInSlice([]string{
directoryservice.DirectoryTypeAdconnector,
directoryservice.DirectoryTypeMicrosoftAd,
directoryservice.DirectoryTypeSimpleAd,
}, false),
},
"edition": {
Type: schema.TypeString,
Expand All @@ -171,58 +164,48 @@ func resourceAwsDirectoryServiceDirectory() *schema.Resource {
}

func buildVpcSettings(d *schema.ResourceData) (vpcSettings *directoryservice.DirectoryVpcSettings, err error) {
if v, ok := d.GetOk("vpc_settings"); !ok {
v, ok := d.GetOk("vpc_settings")
if !ok {
return nil, fmt.Errorf("vpc_settings is required for type = SimpleAD or MicrosoftAD")
} else {
settings := v.([]interface{})

if len(settings) > 1 {
return nil, fmt.Errorf("Only a single vpc_settings block is expected")
} else if len(settings) == 1 {
s := settings[0].(map[string]interface{})
var subnetIds []*string
for _, id := range s["subnet_ids"].(*schema.Set).List() {
subnetIds = append(subnetIds, aws.String(id.(string)))
}
}
settings := v.([]interface{})
s := settings[0].(map[string]interface{})
var subnetIds []*string
for _, id := range s["subnet_ids"].(*schema.Set).List() {
subnetIds = append(subnetIds, aws.String(id.(string)))
}

vpcSettings = &directoryservice.DirectoryVpcSettings{
SubnetIds: subnetIds,
VpcId: aws.String(s["vpc_id"].(string)),
}
}
vpcSettings = &directoryservice.DirectoryVpcSettings{
SubnetIds: subnetIds,
VpcId: aws.String(s["vpc_id"].(string)),
}

return vpcSettings, nil
}

func buildConnectSettings(d *schema.ResourceData) (connectSettings *directoryservice.DirectoryConnectSettings, err error) {
if v, ok := d.GetOk("connect_settings"); !ok {
v, ok := d.GetOk("connect_settings")
if !ok {
return nil, fmt.Errorf("connect_settings is required for type = ADConnector")
} else {
settings := v.([]interface{})

if len(settings) > 1 {
return nil, fmt.Errorf("Only a single connect_settings block is expected")
} else if len(settings) == 1 {
s := settings[0].(map[string]interface{})
}
settings := v.([]interface{})
s := settings[0].(map[string]interface{})

var subnetIds []*string
for _, id := range s["subnet_ids"].(*schema.Set).List() {
subnetIds = append(subnetIds, aws.String(id.(string)))
}
var subnetIds []*string
for _, id := range s["subnet_ids"].(*schema.Set).List() {
subnetIds = append(subnetIds, aws.String(id.(string)))
}

var customerDnsIps []*string
for _, id := range s["customer_dns_ips"].(*schema.Set).List() {
customerDnsIps = append(customerDnsIps, aws.String(id.(string)))
}
var customerDnsIps []*string
for _, id := range s["customer_dns_ips"].(*schema.Set).List() {
customerDnsIps = append(customerDnsIps, aws.String(id.(string)))
}

connectSettings = &directoryservice.DirectoryConnectSettings{
CustomerDnsIps: customerDnsIps,
CustomerUserName: aws.String(s["customer_username"].(string)),
SubnetIds: subnetIds,
VpcId: aws.String(s["vpc_id"].(string)),
}
}
connectSettings = &directoryservice.DirectoryConnectSettings{
CustomerDnsIps: customerDnsIps,
CustomerUserName: aws.String(s["customer_username"].(string)),
SubnetIds: subnetIds,
VpcId: aws.String(s["vpc_id"].(string)),
}

return connectSettings, nil
Expand Down Expand Up @@ -330,13 +313,18 @@ func createActiveDirectoryService(dsconn *directoryservice.DirectoryService, d *
func resourceAwsDirectoryServiceDirectoryCreate(d *schema.ResourceData, meta interface{}) error {
dsconn := meta.(*AWSClient).dsconn

creationFunc, ok := directoryCreationFuncs[d.Get("type").(string)]
if !ok {
// Shouldn't happen as this is validated above
return fmt.Errorf("Unsupported directory type: %s", d.Get("type"))
var directoryId string
var err error
directoryType := d.Get("type").(string)

if directoryType == directoryservice.DirectoryTypeAdconnector {
directoryId, err = createDirectoryConnector(dsconn, d)
} else if directoryType == directoryservice.DirectoryTypeMicrosoftAd {
directoryId, err = createActiveDirectoryService(dsconn, d)
} else if directoryType == directoryservice.DirectoryTypeSimpleAd {
directoryId, err = createSimpleDirectoryService(dsconn, d)
}

directoryId, err := creationFunc(dsconn, d)
if err != nil {
return err
}
Expand All @@ -346,8 +334,12 @@ func resourceAwsDirectoryServiceDirectoryCreate(d *schema.ResourceData, meta int
// Wait for creation
log.Printf("[DEBUG] Waiting for DS (%q) to become available", d.Id())
stateConf := &resource.StateChangeConf{
Pending: []string{"Requested", "Creating", "Created"},
Target: []string{"Active"},
Pending: []string{
directoryservice.DirectoryStageRequested,
directoryservice.DirectoryStageCreating,
directoryservice.DirectoryStageCreated,
},
Target: []string{directoryservice.DirectoryStageActive},
Refresh: func() (interface{}, string, error) {
resp, err := dsconn.DescribeDirectories(&directoryservice.DescribeDirectoriesInput{
DirectoryIds: []*string{aws.String(d.Id())},
Expand Down Expand Up @@ -443,27 +435,23 @@ func resourceAwsDirectoryServiceDirectoryRead(d *schema.ResourceData, meta inter
dir := out.DirectoryDescriptions[0]
log.Printf("[DEBUG] Received DS directory: %s", dir)

d.Set("access_url", *dir.AccessUrl)
d.Set("alias", *dir.Alias)
if dir.Description != nil {
d.Set("description", *dir.Description)
}
d.Set("access_url", dir.AccessUrl)
d.Set("alias", dir.Alias)
d.Set("description", dir.Description)

if *dir.Type == "ADConnector" {
if *dir.Type == directoryservice.DirectoryTypeAdconnector {
d.Set("dns_ip_addresses", schema.NewSet(schema.HashString, flattenStringList(dir.ConnectSettings.ConnectIps)))
} else {
d.Set("dns_ip_addresses", schema.NewSet(schema.HashString, flattenStringList(dir.DnsIpAddrs)))
}
d.Set("name", *dir.Name)
if dir.ShortName != nil {
d.Set("short_name", *dir.ShortName)
}
d.Set("name", dir.Name)
d.Set("short_name", dir.ShortName)
d.Set("size", dir.Size)
d.Set("edition", dir.Edition)
d.Set("type", *dir.Type)
d.Set("type", dir.Type)
d.Set("vpc_settings", flattenDSVpcSettings(dir.VpcSettings))
d.Set("connect_settings", flattenDSConnectSettings(dir.DnsIpAddrs, dir.ConnectSettings))
d.Set("enable_sso", *dir.SsoEnabled)
d.Set("enable_sso", dir.SsoEnabled)

if dir.VpcSettings != nil {
d.Set("security_group_id", *dir.VpcSettings.SecurityGroupId)
Expand Down Expand Up @@ -496,21 +484,24 @@ func resourceAwsDirectoryServiceDirectoryDelete(d *schema.ResourceData, meta int
// Wait for deletion
log.Printf("[DEBUG] Waiting for DS (%q) to be deleted", d.Id())
stateConf := &resource.StateChangeConf{
Pending: []string{"Deleting"},
Target: []string{"Deleted"},
Pending: []string{
directoryservice.DirectoryStageActive,
directoryservice.DirectoryStageDeleting,
},
Target: []string{directoryservice.DirectoryStageDeleted},
Refresh: func() (interface{}, string, error) {
resp, err := dsconn.DescribeDirectories(&directoryservice.DescribeDirectoriesInput{
DirectoryIds: []*string{aws.String(d.Id())},
})
if err != nil {
if dserr, ok := err.(awserr.Error); ok && dserr.Code() == "EntityDoesNotExistException" {
return 42, "Deleted", nil
if isAWSErr(err, directoryservice.ErrCodeEntityDoesNotExistException, "") {
return 42, directoryservice.DirectoryStageDeleted, nil
}
return nil, "error", err
}

if len(resp.DirectoryDescriptions) == 0 {
return 42, "Deleted", nil
return 42, directoryservice.DirectoryStageDeleted, nil
}

ds := resp.DirectoryDescriptions[0]
Expand Down

0 comments on commit 25777a7

Please sign in to comment.