func resourceDigitalOceanFloatingIpUpdate(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*godo.Client)

	if d.HasChange("droplet_id") {
		if v, ok := d.GetOk("droplet_id"); ok {
			log.Printf("[INFO] Assigning the Floating IP %s to the Droplet %d", d.Id(), v.(int))
			action, _, err := client.FloatingIPActions.Assign(d.Id(), v.(int))
			if err != nil {
				return fmt.Errorf(
					"Error Assigning FloatingIP (%s) to the droplet: %s", d.Id(), err)
			}

			_, unassignedErr := waitForFloatingIPReady(d, "completed", []string{"new", "in-progress"}, "status", meta, action.ID)
			if unassignedErr != nil {
				return fmt.Errorf(
					"Error waiting for FloatingIP (%s) to be Assigned: %s", d.Id(), unassignedErr)
			}
		} else {
			log.Printf("[INFO] Unassigning the Floating IP %s", d.Id())
			action, _, err := client.FloatingIPActions.Unassign(d.Id())
			if err != nil {
				return fmt.Errorf(
					"Error Unassigning FloatingIP (%s): %s", d.Id(), err)
			}

			_, unassignedErr := waitForFloatingIPReady(d, "completed", []string{"new", "in-progress"}, "status", meta, action.ID)
			if unassignedErr != nil {
				return fmt.Errorf(
					"Error waiting for FloatingIP (%s) to be Unassigned: %s", d.Id(), unassignedErr)
			}
		}
	}

	return resourceDigitalOceanFloatingIpRead(d, meta)
}
func resourceDigitalOceanFloatingIpDelete(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*godo.Client)

	if _, ok := d.GetOk("droplet_id"); ok {
		log.Printf("[INFO] Unassigning the Floating IP from the Droplet")
		action, _, err := client.FloatingIPActions.Unassign(d.Id())
		if err != nil {
			return fmt.Errorf(
				"Error Unassigning FloatingIP (%s) from the droplet: %s", d.Id(), err)
		}

		_, unassignedErr := waitForFloatingIPReady(d, "completed", []string{"new", "in-progress"}, "status", meta, action.ID)
		if unassignedErr != nil {
			return fmt.Errorf(
				"Error waiting for FloatingIP (%s) to be unassigned: %s", d.Id(), unassignedErr)
		}
	}

	log.Printf("[INFO] Deleting FloatingIP: %s", d.Id())
	_, err := client.FloatingIPs.Delete(d.Id())
	if err != nil {
		return fmt.Errorf("Error deleting FloatingIP: %s", err)
	}

	d.SetId("")
	return nil
}
func resourceDigitalOceanFloatingIpCreate(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*godo.Client)

	log.Printf("[INFO] Create a FloatingIP In a Region")
	regionOpts := &godo.FloatingIPCreateRequest{
		Region: d.Get("region").(string),
	}

	log.Printf("[DEBUG] FloatingIP Create: %#v", regionOpts)
	floatingIp, _, err := client.FloatingIPs.Create(regionOpts)
	if err != nil {
		return fmt.Errorf("Error creating FloatingIP: %s", err)
	}

	d.SetId(floatingIp.IP)

	if v, ok := d.GetOk("droplet_id"); ok {

		log.Printf("[INFO] Assigning the Floating IP to the Droplet %d", v.(int))
		action, _, err := client.FloatingIPActions.Assign(d.Id(), v.(int))
		if err != nil {
			return fmt.Errorf(
				"Error Assigning FloatingIP (%s) to the droplet: %s", d.Id(), err)
		}

		_, unassignedErr := waitForFloatingIPReady(d, "completed", []string{"new", "in-progress"}, "status", meta, action.ID)
		if unassignedErr != nil {
			return fmt.Errorf(
				"Error waiting for FloatingIP (%s) to be Assigned: %s", d.Id(), unassignedErr)
		}
	}

	return resourceDigitalOceanFloatingIpRead(d, meta)
}
func checkVolumeConfig(d *schema.ResourceData) error {
	// Although a volume_id is required to attach a volume, in order to be able to report
	// the attached volumes of an instance, it must be "computed" and thus "optional".
	// This accounts for situations such as "boot from volume" as well as volumes being
	// attached to the instance outside of Terraform.
	if v := d.Get("volume"); v != nil {
		vols := v.(*schema.Set).List()
		if len(vols) > 0 {
			for _, v := range vols {
				va := v.(map[string]interface{})
				if va["volume_id"].(string) == "" {
					return fmt.Errorf("A volume_id must be specified when attaching volumes.")
				}
			}
		}
	}

	if vL, ok := d.GetOk("block_device"); ok {
		if len(vL.([]interface{})) > 1 {
			return fmt.Errorf("Can only specify one block device to boot from.")
		}
	}

	return nil
}
func getImageIDFromConfig(computeClient *gophercloud.ServiceClient, d *schema.ResourceData) (string, error) {
	// If block_device was used, an Image does not need to be specified.
	// If an Image was specified, ignore it
	if _, ok := d.GetOk("block_device"); ok {
		return "", nil
	}

	if imageId := d.Get("image_id").(string); imageId != "" {
		return imageId, nil
	} else {
		// try the OS_IMAGE_ID environment variable
		if v := os.Getenv("OS_IMAGE_ID"); v != "" {
			return v, nil
		}
	}

	imageName := d.Get("image_name").(string)
	if imageName == "" {
		// try the OS_IMAGE_NAME environment variable
		if v := os.Getenv("OS_IMAGE_NAME"); v != "" {
			imageName = v
		}
	}

	if imageName != "" {
		imageId, err := images.IDFromName(computeClient, imageName)
		if err != nil {
			return "", err
		}
		return imageId, nil
	}

	return "", fmt.Errorf("Neither a boot device, image ID, or image name were able to be determined.")
}
func setImageInformation(computeClient *gophercloud.ServiceClient, server *servers.Server, d *schema.ResourceData) error {
	// If block_device was used, an Image does not need to be specified.
	// If an Image was specified, ignore it
	if _, ok := d.GetOk("block_device"); ok {
		d.Set("image_id", "Attempt to boot from volume - no image supplied")
		return nil
	}

	imageId := server.Image["id"].(string)
	if imageId != "" {
		d.Set("image_id", imageId)
		if image, err := images.Get(computeClient, imageId).Extract(); err != nil {
			errCode, ok := err.(*gophercloud.UnexpectedResponseCodeError)
			if !ok {
				return err
			}
			if errCode.Actual == 404 {
				// If the image name can't be found, set the value to "Image not found".
				// The most likely scenario is that the image no longer exists in the Image Service
				// but the instance still has a record from when it existed.
				d.Set("image_name", "Image not found")
				return nil
			} else {
				return err
			}
		} else {
			d.Set("image_name", image.Name)
		}
	}

	return nil
}
func resourceAwsDirectoryServiceDirectoryUpdate(d *schema.ResourceData, meta interface{}) error {
	dsconn := meta.(*AWSClient).dsconn

	if d.HasChange("enable_sso") {
		d.SetPartial("enable_sso")
		var err error

		if v, ok := d.GetOk("enable_sso"); ok && v.(bool) {
			log.Printf("[DEBUG] Enabling SSO for DS directory %q", d.Id())
			_, err = dsconn.EnableSso(&directoryservice.EnableSsoInput{
				DirectoryId: aws.String(d.Id()),
			})
		} else {
			log.Printf("[DEBUG] Disabling SSO for DS directory %q", d.Id())
			_, err = dsconn.DisableSso(&directoryservice.DisableSsoInput{
				DirectoryId: aws.String(d.Id()),
			})
		}

		if err != nil {
			return err
		}
	}

	return resourceAwsDirectoryServiceDirectoryRead(d, meta)
}
func createActiveDirectoryService(dsconn *directoryservice.DirectoryService, d *schema.ResourceData) (directoryId string, err error) {
	input := directoryservice.CreateMicrosoftADInput{
		Name:     aws.String(d.Get("name").(string)),
		Password: aws.String(d.Get("password").(string)),
	}

	if v, ok := d.GetOk("description"); ok {
		input.Description = aws.String(v.(string))
	}
	if v, ok := d.GetOk("short_name"); ok {
		input.ShortName = aws.String(v.(string))
	}

	input.VpcSettings, err = buildVpcSettings(d)
	if err != nil {
		return "", err
	}

	log.Printf("[DEBUG] Creating Microsoft AD Directory Service: %s", input)
	out, err := dsconn.CreateMicrosoftAD(&input)
	if err != nil {
		return "", err
	}
	log.Printf("[DEBUG] Microsoft AD Directory Service created: %s", out)

	return *out.DirectoryId, nil
}
func resourceCloudStackLoadBalancerRuleRead(d *schema.ResourceData, meta interface{}) error {
	cs := meta.(*cloudstack.CloudStackClient)

	// Get the load balancer details
	lb, count, err := cs.LoadBalancer.GetLoadBalancerRuleByID(d.Id())
	if err != nil {
		if count == 0 {
			log.Printf("[DEBUG] Load balancer rule %s does no longer exist", d.Get("name").(string))
			d.SetId("")
			return nil
		}

		return err
	}

	d.Set("algorithm", lb.Algorithm)
	d.Set("public_port", lb.Publicport)
	d.Set("private_port", lb.Privateport)

	setValueOrID(d, "ipaddress", lb.Publicip, lb.Publicipid)

	// Only set network if user specified it to avoid spurious diffs
	if _, ok := d.GetOk("network"); ok {
		network, _, err := cs.Network.GetNetworkByID(lb.Networkid)
		if err != nil {
			return err
		}
		setValueOrID(d, "network", network.Name, lb.Networkid)
	}

	return nil
}
func resourceCloudStackVPCUpdate(d *schema.ResourceData, meta interface{}) error {
	cs := meta.(*cloudstack.CloudStackClient)

	// Check if the name or display text is changed
	if d.HasChange("name") || d.HasChange("display_text") {
		// Create a new parameter struct
		p := cs.VPC.NewUpdateVPCParams(d.Id())

		// Set the display text
		displaytext, ok := d.GetOk("display_text")
		if !ok {
			displaytext = d.Get("name")
		}
		// Set the (new) display text
		p.SetDisplaytext(displaytext.(string))

		// Update the VPC
		_, err := cs.VPC.UpdateVPC(p)
		if err != nil {
			return fmt.Errorf(
				"Error updating VPC %s: %s", d.Get("name").(string), err)
		}
	}

	return resourceCloudStackVPCRead(d, meta)
}
func resourceAWSEbsVolumeUpdate(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).ec2conn
	if _, ok := d.GetOk("tags"); ok {
		setTags(conn, d)
	}
	return resourceAwsEbsVolumeRead(d, meta)
}
func resourceAwsCloudWatchLogGroupUpdate(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).cloudwatchlogsconn

	name := d.Get("name").(string)
	log.Printf("[DEBUG] Updating CloudWatch Log Group: %q", name)

	if d.HasChange("retention_in_days") {
		var err error

		if v, ok := d.GetOk("retention_in_days"); ok {
			input := cloudwatchlogs.PutRetentionPolicyInput{
				LogGroupName:    aws.String(name),
				RetentionInDays: aws.Int64(int64(v.(int))),
			}
			log.Printf("[DEBUG] Setting retention for CloudWatch Log Group: %q: %s", name, input)
			_, err = conn.PutRetentionPolicy(&input)
		} else {
			log.Printf("[DEBUG] Deleting retention for CloudWatch Log Group: %q", name)
			_, err = conn.DeleteRetentionPolicy(&cloudwatchlogs.DeleteRetentionPolicyInput{
				LogGroupName: aws.String(name),
			})
		}

		return err
	}

	return resourceAwsCloudWatchLogGroupRead(d, meta)
}
func resourceArmNetworkSecurityRuleCreate(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*ArmClient)
	secClient := client.secRuleClient

	name := d.Get("name").(string)
	nsgName := d.Get("network_security_group_name").(string)
	resGroup := d.Get("resource_group_name").(string)

	source_port_range := d.Get("source_port_range").(string)
	destination_port_range := d.Get("destination_port_range").(string)
	source_address_prefix := d.Get("source_address_prefix").(string)
	destination_address_prefix := d.Get("destination_address_prefix").(string)
	priority := d.Get("priority").(int)
	access := d.Get("access").(string)
	direction := d.Get("direction").(string)
	protocol := d.Get("protocol").(string)

	armMutexKV.Lock(nsgName)
	defer armMutexKV.Unlock(nsgName)

	properties := network.SecurityRulePropertiesFormat{
		SourcePortRange:          &source_port_range,
		DestinationPortRange:     &destination_port_range,
		SourceAddressPrefix:      &source_address_prefix,
		DestinationAddressPrefix: &destination_address_prefix,
		Priority:                 &priority,
		Access:                   network.SecurityRuleAccess(access),
		Direction:                network.SecurityRuleDirection(direction),
		Protocol:                 network.SecurityRuleProtocol(protocol),
	}

	if v, ok := d.GetOk("description"); ok {
		description := v.(string)
		properties.Description = &description
	}

	sgr := network.SecurityRule{
		Name:       &name,
		Properties: &properties,
	}

	resp, err := secClient.CreateOrUpdate(resGroup, nsgName, name, sgr)
	if err != nil {
		return err
	}
	d.SetId(*resp.ID)

	log.Printf("[DEBUG] Waiting for Network Security Rule (%s) to become available", name)
	stateConf := &resource.StateChangeConf{
		Pending: []string{"Accepted", "Updating"},
		Target:  "Succeeded",
		Refresh: securityRuleStateRefreshFunc(client, resGroup, nsgName, name),
		Timeout: 10 * time.Minute,
	}
	if _, err := stateConf.WaitForState(); err != nil {
		return fmt.Errorf("Error waiting for Network Securty Rule (%s) to become available: %s", name, err)
	}

	return resourceArmNetworkSecurityRuleRead(d, meta)
}
func resourceAwsOpsworksStackDelete(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*AWSClient).opsworksconn

	req := &opsworks.DeleteStackInput{
		StackId: aws.String(d.Id()),
	}

	log.Printf("[DEBUG] Deleting OpsWorks stack: %s", d.Id())

	_, err := client.DeleteStack(req)
	if err != nil {
		return err
	}

	// For a stack in a VPC, OpsWorks has created some default security groups
	// in the VPC, which it will now delete.
	// Unfortunately, the security groups are deleted asynchronously and there
	// is no robust way for us to determine when it is done. The VPC itself
	// isn't deletable until the security groups are cleaned up, so this could
	// make 'terraform destroy' fail if the VPC is also managed and we don't
	// wait for the security groups to be deleted.
	// There is no robust way to check for this, so we'll just wait a
	// nominal amount of time.
	_, inVpc := d.GetOk("vpc_id")
	_, useOpsworksDefaultSg := d.GetOk("use_opsworks_security_group")

	if inVpc && useOpsworksDefaultSg {
		log.Print("[INFO] Waiting for Opsworks built-in security groups to be deleted")
		time.Sleep(30 * time.Second)
	}

	return nil
}
func resourceDNSimpleRecordCreate(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*dnsimple.Client)

	// Create the new record
	newRecord := &dnsimple.ChangeRecord{
		Name:  d.Get("name").(string),
		Type:  d.Get("type").(string),
		Value: d.Get("value").(string),
	}

	if ttl, ok := d.GetOk("ttl"); ok {
		newRecord.Ttl = ttl.(string)
	}

	log.Printf("[DEBUG] DNSimple Record create configuration: %#v", newRecord)

	recId, err := client.CreateRecord(d.Get("domain").(string), newRecord)

	if err != nil {
		return fmt.Errorf("Failed to create DNSimple Record: %s", err)
	}

	d.SetId(recId)
	log.Printf("[INFO] record ID: %s", d.Id())

	return resourceDNSimpleRecordRead(d, meta)
}
func resourceCloudStackNetworkACLCreate(d *schema.ResourceData, meta interface{}) error {
	cs := meta.(*cloudstack.CloudStackClient)

	name := d.Get("name").(string)

	// Retrieve the vpc ID
	vpcid, e := retrieveID(cs, "vpc", d.Get("vpc").(string))
	if e != nil {
		return e.Error()
	}

	// Create a new parameter struct
	p := cs.NetworkACL.NewCreateNetworkACLListParams(name, vpcid)

	// Set the description
	if description, ok := d.GetOk("description"); ok {
		p.SetDescription(description.(string))
	} else {
		p.SetDescription(name)
	}

	// Create the new network ACL list
	r, err := cs.NetworkACL.CreateNetworkACLList(p)
	if err != nil {
		return fmt.Errorf("Error creating network ACL list %s: %s", name, err)
	}

	d.SetId(r.Id)

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

	callerRef := resource.UniqueId()
	if v, ok := d.GetOk("reference_name"); ok {
		callerRef = strings.Join([]string{
			v.(string), "-", callerRef,
		}, "")
	}
	input := &route53.CreateReusableDelegationSetInput{
		CallerReference: aws.String(callerRef),
	}

	log.Printf("[DEBUG] Creating Route53 reusable delegation set: %#v", input)
	out, err := r53.CreateReusableDelegationSet(input)
	if err != nil {
		return err
	}
	log.Printf("[DEBUG] Route53 reusable delegation set created: %#v", out)

	set := out.DelegationSet
	d.SetId(cleanDelegationSetId(*set.Id))
	d.Set("name_servers", expandNameServers(set.NameServers))
	return nil
}
func resourceDnsManagedZoneCreate(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)

	// Build the parameter
	zone := &dns.ManagedZone{
		Name:    d.Get("name").(string),
		DnsName: d.Get("dns_name").(string),
	}
	// Optional things
	if v, ok := d.GetOk("description"); ok {
		zone.Description = v.(string)
	}
	if v, ok := d.GetOk("dns_name"); ok {
		zone.DnsName = v.(string)
	}

	log.Printf("[DEBUG] DNS ManagedZone create request: %#v", zone)
	zone, err := config.clientDns.ManagedZones.Create(config.Project, zone).Do()
	if err != nil {
		return fmt.Errorf("Error creating DNS ManagedZone: %s", err)
	}

	d.SetId(zone.Name)

	return resourceDnsManagedZoneRead(d, meta)
}
func resourceCloudFlareRecordCreate(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*cloudflare.Client)

	// Create the new record
	newRecord := &cloudflare.CreateRecord{
		Name:    d.Get("name").(string),
		Type:    d.Get("type").(string),
		Content: d.Get("value").(string),
	}

	if ttl, ok := d.GetOk("ttl"); ok {
		newRecord.Ttl = ttl.(string)
	}

	if priority, ok := d.GetOk("priority"); ok {
		newRecord.Priority = priority.(string)
	}

	log.Printf("[DEBUG] CloudFlare Record create configuration: %#v", newRecord)

	rec, err := client.CreateRecord(d.Get("domain").(string), newRecord)

	if err != nil {
		return fmt.Errorf("Failed to create CloudFlare Record: %s", err)
	}

	d.SetId(rec.Id)
	log.Printf("[INFO] CloudFlare Record ID: %s", d.Id())

	return resourceCloudFlareRecordRead(d, meta)
}
func resourceAzureDataDiskDelete(d *schema.ResourceData, meta interface{}) error {
	mc := meta.(*Client).mgmtClient
	vmDiskClient := meta.(*Client).vmDiskClient

	lun := d.Get("lun").(int)
	vm := d.Get("virtual_machine").(string)

	// If a name was not supplied, it means we created a new emtpy disk and we now want to
	// delete that disk again. Otherwise we only want to detach the disk and keep the blob.
	_, removeBlob := d.GetOk("name")

	log.Printf("[DEBUG] Detaching data disk %s with removeBlob = %t", d.Id(), removeBlob)
	req, err := vmDiskClient.DeleteDataDisk(vm, vm, vm, lun, removeBlob)
	if err != nil {
		return fmt.Errorf(
			"Error detaching data disk %s with removeBlob = %t: %s", d.Id(), removeBlob, err)
	}

	// Wait until the data disk is detached and optionally deleted
	if err := mc.WaitForOperation(req, nil); err != nil {
		return fmt.Errorf(
			"Error waiting for data disk %s to be detached with removeBlob = %t: %s",
			d.Id(), removeBlob, err)
	}

	d.SetId("")

	return nil
}
func buildNetworks(d *schema.ResourceData, meta interface{}) (error, []*compute.NetworkInterface) {
	// Build up the list of networks
	networksCount := d.Get("network_interface.#").(int)
	networkInterfaces := make([]*compute.NetworkInterface, 0, networksCount)
	for i := 0; i < networksCount; i++ {
		prefix := fmt.Sprintf("network_interface.%d", i)

		source := "global/networks/"
		if v, ok := d.GetOk(prefix + ".network"); ok {
			source += v.(string)
		}

		// Build the networkInterface
		var iface compute.NetworkInterface
		iface.Network = source

		accessConfigsCount := d.Get(prefix + ".access_config.#").(int)
		iface.AccessConfigs = make([]*compute.AccessConfig, accessConfigsCount)
		for j := 0; j < accessConfigsCount; j++ {
			acPrefix := fmt.Sprintf("%s.access_config.%d", prefix, j)
			iface.AccessConfigs[j] = &compute.AccessConfig{
				Type:  "ONE_TO_ONE_NAT",
				NatIP: d.Get(acPrefix + ".nat_ip").(string),
			}
		}

		networkInterfaces = append(networkInterfaces, &iface)
	}
	return nil, networkInterfaces
}
func buildConnectSettings(d *schema.ResourceData) (connectSettings *directoryservice.DirectoryConnectSettings, err error) {
	if v, ok := d.GetOk("connect_settings"); !ok {
		return nil, fmt.Errorf("connect_settings is required for type = ADConnector")
	} else {
		settings := v.([]interface{})

		if len(settings) > 1 {
			return nil, fmt.Errorf("Only a single connect_settings block is expected")
		} else if len(settings) == 1 {
			s := settings[0].(map[string]interface{})

			var subnetIds []*string
			for _, id := range s["subnet_ids"].(*schema.Set).List() {
				subnetIds = append(subnetIds, aws.String(id.(string)))
			}

			var customerDnsIps []*string
			for _, id := range s["customer_dns_ips"].(*schema.Set).List() {
				customerDnsIps = append(customerDnsIps, aws.String(id.(string)))
			}

			connectSettings = &directoryservice.DirectoryConnectSettings{
				CustomerDnsIps:   customerDnsIps,
				CustomerUserName: aws.String(s["customer_username"].(string)),
				SubnetIds:        subnetIds,
				VpcId:            aws.String(s["vpc_id"].(string)),
			}
		}
	}

	return connectSettings, nil
}
func websiteEndpoint(s3conn *s3.S3, d *schema.ResourceData) (*S3Website, error) {
	// If the bucket doesn't have a website configuration, return an empty
	// endpoint
	if _, ok := d.GetOk("website"); !ok {
		return nil, nil
	}

	bucket := d.Get("bucket").(string)

	// Lookup the region for this bucket
	location, err := s3conn.GetBucketLocation(
		&s3.GetBucketLocationInput{
			Bucket: aws.String(bucket),
		},
	)
	if err != nil {
		return nil, err
	}
	var region string
	if location.LocationConstraint != nil {
		region = *location.LocationConstraint
	}

	return WebsiteEndpoint(bucket, region), nil
}
func resourceComputeTargetHttpProxyCreate(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)

	proxy := &compute.TargetHttpProxy{
		Name:   d.Get("name").(string),
		UrlMap: d.Get("url_map").(string),
	}

	if v, ok := d.GetOk("description"); ok {
		proxy.Description = v.(string)
	}

	log.Printf("[DEBUG] TargetHttpProxy insert request: %#v", proxy)
	op, err := config.clientCompute.TargetHttpProxies.Insert(
		config.Project, proxy).Do()
	if err != nil {
		return fmt.Errorf("Error creating TargetHttpProxy: %s", err)
	}

	err = computeOperationWaitGlobal(config, op, "Creating Target Http Proxy")
	if err != nil {
		return err
	}

	d.SetId(proxy.Name)

	return resourceComputeTargetHttpProxyRead(d, meta)
}
func resourceComputeVpnGatewayCreate(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)

	name := d.Get("name").(string)
	network := d.Get("network").(string)
	region := getOptionalRegion(d, config)
	project := config.Project

	vpnGatewaysService := compute.NewTargetVpnGatewaysService(config.clientCompute)

	vpnGateway := &compute.TargetVpnGateway{
		Name:    name,
		Network: network,
	}

	if v, ok := d.GetOk("description"); ok {
		vpnGateway.Description = v.(string)
	}

	op, err := vpnGatewaysService.Insert(project, region, vpnGateway).Do()
	if err != nil {
		return fmt.Errorf("Error Inserting VPN Gateway %s into network %s: %s", name, network, err)
	}

	err = computeOperationWaitRegion(config, op, region, "Inserting VPN Gateway")
	if err != nil {
		return fmt.Errorf("Error Waiting to Insert VPN Gateway %s into network %s: %s", name, network, err)
	}

	return resourceComputeVpnGatewayRead(d, meta)
}
func resourceComputeSslCertificateCreate(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)

	// Build the certificate parameter
	cert := &compute.SslCertificate{
		Name:        d.Get("name").(string),
		Certificate: d.Get("certificate").(string),
		PrivateKey:  d.Get("private_key").(string),
	}

	if v, ok := d.GetOk("description"); ok {
		cert.Description = v.(string)
	}

	op, err := config.clientCompute.SslCertificates.Insert(
		config.Project, cert).Do()

	if err != nil {
		return fmt.Errorf("Error creating ssl certificate: %s", err)
	}

	err = computeOperationWaitGlobal(config, op, "Creating SslCertificate")
	if err != nil {
		return err
	}

	d.SetId(cert.Name)

	return resourceComputeSslCertificateRead(d, meta)
}
func resourceCloudFlareRecordUpdate(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*cloudflare.Client)

	// CloudFlare requires we send all values for an update request
	updateRecord := &cloudflare.UpdateRecord{
		Name:    d.Get("name").(string),
		Type:    d.Get("type").(string),
		Content: d.Get("value").(string),
	}

	if ttl, ok := d.GetOk("ttl"); ok {
		updateRecord.Ttl = ttl.(string)
	}

	if priority, ok := d.GetOk("priority"); ok {
		updateRecord.Priority = priority.(string)
	}

	log.Printf("[DEBUG] CloudFlare Record update configuration: %#v", updateRecord)

	err := client.UpdateRecord(d.Get("domain").(string), d.Id(), updateRecord)
	if err != nil {
		return fmt.Errorf("Failed to update CloudFlare Record: %s", err)
	}

	return resourceCloudFlareRecordRead(d, meta)
}
func resourceAwsIAMServerCertificateCreate(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).iamconn

	createOpts := &iam.UploadServerCertificateInput{
		CertificateBody:       aws.String(d.Get("certificate_body").(string)),
		PrivateKey:            aws.String(d.Get("private_key").(string)),
		ServerCertificateName: aws.String(d.Get("name").(string)),
	}

	if v, ok := d.GetOk("certificate_chain"); ok {
		createOpts.CertificateChain = aws.String(v.(string))
	}

	if v, ok := d.GetOk("path"); ok {
		createOpts.Path = aws.String(v.(string))
	}

	log.Printf("[DEBUG] Creating IAM Server Certificate with opts: %s", createOpts)
	resp, err := conn.UploadServerCertificate(createOpts)
	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok {
			return fmt.Errorf("[WARN] Error uploading server certificate, error: %s: %s", awsErr.Code(), awsErr.Message())
		}
		return fmt.Errorf("[WARN] Error uploading server certificate, error: %s", err)
	}

	d.SetId(*resp.ServerCertificateMetadata.ServerCertificateId)

	return resourceAwsIAMServerCertificateRead(d, meta)
}
func getOptionalRegion(d *schema.ResourceData, config *Config) string {
	if res, ok := d.GetOk("region"); !ok {
		return config.Region
	} else {
		return res.(string)
	}
}
func resourceStorageObjectAclRead(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)

	bucket := d.Get("bucket").(string)
	object := d.Get("object").(string)

	// Predefined ACLs cannot easily be parsed once they have been processed
	// by the GCP server
	if _, ok := d.GetOk("predefined_acl"); !ok {
		role_entity := make([]interface{}, 0)
		re_local := d.Get("role_entity").([]interface{})
		re_local_map := make(map[string]string)
		for _, v := range re_local {
			res, err := getRoleEntityPair(v.(string))

			if err != nil {
				return fmt.Errorf(
					"Old state has malformed Role/Entity pair: %v", err)
			}

			re_local_map[res.Entity] = res.Role
		}

		res, err := config.clientStorage.ObjectAccessControls.List(bucket, object).Do()

		if err != nil {
			if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == 404 {
				log.Printf("[WARN] Removing Storage Object ACL for Bucket %q because it's gone", d.Get("bucket").(string))
				// The resource doesn't exist anymore
				d.SetId("")

				return nil
			}

			return err
		}

		for _, v := range res.Items {
			role := ""
			entity := ""
			for key, val := range v.(map[string]interface{}) {
				if key == "role" {
					role = val.(string)
				} else if key == "entity" {
					entity = val.(string)
				}
			}
			if _, in := re_local_map[entity]; in {
				role_entity = append(role_entity, fmt.Sprintf("%s:%s", role, entity))
				log.Printf("[DEBUG]: saving re %s-%s", role, entity)
			}
		}

		d.Set("role_entity", role_entity)
	}

	d.SetId(getObjectAclId(object))
	return nil
}