github.com/armen/terraform@v0.5.2-0.20150529052519-caa8117a08f1/builtin/providers/aws/resource_aws_vpn_gateway.go (about) 1 package aws 2 3 import ( 4 "fmt" 5 "log" 6 "time" 7 8 "github.com/awslabs/aws-sdk-go/aws" 9 "github.com/awslabs/aws-sdk-go/aws/awserr" 10 "github.com/awslabs/aws-sdk-go/service/ec2" 11 "github.com/hashicorp/terraform/helper/resource" 12 "github.com/hashicorp/terraform/helper/schema" 13 ) 14 15 func resourceAwsVpnGateway() *schema.Resource { 16 return &schema.Resource{ 17 Create: resourceAwsVpnGatewayCreate, 18 Read: resourceAwsVpnGatewayRead, 19 Update: resourceAwsVpnGatewayUpdate, 20 Delete: resourceAwsVpnGatewayDelete, 21 22 Schema: map[string]*schema.Schema{ 23 "availability_zone": &schema.Schema{ 24 Type: schema.TypeString, 25 Optional: true, 26 ForceNew: true, 27 }, 28 29 "vpc_id": &schema.Schema{ 30 Type: schema.TypeString, 31 Optional: true, 32 }, 33 34 "tags": tagsSchema(), 35 }, 36 } 37 } 38 39 func resourceAwsVpnGatewayCreate(d *schema.ResourceData, meta interface{}) error { 40 conn := meta.(*AWSClient).ec2conn 41 42 createOpts := &ec2.CreateVPNGatewayInput{ 43 AvailabilityZone: aws.String(d.Get("availability_zone").(string)), 44 Type: aws.String("ipsec.1"), 45 } 46 47 // Create the VPN gateway 48 log.Printf("[DEBUG] Creating VPN gateway") 49 resp, err := conn.CreateVPNGateway(createOpts) 50 if err != nil { 51 return fmt.Errorf("Error creating VPN gateway: %s", err) 52 } 53 54 // Get the ID and store it 55 vpnGateway := resp.VPNGateway 56 d.SetId(*vpnGateway.VPNGatewayID) 57 log.Printf("[INFO] VPN Gateway ID: %s", *vpnGateway.VPNGatewayID) 58 59 // Attach the VPN gateway to the correct VPC 60 return resourceAwsVpnGatewayUpdate(d, meta) 61 } 62 63 func resourceAwsVpnGatewayRead(d *schema.ResourceData, meta interface{}) error { 64 conn := meta.(*AWSClient).ec2conn 65 66 resp, err := conn.DescribeVPNGateways(&ec2.DescribeVPNGatewaysInput{ 67 VPNGatewayIDs: []*string{aws.String(d.Id())}, 68 }) 69 if err != nil { 70 if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "InvalidVpnGatewayID.NotFound" { 71 d.SetId("") 72 return nil 73 } else { 74 log.Printf("[ERROR] Error finding VpnGateway: %s", err) 75 return err 76 } 77 } 78 79 vpnGateway := resp.VPNGateways[0] 80 if vpnGateway == nil { 81 // Seems we have lost our VPN gateway 82 d.SetId("") 83 return nil 84 } 85 86 if len(vpnGateway.VPCAttachments) == 0 { 87 // Gateway exists but not attached to the VPC 88 d.Set("vpc_id", "") 89 } else { 90 d.Set("vpc_id", vpnGateway.VPCAttachments[0].VPCID) 91 } 92 d.Set("availability_zone", vpnGateway.AvailabilityZone) 93 d.Set("tags", tagsToMap(vpnGateway.Tags)) 94 95 return nil 96 } 97 98 func resourceAwsVpnGatewayUpdate(d *schema.ResourceData, meta interface{}) error { 99 if d.HasChange("vpc_id") { 100 // If we're already attached, detach it first 101 if err := resourceAwsVpnGatewayDetach(d, meta); err != nil { 102 return err 103 } 104 105 // Attach the VPN gateway to the new vpc 106 if err := resourceAwsVpnGatewayAttach(d, meta); err != nil { 107 return err 108 } 109 } 110 111 conn := meta.(*AWSClient).ec2conn 112 113 if err := setTags(conn, d); err != nil { 114 return err 115 } 116 117 d.SetPartial("tags") 118 119 return resourceAwsVpnGatewayRead(d, meta) 120 } 121 122 func resourceAwsVpnGatewayDelete(d *schema.ResourceData, meta interface{}) error { 123 conn := meta.(*AWSClient).ec2conn 124 125 // Detach if it is attached 126 if err := resourceAwsVpnGatewayDetach(d, meta); err != nil { 127 return err 128 } 129 130 log.Printf("[INFO] Deleting VPN gateway: %s", d.Id()) 131 132 return resource.Retry(5*time.Minute, func() error { 133 _, err := conn.DeleteVPNGateway(&ec2.DeleteVPNGatewayInput{ 134 VPNGatewayID: aws.String(d.Id()), 135 }) 136 if err == nil { 137 return nil 138 } 139 140 ec2err, ok := err.(awserr.Error) 141 if !ok { 142 return err 143 } 144 145 switch ec2err.Code() { 146 case "InvalidVpnGatewayID.NotFound": 147 return nil 148 case "IncorrectState": 149 return err // retry 150 } 151 152 return resource.RetryError{Err: err} 153 }) 154 } 155 156 func resourceAwsVpnGatewayAttach(d *schema.ResourceData, meta interface{}) error { 157 conn := meta.(*AWSClient).ec2conn 158 159 if d.Get("vpc_id").(string) == "" { 160 log.Printf( 161 "[DEBUG] Not attaching VPN Gateway '%s' as no VPC ID is set", 162 d.Id()) 163 return nil 164 } 165 166 log.Printf( 167 "[INFO] Attaching VPN Gateway '%s' to VPC '%s'", 168 d.Id(), 169 d.Get("vpc_id").(string)) 170 171 _, err := conn.AttachVPNGateway(&ec2.AttachVPNGatewayInput{ 172 VPNGatewayID: aws.String(d.Id()), 173 VPCID: aws.String(d.Get("vpc_id").(string)), 174 }) 175 if err != nil { 176 return err 177 } 178 179 // A note on the states below: the AWS docs (as of July, 2014) say 180 // that the states would be: attached, attaching, detached, detaching, 181 // but when running, I noticed that the state is usually "available" when 182 // it is attached. 183 184 // Wait for it to be fully attached before continuing 185 log.Printf("[DEBUG] Waiting for VPN gateway (%s) to attach", d.Id()) 186 stateConf := &resource.StateChangeConf{ 187 Pending: []string{"detached", "attaching"}, 188 Target: "available", 189 Refresh: vpnGatewayAttachStateRefreshFunc(conn, d.Id(), "available"), 190 Timeout: 1 * time.Minute, 191 } 192 if _, err := stateConf.WaitForState(); err != nil { 193 return fmt.Errorf( 194 "Error waiting for VPN gateway (%s) to attach: %s", 195 d.Id(), err) 196 } 197 198 return nil 199 } 200 201 func resourceAwsVpnGatewayDetach(d *schema.ResourceData, meta interface{}) error { 202 conn := meta.(*AWSClient).ec2conn 203 204 // Get the old VPC ID to detach from 205 vpcID, _ := d.GetChange("vpc_id") 206 207 if vpcID.(string) == "" { 208 log.Printf( 209 "[DEBUG] Not detaching VPN Gateway '%s' as no VPC ID is set", 210 d.Id()) 211 return nil 212 } 213 214 log.Printf( 215 "[INFO] Detaching VPN Gateway '%s' from VPC '%s'", 216 d.Id(), 217 vpcID.(string)) 218 219 wait := true 220 _, err := conn.DetachVPNGateway(&ec2.DetachVPNGatewayInput{ 221 VPNGatewayID: aws.String(d.Id()), 222 VPCID: aws.String(vpcID.(string)), 223 }) 224 if err != nil { 225 ec2err, ok := err.(awserr.Error) 226 if ok { 227 if ec2err.Code() == "InvalidVpnGatewayID.NotFound" { 228 err = nil 229 wait = false 230 } else if ec2err.Code() == "InvalidVpnGatewayAttachment.NotFound" { 231 err = nil 232 wait = false 233 } 234 } 235 236 if err != nil { 237 return err 238 } 239 } 240 241 if !wait { 242 return nil 243 } 244 245 // Wait for it to be fully detached before continuing 246 log.Printf("[DEBUG] Waiting for VPN gateway (%s) to detach", d.Id()) 247 stateConf := &resource.StateChangeConf{ 248 Pending: []string{"attached", "detaching", "available"}, 249 Target: "detached", 250 Refresh: vpnGatewayAttachStateRefreshFunc(conn, d.Id(), "detached"), 251 Timeout: 1 * time.Minute, 252 } 253 if _, err := stateConf.WaitForState(); err != nil { 254 return fmt.Errorf( 255 "Error waiting for vpn gateway (%s) to detach: %s", 256 d.Id(), err) 257 } 258 259 return nil 260 } 261 262 // vpnGatewayAttachStateRefreshFunc returns a resource.StateRefreshFunc that is used to watch 263 // the state of a VPN gateway's attachment 264 func vpnGatewayAttachStateRefreshFunc(conn *ec2.EC2, id string, expected string) resource.StateRefreshFunc { 265 var start time.Time 266 return func() (interface{}, string, error) { 267 if start.IsZero() { 268 start = time.Now() 269 } 270 271 resp, err := conn.DescribeVPNGateways(&ec2.DescribeVPNGatewaysInput{ 272 VPNGatewayIDs: []*string{aws.String(id)}, 273 }) 274 if err != nil { 275 if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "InvalidVpnGatewayID.NotFound" { 276 resp = nil 277 } else { 278 log.Printf("[ERROR] Error on VpnGatewayStateRefresh: %s", err) 279 return nil, "", err 280 } 281 } 282 283 if resp == nil { 284 // Sometimes AWS just has consistency issues and doesn't see 285 // our instance yet. Return an empty state. 286 return nil, "", nil 287 } 288 289 vpnGateway := resp.VPNGateways[0] 290 291 if time.Now().Sub(start) > 10*time.Second { 292 return vpnGateway, expected, nil 293 } 294 295 if len(vpnGateway.VPCAttachments) == 0 { 296 // No attachments, we're detached 297 return vpnGateway, "detached", nil 298 } 299 300 return vpnGateway, *vpnGateway.VPCAttachments[0].State, nil 301 } 302 }