func resourceDNSimpleRecordUpdate(d *schema.ResourceData, meta interface{}) error { client := meta.(*dnsimple.Client) updateRecord := &dnsimple.ChangeRecord{} if attr, ok := d.GetOk("name"); ok { updateRecord.Name = attr.(string) } if attr, ok := d.GetOk("type"); ok { updateRecord.Type = attr.(string) } if attr, ok := d.GetOk("value"); ok { updateRecord.Value = attr.(string) } if attr, ok := d.GetOk("ttl"); ok { updateRecord.Ttl = attr.(string) } log.Printf("[DEBUG] DNSimple Record update configuration: %#v", updateRecord) _, err := client.UpdateRecord(d.Get("domain").(string), d.Id(), updateRecord) if err != nil { return fmt.Errorf("Failed to update DNSimple Record: %s", err) } return resourceDNSimpleRecordRead(d, meta) }
// resourceAzureAffinityGroupRead does all the necessary API calls to // read the state of the affinity group off Azure. func resourceAzureAffinityGroupRead(d *schema.ResourceData, meta interface{}) error { affinityGroupClient := meta.(*Client).affinityGroupClient log.Println("[INFO] Issuing Azure Affinity Group list request.") affinityGroups, err := affinityGroupClient.ListAffinityGroups() if err != nil { return fmt.Errorf("Error obtaining Affinity Group list off Azure: %s", err) } var found bool name := d.Get("name").(string) for _, group := range affinityGroups.AffinityGroups { if group.Name == name { found = true d.Set("location", group.Location) d.Set("label", group.Label) d.Set("description", group.Description) break } } if !found { // it means the affinity group has been deleted in the meantime, so we // must stop tracking it: d.SetId("") } return nil }
func resourceHerokuAddonRead(d *schema.ResourceData, meta interface{}) error { client := meta.(*heroku.Service) addon, err := resourceHerokuAddonRetrieve( d.Get("app").(string), d.Id(), client) if err != nil { return err } // Determine the plan. If we were configured without a specific plan, // then just avoid the plan altogether (accepting anything that // Heroku sends down). plan := addon.Plan.Name if v := d.Get("plan").(string); v != "" { if idx := strings.IndexRune(v, ':'); idx == -1 { idx = strings.IndexRune(plan, ':') if idx > -1 { plan = plan[:idx] } } } d.Set("name", addon.Name) d.Set("plan", plan) d.Set("provider_id", addon.ProviderID) if err := d.Set("config_vars", addon.ConfigVars); err != nil { return err } return nil }
// setTags is a helper to set the tags for a resource. It expects the // tags field to be named "tags" func setTagsS3(conn *s3.S3, d *schema.ResourceData) error { if d.HasChange("tags") { oraw, nraw := d.GetChange("tags") o := oraw.(map[string]interface{}) n := nraw.(map[string]interface{}) create, remove := diffTagsS3(tagsFromMapS3(o), tagsFromMapS3(n)) // Set tags if len(remove) > 0 { log.Printf("[DEBUG] Removing tags: %#v", remove) _, err := conn.DeleteBucketTagging(&s3.DeleteBucketTaggingInput{ Bucket: aws.String(d.Get("bucket").(string)), }) if err != nil { return err } } if len(create) > 0 { log.Printf("[DEBUG] Creating tags: %#v", create) req := &s3.PutBucketTaggingInput{ Bucket: aws.String(d.Get("bucket").(string)), Tagging: &s3.Tagging{ TagSet: create, }, } _, err := conn.PutBucketTagging(req) if err != nil { return err } } } return nil }
func resourceContainerMetadataV2(d *schema.ResourceData) map[string]string { m := make(map[string]string) for key, val := range d.Get("metadata").(map[string]interface{}) { m[key] = val.(string) } return m }
// resourceAzureLocalNetworkConnectionRead does all the necessary API calls to // read the state of our local natwork from Azure. func resourceAzureLocalNetworkConnectionRead(d *schema.ResourceData, meta interface{}) error { azureClient := meta.(*Client) vnetClient := azureClient.vnetClient log.Println("[INFO] Fetching current network configuration from Azure.") netConf, err := vnetClient.GetVirtualNetworkConfiguration() if err != nil { return fmt.Errorf("Failed to get the current network configuration from Azure: %s", err) } var found bool name := d.Get("name").(string) // browsing for our network config: for _, lnet := range netConf.Configuration.LocalNetworkSites { if lnet.Name == name { found = true d.Set("vpn_gateway_address", lnet.VPNGatewayAddress) d.Set("address_space_prefixes", lnet.AddressSpace.AddressPrefix) break } } // remove the resource from the state of it has been deleted in the meantime: if !found { log.Println(fmt.Printf("[INFO] Azure local network '%s' has been deleted remotely. Removimg from Terraform.", name)) d.SetId("") } return nil }
func resourceFWRuleV1Read(d *schema.ResourceData, meta interface{}) error { log.Printf("[DEBUG] Retrieve information about firewall rule: %s", d.Id()) config := meta.(*Config) networkingClient, err := config.networkingV2Client(d.Get("region").(string)) if err != nil { return fmt.Errorf("Error creating OpenStack networking client: %s", err) } rule, err := rules.Get(networkingClient, d.Id()).Extract() if err != nil { return CheckDeleted(d, err, "FW rule") } d.Set("protocol", rule.Protocol) d.Set("action", rule.Action) d.Set("name", rule.Name) d.Set("description", rule.Description) d.Set("ip_version", rule.IPVersion) d.Set("source_ip_address", rule.SourceIPAddress) d.Set("destination_ip_address", rule.DestinationIPAddress) d.Set("source_port", rule.SourcePort) d.Set("destination_port", rule.DestinationPort) d.Set("enabled", rule.Enabled) return nil }
func resourceSqlDatabaseDelete(d *schema.ResourceData, meta interface{}) error { config := meta.(*Config) database_name := d.Get("name").(string) instance_name := d.Get("instance").(string) project := config.Project op, err := config.clientSqlAdmin.Databases.Delete(project, instance_name, database_name).Do() if err != nil { return fmt.Errorf("Error, failed to delete"+ "database %s in instance %s: %s", database_name, instance_name, err) } err = sqladminOperationWait(config, op, "Delete Database") if err != nil { return fmt.Errorf("Error, failure waiting for deletion of %s "+ "in %s: %s", database_name, instance_name, err) } return nil }
func resourceAwsSecurityGroupUpdate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).ec2conn sgRaw, _, err := SGStateRefreshFunc(conn, d.Id())() if err != nil { return err } if sgRaw == nil { d.SetId("") return nil } group := sgRaw.(*ec2.SecurityGroup) err = resourceAwsSecurityGroupUpdateRules(d, "ingress", meta, group) if err != nil { return err } if d.Get("vpc_id") != nil { err = resourceAwsSecurityGroupUpdateRules(d, "egress", meta, group) if err != nil { return err } } if err := setTags(conn, d); err != nil { return err } d.SetPartial("tags") return resourceAwsSecurityGroupRead(d, meta) }
func resourceAwsIamPolicyAttachmentCreate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).iamconn name := d.Get("name").(string) arn := d.Get("policy_arn").(string) users := expandStringList(d.Get("users").(*schema.Set).List()) roles := expandStringList(d.Get("roles").(*schema.Set).List()) groups := expandStringList(d.Get("groups").(*schema.Set).List()) if len(users) == 0 && len(roles) == 0 && len(groups) == 0 { return fmt.Errorf("[WARN] No Users, Roles, or Groups specified for IAM Policy Attachment %s", name) } else { var userErr, roleErr, groupErr error if users != nil { userErr = attachPolicyToUsers(conn, users, arn) } if roles != nil { roleErr = attachPolicyToRoles(conn, roles, arn) } if groups != nil { groupErr = attachPolicyToGroups(conn, groups, arn) } if userErr != nil || roleErr != nil || groupErr != nil { return composeErrors(fmt.Sprint("[WARN] Error attaching policy with IAM Policy Attachment ", name, ":"), userErr, roleErr, groupErr) } } d.SetId(d.Get("name").(string)) return resourceAwsIamPolicyAttachmentRead(d, meta) }
func resourceSqlDatabaseCreate(d *schema.ResourceData, meta interface{}) error { config := meta.(*Config) database_name := d.Get("name").(string) instance_name := d.Get("instance").(string) project := config.Project db := &sqladmin.Database{ Name: database_name, Instance: instance_name, } op, err := config.clientSqlAdmin.Databases.Insert(project, instance_name, db).Do() if err != nil { return fmt.Errorf("Error, failed to insert "+ "database %s into instance %s: %s", database_name, instance_name, err) } err = sqladminOperationWait(config, op, "Insert Database") if err != nil { return fmt.Errorf("Error, failure waiting for insertion of %s "+ "into %s: %s", database_name, instance_name, err) } return resourceSqlDatabaseRead(d, meta) }
func resourceLBMonitorV1Read(d *schema.ResourceData, meta interface{}) error { config := meta.(*Config) networkingClient, err := config.networkingV2Client(d.Get("region").(string)) if err != nil { return fmt.Errorf("Error creating OpenStack networking client: %s", err) } m, err := monitors.Get(networkingClient, d.Id()).Extract() if err != nil { return CheckDeleted(d, err, "LB monitor") } log.Printf("[DEBUG] Retreived OpenStack LB Monitor %s: %+v", d.Id(), m) d.Set("type", m.Type) d.Set("delay", m.Delay) d.Set("timeout", m.Timeout) d.Set("max_retries", m.MaxRetries) d.Set("tenant_id", m.TenantID) d.Set("url_path", m.URLPath) d.Set("http_method", m.HTTPMethod) d.Set("expected_codes", m.ExpectedCodes) d.Set("admin_state_up", strconv.FormatBool(m.AdminStateUp)) return nil }
func resourceAwsProxyProtocolPolicyRead(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) ports := []*string{} for ip := range backends { ipstr := strconv.Itoa(int(ip)) ports = append(ports, &ipstr) } d.Set("instance_ports", ports) d.Set("load_balancer", *elbname) return nil }
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 resourceAwsKinesisStreamRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).kinesisconn sn := d.Get("name").(string) state, err := readKinesisStreamState(conn, sn) if err != nil { if awsErr, ok := err.(awserr.Error); ok { if awsErr.Code() == "ResourceNotFoundException" { d.SetId("") return nil } return fmt.Errorf("[WARN] Error reading Kinesis Stream: \"%s\", code: \"%s\"", awsErr.Message(), awsErr.Code()) } return err } d.Set("arn", state.arn) d.Set("shard_count", state.shardCount) // set tags describeTagsOpts := &kinesis.ListTagsForStreamInput{ StreamName: aws.String(sn), } tagsResp, err := conn.ListTagsForStream(describeTagsOpts) if err != nil { log.Printf("[DEBUG] Error retrieving tags for Stream: %s. %s", sn, err) } else { d.Set("tags", tagsToMapKinesis(tagsResp.Tags)) } return nil }
func resourceAwsMainRouteTableAssociationCreate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).ec2conn vpcId := d.Get("vpc_id").(string) routeTableId := d.Get("route_table_id").(string) log.Printf("[INFO] Creating main route table association: %s => %s", vpcId, routeTableId) mainAssociation, err := findMainRouteTableAssociation(conn, vpcId) if err != nil { return err } resp, err := conn.ReplaceRouteTableAssociation(&ec2.ReplaceRouteTableAssociationInput{ AssociationId: mainAssociation.RouteTableAssociationId, RouteTableId: aws.String(routeTableId), }) if err != nil { return err } d.Set("original_route_table_id", mainAssociation.RouteTableId) d.SetId(*resp.NewAssociationId) log.Printf("[INFO] New main route table association ID: %s", d.Id()) return nil }
func getNetworkName(d *schema.ResourceData, meta interface{}, networkID string) (string, error) { config := meta.(*Config) networkingClient, err := config.networkingV2Client(d.Get("region").(string)) if err != nil { return "", fmt.Errorf("Error creating OpenStack network client: %s", err) } opts := networks.ListOpts{ID: networkID} pager := networks.List(networkingClient, opts) networkName := "" err = pager.EachPage(func(page pagination.Page) (bool, error) { networkList, err := networks.ExtractNetworks(page) if err != nil { return false, err } for _, n := range networkList { if n.ID == networkID { networkName = n.Name return false, nil } } return true, nil }) return networkName, err }
func getAwsAutoscalingPutLifecycleHookInput(d *schema.ResourceData) autoscaling.PutLifecycleHookInput { var params = autoscaling.PutLifecycleHookInput{ AutoScalingGroupName: aws.String(d.Get("autoscaling_group_name").(string)), LifecycleHookName: aws.String(d.Get("name").(string)), } if v, ok := d.GetOk("default_result"); ok { params.DefaultResult = aws.String(v.(string)) } if v, ok := d.GetOk("heartbeat_timeout"); ok { params.HeartbeatTimeout = aws.Int64(int64(v.(int))) } if v, ok := d.GetOk("lifecycle_transition"); ok { params.LifecycleTransition = aws.String(v.(string)) } if v, ok := d.GetOk("notification_metadata"); ok { params.NotificationMetadata = aws.String(v.(string)) } if v, ok := d.GetOk("notification_target_arn"); ok { params.NotificationTargetARN = aws.String(v.(string)) } if v, ok := d.GetOk("role_arn"); ok { params.RoleARN = aws.String(v.(string)) } return params }
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 resourceAwsAutoscalingLifecycleHookPut(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).autoscalingconn params := getAwsAutoscalingPutLifecycleHookInput(d) log.Printf("[DEBUG] AutoScaling PutLifecyleHook: %s", params) err := resource.Retry(5*time.Minute, func() error { _, err := conn.PutLifecycleHook(¶ms) if err != nil { if awsErr, ok := err.(awserr.Error); ok { if strings.Contains(awsErr.Message(), "Unable to publish test message to notification target") { return fmt.Errorf("[DEBUG] Retrying AWS AutoScaling Lifecycle Hook: %s", params) } } return resource.RetryError{Err: fmt.Errorf("Error putting lifecycle hook: %s", err)} } return nil }) if err != nil { return err } d.SetId(d.Get("name").(string)) return resourceAwsAutoscalingLifecycleHookRead(d, meta) }
func roleFromResourceData(d *schema.ResourceData) (*chefc.Role, error) { role := &chefc.Role{ Name: d.Get("name").(string), Description: d.Get("description").(string), ChefType: "role", } var err error err = json.Unmarshal( []byte(d.Get("default_attributes_json").(string)), &role.DefaultAttributes, ) if err != nil { return nil, fmt.Errorf("default_attributes_json: %s", err) } err = json.Unmarshal( []byte(d.Get("override_attributes_json").(string)), &role.OverrideAttributes, ) if err != nil { return nil, fmt.Errorf("override_attributes_json: %s", err) } runListI := d.Get("run_list").([]interface{}) role.RunList = make([]string, len(runListI)) for i, vI := range runListI { role.RunList[i] = vI.(string) } return role, nil }
func resourceLBVipV1Read(d *schema.ResourceData, meta interface{}) error { config := meta.(*Config) networkingClient, err := config.networkingV2Client(d.Get("region").(string)) if err != nil { return fmt.Errorf("Error creating OpenStack networking client: %s", err) } p, err := vips.Get(networkingClient, d.Id()).Extract() if err != nil { return CheckDeleted(d, err, "LB VIP") } log.Printf("[DEBUG] Retreived OpenStack LB VIP %s: %+v", d.Id(), p) d.Set("name", p.Name) d.Set("subnet_id", p.SubnetID) d.Set("protocol", p.Protocol) d.Set("port", p.ProtocolPort) d.Set("pool_id", p.PoolID) d.Set("port_id", p.PortID) d.Set("tenant_id", p.TenantID) d.Set("address", p.Address) d.Set("description", p.Description) d.Set("conn_limit", p.ConnLimit) d.Set("admin_state_up", p.AdminStateUp) return nil }
func resourceDynRecordDelete(d *schema.ResourceData, meta interface{}) error { mutex.Lock() defer mutex.Unlock() client := meta.(*dynect.ConvenientClient) record := &dynect.Record{ ID: d.Id(), Name: d.Get("name").(string), Zone: d.Get("zone").(string), FQDN: d.Get("fqdn").(string), Type: d.Get("type").(string), } log.Printf("[INFO] Deleting Dyn record: %s, %s", record.FQDN, record.ID) // delete the record err := client.DeleteRecord(record) if err != nil { return fmt.Errorf("Failed to delete Dyn record: %s", err) } // publish the zone err = client.PublishZone(record.Zone) if err != nil { return fmt.Errorf("Failed to publish Dyn zone: %s", err) } return nil }
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 resourceArmLocalNetworkGatewayCreate(d *schema.ResourceData, meta interface{}) error { lnetClient := meta.(*ArmClient).localNetConnClient name := d.Get("name").(string) location := d.Get("location").(string) resGroup := d.Get("resource_group_name").(string) ipAddress := d.Get("gateway_address").(string) // fetch the 'address_space_prefixes: prefixes := []string{} for _, pref := range d.Get("address_space").([]interface{}) { prefixes = append(prefixes, pref.(string)) } resp, err := lnetClient.CreateOrUpdate(resGroup, name, network.LocalNetworkGateway{ Name: &name, Location: &location, Properties: &network.LocalNetworkGatewayPropertiesFormat{ LocalNetworkAddressSpace: &network.AddressSpace{ AddressPrefixes: &prefixes, }, GatewayIPAddress: &ipAddress, }, }) if err != nil { return fmt.Errorf("Error creating Azure ARM Local Network Gateway '%s': %s", name, err) } d.SetId(*resp.ID) return resourceArmLocalNetworkGatewayRead(d, meta) }
func resourceAwsLBCookieStickinessPolicyDelete(d *schema.ResourceData, meta interface{}) error { elbconn := meta.(*AWSClient).elbconn lbName, _, policyName := resourceAwsLBCookieStickinessPolicyParseId(d.Id()) // Perversely, if we Set an empty list of PolicyNames, we detach the // policies attached to a listener, which is required to delete the // policy itself. setLoadBalancerOpts := &elb.SetLoadBalancerPoliciesOfListenerInput{ LoadBalancerName: aws.String(d.Get("load_balancer").(string)), LoadBalancerPort: aws.Int64(int64(d.Get("lb_port").(int))), PolicyNames: []*string{}, } if _, err := elbconn.SetLoadBalancerPoliciesOfListener(setLoadBalancerOpts); err != nil { return fmt.Errorf("Error removing LBCookieStickinessPolicy: %s", err) } request := &elb.DeleteLoadBalancerPolicyInput{ LoadBalancerName: aws.String(lbName), PolicyName: aws.String(policyName), } if _, err := elbconn.DeleteLoadBalancerPolicy(request); err != nil { return fmt.Errorf("Error deleting LB stickiness policy %s: %s", d.Id(), err) } return nil }
func resourceAwsNetworkAclRuleRead(d *schema.ResourceData, meta interface{}) error { resp, err := findNetworkAclRule(d, meta) if err != nil { return err } d.Set("rule_number", resp.RuleNumber) d.Set("cidr_block", resp.CidrBlock) d.Set("egress", resp.Egress) if resp.IcmpTypeCode != nil { d.Set("icmp_code", resp.IcmpTypeCode.Code) d.Set("icmp_type", resp.IcmpTypeCode.Type) } if resp.PortRange != nil { d.Set("from_port", resp.PortRange.From) d.Set("to_port", resp.PortRange.To) } d.Set("rule_action", resp.RuleAction) p, protocolErr := strconv.Atoi(*resp.Protocol) log.Printf("[INFO] Converting the protocol %v", p) if protocolErr == nil { var ok bool protocol, ok := protocolStrings(protocolIntegers())[p] if !ok { return fmt.Errorf("Invalid Protocol %s for rule %#v", *resp.Protocol, d.Get("rule_number").(int)) } log.Printf("[INFO] Transformed Protocol %s back into %s", *resp.Protocol, protocol) d.Set("protocol", protocol) } return nil }
func resourceAwsKinesisStreamDelete(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).kinesisconn sn := d.Get("name").(string) _, err := conn.DeleteStream(&kinesis.DeleteStreamInput{ StreamName: aws.String(sn), }) if err != nil { return err } stateConf := &resource.StateChangeConf{ Pending: []string{"DELETING"}, Target: "DESTROYED", Refresh: streamStateRefreshFunc(conn, sn), Timeout: 5 * time.Minute, Delay: 10 * time.Second, MinTimeout: 3 * time.Second, } _, err = stateConf.WaitForState() if err != nil { return fmt.Errorf( "Error waiting for Stream (%s) to be destroyed: %s", sn, err) } d.SetId("") return nil }
func resourceComputeHttpHealthCheckRead(d *schema.ResourceData, meta interface{}) error { config := meta.(*Config) hchk, err := config.clientCompute.HttpHealthChecks.Get( config.Project, d.Id()).Do() if err != nil { if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == 404 { // The resource doesn't exist anymore log.Printf("[WARN] Removing HTTP Health Check %q because it's gone", d.Get("name").(string)) d.SetId("") return nil } return fmt.Errorf("Error reading HttpHealthCheck: %s", err) } d.Set("host", hchk.Host) d.Set("request_path", hchk.RequestPath) d.Set("check_interval_sec", hchk.CheckIntervalSec) d.Set("health_threshold", hchk.HealthyThreshold) d.Set("port", hchk.Port) d.Set("timeout_sec", hchk.TimeoutSec) d.Set("unhealthy_threshold", hchk.UnhealthyThreshold) d.Set("self_link", hchk.SelfLink) return nil }
// setTags is a helper to set the tags for a resource. It expects the // tags field to be named "tag" func setAutoscalingTags(conn *autoscaling.AutoScaling, d *schema.ResourceData) error { if d.HasChange("tag") { oraw, nraw := d.GetChange("tag") o := setToMapByKey(oraw.(*schema.Set), "key") n := setToMapByKey(nraw.(*schema.Set), "key") resourceID := d.Get("name").(string) c, r := diffAutoscalingTags( autoscalingTagsFromMap(o, resourceID), autoscalingTagsFromMap(n, resourceID), resourceID) create := autoscaling.CreateOrUpdateTagsInput{ Tags: c, } remove := autoscaling.DeleteTagsInput{ Tags: r, } // Set tags if len(r) > 0 { log.Printf("[DEBUG] Removing autoscaling tags: %#v", r) if _, err := conn.DeleteTags(&remove); err != nil { return err } } if len(c) > 0 { log.Printf("[DEBUG] Creating autoscaling tags: %#v", c) if _, err := conn.CreateOrUpdateTags(&create); err != nil { return err } } } return nil }