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

	d.Partial(true)

	firewall, err := resourceFirewall(d, meta)
	if err != nil {
		return err
	}

	op, err := config.clientCompute.Firewalls.Update(
		config.Project, d.Id(), firewall).Do()
	if err != nil {
		return fmt.Errorf("Error updating firewall: %s", err)
	}

	err = computeOperationWaitGlobal(config, op, "Updating Firewall")
	if err != nil {
		return err
	}

	d.Partial(false)

	return resourceComputeFirewallRead(d, meta)
}
func resourceAwsAutoscalingGroupUpdate(d *schema.ResourceData, meta interface{}) error {
	autoscalingconn := meta.(*AWSClient).autoscalingconn

	opts := autoscaling.UpdateAutoScalingGroup{
		Name: d.Id(),
	}

	if d.HasChange("desired_capacity") {
		opts.DesiredCapacity = d.Get("desired_capacity").(int)
		opts.SetDesiredCapacity = true
	}

	if d.HasChange("min_size") {
		opts.MinSize = d.Get("min_size").(int)
		opts.SetMinSize = true
	}

	if d.HasChange("max_size") {
		opts.MaxSize = d.Get("max_size").(int)
		opts.SetMaxSize = true
	}

	log.Printf("[DEBUG] AutoScaling Group update configuration: %#v", opts)
	_, err := autoscalingconn.UpdateAutoScalingGroup(&opts)
	if err != nil {
		d.Partial(true)
		return fmt.Errorf("Error updating Autoscaling group: %s", err)
	}

	return resourceAwsAutoscalingGroupRead(d, meta)
}
func resourceMarathonAppCreate(d *schema.ResourceData, meta interface{}) error {
	config := meta.(Config)
	client := config.Client

	application := mutateResourceToApplication(d)

	application, err := client.CreateApplication(application)
	if err != nil {
		log.Println("[ERROR] creating application", err)
		return err
	}
	d.Partial(true)
	d.SetId(application.ID)
	setSchemaFieldsForApp(application, d)

	for _, deploymentID := range application.DeploymentIDs() {
		err = client.WaitOnDeployment(deploymentID.DeploymentID, config.DefaultDeploymentTimeout)
		if err != nil {
			log.Println("[ERROR] waiting for application for deployment", deploymentID, err)
			return err
		}
	}

	d.Partial(false)

	return resourceMarathonAppRead(d, meta)
}
func resourceBrightboxDatabaseServerUpdate(
	d *schema.ResourceData,
	meta interface{},
) error {
	client := meta.(*CompositeClient).ApiClient
	log.Printf("[DEBUG] Setting Partial")
	d.Partial(true)
	// Create/Update Database
	database_server_opts := getBlankDatabaseServerOpts()
	err := addUpdateableDatabaseServerOptions(d, database_server_opts)
	if err != nil {
		return err
	}
	if databaseDetailsChanged(d) {
		log.Printf("[INFO] Changing database details")
		err := removeDatabaseAccessRestrictions(client, d.Id())
		if err != nil {
			return err
		}
		err = changeDatabase(d)
		if err != nil {
			return err
		}
		assign_string_set_always(d, &database_server_opts.AllowAccess, "allow_access")
	} else {
		log.Printf("[DEBUG] No change to database details detected")
		assign_string_set(d, &database_server_opts.AllowAccess, "allow_access")
	}
	return updateDatabaseServerAttributes(d, client, database_server_opts)
}
func resourceAwsSubnetUpdate(d *schema.ResourceData, meta interface{}) error {
	ec2conn := meta.(*AWSClient).ec2conn

	d.Partial(true)

	if err := setTags(ec2conn, d); err != nil {
		return err
	} else {
		d.SetPartial("tags")
	}

	if d.HasChange("map_public_ip_on_launch") {
		modifyOpts := &ec2.ModifySubnetAttribute{
			SubnetId:            d.Id(),
			MapPublicIpOnLaunch: true,
		}

		log.Printf("[DEBUG] Subnet modify attributes: %#v", modifyOpts)

		_, err := ec2conn.ModifySubnetAttribute(modifyOpts)

		if err != nil {
			return err
		} else {
			d.SetPartial("map_public_ip_on_launch")
		}
	}

	d.Partial(false)

	return resourceAwsSubnetRead(d, meta)
}
func resourceAwsRoute53ZoneUpdate(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).r53conn

	d.Partial(true)

	if d.HasChange("comment") {
		zoneInput := route53.UpdateHostedZoneCommentInput{
			Id:      aws.String(d.Id()),
			Comment: aws.String(d.Get("comment").(string)),
		}

		_, err := conn.UpdateHostedZoneComment(&zoneInput)
		if err != nil {
			return err
		} else {
			d.SetPartial("comment")
		}
	}

	if err := setTagsR53(conn, d, "hostedzone"); err != nil {
		return err
	} else {
		d.SetPartial("tags")
	}

	d.Partial(false)

	return resourceAwsRoute53ZoneRead(d, meta)
}
func resourceAwsProxyProtocolPolicyCreate(d *schema.ResourceData, meta interface{}) error {
	elbconn := meta.(*AWSClient).elbconn
	elbname := aws.String(d.Get("load_balancer").(string))

	input := &elb.CreateLoadBalancerPolicyInput{
		LoadBalancerName: elbname,
		PolicyAttributes: []*elb.PolicyAttribute{
			&elb.PolicyAttribute{
				AttributeName:  aws.String("ProxyProtocol"),
				AttributeValue: aws.String("True"),
			},
		},
		PolicyName:     aws.String("TFEnableProxyProtocol"),
		PolicyTypeName: aws.String("ProxyProtocolPolicyType"),
	}

	// Create a policy
	log.Printf("[DEBUG] ELB create a policy %s from policy type %s",
		*input.PolicyName, *input.PolicyTypeName)

	if _, err := elbconn.CreateLoadBalancerPolicy(input); err != nil {
		return fmt.Errorf("Error creating a policy %s: %s",
			*input.PolicyName, err)
	}

	// Assign the policy name for use later
	d.Partial(true)
	d.SetId(fmt.Sprintf("%s:%s", *elbname, *input.PolicyName))
	d.SetPartial("load_balancer")
	log.Printf("[INFO] ELB PolicyName: %s", *input.PolicyName)

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

	region := getOptionalRegion(d, config)

	d.Partial(true)

	if d.HasChange("target") {
		target_name := d.Get("target").(string)
		target_ref := &compute.TargetReference{Target: target_name}
		op, err := config.clientCompute.ForwardingRules.SetTarget(
			config.Project, region, d.Id(), target_ref).Do()
		if err != nil {
			return fmt.Errorf("Error updating target: %s", err)
		}

		err = computeOperationWaitRegion(config, op, region, "Updating Forwarding Rule")
		if err != nil {
			return err
		}

		d.SetPartial("target")
	}

	d.Partial(false)

	return resourceComputeForwardingRuleRead(d, meta)
}
func resourceAwsDbParameterGroupCreate(d *schema.ResourceData, meta interface{}) error {
	rdsconn := meta.(*AWSClient).rdsconn

	createOpts := rds.CreateDBParameterGroupInput{
		DBParameterGroupName:   aws.String(d.Get("name").(string)),
		DBParameterGroupFamily: aws.String(d.Get("family").(string)),
		Description:            aws.String(d.Get("description").(string)),
	}

	log.Printf("[DEBUG] Create DB Parameter Group: %#v", createOpts)
	_, err := rdsconn.CreateDBParameterGroup(&createOpts)
	if err != nil {
		return fmt.Errorf("Error creating DB Parameter Group: %s", err)
	}

	d.Partial(true)
	d.SetPartial("name")
	d.SetPartial("family")
	d.SetPartial("description")
	d.Partial(false)

	d.SetId(*createOpts.DBParameterGroupName)
	log.Printf("[INFO] DB Parameter Group ID: %s", d.Id())

	return resourceAwsDbParameterGroupUpdate(d, meta)
}
func resourceAwsSpotFleetRequestUpdate(d *schema.ResourceData, meta interface{}) error {
	// http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ModifySpotFleetRequest.html
	conn := meta.(*AWSClient).ec2conn

	d.Partial(true)

	req := &ec2.ModifySpotFleetRequestInput{
		SpotFleetRequestId: aws.String(d.Id()),
	}

	if val, ok := d.GetOk("target_capacity"); ok {
		req.TargetCapacity = aws.Int64(int64(val.(int)))
	}

	if val, ok := d.GetOk("excess_capacity_termination_policy"); ok {
		req.ExcessCapacityTerminationPolicy = aws.String(val.(string))
	}

	resp, err := conn.ModifySpotFleetRequest(req)
	if err == nil && aws.BoolValue(resp.Return) {
		// TODO: rollback to old values?
	}

	return nil
}
func instanceProfileSetRoles(d *schema.ResourceData, iamconn *iam.IAM) error {
	oldInterface, newInterface := d.GetChange("roles")
	oldRoles := oldInterface.(*schema.Set)
	newRoles := newInterface.(*schema.Set)

	currentRoles := schema.CopySet(oldRoles)

	d.Partial(true)

	for _, role := range oldRoles.Difference(newRoles).List() {
		err := instanceProfileRemoveRole(iamconn, d.Id(), role.(string))
		if err != nil {
			return fmt.Errorf("Error removing role %s from IAM instance profile %s: %s", role, d.Id(), err)
		}
		currentRoles.Remove(role)
		d.Set("roles", currentRoles)
		d.SetPartial("roles")
	}

	for _, role := range newRoles.Difference(oldRoles).List() {
		err := instanceProfileAddRole(iamconn, d.Id(), role.(string))
		if err != nil {
			return fmt.Errorf("Error adding role %s to IAM instance profile %s: %s", role, d.Id(), err)
		}
		currentRoles.Add(role)
		d.Set("roles", currentRoles)
		d.SetPartial("roles")
	}

	d.Partial(false)

	return nil
}
func resourceChronosJobCreate(rd *schema.ResourceData, meta interface{}) error {
	chronosConfig := meta.(Config)

	j := jobFromResource(rd)

	jsonBytes, err := json.Marshal(j)
	if err != nil {
		return err
	}

	req, err := chronosConfig.CreateRequest("POST", chronosConfig.GetCreateUrl(), "application/json", bytes.NewBuffer(jsonBytes))
	if err != nil {
		return err
	}

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return err
	}

	if err = checkStatusCodeIsSuccessful(resp.StatusCode); err != nil {
		return err
	}

	rd.Partial(true)
	rd.SetId(j.Name)
	setSchemaFieldsForJob(j, rd)
	rd.Partial(false)

	return resourceChronosJobRead(rd, meta)
}
func resourceVultrServerUpdate(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*lib.Client)

	d.Partial(true)

	if d.HasChange("name") {
		oldName, newName := d.GetChange("name")

		err := client.RenameServer(d.Id(), newName.(string))

		if err != nil {
			return fmt.Errorf("Error renaming server (%s): %s", d.Id(), err)
		}

		_, err = WaitForServerAttribute(d, newName.(string), []string{"", oldName.(string)}, "name", meta)

		if err != nil {
			return fmt.Errorf("Error waiting for rename server (%s) to finish: %s", d.Id(), err)
		}

		d.SetPartial("name")
	}

	return resourceVultrServerRead(d, meta)
}
示例#14
0
func resourceAwsAmiUpdate(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*AWSClient).ec2conn

	d.Partial(true)

	if err := setTags(client, d); err != nil {
		return err
	} else {
		d.SetPartial("tags")
	}

	if d.Get("description").(string) != "" {
		_, err := client.ModifyImageAttribute(&ec2.ModifyImageAttributeInput{
			ImageId: aws.String(d.Id()),
			Description: &ec2.AttributeValue{
				Value: aws.String(d.Get("description").(string)),
			},
		})
		if err != nil {
			return err
		}
		d.SetPartial("description")
	}

	d.Partial(false)

	return resourceAwsAmiRead(d, meta)
}
示例#15
0
func resourceAwsElbUpdate(d *schema.ResourceData, meta interface{}) error {
	elbconn := meta.(*AWSClient).elbconn

	d.Partial(true)

	// If we currently have instances, or did have instances,
	// we want to figure out what to add and remove from the load
	// balancer
	if d.HasChange("instances") {
		o, n := d.GetChange("instances")
		os := o.(*schema.Set)
		ns := n.(*schema.Set)
		remove := expandStringList(os.Difference(ns).List())
		add := expandStringList(ns.Difference(os).List())

		if len(add) > 0 {
			registerInstancesOpts := elb.RegisterInstancesWithLoadBalancer{
				LoadBalancerName: d.Id(),
				Instances:        add,
			}

			_, err := elbconn.RegisterInstancesWithLoadBalancer(&registerInstancesOpts)
			if err != nil {
				return fmt.Errorf("Failure registering instances: %s", err)
			}
		}
		if len(remove) > 0 {
			deRegisterInstancesOpts := elb.DeregisterInstancesFromLoadBalancer{
				LoadBalancerName: d.Id(),
				Instances:        remove,
			}

			_, err := elbconn.DeregisterInstancesFromLoadBalancer(&deRegisterInstancesOpts)
			if err != nil {
				return fmt.Errorf("Failure deregistering instances: %s", err)
			}
		}

		d.SetPartial("instances")
	}

	log.Println("[INFO] outside modify attributes")
	if d.HasChange("cross_zone_load_balancing") {
		log.Println("[INFO] inside modify attributes")
		attrs := elb.ModifyLoadBalancerAttributes{
			LoadBalancerName: d.Get("name").(string),
			LoadBalancerAttributes: elb.LoadBalancerAttributes{
				CrossZoneLoadBalancingEnabled: d.Get("cross_zone_load_balancing").(bool),
			},
		}
		_, err := elbconn.ModifyLoadBalancerAttributes(&attrs)
		if err != nil {
			return fmt.Errorf("Failure configuring health check: %s", err)
		}
		d.SetPartial("cross_zone_load_balancing")
	}

	d.Partial(false)
	return resourceAwsElbRead(d, meta)
}
func resourceBrightboxContainerCreate(
	d *schema.ResourceData,
	meta interface{},
) error {
	composite := meta.(*CompositeClient)
	client := composite.ApiClient
	log.Printf("[DEBUG] Setting Partial")
	d.Partial(true)
	log.Printf("[INFO] Creating API client")
	err := createApiClient(d, client)
	if err != nil {
		return err
	}
	d.SetPartial("orbit_url")
	container_url := createContainerUrl(createStorageUrl(d), d.Get("name").(string))
	log.Printf("[INFO] Creating container at %s in Orbit", container_url)
	log.Printf("[DEBUG] Using Auth Token: %s", *composite.OrbitAuthToken)
	err = createContainer(container_url, composite.OrbitAuthToken)
	if err != nil {
		return err
	}
	log.Printf("[DEBUG] Clearing Partial")
	d.Partial(false)
	return nil
}
func resourceAwsAmiCopyCreate(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*AWSClient).ec2conn

	req := &ec2.CopyImageInput{
		Name:          aws.String(d.Get("name").(string)),
		Description:   aws.String(d.Get("description").(string)),
		SourceImageId: aws.String(d.Get("source_ami_id").(string)),
		SourceRegion:  aws.String(d.Get("source_ami_region").(string)),
	}

	res, err := client.CopyImage(req)
	if err != nil {
		return err
	}

	id := *res.ImageId
	d.SetId(id)
	d.Partial(true) // make sure we record the id even if the rest of this gets interrupted
	d.Set("id", id)
	d.Set("manage_ebs_snapshots", true)
	d.SetPartial("id")
	d.SetPartial("manage_ebs_snapshots")
	d.Partial(false)

	_, err = resourceAwsAmiWaitForAvailable(id, client)
	if err != nil {
		return err
	}

	return resourceAwsAmiUpdate(d, meta)
}
func UpdateRepository(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*Client)

	d.Partial(true)

	if d.HasChange("name") {
		// Renaming has its own special operation.
		err := RenameRepository(d, meta)
		if err != nil {
			return err
		}

		d.SetPartial("name")
	}

	req := &RepositoryWrap{
		Repository: Repository{
			Title:            d.Get("title").(string),
			ColorLabel:       d.Get("color_label").(string),
			DefaultGitBranch: d.Get("default_git_branch").(string),
		},
	}

	err := client.Put([]string{"repositories", d.Id()}, req, nil)
	if err != nil {
		return err
	}

	d.Partial(false)

	return ReadRepository(d, meta)
}
func resourceCloudcaTierUpdate(d *schema.ResourceData, meta interface{}) error {
	ccaClient := meta.(*cca.CcaClient)
	resources, _ := ccaClient.GetResources(d.Get("service_code").(string), d.Get("environment_name").(string))
	ccaResources := resources.(cloudca.Resources)

	d.Partial(true)

	if d.HasChange("name") || d.HasChange("description") {
		newName := d.Get("name").(string)
		newDescription := d.Get("description").(string)
		_, err := ccaResources.Tiers.Update(d.Id(), cloudca.Tier{Id: d.Id(), Name: newName, Description: newDescription})
		if err != nil {
			return err
		}
	}

	if d.HasChange("network_acl_id") {
		_, aclErr := ccaResources.Tiers.ChangeAcl(d.Id(), d.Get("network_acl_id").(string))
		if aclErr != nil {
			return aclErr
		}
	}

	d.Partial(false)

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

	d.Partial(true)

	if d.HasChange("url_map") {
		url_map := d.Get("url_map").(string)
		url_map_ref := &compute.UrlMapReference{UrlMap: url_map}
		op, err := config.clientCompute.TargetHttpProxies.SetUrlMap(
			config.Project, d.Id(), url_map_ref).Do()
		if err != nil {
			return fmt.Errorf("Error updating target: %s", err)
		}

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

		d.SetPartial("url_map")
	}

	d.Partial(false)

	return resourceComputeTargetHttpProxyRead(d, meta)
}
示例#21
0
func resourceAwsSubnetUpdate(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).ec2conn

	d.Partial(true)

	if err := setTags(conn, d); err != nil {
		return err
	} else {
		d.SetPartial("tags")
	}

	if d.HasChange("map_public_ip_on_launch") {
		modifyOpts := &ec2.ModifySubnetAttributeInput{
			SubnetId: aws.String(d.Id()),
			MapPublicIpOnLaunch: &ec2.AttributeBooleanValue{
				Value: aws.Bool(d.Get("map_public_ip_on_launch").(bool)),
			},
		}

		log.Printf("[DEBUG] Subnet modify attributes: %#v", modifyOpts)

		_, err := conn.ModifySubnetAttribute(modifyOpts)

		if err != nil {
			return err
		} else {
			d.SetPartial("map_public_ip_on_launch")
		}
	}

	d.Partial(false)

	return resourceAwsSubnetRead(d, meta)
}
func resourceCloudcaVolumeUpdate(d *schema.ResourceData, meta interface{}) error {
	ccaClient := meta.(*cca.CcaClient)
	resources, _ := ccaClient.GetResources(d.Get("service_code").(string), d.Get("environment_name").(string))
	ccaResources := resources.(cloudca.Resources)

	d.Partial(true)
	if d.HasChange("instance_id") {
		oldInstanceId, newInstanceId := d.GetChange("instance_id")
		volume := &cloudca.Volume{
			Id: d.Id(),
		}
		if oldInstanceId != "" {
			err := ccaResources.Volumes.DetachFromInstance(volume)
			if err != nil {
				return err
			}
		}
		if newInstanceId != "" {
			err := ccaResources.Volumes.AttachToInstance(volume, newInstanceId.(string))
			if err != nil {
				return err
			}
		}
		d.SetPartial("instance_id")
	}
	d.Partial(false)
	return resourceCloudcaVolumeRead(d, meta)
}
示例#23
0
func resourceAwsInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).ec2conn

	d.Partial(true)
	if err := setTags(conn, d); err != nil {
		return err
	} else {
		d.SetPartial("tags")
	}

	// SourceDestCheck can only be set on VPC instances
	if d.Get("subnet_id").(string) != "" {
		log.Printf("[INFO] Modifying instance %s", d.Id())
		_, err := conn.ModifyInstanceAttribute(&ec2.ModifyInstanceAttributeInput{
			InstanceID: aws.String(d.Id()),
			SourceDestCheck: &ec2.AttributeBooleanValue{
				Value: aws.Boolean(d.Get("source_dest_check").(bool)),
			},
		})
		if err != nil {
			return err
		}
	}

	if d.HasChange("vpc_security_group_ids") {
		var groups []*string
		if v := d.Get("vpc_security_group_ids").(*schema.Set); v.Len() > 0 {
			for _, v := range v.List() {
				groups = append(groups, aws.String(v.(string)))
			}
		}
		_, err := conn.ModifyInstanceAttribute(&ec2.ModifyInstanceAttributeInput{
			InstanceID: aws.String(d.Id()),
			Groups:     groups,
		})
		if err != nil {
			return err
		}
	}

	if d.HasChange("disable_api_termination") {
		_, err := conn.ModifyInstanceAttribute(&ec2.ModifyInstanceAttributeInput{
			InstanceID: aws.String(d.Id()),
			DisableAPITermination: &ec2.AttributeBooleanValue{
				Value: aws.Boolean(d.Get("disable_api_termination").(bool)),
			},
		})
		if err != nil {
			return err
		}
	}

	// TODO(mitchellh): wait for the attributes we modified to
	// persist the change...

	d.Partial(false)

	return resourceAwsInstanceRead(d, meta)
}
func resourceCloudStackDiskCreate(d *schema.ResourceData, meta interface{}) error {
	cs := meta.(*cloudstack.CloudStackClient)
	d.Partial(true)

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

	// Create a new parameter struct
	p := cs.Volume.NewCreateVolumeParams(name)

	// Retrieve the disk_offering UUID
	diskofferingid, e := retrieveUUID(cs, "disk_offering", d.Get("disk_offering").(string))
	if e != nil {
		return e.Error()
	}
	// Set the disk_offering UUID
	p.SetDiskofferingid(diskofferingid)

	if d.Get("size").(int) != 0 {
		// Set the volume size
		p.SetSize(int64(d.Get("size").(int)))
	}

	// Retrieve the zone UUID
	zoneid, e := retrieveUUID(cs, "zone", d.Get("zone").(string))
	if e != nil {
		return e.Error()
	}
	// Set the zone ID
	p.SetZoneid(zoneid)

	// Create the new volume
	r, err := cs.Volume.CreateVolume(p)
	if err != nil {
		return fmt.Errorf("Error creating the new disk %s: %s", name, err)
	}

	// Set the volume UUID and partials
	d.SetId(r.Id)
	d.SetPartial("name")
	d.SetPartial("device")
	d.SetPartial("disk_offering")
	d.SetPartial("size")
	d.SetPartial("virtual_machine")
	d.SetPartial("zone")

	if d.Get("attach").(bool) {
		err := resourceCloudStackDiskAttach(d, meta)
		if err != nil {
			return fmt.Errorf("Error attaching the new disk %s to virtual machine: %s", name, err)
		}

		// Set the additional partial
		d.SetPartial("attach")
	}

	d.Partial(false)
	return resourceCloudStackDiskRead(d, meta)
}
func resourceLinodeLinodeUpdate(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*linodego.Client)
	d.Partial(true)

	id, err := strconv.ParseInt(d.Id(), 10, 64)
	if err != nil {
		return fmt.Errorf("Failed to parse linode id %s as an int because %s", d.Id(), err)
	}

	linodes, err := client.Linode.List(int(id))
	if err != nil {
		return fmt.Errorf("Failed to fetch data about the current linode because %s", err)
	}
	linode := linodes.Linodes[0]

	if d.HasChange("name") || d.HasChange("group") {
		if err = changeLinodeSettings(client, linode, d); err != nil {
			return err
		}
	}

	configResp, err := client.Config.List(int(id), -1)
	if err != nil {
		return fmt.Errorf("Failed to fetch the config for linode %d because %s", id, err)
	}
	if len(configResp.LinodeConfigs) != 1 {
		return fmt.Errorf("Linode %d has an incorrect number of configs %d, this plugin can only handle 1", id, len(configResp.LinodeConfigs))
	}
	config := configResp.LinodeConfigs[0]

	if err = changeLinodeConfig(client, config, d); err != nil {
		return fmt.Errorf("Failed to update Linode %d config because %s", id, config)
	}

	if d.HasChange("private_networking") {
		if !d.Get("private_networking").(bool) {
			return fmt.Errorf("Can't deactivate private networking for linode %s", d.Id())
		} else {
			_, err = client.Ip.AddPrivate(int(id))
			if err != nil {
				return fmt.Errorf("Failed to activate private networking on linode %s because %s", d.Id(), err)
			}
			if d.Get("manage_private_ip_automatically").(bool) {
				_, err = client.Linode.Reboot(int(id), 0)
				if err != nil {
					return fmt.Errorf("Failed to reboot linode %s because %s", d.Id(), err)
				}
				err = waitForJobsToComplete(client, int(id))
				if err != nil {
					return fmt.Errorf("Failed while waiting for linode %s to finish rebooting because %s", d.Id(), err)
				}
			}
		}
	}

	return resourceLinodeLinodeRead(d, meta)
}
func resourceCloudcaInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
	ccaClient := meta.(*cca.CcaClient)
	resources, _ := ccaClient.GetResources(d.Get("service_code").(string), d.Get("environment_name").(string))
	ccaResources := resources.(cloudca.Resources)

	d.Partial(true)

	if d.HasChange("compute_offering") || d.HasChange("cpu_count") || d.HasChange("memory_in_mb") {
		newComputeOffering := d.Get("compute_offering").(string)
		log.Printf("[DEBUG] Compute offering has changed for %s, changing compute offering...", newComputeOffering)
		newComputeOfferingId, ferr := retrieveComputeOfferingID(&ccaResources, newComputeOffering)
		if ferr != nil {
			return ferr
		}
		instanceToUpdate := cloudca.Instance{Id: d.Id(),
			ComputeOfferingId: newComputeOfferingId,
		}

		hasCustomFields := false
		if cpuCount, ok := d.GetOk("cpu_count"); ok {
			instanceToUpdate.CpuCount = cpuCount.(int)
			hasCustomFields = true
		}
		if memoryInMB, ok := d.GetOk("memory_in_mb"); ok {
			instanceToUpdate.MemoryInMB = memoryInMB.(int)
			hasCustomFields = true
		}

		computeOffering, cerr := ccaResources.ComputeOfferings.Get(newComputeOfferingId)
		if cerr != nil {
			return cerr
		} else if !computeOffering.Custom && hasCustomFields {
			return fmt.Errorf("Cannot have a CPU count or memory in MB because \"%s\" isn't a custom compute offering", computeOffering.Name)
		}

		_, err := ccaResources.Instances.ChangeComputeOffering(instanceToUpdate)
		if err != nil {
			return err
		}
		d.SetPartial("compute_offering")
	}

	if d.HasChange("ssh_key_name") {
		sshKeyName := d.Get("ssh_key_name").(string)
		log.Printf("[DEBUG] SSH key name has changed for %s, associating new SSH key...", sshKeyName)
		_, err := ccaResources.Instances.AssociateSSHKey(d.Id(), sshKeyName)
		if err != nil {
			return err
		}
		d.SetPartial("ssh_key_name")
	}

	d.Partial(false)

	return nil
}
func resourceMAASInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
	log.Printf("[DEBUG] [resourceMAASInstanceUpdate] Modifying instance %s\n", d.Id())

	d.Partial(true)

	d.Partial(false)

	log.Printf("[DEBUG] Done Modifying instance %s", d.Id())
	return resourceMAASInstanceRead(d, meta)
}
func resourceAwsProxyProtocolPolicyUpdate(d *schema.ResourceData, meta interface{}) error {
	elbconn := meta.(*AWSClient).elbconn
	elbname := aws.String(d.Get("load_balancer").(string))

	// Retrieve the current ELB policies for updating the state
	req := &elb.DescribeLoadBalancersInput{
		LoadBalancerNames: []*string{elbname},
	}
	resp, err := elbconn.DescribeLoadBalancers(req)
	if err != nil {
		if isLoadBalancerNotFound(err) {
			// The ELB is gone now, so just remove it from the state
			d.SetId("")
			return nil
		}
		return fmt.Errorf("Error retrieving ELB attributes: %s", err)
	}

	backends := flattenBackendPolicies(resp.LoadBalancerDescriptions[0].BackendServerDescriptions)
	_, policyName := resourceAwsProxyProtocolPolicyParseId(d.Id())

	d.Partial(true)
	if d.HasChange("instance_ports") {
		o, n := d.GetChange("instance_ports")
		os := o.(*schema.Set)
		ns := n.(*schema.Set)
		remove := os.Difference(ns).List()
		add := ns.Difference(os).List()

		inputs := []*elb.SetLoadBalancerPoliciesForBackendServerInput{}

		i, err := resourceAwsProxyProtocolPolicyRemove(policyName, remove, backends)
		if err != nil {
			return err
		}
		inputs = append(inputs, i...)

		i, err = resourceAwsProxyProtocolPolicyAdd(policyName, add, backends)
		if err != nil {
			return err
		}
		inputs = append(inputs, i...)

		for _, input := range inputs {
			input.LoadBalancerName = elbname
			if _, err := elbconn.SetLoadBalancerPoliciesForBackendServer(input); err != nil {
				return fmt.Errorf("Error setting policy for backend: %s", err)
			}
		}

		d.SetPartial("instance_ports")
	}

	return resourceAwsProxyProtocolPolicyRead(d, meta)
}
示例#29
0
func resourceAwsElbCreate(d *schema.ResourceData, meta interface{}) error {
	elbconn := meta.(*AWSClient).elbconn

	// Expand the "listener" set to aws-sdk-go compat []*elb.Listener
	listeners, err := expandListeners(d.Get("listener").(*schema.Set).List())
	if err != nil {
		return err
	}

	tags := tagsFromMapELB(d.Get("tags").(map[string]interface{}))
	// Provision the elb
	elbOpts := &elb.CreateLoadBalancerInput{
		LoadBalancerName: aws.String(d.Get("name").(string)),
		Listeners:        listeners,
		Tags:             tags,
	}

	if scheme, ok := d.GetOk("internal"); ok && scheme.(bool) {
		elbOpts.Scheme = aws.String("internal")
	}

	if v, ok := d.GetOk("availability_zones"); ok {
		elbOpts.AvailabilityZones = expandStringList(v.(*schema.Set).List())
	}

	if v, ok := d.GetOk("security_groups"); ok {
		elbOpts.SecurityGroups = expandStringList(v.(*schema.Set).List())
	}

	if v, ok := d.GetOk("subnets"); ok {
		elbOpts.Subnets = expandStringList(v.(*schema.Set).List())
	}

	log.Printf("[DEBUG] ELB create configuration: %#v", elbOpts)
	if _, err := elbconn.CreateLoadBalancer(elbOpts); err != nil {
		return fmt.Errorf("Error creating ELB: %s", err)
	}

	// Assign the elb's unique identifier for use later
	d.SetId(d.Get("name").(string))
	log.Printf("[INFO] ELB ID: %s", d.Id())

	// Enable partial mode and record what we set
	d.Partial(true)
	d.SetPartial("name")
	d.SetPartial("internal")
	d.SetPartial("availability_zones")
	d.SetPartial("listener")
	d.SetPartial("security_groups")
	d.SetPartial("subnets")

	d.Set("tags", tagsToMapELB(tags))

	return resourceAwsElbUpdate(d, meta)
}
func resourceAwsNetworkInterfaceUpdate(d *schema.ResourceData, meta interface{}) error {
	ec2conn := meta.(*AWSClient).ec2conn
	d.Partial(true)

	if d.HasChange("attachment") {
		ec2conn := meta.(*AWSClient).ec2conn
		oa, na := d.GetChange("attachment")

		detach_err := resourceAwsNetworkInterfaceDetach(oa.(*schema.Set), meta, d.Id())
		if detach_err != nil {
			return detach_err
		}

		// if there is a new attachment, attach it
		if na != nil && len(na.(*schema.Set).List()) > 0 {
			new_attachment := na.(*schema.Set).List()[0].(map[string]interface{})
			attach_request := &ec2.AttachNetworkInterfaceRequest{
				DeviceIndex:        aws.Integer(new_attachment["device_index"].(int)),
				InstanceID:         aws.String(new_attachment["instance"].(string)),
				NetworkInterfaceID: aws.String(d.Id()),
			}
			_, attach_err := ec2conn.AttachNetworkInterface(attach_request)
			if attach_err != nil {
				return fmt.Errorf("Error attaching ENI: %s", attach_err)
			}
		}

		d.SetPartial("attachment")
	}

	if d.HasChange("security_groups") {
		request := &ec2.ModifyNetworkInterfaceAttributeRequest{
			NetworkInterfaceID: aws.String(d.Id()),
			Groups:             expandStringList(d.Get("security_groups").(*schema.Set).List()),
		}

		err := ec2conn.ModifyNetworkInterfaceAttribute(request)
		if err != nil {
			return fmt.Errorf("Failure updating ENI: %s", err)
		}

		d.SetPartial("security_groups")
	}

	if err := setTags(ec2conn, d); err != nil {
		return err
	} else {
		d.SetPartial("tags")
	}

	d.Partial(false)

	return resourceAwsNetworkInterfaceRead(d, meta)
}