github.com/i0n/terraform@v0.4.3-0.20150506151324-010a39a58ec1/builtin/providers/aws/resource_aws_route_table.go (about)

     1  package aws
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  	"log"
     7  	"time"
     8  
     9  	"github.com/awslabs/aws-sdk-go/aws"
    10  	"github.com/awslabs/aws-sdk-go/service/ec2"
    11  	"github.com/hashicorp/terraform/helper/hashcode"
    12  	"github.com/hashicorp/terraform/helper/resource"
    13  	"github.com/hashicorp/terraform/helper/schema"
    14  )
    15  
    16  func resourceAwsRouteTable() *schema.Resource {
    17  	return &schema.Resource{
    18  		Create: resourceAwsRouteTableCreate,
    19  		Read:   resourceAwsRouteTableRead,
    20  		Update: resourceAwsRouteTableUpdate,
    21  		Delete: resourceAwsRouteTableDelete,
    22  
    23  		Schema: map[string]*schema.Schema{
    24  			"vpc_id": &schema.Schema{
    25  				Type:     schema.TypeString,
    26  				Required: true,
    27  				ForceNew: true,
    28  			},
    29  
    30  			"tags": tagsSchema(),
    31  
    32  			"propagating_vgws": &schema.Schema{
    33  				Type:     schema.TypeSet,
    34  				Optional: true,
    35  				Elem:     &schema.Schema{Type: schema.TypeString},
    36  				Set: func(v interface{}) int {
    37  					return hashcode.String(v.(string))
    38  				},
    39  			},
    40  
    41  			"route": &schema.Schema{
    42  				Type:     schema.TypeSet,
    43  				Optional: true,
    44  				Elem: &schema.Resource{
    45  					Schema: map[string]*schema.Schema{
    46  						"cidr_block": &schema.Schema{
    47  							Type:     schema.TypeString,
    48  							Required: true,
    49  						},
    50  
    51  						"gateway_id": &schema.Schema{
    52  							Type:     schema.TypeString,
    53  							Optional: true,
    54  						},
    55  
    56  						"instance_id": &schema.Schema{
    57  							Type:     schema.TypeString,
    58  							Optional: true,
    59  						},
    60  
    61  						"vpc_peering_connection_id": &schema.Schema{
    62  							Type:     schema.TypeString,
    63  							Optional: true,
    64  						},
    65  
    66  						"network_interface_id": &schema.Schema{
    67  							Type:     schema.TypeString,
    68  							Optional: true,
    69  						},
    70  					},
    71  				},
    72  				Set: resourceAwsRouteTableHash,
    73  			},
    74  		},
    75  	}
    76  }
    77  
    78  func resourceAwsRouteTableCreate(d *schema.ResourceData, meta interface{}) error {
    79  	conn := meta.(*AWSClient).ec2conn
    80  
    81  	// Create the routing table
    82  	createOpts := &ec2.CreateRouteTableInput{
    83  		VPCID: aws.String(d.Get("vpc_id").(string)),
    84  	}
    85  	log.Printf("[DEBUG] RouteTable create config: %#v", createOpts)
    86  
    87  	resp, err := conn.CreateRouteTable(createOpts)
    88  	if err != nil {
    89  		return fmt.Errorf("Error creating route table: %s", err)
    90  	}
    91  
    92  	// Get the ID and store it
    93  	rt := resp.RouteTable
    94  	d.SetId(*rt.RouteTableID)
    95  	log.Printf("[INFO] Route Table ID: %s", d.Id())
    96  
    97  	// Wait for the route table to become available
    98  	log.Printf(
    99  		"[DEBUG] Waiting for route table (%s) to become available",
   100  		d.Id())
   101  	stateConf := &resource.StateChangeConf{
   102  		Pending: []string{"pending"},
   103  		Target:  "ready",
   104  		Refresh: resourceAwsRouteTableStateRefreshFunc(conn, d.Id()),
   105  		Timeout: 1 * time.Minute,
   106  	}
   107  	if _, err := stateConf.WaitForState(); err != nil {
   108  		return fmt.Errorf(
   109  			"Error waiting for route table (%s) to become available: %s",
   110  			d.Id(), err)
   111  	}
   112  
   113  	return resourceAwsRouteTableUpdate(d, meta)
   114  }
   115  
   116  func resourceAwsRouteTableRead(d *schema.ResourceData, meta interface{}) error {
   117  	conn := meta.(*AWSClient).ec2conn
   118  
   119  	rtRaw, _, err := resourceAwsRouteTableStateRefreshFunc(conn, d.Id())()
   120  	if err != nil {
   121  		return err
   122  	}
   123  	if rtRaw == nil {
   124  		d.SetId("")
   125  		return nil
   126  	}
   127  
   128  	rt := rtRaw.(*ec2.RouteTable)
   129  	d.Set("vpc_id", rt.VPCID)
   130  
   131  	propagatingVGWs := make([]string, 0, len(rt.PropagatingVGWs))
   132  	for _, vgw := range rt.PropagatingVGWs {
   133  		propagatingVGWs = append(propagatingVGWs, *vgw.GatewayID)
   134  	}
   135  	d.Set("propagating_vgws", propagatingVGWs)
   136  
   137  	// Create an empty schema.Set to hold all routes
   138  	route := &schema.Set{F: resourceAwsRouteTableHash}
   139  
   140  	// Loop through the routes and add them to the set
   141  	for _, r := range rt.Routes {
   142  		if r.GatewayID != nil && *r.GatewayID == "local" {
   143  			continue
   144  		}
   145  
   146  		if r.Origin != nil && *r.Origin == "EnableVgwRoutePropagation" {
   147  			continue
   148  		}
   149  
   150  		m := make(map[string]interface{})
   151  
   152  		if r.DestinationCIDRBlock != nil {
   153  			m["cidr_block"] = *r.DestinationCIDRBlock
   154  		}
   155  		if r.GatewayID != nil {
   156  			m["gateway_id"] = *r.GatewayID
   157  		}
   158  		if r.InstanceID != nil {
   159  			m["instance_id"] = *r.InstanceID
   160  		}
   161  		if r.VPCPeeringConnectionID != nil {
   162  			m["vpc_peering_connection_id"] = *r.VPCPeeringConnectionID
   163  		}
   164  		if r.NetworkInterfaceID != nil {
   165  			m["network_interface_id"] = *r.NetworkInterfaceID
   166  		}
   167  
   168  		route.Add(m)
   169  	}
   170  	d.Set("route", route)
   171  
   172  	// Tags
   173  	d.Set("tags", tagsToMapSDK(rt.Tags))
   174  
   175  	return nil
   176  }
   177  
   178  func resourceAwsRouteTableUpdate(d *schema.ResourceData, meta interface{}) error {
   179  	conn := meta.(*AWSClient).ec2conn
   180  
   181  	if d.HasChange("propagating_vgws") {
   182  		o, n := d.GetChange("propagating_vgws")
   183  		os := o.(*schema.Set)
   184  		ns := n.(*schema.Set)
   185  		remove := os.Difference(ns).List()
   186  		add := ns.Difference(os).List()
   187  
   188  		// Now first loop through all the old propagations and disable any obsolete ones
   189  		for _, vgw := range remove {
   190  			id := vgw.(string)
   191  
   192  			// Disable the propagation as it no longer exists in the config
   193  			log.Printf(
   194  				"[INFO] Deleting VGW propagation from %s: %s",
   195  				d.Id(), id)
   196  			_, err := conn.DisableVGWRoutePropagation(&ec2.DisableVGWRoutePropagationInput{
   197  				RouteTableID: aws.String(d.Id()),
   198  				GatewayID:    aws.String(id),
   199  			})
   200  			if err != nil {
   201  				return err
   202  			}
   203  		}
   204  
   205  		// Make sure we save the state of the currently configured rules
   206  		propagatingVGWs := os.Intersection(ns)
   207  		d.Set("propagating_vgws", propagatingVGWs)
   208  
   209  		// Then loop through all the newly configured propagations and enable them
   210  		for _, vgw := range add {
   211  			id := vgw.(string)
   212  
   213  			log.Printf("[INFO] Enabling VGW propagation for %s: %s", d.Id(), id)
   214  			_, err := conn.EnableVGWRoutePropagation(&ec2.EnableVGWRoutePropagationInput{
   215  				RouteTableID: aws.String(d.Id()),
   216  				GatewayID:    aws.String(id),
   217  			})
   218  			if err != nil {
   219  				return err
   220  			}
   221  
   222  			propagatingVGWs.Add(vgw)
   223  			d.Set("propagating_vgws", propagatingVGWs)
   224  		}
   225  	}
   226  
   227  	// Check if the route set as a whole has changed
   228  	if d.HasChange("route") {
   229  		o, n := d.GetChange("route")
   230  		ors := o.(*schema.Set).Difference(n.(*schema.Set))
   231  		nrs := n.(*schema.Set).Difference(o.(*schema.Set))
   232  
   233  		// Now first loop through all the old routes and delete any obsolete ones
   234  		for _, route := range ors.List() {
   235  			m := route.(map[string]interface{})
   236  
   237  			// Delete the route as it no longer exists in the config
   238  			log.Printf(
   239  				"[INFO] Deleting route from %s: %s",
   240  				d.Id(), m["cidr_block"].(string))
   241  			_, err := conn.DeleteRoute(&ec2.DeleteRouteInput{
   242  				RouteTableID:         aws.String(d.Id()),
   243  				DestinationCIDRBlock: aws.String(m["cidr_block"].(string)),
   244  			})
   245  			if err != nil {
   246  				return err
   247  			}
   248  		}
   249  
   250  		// Make sure we save the state of the currently configured rules
   251  		routes := o.(*schema.Set).Intersection(n.(*schema.Set))
   252  		d.Set("route", routes)
   253  
   254  		// Then loop through all the newly configured routes and create them
   255  		for _, route := range nrs.List() {
   256  			m := route.(map[string]interface{})
   257  
   258  			opts := ec2.CreateRouteInput{
   259  				RouteTableID:           aws.String(d.Id()),
   260  				DestinationCIDRBlock:   aws.String(m["cidr_block"].(string)),
   261  				GatewayID:              aws.String(m["gateway_id"].(string)),
   262  				InstanceID:             aws.String(m["instance_id"].(string)),
   263  				VPCPeeringConnectionID: aws.String(m["vpc_peering_connection_id"].(string)),
   264  				NetworkInterfaceID:     aws.String(m["network_interface_id"].(string)),
   265  			}
   266  
   267  			log.Printf("[INFO] Creating route for %s: %#v", d.Id(), opts)
   268  			if _, err := conn.CreateRoute(&opts); err != nil {
   269  				return err
   270  			}
   271  
   272  			routes.Add(route)
   273  			d.Set("route", routes)
   274  		}
   275  	}
   276  
   277  	if err := setTagsSDK(conn, d); err != nil {
   278  		return err
   279  	} else {
   280  		d.SetPartial("tags")
   281  	}
   282  
   283  	return resourceAwsRouteTableRead(d, meta)
   284  }
   285  
   286  func resourceAwsRouteTableDelete(d *schema.ResourceData, meta interface{}) error {
   287  	conn := meta.(*AWSClient).ec2conn
   288  
   289  	// First request the routing table since we'll have to disassociate
   290  	// all the subnets first.
   291  	rtRaw, _, err := resourceAwsRouteTableStateRefreshFunc(conn, d.Id())()
   292  	if err != nil {
   293  		return err
   294  	}
   295  	if rtRaw == nil {
   296  		return nil
   297  	}
   298  	rt := rtRaw.(*ec2.RouteTable)
   299  
   300  	// Do all the disassociations
   301  	for _, a := range rt.Associations {
   302  		log.Printf("[INFO] Disassociating association: %s", *a.RouteTableAssociationID)
   303  		_, err := conn.DisassociateRouteTable(&ec2.DisassociateRouteTableInput{
   304  			AssociationID: a.RouteTableAssociationID,
   305  		})
   306  		if err != nil {
   307  			return err
   308  		}
   309  	}
   310  
   311  	// Delete the route table
   312  	log.Printf("[INFO] Deleting Route Table: %s", d.Id())
   313  	_, err = conn.DeleteRouteTable(&ec2.DeleteRouteTableInput{
   314  		RouteTableID: aws.String(d.Id()),
   315  	})
   316  	if err != nil {
   317  		ec2err, ok := err.(aws.APIError)
   318  		if ok && ec2err.Code == "InvalidRouteTableID.NotFound" {
   319  			return nil
   320  		}
   321  
   322  		return fmt.Errorf("Error deleting route table: %s", err)
   323  	}
   324  
   325  	// Wait for the route table to really destroy
   326  	log.Printf(
   327  		"[DEBUG] Waiting for route table (%s) to become destroyed",
   328  		d.Id())
   329  
   330  	stateConf := &resource.StateChangeConf{
   331  		Pending: []string{"ready"},
   332  		Target:  "",
   333  		Refresh: resourceAwsRouteTableStateRefreshFunc(conn, d.Id()),
   334  		Timeout: 1 * time.Minute,
   335  	}
   336  	if _, err := stateConf.WaitForState(); err != nil {
   337  		return fmt.Errorf(
   338  			"Error waiting for route table (%s) to become destroyed: %s",
   339  			d.Id(), err)
   340  	}
   341  
   342  	return nil
   343  }
   344  
   345  func resourceAwsRouteTableHash(v interface{}) int {
   346  	var buf bytes.Buffer
   347  	m := v.(map[string]interface{})
   348  	buf.WriteString(fmt.Sprintf("%s-", m["cidr_block"].(string)))
   349  
   350  	if v, ok := m["gateway_id"]; ok {
   351  		buf.WriteString(fmt.Sprintf("%s-", v.(string)))
   352  	}
   353  
   354  	if v, ok := m["instance_id"]; ok {
   355  		buf.WriteString(fmt.Sprintf("%s-", v.(string)))
   356  	}
   357  
   358  	if v, ok := m["vpc_peering_connection_id"]; ok {
   359  		buf.WriteString(fmt.Sprintf("%s-", v.(string)))
   360  	}
   361  
   362  	if v, ok := m["network_interface_id"]; ok {
   363  		buf.WriteString(fmt.Sprintf("%s-", v.(string)))
   364  	}
   365  
   366  	return hashcode.String(buf.String())
   367  }
   368  
   369  // resourceAwsRouteTableStateRefreshFunc returns a resource.StateRefreshFunc that is used to watch
   370  // a RouteTable.
   371  func resourceAwsRouteTableStateRefreshFunc(conn *ec2.EC2, id string) resource.StateRefreshFunc {
   372  	return func() (interface{}, string, error) {
   373  		resp, err := conn.DescribeRouteTables(&ec2.DescribeRouteTablesInput{
   374  			RouteTableIDs: []*string{aws.String(id)},
   375  		})
   376  		if err != nil {
   377  			if ec2err, ok := err.(aws.APIError); ok && ec2err.Code == "InvalidRouteTableID.NotFound" {
   378  				resp = nil
   379  			} else {
   380  				log.Printf("Error on RouteTableStateRefresh: %s", err)
   381  				return nil, "", err
   382  			}
   383  		}
   384  
   385  		if resp == nil {
   386  			// Sometimes AWS just has consistency issues and doesn't see
   387  			// our instance yet. Return an empty state.
   388  			return nil, "", nil
   389  		}
   390  
   391  		rt := resp.RouteTables[0]
   392  		return rt, "ready", nil
   393  	}
   394  }