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 }
// 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 resourceAwsIamAccessKeyCreate(d *schema.ResourceData, meta interface{}) error { iamconn := meta.(*AWSClient).iamconn request := &iam.CreateAccessKeyInput{ UserName: aws.String(d.Get("user").(string)), } createResp, err := iamconn.CreateAccessKey(request) if err != nil { return fmt.Errorf( "Error creating access key for user %s: %s", *request.UserName, err, ) } if err := d.Set("secret", createResp.AccessKey.SecretAccessKey); err != nil { return err } return resourceAwsIamAccessKeyReadResult(d, &iam.AccessKeyMetadata{ AccessKeyID: createResp.AccessKey.AccessKeyID, CreateDate: createResp.AccessKey.CreateDate, Status: createResp.AccessKey.Status, UserName: createResp.AccessKey.UserName, }) }
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 getInstanceAccessAddresses(d *schema.ResourceData, networks []map[string]interface{}) (string, string) { var hostv4, hostv6 string // Start with a global floating IP floatingIP := d.Get("floating_ip").(string) if floatingIP != "" { hostv4 = floatingIP } // Loop through all networks and check for the following: // * If the network is set as an access network. // * If the network has a floating IP. // * If the network has a v4/v6 fixed IP. for _, n := range networks { if n["floating_ip"] != nil { hostv4 = n["floating_ip"].(string) } else { if hostv4 == "" && n["fixed_ip_v4"] != nil { hostv4 = n["fixed_ip_v4"].(string) } } if hostv6 == "" && n["fixed_ip_v6"] != nil { hostv6 = n["fixed_ip_v6"].(string) } if an, ok := n["access_network"].(bool); ok && an { break } } log.Printf("[DEBUG] OpenStack Instance Network Access Addresses: %s, %s", hostv4, hostv6) return hostv4, hostv6 }
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 resourceInstanceMetadataV2(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 }
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 }
// 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 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 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 (lt *opsworksLayerType) SetVolumeConfigurations(d *schema.ResourceData, v []*opsworks.VolumeConfiguration) { newValue := make([]*map[string]interface{}, len(v)) for i := 0; i < len(v); i++ { config := v[i] data := make(map[string]interface{}) newValue[i] = &data if config.Iops != nil { data["iops"] = int(*config.Iops) } else { data["iops"] = 0 } if config.MountPoint != nil { data["mount_point"] = *config.MountPoint } if config.NumberOfDisks != nil { data["number_of_disks"] = int(*config.NumberOfDisks) } if config.RaidLevel != nil { data["raid_level"] = strconv.Itoa(int(*config.RaidLevel)) } if config.Size != nil { data["size"] = int(*config.Size) } if config.VolumeType != nil { data["type"] = *config.VolumeType } } d.Set("ebs_volume", newValue) }
func (lt *opsworksLayerType) VolumeConfigurations(d *schema.ResourceData) []*opsworks.VolumeConfiguration { configuredVolumes := d.Get("ebs_volume").(*schema.Set).List() result := make([]*opsworks.VolumeConfiguration, len(configuredVolumes)) for i := 0; i < len(configuredVolumes); i++ { volumeData := configuredVolumes[i].(map[string]interface{}) result[i] = &opsworks.VolumeConfiguration{ MountPoint: aws.String(volumeData["mount_point"].(string)), NumberOfDisks: aws.Int64(int64(volumeData["number_of_disks"].(int))), Size: aws.Int64(int64(volumeData["size"].(int))), VolumeType: aws.String(volumeData["type"].(string)), } iops := int64(volumeData["iops"].(int)) if iops != 0 { result[i].Iops = aws.Int64(iops) } raidLevelStr := volumeData["raid_level"].(string) if raidLevelStr != "" { raidLevel, err := strconv.Atoi(raidLevelStr) if err == nil { result[i].RaidLevel = aws.Int64(int64(raidLevel)) } } } return result }
func (lt *opsworksLayerType) AttributeMap(d *schema.ResourceData) map[string]*string { attrs := map[string]*string{} for key, def := range lt.Attributes { value := d.Get(key) switch def.Type { case schema.TypeString: strValue := value.(string) attrs[def.AttrName] = &strValue case schema.TypeInt: intValue := value.(int) strValue := strconv.Itoa(intValue) attrs[def.AttrName] = &strValue case schema.TypeBool: boolValue := value.(bool) if boolValue { attrs[def.AttrName] = &opsworksTrueString } else { attrs[def.AttrName] = &opsworksFalseString } default: // should never happen panic(fmt.Errorf("Unsupported OpsWorks layer attribute type")) } } return attrs }
func expandAzureRmVirtualMachineDataDisk(d *schema.ResourceData) ([]compute.DataDisk, error) { disks := d.Get("storage_data_disk").([]interface{}) data_disks := make([]compute.DataDisk, 0, len(disks)) for _, disk_config := range disks { config := disk_config.(map[string]interface{}) name := config["name"].(string) vhd := config["vhd_uri"].(string) createOption := config["create_option"].(string) lun := int32(config["lun"].(int)) disk_size := int32(config["disk_size_gb"].(int)) data_disk := compute.DataDisk{ Name: &name, Vhd: &compute.VirtualHardDisk{ URI: &vhd, }, Lun: &lun, DiskSizeGB: &disk_size, CreateOption: compute.DiskCreateOptionTypes(createOption), } data_disks = append(data_disks, data_disk) } return data_disks, nil }
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 expandAzureRmVirtualMachineOsProfileLinuxConfig(d *schema.ResourceData) (*compute.LinuxConfiguration, error) { osProfilesLinuxConfig := d.Get("os_profile_linux_config").(*schema.Set).List() linuxConfig := osProfilesLinuxConfig[0].(map[string]interface{}) disablePasswordAuth := linuxConfig["disable_password_authentication"].(bool) config := &compute.LinuxConfiguration{ DisablePasswordAuthentication: &disablePasswordAuth, } linuxKeys := linuxConfig["ssh_keys"].([]interface{}) sshPublicKeys := []compute.SSHPublicKey{} for _, key := range linuxKeys { sshKey, ok := key.(map[string]interface{}) if !ok { continue } path := sshKey["path"].(string) keyData := sshKey["key_data"].(string) sshPublicKey := compute.SSHPublicKey{ Path: &path, KeyData: &keyData, } sshPublicKeys = append(sshPublicKeys, sshPublicKey) } config.SSH = &compute.SSHConfiguration{ PublicKeys: &sshPublicKeys, } return config, nil }
func websiteEndpoint(s3conn *s3.S3, d *schema.ResourceData) (*S3Website, error) { // If the bucket doesn't have a website configuration, return an empty // endpoint if _, ok := d.GetOk("website"); !ok { return nil, nil } bucket := d.Get("bucket").(string) // Lookup the region for this bucket location, err := s3conn.GetBucketLocation( &s3.GetBucketLocationInput{ Bucket: aws.String(bucket), }, ) if err != nil { return nil, err } var region string if location.LocationConstraint != nil { region = *location.LocationConstraint } return WebsiteEndpoint(bucket, region), nil }
func 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 resourceAwsS3BucketVersioningUpdate(s3conn *s3.S3, d *schema.ResourceData) error { v := d.Get("versioning").(*schema.Set).List() bucket := d.Get("bucket").(string) vc := &s3.VersioningConfiguration{} if len(v) > 0 { c := v[0].(map[string]interface{}) if c["enabled"].(bool) { vc.Status = aws.String(s3.BucketVersioningStatusEnabled) } else { vc.Status = aws.String(s3.BucketVersioningStatusSuspended) } } else { vc.Status = aws.String(s3.BucketVersioningStatusSuspended) } i := &s3.PutBucketVersioningInput{ Bucket: aws.String(bucket), VersioningConfiguration: vc, } log.Printf("[DEBUG] S3 put bucket versioning: %#v", i) _, err := s3conn.PutBucketVersioning(i) if err != nil { return fmt.Errorf("Error putting S3 versioning: %s", err) } return nil }
func setImageInformation(computeClient *gophercloud.ServiceClient, server *servers.Server, d *schema.ResourceData) error { // If block_device was used, an Image does not need to be specified. // If an Image was specified, ignore it if _, ok := d.GetOk("block_device"); ok { d.Set("image_id", "Attempt to boot from volume - no image supplied") return nil } imageId := server.Image["id"].(string) if imageId != "" { d.Set("image_id", imageId) if image, err := images.Get(computeClient, imageId).Extract(); err != nil { errCode, ok := err.(*gophercloud.UnexpectedResponseCodeError) if !ok { return err } if errCode.Actual == 404 { // If the image name can't be found, set the value to "Image not found". // The most likely scenario is that the image no longer exists in the Image Service // but the instance still has a record from when it existed. d.Set("image_name", "Image not found") return nil } else { return err } } else { d.Set("image_name", image.Name) } } return nil }
func resourceAwsS3BucketLoggingUpdate(s3conn *s3.S3, d *schema.ResourceData) error { logging := d.Get("logging").(*schema.Set).List() bucket := d.Get("bucket").(string) loggingStatus := &s3.BucketLoggingStatus{} if len(logging) > 0 { c := logging[0].(map[string]interface{}) loggingEnabled := &s3.LoggingEnabled{} if val, ok := c["target_bucket"]; ok { loggingEnabled.TargetBucket = aws.String(val.(string)) } if val, ok := c["target_prefix"]; ok { loggingEnabled.TargetPrefix = aws.String(val.(string)) } loggingStatus.LoggingEnabled = loggingEnabled } i := &s3.PutBucketLoggingInput{ Bucket: aws.String(bucket), BucketLoggingStatus: loggingStatus, } log.Printf("[DEBUG] S3 put bucket logging: %#v", i) _, err := s3conn.PutBucketLogging(i) if err != nil { return fmt.Errorf("Error putting S3 logging: %s", err) } return nil }
func checkVolumeConfig(d *schema.ResourceData) error { // Although a volume_id is required to attach a volume, in order to be able to report // the attached volumes of an instance, it must be "computed" and thus "optional". // This accounts for situations such as "boot from volume" as well as volumes being // attached to the instance outside of Terraform. if v := d.Get("volume"); v != nil { vols := v.(*schema.Set).List() if len(vols) > 0 { for _, v := range vols { va := v.(map[string]interface{}) if va["volume_id"].(string) == "" { return fmt.Errorf("A volume_id must be specified when attaching volumes.") } } } } if vL, ok := d.GetOk("block_device"); ok { if len(vL.([]interface{})) > 1 { return fmt.Errorf("Can only specify one block device to boot from.") } } return nil }
func getNetworkName(d *schema.ResourceData, meta interface{}, networkID string) (string, 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) } opts := networks.ListOpts{ID: networkID} pager := networks.List(networkClient, 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 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 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) }
// MapValueSpecs converts ResourceData into a map func MapValueSpecs(d *schema.ResourceData) map[string]string { m := make(map[string]string) for key, val := range d.Get("value_specs").(map[string]interface{}) { m[key] = val.(string) } return m }
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 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 }
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} }) }