github.com/chalford/terraform@v0.3.7-0.20150113080010-a78c69a8c81f/builtin/providers/aws/resource_aws_subnet.go (about)

     1  package aws
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"time"
     7  
     8  	"github.com/hashicorp/terraform/helper/resource"
     9  	"github.com/hashicorp/terraform/helper/schema"
    10  	"github.com/mitchellh/goamz/ec2"
    11  )
    12  
    13  func resourceAwsSubnet() *schema.Resource {
    14  	return &schema.Resource{
    15  		Create: resourceAwsSubnetCreate,
    16  		Read:   resourceAwsSubnetRead,
    17  		Update: resourceAwsSubnetUpdate,
    18  		Delete: resourceAwsSubnetDelete,
    19  
    20  		Schema: map[string]*schema.Schema{
    21  			"vpc_id": &schema.Schema{
    22  				Type:     schema.TypeString,
    23  				Optional: true,
    24  				ForceNew: true,
    25  				Computed: true,
    26  			},
    27  
    28  			"cidr_block": &schema.Schema{
    29  				Type:     schema.TypeString,
    30  				Required: true,
    31  				ForceNew: true,
    32  			},
    33  
    34  			"availability_zone": &schema.Schema{
    35  				Type:     schema.TypeString,
    36  				Optional: true,
    37  				Computed: true,
    38  				ForceNew: true,
    39  			},
    40  
    41  			"map_public_ip_on_launch": &schema.Schema{
    42  				Type:     schema.TypeBool,
    43  				Optional: true,
    44  			},
    45  
    46  			"tags": tagsSchema(),
    47  		},
    48  	}
    49  }
    50  
    51  func resourceAwsSubnetCreate(d *schema.ResourceData, meta interface{}) error {
    52  	ec2conn := meta.(*AWSClient).ec2conn
    53  
    54  	createOpts := &ec2.CreateSubnet{
    55  		AvailabilityZone: d.Get("availability_zone").(string),
    56  		CidrBlock:        d.Get("cidr_block").(string),
    57  		VpcId:            d.Get("vpc_id").(string),
    58  	}
    59  
    60  	resp, err := ec2conn.CreateSubnet(createOpts)
    61  
    62  	if err != nil {
    63  		return fmt.Errorf("Error creating subnet: %s", err)
    64  	}
    65  
    66  	// Get the ID and store it
    67  	subnet := &resp.Subnet
    68  	d.SetId(subnet.SubnetId)
    69  	log.Printf("[INFO] Subnet ID: %s", subnet.SubnetId)
    70  
    71  	// Wait for the Subnet to become available
    72  	log.Printf("[DEBUG] Waiting for subnet (%s) to become available", subnet.SubnetId)
    73  	stateConf := &resource.StateChangeConf{
    74  		Pending: []string{"pending"},
    75  		Target:  "available",
    76  		Refresh: SubnetStateRefreshFunc(ec2conn, subnet.SubnetId),
    77  		Timeout: 10 * time.Minute,
    78  	}
    79  
    80  	_, err = stateConf.WaitForState()
    81  
    82  	if err != nil {
    83  		return fmt.Errorf(
    84  			"Error waiting for subnet (%s) to become ready: %s",
    85  			d.Id(), err)
    86  	}
    87  
    88  	return resourceAwsSubnetUpdate(d, meta)
    89  }
    90  
    91  func resourceAwsSubnetRead(d *schema.ResourceData, meta interface{}) error {
    92  	ec2conn := meta.(*AWSClient).ec2conn
    93  
    94  	resp, err := ec2conn.DescribeSubnets([]string{d.Id()}, ec2.NewFilter())
    95  
    96  	if err != nil {
    97  		return err
    98  	}
    99  	if resp == nil {
   100  		return nil
   101  	}
   102  
   103  	subnet := &resp.Subnets[0]
   104  
   105  	d.Set("vpc_id", subnet.VpcId)
   106  	d.Set("availability_zone", subnet.AvailabilityZone)
   107  	d.Set("cidr_block", subnet.CidrBlock)
   108  	d.Set("map_public_ip_on_launch", subnet.MapPublicIpOnLaunch)
   109  	d.Set("tags", tagsToMap(subnet.Tags))
   110  
   111  	return nil
   112  }
   113  
   114  func resourceAwsSubnetUpdate(d *schema.ResourceData, meta interface{}) error {
   115  	ec2conn := meta.(*AWSClient).ec2conn
   116  
   117  	d.Partial(true)
   118  
   119  	if err := setTags(ec2conn, d); err != nil {
   120  		return err
   121  	} else {
   122  		d.SetPartial("tags")
   123  	}
   124  
   125  	if d.HasChange("map_public_ip_on_launch") {
   126  		modifyOpts := &ec2.ModifySubnetAttribute{
   127  			SubnetId:            d.Id(),
   128  			MapPublicIpOnLaunch: true,
   129  		}
   130  
   131  		log.Printf("[DEBUG] Subnet modify attributes: %#v", modifyOpts)
   132  
   133  		_, err := ec2conn.ModifySubnetAttribute(modifyOpts)
   134  
   135  		if err != nil {
   136  			return err
   137  		} else {
   138  			d.SetPartial("map_public_ip_on_launch")
   139  		}
   140  	}
   141  
   142  	d.Partial(false)
   143  
   144  	return resourceAwsSubnetRead(d, meta)
   145  }
   146  
   147  func resourceAwsSubnetDelete(d *schema.ResourceData, meta interface{}) error {
   148  	ec2conn := meta.(*AWSClient).ec2conn
   149  
   150  	log.Printf("[INFO] Deleting subnet: %s", d.Id())
   151  	if _, err := ec2conn.DeleteSubnet(d.Id()); err != nil {
   152  		ec2err, ok := err.(*ec2.Error)
   153  		if ok && ec2err.Code == "InvalidSubnetID.NotFound" {
   154  			return nil
   155  		}
   156  
   157  		return fmt.Errorf("Error deleting subnet: %s", err)
   158  	}
   159  
   160  	return nil
   161  }
   162  
   163  // SubnetStateRefreshFunc returns a resource.StateRefreshFunc that is used to watch a Subnet.
   164  func SubnetStateRefreshFunc(conn *ec2.EC2, id string) resource.StateRefreshFunc {
   165  	return func() (interface{}, string, error) {
   166  		resp, err := conn.DescribeSubnets([]string{id}, ec2.NewFilter())
   167  		if err != nil {
   168  			if ec2err, ok := err.(*ec2.Error); ok && ec2err.Code == "InvalidSubnetID.NotFound" {
   169  				resp = nil
   170  			} else {
   171  				log.Printf("Error on SubnetStateRefresh: %s", err)
   172  				return nil, "", err
   173  			}
   174  		}
   175  
   176  		if resp == nil {
   177  			// Sometimes AWS just has consistency issues and doesn't see
   178  			// our instance yet. Return an empty state.
   179  			return nil, "", nil
   180  		}
   181  
   182  		subnet := &resp.Subnets[0]
   183  		return subnet, subnet.State, nil
   184  	}
   185  }