Skip to content

Commit

Permalink
Merge pull request #1526 from PeopleNet/route53_private_hosted_zone
Browse files Browse the repository at this point in the history
AWS/Route53Zone - create private hosted zone associated with VPC.
  • Loading branch information
catsby committed May 14, 2015
2 parents beb3ea9 + 4360752 commit b3a4965
Show file tree
Hide file tree
Showing 9 changed files with 674 additions and 26 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,14 @@ IMPROVEMENTS:

* **New config function: `formatlist`** - Format lists in a similar way to `format`.
Useful for creating URLs from a list of IPs. [GH-1829]
* **New resource: `aws_route53_zone_association`**
* provider/aws: `aws_autoscaling_group` can wait for capacity in ELB
via `min_elb_capacity` [GH-1970]
* provider/aws: `aws_db_instances` supports `license_model` [GH-1966]
* provider/aws: `aws_elasticache_cluster` add support for Tags [GH-1965]
* provider/aws: `aws_s3_bucket` exports `hosted_zone_id` and `region` [GH-1865]
* provider/aws: `aws_route53_record` exports `fqdn` [GH-1847]
* provider/aws: `aws_route53_zone` can create private hosted zones [GH-1526]
* provider/google: `google_compute_instance` `scratch` attribute added [GH-1920]

BUG FIXES:
Expand Down
1 change: 1 addition & 0 deletions builtin/providers/aws/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ func Provider() terraform.ResourceProvider {
"aws_network_interface": resourceAwsNetworkInterface(),
"aws_proxy_protocol_policy": resourceAwsProxyProtocolPolicy(),
"aws_route53_record": resourceAwsRoute53Record(),
"aws_route53_zone_association": resourceAwsRoute53ZoneAssociation(),
"aws_route53_zone": resourceAwsRoute53Zone(),
"aws_route_table_association": resourceAwsRouteTableAssociation(),
"aws_route_table": resourceAwsRouteTable(),
Expand Down
77 changes: 70 additions & 7 deletions builtin/providers/aws/resource_aws_route53_zone.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,19 @@ func resourceAwsRoute53Zone() *schema.Resource {
ForceNew: true,
},

"vpc_id": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},

"vpc_region": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},

"zone_id": &schema.Schema{
Type: schema.TypeString,
Computed: true,
Expand All @@ -53,6 +66,16 @@ func resourceAwsRoute53ZoneCreate(d *schema.ResourceData, meta interface{}) erro
HostedZoneConfig: comment,
CallerReference: aws.String(time.Now().Format(time.RFC3339Nano)),
}
if v := d.Get("vpc_id"); v != "" {
req.VPC = &route53.VPC{
VPCID: aws.String(v.(string)),
VPCRegion: aws.String(meta.(*AWSClient).region),
}
if w := d.Get("vpc_region"); w != "" {
req.VPC.VPCRegion = aws.String(w.(string))
}
d.Set("vpc_region", req.VPC.VPCRegion)
}

log.Printf("[DEBUG] Creating Route53 hosted zone: %s", *req.Name)
resp, err := r53.CreateHostedZone(req)
Expand Down Expand Up @@ -98,13 +121,33 @@ func resourceAwsRoute53ZoneRead(d *schema.ResourceData, meta interface{}) error
return err
}

ns := make([]string, len(zone.DelegationSet.NameServers))
for i := range zone.DelegationSet.NameServers {
ns[i] = *zone.DelegationSet.NameServers[i]
}
sort.Strings(ns)
if err := d.Set("name_servers", ns); err != nil {
return fmt.Errorf("[DEBUG] Error setting name servers for: %s, error: %#v", d.Id(), err)
if !*zone.HostedZone.Config.PrivateZone {
ns := make([]string, len(zone.DelegationSet.NameServers))
for i := range zone.DelegationSet.NameServers {
ns[i] = *zone.DelegationSet.NameServers[i]
}
sort.Strings(ns)
if err := d.Set("name_servers", ns); err != nil {
return fmt.Errorf("[DEBUG] Error setting name servers for: %s, error: %#v", d.Id(), err)
}
} else {
ns, err := getNameServers(d.Id(), d.Get("name").(string), r53)
if err != nil {
return err
}
if err := d.Set("name_servers", ns); err != nil {
return fmt.Errorf("[DEBUG] Error setting name servers for: %s, error: %#v", d.Id(), err)
}

var associatedVPC *route53.VPC
for _, vpc := range zone.VPCs {
if *vpc.VPCID == d.Get("vpc_id") {
associatedVPC = vpc
}
}
if associatedVPC == nil {
return fmt.Errorf("[DEBUG] VPC: %v is not associated with Zone: %v", d.Get("vpc_id"), d.Id())
}
}

// get tags
Expand Down Expand Up @@ -181,3 +224,23 @@ func cleanPrefix(ID, prefix string) string {
}
return ID
}

