func resourceAwsInternetGatewayRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).ec2conn igRaw, _, err := IGStateRefreshFunc(conn, d.Id())() if err != nil { return err } if igRaw == nil { // Seems we have lost our internet gateway d.SetId("") return nil } ig := igRaw.(*ec2.InternetGateway) if len(ig.Attachments) == 0 { // Gateway exists but not attached to the VPC d.Set("vpc_id", "") } else { d.Set("vpc_id", ig.Attachments[0].VpcId) } d.Set("tags", tagsToMap(ig.Tags)) return nil }
func associateFloatingIPsToInstance(computeClient *gophercloud.ServiceClient, d *schema.ResourceData) error { floatingIP := d.Get("floating_ip").(string) rawNetworks := d.Get("network").([]interface{}) instanceID := d.Id() if floatingIP != "" { if err := associateFloatingIPToInstance(computeClient, floatingIP, instanceID, ""); err != nil { return err } } else { for _, raw := range rawNetworks { if raw == nil { continue } rawMap := raw.(map[string]interface{}) if rawMap["floating_ip"].(string) != "" { floatingIP := rawMap["floating_ip"].(string) fixedIP := rawMap["fixed_ip_v4"].(string) if err := associateFloatingIPToInstance(computeClient, floatingIP, instanceID, fixedIP); err != nil { return err } } } } return nil }
// resourceAwsLambdaEventSourceMappingUpdate maps to: // UpdateEventSourceMapping in the API / SDK func resourceAwsLambdaEventSourceMappingUpdate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).lambdaconn log.Printf("[DEBUG] Updating Lambda event source mapping: %s", d.Id()) params := &lambda.UpdateEventSourceMappingInput{ UUID: aws.String(d.Id()), BatchSize: aws.Int64(int64(d.Get("batch_size").(int))), FunctionName: aws.String(d.Get("function_name").(string)), Enabled: aws.Bool(d.Get("enabled").(bool)), } err := resource.Retry(1*time.Minute, func() *resource.RetryError { _, err := conn.UpdateEventSourceMapping(params) if err != nil { if awserr, ok := err.(awserr.Error); ok { if awserr.Code() == "InvalidParameterValueException" { return resource.RetryableError(awserr) } } return resource.NonRetryableError(err) } return nil }) if err != nil { return fmt.Errorf("Error updating Lambda event source mapping: %s", err) } return resourceAwsLambdaEventSourceMappingRead(d, meta) }
func resourceComputeTargetPoolDelete(d *schema.ResourceData, meta interface{}) error { config := meta.(*Config) region, err := getRegion(d, config) if err != nil { return err } project, err := getProject(d, config) if err != nil { return err } // Delete the TargetPool op, err := config.clientCompute.TargetPools.Delete( project, region, d.Id()).Do() if err != nil { return fmt.Errorf("Error deleting TargetPool: %s", err) } err = computeOperationWaitRegion(config, op, region, "Deleting Target Pool") if err != nil { return err } d.SetId("") return nil }
func getVolumeAttachments(computeClient *gophercloud.ServiceClient, d *schema.ResourceData) error { var attachments []volumeattach.VolumeAttachment err := volumeattach.List(computeClient, d.Id()).EachPage(func(page pagination.Page) (bool, error) { actual, err := volumeattach.ExtractVolumeAttachments(page) if err != nil { return false, err } attachments = actual return true, nil }) if err != nil { return err } vols := make([]map[string]interface{}, len(attachments)) for i, attachment := range attachments { vols[i] = make(map[string]interface{}) vols[i]["id"] = attachment.ID vols[i]["volume_id"] = attachment.VolumeID vols[i]["device"] = attachment.Device } log.Printf("[INFO] Volume attachments: %v", vols) d.Set("volume", vols) return nil }
func resourceComputeTargetPoolRead(d *schema.ResourceData, meta interface{}) error { config := meta.(*Config) region, err := getRegion(d, config) if err != nil { return err } project, err := getProject(d, config) if err != nil { return err } tpool, err := config.clientCompute.TargetPools.Get( project, region, d.Id()).Do() if err != nil { if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == 404 { log.Printf("[WARN] Removing Target Pool %q because it's gone", d.Get("name").(string)) // The resource doesn't exist anymore d.SetId("") return nil } return fmt.Errorf("Error reading TargetPool: %s", err) } d.Set("self_link", tpool.SelfLink) return nil }
func resourceCloudStackInstanceRead(d *schema.ResourceData, meta interface{}) error { cs := meta.(*cloudstack.CloudStackClient) // Get the virtual machine details vm, count, err := cs.VirtualMachine.GetVirtualMachineByID(d.Id()) if err != nil { if count == 0 { log.Printf("[DEBUG] Instance %s does no longer exist", d.Get("name").(string)) d.SetId("") return nil } return err } // Update the config d.Set("name", vm.Name) d.Set("display_name", vm.Displayname) d.Set("ipaddress", vm.Nic[0].Ipaddress) //NB cloudstack sometimes sends back the wrong keypair name, so dont update it setValueOrID(d, "network", vm.Nic[0].Networkname, vm.Nic[0].Networkid) setValueOrID(d, "service_offering", vm.Serviceofferingname, vm.Serviceofferingid) setValueOrID(d, "template", vm.Templatename, vm.Templateid) setValueOrID(d, "project", vm.Project, vm.Projectid) setValueOrID(d, "zone", vm.Zonename, vm.Zoneid) return nil }
func resourceAwsInternetGatewayDelete(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).ec2conn // Detach if it is attached if err := resourceAwsInternetGatewayDetach(d, meta); err != nil { return err } log.Printf("[INFO] Deleting Internet Gateway: %s", d.Id()) return resource.Retry(5*time.Minute, func() error { _, err := conn.DeleteInternetGateway(&ec2.DeleteInternetGatewayInput{ InternetGatewayId: aws.String(d.Id()), }) if err == nil { return nil } ec2err, ok := err.(awserr.Error) if !ok { return err } switch ec2err.Code() { case "InvalidInternetGatewayID.NotFound": return nil case "DependencyViolation": return err // retry } return resource.RetryError{Err: err} }) }
func resourceAwsIamAccessKeyRead(d *schema.ResourceData, meta interface{}) error { iamconn := meta.(*AWSClient).iamconn request := &iam.ListAccessKeysInput{ UserName: aws.String(d.Get("user").(string)), } getResp, err := iamconn.ListAccessKeys(request) if err != nil { if iamerr, ok := err.(awserr.Error); ok && iamerr.Code() == "NoSuchEntity" { // XXX TEST ME // the user does not exist, so the key can't exist. d.SetId("") return nil } return fmt.Errorf("Error reading IAM acces key: %s", err) } for _, key := range getResp.AccessKeyMetadata { if key.AccessKeyID != nil && *key.AccessKeyID == d.Id() { return resourceAwsIamAccessKeyReadResult(d, key) } } // Guess the key isn't around anymore. d.SetId("") return nil }
func resourceComputeDiskDelete(d *schema.ResourceData, meta interface{}) error { config := meta.(*Config) // Delete the disk op, err := config.clientCompute.Disks.Delete( config.Project, d.Get("zone").(string), d.Id()).Do() if err != nil { return fmt.Errorf("Error deleting disk: %s", err) } // Wait for the operation to complete w := &OperationWaiter{ Service: config.clientCompute, Op: op, Project: config.Project, Zone: d.Get("zone").(string), Type: OperationWaitZone, } state := w.Conf() state.Timeout = 2 * time.Minute state.MinTimeout = 1 * time.Second opRaw, err := state.WaitForState() if err != nil { return fmt.Errorf("Error waiting for disk to delete: %s", err) } op = opRaw.(*compute.Operation) if op.Error != nil { // Return the error return OperationError(*op.Error) } d.SetId("") return nil }
func getAwsAutoscalingGroup( d *schema.ResourceData, meta interface{}) (*autoscaling.Group, error) { conn := meta.(*AWSClient).autoscalingconn describeOpts := autoscaling.DescribeAutoScalingGroupsInput{ AutoScalingGroupNames: []*string{aws.String(d.Id())}, } log.Printf("[DEBUG] AutoScaling Group describe configuration: %#v", describeOpts) describeGroups, err := conn.DescribeAutoScalingGroups(&describeOpts) if err != nil { autoscalingerr, ok := err.(awserr.Error) if ok && autoscalingerr.Code() == "InvalidGroup.NotFound" { d.SetId("") return nil, nil } return nil, fmt.Errorf("Error retrieving AutoScaling groups: %s", err) } // Search for the autoscaling group for idx, asc := range describeGroups.AutoScalingGroups { if *asc.AutoScalingGroupName == d.Id() { return describeGroups.AutoScalingGroups[idx], nil } } // ASG not found d.SetId("") return nil, nil }
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 resourceAwsApiGatewayMethodDelete(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).apigateway log.Printf("[DEBUG] Deleting API Gateway Method: %s", d.Id()) return resource.Retry(5*time.Minute, func() *resource.RetryError { _, err := conn.DeleteMethod(&apigateway.DeleteMethodInput{ HttpMethod: aws.String(d.Get("http_method").(string)), ResourceId: aws.String(d.Get("resource_id").(string)), RestApiId: aws.String(d.Get("rest_api_id").(string)), }) if err == nil { return nil } apigatewayErr, ok := err.(awserr.Error) if apigatewayErr.Code() == "NotFoundException" { return nil } if !ok { return resource.NonRetryableError(err) } return resource.NonRetryableError(err) }) }
func resourceAwsApiGatewayMethodUpdate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).apigateway log.Printf("[DEBUG] Reading API Gateway Method %s", d.Id()) operations := make([]*apigateway.PatchOperation, 0) if d.HasChange("resource_id") { operations = append(operations, &apigateway.PatchOperation{ Op: aws.String("replace"), Path: aws.String("/resourceId"), Value: aws.String(d.Get("resource_id").(string)), }) } if d.HasChange("request_models") { operations = append(operations, expandApiGatewayRequestResponseModelOperations(d, "request_models", "requestModels")...) } method, err := conn.UpdateMethod(&apigateway.UpdateMethodInput{ HttpMethod: aws.String(d.Get("http_method").(string)), ResourceId: aws.String(d.Get("resource_id").(string)), RestApiId: aws.String(d.Get("rest_api_id").(string)), PatchOperations: operations, }) if err != nil { return err } log.Printf("[DEBUG] Received API Gateway Method: %s", method) return resourceAwsApiGatewayMethodRead(d, meta) }
// setTags is a helper to set the tags for a resource. It expects the // tags field to be named "tags" func setTagsR53(conn *route53.Route53, d *schema.ResourceData, resourceType string) error { if d.HasChange("tags") { oraw, nraw := d.GetChange("tags") o := oraw.(map[string]interface{}) n := nraw.(map[string]interface{}) create, remove := diffTagsR53(tagsFromMapR53(o), tagsFromMapR53(n)) // Set tags r := make([]*string, len(remove)) for i, t := range remove { r[i] = t.Key } log.Printf("[DEBUG] Changing tags: \n\tadding: %#v\n\tremoving:%#v", create, remove) req := &route53.ChangeTagsForResourceInput{ ResourceID: aws.String(d.Id()), ResourceType: aws.String(resourceType), } if len(create) > 0 { req.AddTags = create } if len(r) > 0 { req.RemoveTagKeys = r } _, err := conn.ChangeTagsForResource(req) if err != nil { return err } } return nil }
func resourceArmNetworkSecurityGroupRead(d *schema.ResourceData, meta interface{}) error { secGroupClient := meta.(*ArmClient).secGroupClient id, err := parseAzureResourceID(d.Id()) if err != nil { return err } resGroup := id.ResourceGroup name := id.Path["networkSecurityGroups"] resp, err := secGroupClient.Get(resGroup, name, "") if resp.StatusCode == http.StatusNotFound { d.SetId("") return nil } if err != nil { return fmt.Errorf("Error making Read request on Azure Network Security Group %s: %s", name, err) } if resp.Properties.SecurityRules != nil { d.Set("security_rule", flattenNetworkSecurityRules(resp.Properties.SecurityRules)) } flattenAndSetTags(d, resp.Tags) return nil }
func resourceLBMemberV1Delete(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) } err = members.Delete(networkingClient, d.Id()).ExtractErr() if err != nil { CheckDeleted(d, err, "LB member") } stateConf := &resource.StateChangeConf{ Pending: []string{"ACTIVE", "PENDING_DELETE"}, Target: []string{"DELETED"}, Refresh: waitForLBMemberDelete(networkingClient, d.Id()), Timeout: 2 * time.Minute, Delay: 5 * time.Second, MinTimeout: 3 * time.Second, } _, err = stateConf.WaitForState() if err != nil { return fmt.Errorf("Error deleting OpenStack LB member: %s", err) } d.SetId("") return nil }
func resourceAwsAutoscalingGroupDrain(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).autoscalingconn // First, set the capacity to zero so the group will drain log.Printf("[DEBUG] Reducing autoscaling group capacity to zero") opts := autoscaling.UpdateAutoScalingGroupInput{ AutoScalingGroupName: aws.String(d.Id()), DesiredCapacity: aws.Long(0), MinSize: aws.Long(0), MaxSize: aws.Long(0), } if _, err := conn.UpdateAutoScalingGroup(&opts); err != nil { return fmt.Errorf("Error setting capacity to zero to drain: %s", err) } // Next, wait for the autoscale group to drain log.Printf("[DEBUG] Waiting for group to have zero instances") return resource.Retry(10*time.Minute, func() error { g, err := getAwsAutoscalingGroup(d, meta) if err != nil { return resource.RetryError{Err: err} } if g == nil { return nil } if len(g.Instances) == 0 { return nil } return fmt.Errorf("group still has %d instances", len(g.Instances)) }) }
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 }
// resourceAwsLambdaEventSourceMappingRead maps to: // GetEventSourceMapping in the API / SDK func resourceAwsLambdaEventSourceMappingRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).lambdaconn log.Printf("[DEBUG] Fetching Lambda event source mapping: %s", d.Id()) params := &lambda.GetEventSourceMappingInput{ UUID: aws.String(d.Id()), } eventSourceMappingConfiguration, err := conn.GetEventSourceMapping(params) if err != nil { return err } d.Set("batch_size", eventSourceMappingConfiguration.BatchSize) d.Set("event_source_arn", eventSourceMappingConfiguration.EventSourceArn) d.Set("function_arn", eventSourceMappingConfiguration.FunctionArn) d.Set("last_modified", eventSourceMappingConfiguration.LastModified) d.Set("last_processing_result", eventSourceMappingConfiguration.LastProcessingResult) d.Set("state", eventSourceMappingConfiguration.State) d.Set("state_transition_reason", eventSourceMappingConfiguration.StateTransitionReason) d.Set("uuid", eventSourceMappingConfiguration.UUID) return nil }
func resourceAwsApiGatewayMethodCreate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).apigateway models := make(map[string]string) for k, v := range d.Get("request_models").(map[string]interface{}) { models[k] = v.(string) } parameters := make(map[string]bool) if parameterData, ok := d.GetOk("request_parameters"); ok { params := parameterData.(*schema.Set).List() for k := range params { parameters[params[k].(string)] = true } } _, err := conn.PutMethod(&apigateway.PutMethodInput{ AuthorizationType: aws.String(d.Get("authorization").(string)), HttpMethod: aws.String(d.Get("http_method").(string)), ResourceId: aws.String(d.Get("resource_id").(string)), RestApiId: aws.String(d.Get("rest_api_id").(string)), RequestModels: aws.StringMap(models), // TODO implement once [GH-2143](https://github.com/hashicorp/terraform/issues/2143) has been implemented RequestParameters: nil, ApiKeyRequired: aws.Bool(d.Get("api_key_required").(bool)), }) if err != nil { return fmt.Errorf("Error creating API Gateway Method: %s", err) } d.SetId(fmt.Sprintf("agm-%s-%s-%s", d.Get("rest_api_id").(string), d.Get("resource_id").(string), d.Get("http_method").(string))) log.Printf("[DEBUG] API Gateway Method ID: %s", d.Id()) return nil }
func resourceArmNetworkSecurityRuleRead(d *schema.ResourceData, meta interface{}) error { secRuleClient := meta.(*ArmClient).secRuleClient id, err := parseAzureResourceID(d.Id()) if err != nil { return err } resGroup := id.ResourceGroup networkSGName := id.Path["networkSecurityGroups"] sgRuleName := id.Path["securityRules"] resp, err := secRuleClient.Get(resGroup, networkSGName, sgRuleName) if err != nil { if resp.StatusCode == http.StatusNotFound { d.SetId("") return nil } return fmt.Errorf("Error making Read request on Azure Network Security Rule %s: %s", sgRuleName, err) } d.Set("resource_group_name", resGroup) d.Set("access", resp.Properties.Access) d.Set("destination_address_prefix", resp.Properties.DestinationAddressPrefix) d.Set("destination_port_range", resp.Properties.DestinationPortRange) d.Set("direction", resp.Properties.Direction) d.Set("description", resp.Properties.Description) d.Set("name", resp.Name) d.Set("priority", resp.Properties.Priority) d.Set("protocol", resp.Properties.Protocol) d.Set("source_address_prefix", resp.Properties.SourceAddressPrefix) d.Set("source_port_range", resp.Properties.SourcePortRange) return nil }
func resourceAwsKeyPairRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).ec2conn req := &ec2.DescribeKeyPairsInput{ KeyNames: []*string{aws.String(d.Id())}, } resp, err := conn.DescribeKeyPairs(req) if err != nil { awsErr, ok := err.(awserr.Error) if ok && awsErr.Code() == "InvalidKeyPair.NotFound" { d.SetId("") return nil } return fmt.Errorf("Error retrieving KeyPair: %s", err) } for _, keyPair := range resp.KeyPairs { if *keyPair.KeyName == d.Id() { d.Set("key_name", keyPair.KeyName) d.Set("fingerprint", keyPair.KeyFingerprint) return nil } } return fmt.Errorf("Unable to find key pair within: %#v", resp.KeyPairs) }
func resourceComputeServerGroupV2Read(d *schema.ResourceData, meta interface{}) error { config := meta.(*Config) computeClient, err := config.computeV2Client(d.Get("region").(string)) if err != nil { return fmt.Errorf("Error creating OpenStack compute client: %s", err) } sg, err := servergroups.Get(computeClient, d.Id()).Extract() if err != nil { return CheckDeleted(d, err, "server group") } log.Printf("[DEBUG] Retrieved ServerGroup %s: %+v", d.Id(), sg) // Set the name d.Set("name", sg.Name) // Set the policies policies := []string{} for _, p := range sg.Policies { policies = append(policies, p) } d.Set("policies", policies) // Set the members members := []string{} for _, m := range sg.Members { members = append(members, m) } d.Set("members", members) return nil }
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 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 resourceLBMonitorV1Read(d *schema.ResourceData, meta interface{}) error { config := meta.(*Config) networkingClient, err := config.networkingV2Client(GetRegion(d)) 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] Retrieved 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)) d.Set("region", GetRegion(d)) return nil }
// resourceAwsDbInstanceRetrieve fetches DBInstance information from the AWS // API. It returns an error if there is a communication problem or unexpected // error with AWS. When the DBInstance is not found, it returns no error and a // nil pointer. func resourceAwsDbInstanceRetrieve( d *schema.ResourceData, meta interface{}) (*rds.DBInstance, error) { conn := meta.(*AWSClient).rdsconn opts := rds.DescribeDBInstancesInput{ DBInstanceIdentifier: aws.String(d.Id()), } log.Printf("[DEBUG] DB Instance describe configuration: %#v", opts) resp, err := conn.DescribeDBInstances(&opts) if err != nil { dbinstanceerr, ok := err.(awserr.Error) if ok && dbinstanceerr.Code() == "DBInstanceNotFound" { return nil, nil } return nil, fmt.Errorf("Error retrieving DB Instances: %s", err) } if len(resp.DBInstances) != 1 || *resp.DBInstances[0].DBInstanceIdentifier != d.Id() { if err != nil { return nil, nil } } return resp.DBInstances[0], nil }
func resourceListenerV2Read(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) } listener, err := listeners.Get(networkingClient, d.Id()).Extract() if err != nil { return CheckDeleted(d, err, "LBV2 listener") } log.Printf("[DEBUG] Retrieved OpenStack LBaaSV2 listener %s: %+v", d.Id(), listener) d.Set("id", listener.ID) d.Set("name", listener.Name) d.Set("protocol", listener.Protocol) d.Set("tenant_id", listener.TenantID) d.Set("description", listener.Description) d.Set("protocol_port", listener.ProtocolPort) d.Set("admin_state_up", listener.AdminStateUp) d.Set("default_pool_id", listener.DefaultPoolID) d.Set("connection_limit", listener.ConnLimit) d.Set("sni_container_refs", listener.SniContainerRefs) d.Set("default_tls_container_ref", listener.DefaultTlsContainerRef) return nil }
func resourceCloudStackNICRead(d *schema.ResourceData, meta interface{}) error { cs := meta.(*cloudstack.CloudStackClient) // Get the virtual machine details vm, count, err := cs.VirtualMachine.GetVirtualMachineByName(d.Get("virtual_machine").(string)) if err != nil { if count == 0 { log.Printf("[DEBUG] Instance %s does no longer exist", d.Get("virtual_machine").(string)) d.SetId("") return nil } else { return err } } // Read NIC info found := false for _, n := range vm.Nic { if n.Id == d.Id() { d.Set("ipaddress", n.Ipaddress) setValueOrID(d, "network", n.Networkname, n.Networkid) setValueOrID(d, "virtual_machine", vm.Name, vm.Id) found = true break } } if !found { log.Printf("[DEBUG] NIC for network %s does no longer exist", d.Get("network").(string)) d.SetId("") } return nil }