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 resourceAwsS3BucketObjectRead(d *schema.ResourceData, meta interface{}) error { s3conn := meta.(*AWSClient).s3conn bucket := d.Get("bucket").(string) key := d.Get("key").(string) etag := d.Get("etag").(string) resp, err := s3conn.HeadObject( &s3.HeadObjectInput{ Bucket: aws.String(bucket), Key: aws.String(key), IfMatch: aws.String(etag), }) if err != nil { // If S3 returns a 404 Request Failure, mark the object as destroyed if awsErr, ok := err.(awserr.RequestFailure); ok && awsErr.StatusCode() == 404 { d.SetId("") log.Printf("[WARN] Error Reading Object (%s), object not found (HTTP status 404)", key) return nil } return err } d.Set("cache_control", resp.CacheControl) d.Set("content_disposition", resp.ContentDisposition) d.Set("content_encoding", resp.ContentEncoding) d.Set("content_language", resp.ContentLanguage) d.Set("content_type", resp.ContentType) d.Set("version_id", resp.VersionId) log.Printf("[DEBUG] Reading S3 Bucket Object meta: %s", resp) return nil }
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 }
// resourceAzureSecurityGroupRuleExists does all the necessary API calls to // check for the existence of the network security group rule on Azure. func resourceAzureSecurityGroupRuleExists(d *schema.ResourceData, meta interface{}) (bool, error) { secGroupClient := meta.(*Client).secGroupClient secGroupName := d.Get("security_group_name").(string) // get info on the network security group and search for our rule: log.Println("[INFO] Sending network security group rule query for existence check to Azure.") secgroup, err := secGroupClient.GetNetworkSecurityGroup(secGroupName) if err != nil { if !management.IsResourceNotFoundError(err) { return false, fmt.Errorf("Error issuing network security group rules query: %s", err) } else { // it meants that the network security group this rule belonged to has // been deleted; so we must remove this resource from the schema: d.SetId("") return false, nil } } // try and find our security group rule: name := d.Get("name").(string) for _, rule := range secgroup.Rules { if rule.Name == name { return true, nil } } // if here; it means the resource has been deleted in the // meantime and must be removed from the schema: d.SetId("") return false, 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 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 resourceComputeProjectMetadataRead(d *schema.ResourceData, meta interface{}) error { config := meta.(*Config) // Load project service log.Printf("[DEBUG] Loading project service: %s", config.Project) project, err := config.clientCompute.Projects.Get(config.Project).Do() if err != nil { return fmt.Errorf("Error loading project '%s': %s", config.Project, err) } md := project.CommonInstanceMetadata newMD := make(map[string]interface{}) for _, kv := range md.Items { newMD[kv.Key] = kv.Value } if err = d.Set("metadata", newMD); err != nil { return fmt.Errorf("Error setting metadata: %s", err) } d.SetId("common_metadata") return nil }
// resourceAzureStorageBlobCreate does all the necessary API calls to // create the storage blob on Azure. func resourceAzureStorageBlobCreate(d *schema.ResourceData, meta interface{}) error { azureClient := meta.(*Client) storName := d.Get("storage_service_name").(string) blobClient, err := azureClient.getStorageServiceBlobClient(storName) if err != nil { return err } log.Println("[INFO] Issuing create on Azure storage blob.") name := d.Get("name").(string) blobType := d.Get("type").(string) cont := d.Get("storage_container_name").(string) switch blobType { case "BlockBlob": err = blobClient.CreateBlockBlob(cont, name) case "PageBlob": size := int64(d.Get("size").(int)) err = blobClient.PutPageBlob(cont, name, size, map[string]string{}) default: err = fmt.Errorf("Invalid blob type specified; see parameter desciptions for more info.") } if err != nil { return fmt.Errorf("Error creating storage blob on Azure: %s", err) } d.SetId(name) return resourceAzureStorageBlobRead(d, meta) }
func resourceAwsKeyPairCreate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).ec2conn var keyName string if v, ok := d.GetOk("key_name"); ok { keyName = v.(string) } else if v, ok := d.GetOk("key_name_prefix"); ok { keyName = resource.PrefixedUniqueId(v.(string)) } else { keyName = resource.UniqueId() } publicKey := d.Get("public_key").(string) req := &ec2.ImportKeyPairInput{ KeyName: aws.String(keyName), PublicKeyMaterial: []byte(publicKey), } resp, err := conn.ImportKeyPair(req) if err != nil { return fmt.Errorf("Error import KeyPair: %s", err) } d.SetId(*resp.KeyName) return nil }
func resourceVSphereVirtualDiskDelete(d *schema.ResourceData, meta interface{}) error { client := meta.(*govmomi.Client) vDisk := virtualDisk{} if v, ok := d.GetOk("vmdk_path"); ok { vDisk.vmdkPath = v.(string) } if v, ok := d.GetOk("datastore"); ok { vDisk.datastore = v.(string) } dc, err := getDatacenter(client, d.Get("datacenter").(string)) if err != nil { return err } diskPath := fmt.Sprintf("[%v] %v", vDisk.datastore, vDisk.vmdkPath) virtualDiskManager := object.NewVirtualDiskManager(client.Client) task, err := virtualDiskManager.DeleteVirtualDisk(context.TODO(), diskPath, dc) if err != nil { return err } _, err = task.WaitForResult(context.TODO(), nil) if err != nil { log.Printf("[INFO] Failed to delete disk: %v", err) return err } log.Printf("[INFO] Deleted disk: %v", diskPath) 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 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 resourceSqlDatabaseRead(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, err := config.clientSqlAdmin.Databases.Get(project, instance_name, database_name).Do() if err != nil { if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == 404 { log.Printf("[WARN] Removing SQL Database %q because it's gone", d.Get("name").(string)) // The resource doesn't exist anymore d.SetId("") return nil } return fmt.Errorf("Error, failed to get"+ "database %s in instance %s: %s", database_name, instance_name, err) } d.Set("self_link", db.SelfLink) d.SetId(instance_name + ":" + database_name) 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 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 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 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 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 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 }
// resourceAzureStorageBlobExists does all the necessary API calls to // check for the existence of the blob on Azure. func resourceAzureStorageBlobExists(d *schema.ResourceData, meta interface{}) (bool, error) { azureClient := meta.(*Client) storName := d.Get("storage_service_name").(string) blobClient, err := azureClient.getStorageServiceBlobClient(storName) if err != nil { return false, err } log.Println("[INFO] Querying Azure for storage blob's existence.") name := d.Get("name").(string) cont := d.Get("storage_container_name").(string) exists, err := blobClient.BlobExists(cont, name) if err != nil { return false, fmt.Errorf("Error whilst checking for Azure storage blob's existence: %s", err) } // if not found; it means it was deleted in the meantime and // we must remove it from the schema. if !exists { d.SetId("") } return exists, nil }
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 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 resourceComputeInstanceV2Delete(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) } err = servers.Delete(computeClient, d.Id()).ExtractErr() if err != nil { return fmt.Errorf("Error deleting OpenStack server: %s", err) } // Wait for the instance to delete before moving on. log.Printf("[DEBUG] Waiting for instance (%s) to delete", d.Id()) stateConf := &resource.StateChangeConf{ Pending: []string{"ACTIVE"}, Target: []string{"DELETED"}, Refresh: ServerV2StateRefreshFunc(computeClient, d.Id()), Timeout: 30 * time.Minute, Delay: 10 * time.Second, MinTimeout: 3 * time.Second, } _, err = stateConf.WaitForState() if err != nil { return fmt.Errorf( "Error waiting for instance (%s) to delete: %s", d.Id(), err) } d.SetId("") 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 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 resourceAwsElasticacheClusterDelete(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).elasticacheconn req := &elasticache.DeleteCacheClusterInput{ CacheClusterId: aws.String(d.Id()), } _, err := conn.DeleteCacheCluster(req) if err != nil { return err } log.Printf("[DEBUG] Waiting for deletion: %v", d.Id()) stateConf := &resource.StateChangeConf{ Pending: []string{"creating", "available", "deleting", "incompatible-parameters", "incompatible-network", "restore-failed"}, Target: "", Refresh: cacheClusterStateRefreshFunc(conn, d.Id(), "", []string{}), Timeout: 10 * time.Minute, Delay: 10 * time.Second, MinTimeout: 3 * time.Second, } _, sterr := stateConf.WaitForState() if sterr != nil { return fmt.Errorf("Error waiting for elasticache (%s) to delete: %s", d.Id(), sterr) } d.SetId("") return nil }
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 resourceNetworkFloatingIPV2Create(d *schema.ResourceData, meta interface{}) error { config := meta.(*Config) networkClient, err := config.networkingV2Client(d.Get("region").(string)) if err != nil { return fmt.Errorf("Error creating OpenStack network client: %s", err) } poolID, err := getNetworkID(d, meta, d.Get("pool").(string)) if err != nil { return fmt.Errorf("Error retrieving floating IP pool name: %s", err) } if len(poolID) == 0 { return fmt.Errorf("No network found with name: %s", d.Get("pool").(string)) } createOpts := floatingips.CreateOpts{ FloatingNetworkID: poolID, PortID: d.Get("port_id").(string), } log.Printf("[DEBUG] Create Options: %#v", createOpts) floatingIP, err := floatingips.Create(networkClient, createOpts).Extract() if err != nil { return fmt.Errorf("Error allocating floating IP: %s", err) } d.SetId(floatingIP.ID) return resourceNetworkFloatingIPV2Read(d, meta) }
func resourceAwsS3BucketPolicyPut(d *schema.ResourceData, meta interface{}) error { s3conn := meta.(*AWSClient).s3conn bucket := d.Get("bucket").(string) policy := d.Get("policy").(string) d.SetId(bucket) log.Printf("[DEBUG] S3 bucket: %s, put policy: %s", bucket, policy) params := &s3.PutBucketPolicyInput{ Bucket: aws.String(bucket), Policy: aws.String(policy), } err := resource.Retry(1*time.Minute, func() *resource.RetryError { if _, err := s3conn.PutBucketPolicy(params); err != nil { if awserr, ok := err.(awserr.Error); ok { if awserr.Code() == "MalformedPolicy" { return resource.RetryableError(awserr) } } return resource.NonRetryableError(err) } return nil }) if err != nil { return fmt.Errorf("Error putting S3 policy: %s", err) } 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 }