func getNameServers(zoneId string, zoneName string, r53 *route53.Route53) ([]string, error) {
resp, err := r53.ListResourceRecordSets(&route53.ListResourceRecordSetsInput{
HostedZoneID: aws.String(zoneId),
StartRecordName: aws.String(zoneName),
StartRecordType: aws.String("NS"),
})
if err != nil {
return nil, err
}
if len(resp.ResourceRecordSets) == 0 {
return nil, nil
}
ns := make([]string, len(resp.ResourceRecordSets[0].ResourceRecords))
for i := range resp.ResourceRecordSets[0].ResourceRecords {
ns[i] = *resp.ResourceRecordSets[0].ResourceRecords[i].Value
}
sort.Strings(ns)
return ns, nil
}
147 changes: 147 additions & 0 deletions builtin/providers/aws/resource_aws_route53_zone_association.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
package aws

import (
"fmt"
"log"
"strings"
"time"

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

"github.com/awslabs/aws-sdk-go/aws"
"github.com/awslabs/aws-sdk-go/service/route53"
)

func resourceAwsRoute53ZoneAssociation() *schema.Resource {
return &schema.Resource{
Create: resourceAwsRoute53ZoneAssociationCreate,
Read: resourceAwsRoute53ZoneAssociationRead,
Update: resourceAwsRoute53ZoneAssociationUpdate,
Delete: resourceAwsRoute53ZoneAssociationDelete,

Schema: map[string]*schema.Schema{
"zone_id": &schema.Schema{
Type: schema.TypeString,
Required: true,
},

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

"vpc_region": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
},
},
}
}

func resourceAwsRoute53ZoneAssociationCreate(d *schema.ResourceData, meta interface{}) error {
r53 := meta.(*AWSClient).r53conn

req := &route53.AssociateVPCWithHostedZoneInput{
HostedZoneID: aws.String(d.Get("zone_id").(string)),
VPC: &route53.VPC{
VPCID: aws.String(d.Get("vpc_id").(string)),
VPCRegion: aws.String(meta.(*AWSClient).region),
},
Comment: aws.String("Managed by Terraform"),
}
if w := d.Get("vpc_region"); w != "" {
req.VPC.VPCRegion = aws.String(w.(string))
}

log.Printf("[DEBUG] Associating Route53 Private Zone %s with VPC %s with region %s", *req.HostedZoneID, *req.VPC.VPCID, *req.VPC.VPCRegion)
resp, err := r53.AssociateVPCWithHostedZone(req)
if err != nil {
return err
}

// Store association id
d.SetId(fmt.Sprintf("%s:%s", *req.HostedZoneID, *req.VPC.VPCID))
d.Set("vpc_region", req.VPC.VPCRegion)

// Wait until we are done initializing
wait := resource.StateChangeConf{
Delay: 30 * time.Second,
Pending: []string{"PENDING"},
Target: "INSYNC",
Timeout: 10 * time.Minute,
MinTimeout: 2 * time.Second,
Refresh: func() (result interface{}, state string, err error) {
changeRequest := &route53.GetChangeInput{
ID: aws.String(cleanChangeID(*resp.ChangeInfo.ID)),
}
return resourceAwsGoRoute53Wait(r53, changeRequest)
},
}
_, err = wait.WaitForState()
if err != nil {
return err
}

return resourceAwsRoute53ZoneAssociationUpdate(d, meta)
}

func resourceAwsRoute53ZoneAssociationRead(d *schema.ResourceData, meta interface{}) error {
r53 := meta.(*AWSClient).r53conn
zone_id, vpc_id := resourceAwsRoute53ZoneAssociationParseId(d.Id())
zone, err := r53.GetHostedZone(&route53.GetHostedZoneInput{ID: aws.String(zone_id)})
if err != nil {
// Handle a deleted zone
if r53err, ok := err.(aws.APIError); ok && r53err.Code == "NoSuchHostedZone" {
d.SetId("")
return nil
}
return err
}

for _, vpc := range zone.VPCs {
if vpc_id == *vpc.VPCID {
// association is there, return
return nil
}
}

// no association found
d.SetId("")
return nil
}

func resourceAwsRoute53ZoneAssociationUpdate(d *schema.ResourceData, meta interface{}) error {
return resourceAwsRoute53ZoneAssociationRead(d, meta)
}

func resourceAwsRoute53ZoneAssociationDelete(d *schema.ResourceData, meta interface{}) error {
r53 := meta.(*AWSClient).r53conn
zone_id, vpc_id := resourceAwsRoute53ZoneAssociationParseId(d.Id())
log.Printf("[DEBUG] Deleting Route53 Private Zone (%s) association (VPC: %s)",
zone_id, vpc_id)

req := &route53.DisassociateVPCFromHostedZoneInput{
HostedZoneID: aws.String(zone_id),
VPC: &route53.VPC{
VPCID: aws.String(vpc_id),
VPCRegion: aws.String(d.Get("vpc_region").(string)),
},
Comment: aws.String("Managed by Terraform"),
}

_, err := r53.DisassociateVPCFromHostedZone(req)
if err != nil {
return err
}

return nil
}

func resourceAwsRoute53ZoneAssociationParseId(id string) (zone_id, vpc_id string) {
parts := strings.SplitN(id, ":", 2)
zone_id = parts[0]
vpc_id = parts[1]
return
}
Loading

0 comments on commit b3a4965

Please sign in to comment.