github.com/minamijoyo/terraform@v0.7.8-0.20161029001309-18b3736ba44b/builtin/providers/aws/resource_aws_vpc_endpoint.go (about)

     1  package aws
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  
     7  	"github.com/aws/aws-sdk-go/aws"
     8  	"github.com/aws/aws-sdk-go/aws/awserr"
     9  	"github.com/aws/aws-sdk-go/service/ec2"
    10  	"github.com/hashicorp/errwrap"
    11  	"github.com/hashicorp/terraform/helper/schema"
    12  )
    13  
    14  func resourceAwsVpcEndpoint() *schema.Resource {
    15  	return &schema.Resource{
    16  		Create: resourceAwsVPCEndpointCreate,
    17  		Read:   resourceAwsVPCEndpointRead,
    18  		Update: resourceAwsVPCEndpointUpdate,
    19  		Delete: resourceAwsVPCEndpointDelete,
    20  		Importer: &schema.ResourceImporter{
    21  			State: schema.ImportStatePassthrough,
    22  		},
    23  
    24  		Schema: map[string]*schema.Schema{
    25  			"policy": &schema.Schema{
    26  				Type:         schema.TypeString,
    27  				Optional:     true,
    28  				Computed:     true,
    29  				ValidateFunc: validateJsonString,
    30  				StateFunc: func(v interface{}) string {
    31  					json, _ := normalizeJsonString(v)
    32  					return json
    33  				},
    34  			},
    35  			"vpc_id": &schema.Schema{
    36  				Type:     schema.TypeString,
    37  				Required: true,
    38  				ForceNew: true,
    39  			},
    40  			"service_name": &schema.Schema{
    41  				Type:     schema.TypeString,
    42  				Required: true,
    43  				ForceNew: true,
    44  			},
    45  			"route_table_ids": &schema.Schema{
    46  				Type:     schema.TypeSet,
    47  				Optional: true,
    48  				Elem:     &schema.Schema{Type: schema.TypeString},
    49  				Set:      schema.HashString,
    50  			},
    51  			"prefix_list_id": &schema.Schema{
    52  				Type:     schema.TypeString,
    53  				Computed: true,
    54  			},
    55  		},
    56  	}
    57  }
    58  
    59  func resourceAwsVPCEndpointCreate(d *schema.ResourceData, meta interface{}) error {
    60  	conn := meta.(*AWSClient).ec2conn
    61  	input := &ec2.CreateVpcEndpointInput{
    62  		VpcId:       aws.String(d.Get("vpc_id").(string)),
    63  		ServiceName: aws.String(d.Get("service_name").(string)),
    64  	}
    65  
    66  	if v, ok := d.GetOk("route_table_ids"); ok {
    67  		list := v.(*schema.Set).List()
    68  		if len(list) > 0 {
    69  			input.RouteTableIds = expandStringList(list)
    70  		}
    71  	}
    72  
    73  	if v, ok := d.GetOk("policy"); ok {
    74  		policy, err := normalizeJsonString(v)
    75  		if err != nil {
    76  			return errwrap.Wrapf("policy contains an invalid JSON: {{err}}", err)
    77  		}
    78  		input.PolicyDocument = aws.String(policy)
    79  	}
    80  
    81  	log.Printf("[DEBUG] Creating VPC Endpoint: %#v", input)
    82  	output, err := conn.CreateVpcEndpoint(input)
    83  	if err != nil {
    84  		return fmt.Errorf("Error creating VPC Endpoint: %s", err)
    85  	}
    86  	log.Printf("[DEBUG] VPC Endpoint %q created.", *output.VpcEndpoint.VpcEndpointId)
    87  
    88  	d.SetId(*output.VpcEndpoint.VpcEndpointId)
    89  
    90  	return resourceAwsVPCEndpointRead(d, meta)
    91  }
    92  
    93  func resourceAwsVPCEndpointRead(d *schema.ResourceData, meta interface{}) error {
    94  	conn := meta.(*AWSClient).ec2conn
    95  	input := &ec2.DescribeVpcEndpointsInput{
    96  		VpcEndpointIds: []*string{aws.String(d.Id())},
    97  	}
    98  
    99  	log.Printf("[DEBUG] Reading VPC Endpoint: %q", d.Id())
   100  	output, err := conn.DescribeVpcEndpoints(input)
   101  
   102  	if err != nil {
   103  		ec2err, ok := err.(awserr.Error)
   104  		if !ok {
   105  			return fmt.Errorf("Error reading VPC Endpoint: %s", err.Error())
   106  		}
   107  
   108  		if ec2err.Code() == "InvalidVpcEndpointId.NotFound" {
   109  			log.Printf("[WARN] VPC Endpoint (%s) not found, removing from state", d.Id())
   110  			d.SetId("")
   111  			return nil
   112  		}
   113  
   114  		return fmt.Errorf("Error reading VPC Endpoint: %s", err.Error())
   115  	}
   116  
   117  	if len(output.VpcEndpoints) != 1 {
   118  		return fmt.Errorf("There's no unique VPC Endpoint, but %d endpoints: %#v",
   119  			len(output.VpcEndpoints), output.VpcEndpoints)
   120  	}
   121  
   122  	vpce := output.VpcEndpoints[0]
   123  
   124  	// A VPC Endpoint is associated with exactly one prefix list name (also called Service Name).
   125  	// The prefix list ID can be used in security groups, so retrieve it to support that capability.
   126  	prefixListServiceName := *vpce.ServiceName
   127  	prefixListInput := &ec2.DescribePrefixListsInput{
   128  		Filters: []*ec2.Filter{
   129  			{Name: aws.String("prefix-list-name"), Values: []*string{aws.String(prefixListServiceName)}},
   130  		},
   131  	}
   132  
   133  	log.Printf("[DEBUG] Reading VPC Endpoint prefix list: %s", prefixListServiceName)
   134  	prefixListsOutput, err := conn.DescribePrefixLists(prefixListInput)
   135  
   136  	if err != nil {
   137  		_, ok := err.(awserr.Error)
   138  		if !ok {
   139  			return fmt.Errorf("Error reading VPC Endpoint prefix list: %s", err.Error())
   140  		}
   141  	}
   142  
   143  	if len(prefixListsOutput.PrefixLists) != 1 {
   144  		return fmt.Errorf("There are multiple prefix lists associated with the service name '%s'. Unexpected", prefixListServiceName)
   145  	}
   146  
   147  	policy, err := normalizeJsonString(*vpce.PolicyDocument)
   148  	if err != nil {
   149  		return errwrap.Wrapf("policy contains an invalid JSON: {{err}}", err)
   150  	}
   151  
   152  	d.Set("vpc_id", vpce.VpcId)
   153  	d.Set("policy", policy)
   154  	d.Set("service_name", vpce.ServiceName)
   155  	if err := d.Set("route_table_ids", aws.StringValueSlice(vpce.RouteTableIds)); err != nil {
   156  		return err
   157  	}
   158  	d.Set("prefix_list_id", prefixListsOutput.PrefixLists[0].PrefixListId)
   159  
   160  	return nil
   161  }
   162  
   163  func resourceAwsVPCEndpointUpdate(d *schema.ResourceData, meta interface{}) error {
   164  	conn := meta.(*AWSClient).ec2conn
   165  	input := &ec2.ModifyVpcEndpointInput{
   166  		VpcEndpointId: aws.String(d.Id()),
   167  	}
   168  
   169  	if d.HasChange("route_table_ids") {
   170  		o, n := d.GetChange("route_table_ids")
   171  		os := o.(*schema.Set)
   172  		ns := n.(*schema.Set)
   173  
   174  		add := expandStringList(ns.Difference(os).List())
   175  		if len(add) > 0 {
   176  			input.AddRouteTableIds = add
   177  		}
   178  
   179  		remove := expandStringList(os.Difference(ns).List())
   180  		if len(remove) > 0 {
   181  			input.RemoveRouteTableIds = remove
   182  		}
   183  	}
   184  
   185  	if d.HasChange("policy") {
   186  		policy, err := normalizeJsonString(d.Get("policy"))
   187  		if err != nil {
   188  			return errwrap.Wrapf("policy contains an invalid JSON: {{err}}", err)
   189  		}
   190  		input.PolicyDocument = aws.String(policy)
   191  	}
   192  
   193  	log.Printf("[DEBUG] Updating VPC Endpoint: %#v", input)
   194  	_, err := conn.ModifyVpcEndpoint(input)
   195  	if err != nil {
   196  		return fmt.Errorf("Error updating VPC Endpoint: %s", err)
   197  	}
   198  	log.Printf("[DEBUG] VPC Endpoint %q updated", input.VpcEndpointId)
   199  
   200  	return resourceAwsVPCEndpointRead(d, meta)
   201  }
   202  
   203  func resourceAwsVPCEndpointDelete(d *schema.ResourceData, meta interface{}) error {
   204  	conn := meta.(*AWSClient).ec2conn
   205  	input := &ec2.DeleteVpcEndpointsInput{
   206  		VpcEndpointIds: []*string{aws.String(d.Id())},
   207  	}
   208  
   209  	log.Printf("[DEBUG] Deleting VPC Endpoint: %#v", input)
   210  	_, err := conn.DeleteVpcEndpoints(input)
   211  
   212  	if err != nil {
   213  		ec2err, ok := err.(awserr.Error)
   214  		if !ok {
   215  			return fmt.Errorf("Error deleting VPC Endpoint: %s", err.Error())
   216  		}
   217  
   218  		if ec2err.Code() == "InvalidVpcEndpointId.NotFound" {
   219  			log.Printf("[DEBUG] VPC Endpoint %q is already gone", d.Id())
   220  		} else {
   221  			return fmt.Errorf("Error deleting VPC Endpoint: %s", err.Error())
   222  		}
   223  	}
   224  
   225  	log.Printf("[DEBUG] VPC Endpoint %q deleted", d.Id())
   226  	d.SetId("")
   227  
   228  	return nil
   229  }