func resourceAwsIamGroupMembershipRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).iamconn group := d.Get("group").(string) resp, err := conn.GetGroup(&iam.GetGroupInput{ GroupName: aws.String(group), }) if err != nil { if awsErr, ok := err.(awserr.Error); ok { // aws specific error if awsErr.Code() == "NoSuchEntity" { // group not found d.SetId("") return nil } } return err } ul := make([]string, 0, len(resp.Users)) for _, u := range resp.Users { ul = append(ul, *u.UserName) } if err := d.Set("users", ul); err != nil { return fmt.Errorf("[WARN] Error setting user list from IAM Group Membership (%s), error: %s", group, err) } return nil }
// 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 resourceHerokuAddonCreate(d *schema.ResourceData, meta interface{}) error { addonLock.Lock() defer addonLock.Unlock() client := meta.(*heroku.Service) app := d.Get("app").(string) opts := heroku.AddonCreateOpts{Plan: d.Get("plan").(string)} if v := d.Get("config"); v != nil { config := make(map[string]string) for _, v := range v.([]interface{}) { for k, v := range v.(map[string]interface{}) { config[k] = v.(string) } } opts.Config = &config } log.Printf("[DEBUG] Addon create configuration: %#v, %#v", app, opts) a, err := client.AddonCreate(app, opts) if err != nil { return err } d.SetId(a.ID) log.Printf("[INFO] Addon ID: %s", d.Id()) return resourceHerokuAddonRead(d, meta) }
func resourceObjectStorageContainerV1Create(d *schema.ResourceData, meta interface{}) error { config := meta.(*Config) objectStorageClient, err := config.objectStorageV1Client(d.Get("region").(string)) if err != nil { return fmt.Errorf("Error creating OpenStack object storage client: %s", err) } cn := d.Get("name").(string) createOpts := &containers.CreateOpts{ ContainerRead: d.Get("container_read").(string), ContainerSyncTo: d.Get("container_sync_to").(string), ContainerSyncKey: d.Get("container_sync_key").(string), ContainerWrite: d.Get("container_write").(string), ContentType: d.Get("content_type").(string), Metadata: resourceContainerMetadataV2(d), } log.Printf("[DEBUG] Create Options: %#v", createOpts) _, err = containers.Create(objectStorageClient, cn, createOpts).Extract() if err != nil { return fmt.Errorf("Error creating OpenStack container: %s", err) } log.Printf("[INFO] Container ID: %s", cn) // Store the ID now d.SetId(cn) return resourceObjectStorageContainerV1Read(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 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) log.Printf("[DEBUG] Reading S3 Bucket Object meta: %s", resp) return nil }
func resourceComputeVpnGatewayRead(d *schema.ResourceData, meta interface{}) error { config := meta.(*Config) name := d.Get("name").(string) region := d.Get("region").(string) project := config.Project vpnGatewaysService := compute.NewTargetVpnGatewaysService(config.clientCompute) vpnGateway, err := vpnGatewaysService.Get(project, region, name).Do() if err != nil { if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == 404 { log.Printf("[WARN] Removing VPN Gateway %q because it's gone", d.Get("name").(string)) // The resource doesn't exist anymore d.SetId("") return nil } return fmt.Errorf("Error Reading VPN Gateway %s: %s", name, err) } d.Set("self_link", vpnGateway.SelfLink) d.SetId(name) return nil }
func resourceAwsSecurityGroupRead(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 } sg := sgRaw.(*ec2.SecurityGroup) ingressRules := resourceAwsSecurityGroupIPPermGather(d, sg.IpPermissions) egressRules := resourceAwsSecurityGroupIPPermGather(d, sg.IpPermissionsEgress) d.Set("description", sg.Description) d.Set("name", sg.GroupName) d.Set("vpc_id", sg.VpcId) d.Set("owner_id", sg.OwnerId) d.Set("ingress", ingressRules) d.Set("egress", egressRules) d.Set("tags", tagsToMap(sg.Tags)) 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 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 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 resourceDNSimpleRecordCreate(d *schema.ResourceData, meta interface{}) error { client := meta.(*dnsimple.Client) // Create the new record newRecord := &dnsimple.ChangeRecord{ Name: d.Get("name").(string), Type: d.Get("type").(string), Value: d.Get("value").(string), } if ttl, ok := d.GetOk("ttl"); ok { newRecord.Ttl = ttl.(string) } log.Printf("[DEBUG] DNSimple Record create configuration: %#v", newRecord) recId, err := client.CreateRecord(d.Get("domain").(string), newRecord) if err != nil { return fmt.Errorf("Failed to create DNSimple Record: %s", err) } d.SetId(recId) log.Printf("[INFO] record ID: %s", d.Id()) return resourceDNSimpleRecordRead(d, meta) }
func resourceAwsCloudWatchMetricAlarmDelete(d *schema.ResourceData, meta interface{}) error { p, err := getAwsCloudWatchMetricAlarm(d, meta) if err != nil { return err } if p == nil { log.Printf("[DEBUG] CloudWatch Metric Alarm %s is already gone", d.Id()) return nil } log.Printf("[INFO] Deleting CloudWatch Metric Alarm: %s", d.Id()) conn := meta.(*AWSClient).cloudwatchconn params := cloudwatch.DeleteAlarmsInput{ AlarmNames: []*string{aws.String(d.Id())}, } if _, err := conn.DeleteAlarms(¶ms); err != nil { return fmt.Errorf("Error deleting CloudWatch Metric Alarm: %s", err) } log.Println("[INFO] CloudWatch Metric Alarm deleted") d.SetId("") return nil }
func resourceAwsIamUserPolicyRead(d *schema.ResourceData, meta interface{}) error { iamconn := meta.(*AWSClient).iamconn user, name := resourceAwsIamUserPolicyParseId(d.Id()) request := &iam.GetUserPolicyInput{ PolicyName: aws.String(name), UserName: aws.String(user), } var err error getResp, err := iamconn.GetUserPolicy(request) if err != nil { if iamerr, ok := err.(awserr.Error); ok && iamerr.Code() == "NoSuchEntity" { // XXX test me d.SetId("") return nil } return fmt.Errorf("Error reading IAM policy %s from user %s: %s", name, user, err) } if getResp.PolicyDocument == nil { return fmt.Errorf("GetUserPolicy returned a nil policy document") } policy, err := url.QueryUnescape(*getResp.PolicyDocument) if err != nil { return err } return d.Set("policy", policy) }
func resourceAwsDbParameterGroupCreate(d *schema.ResourceData, meta interface{}) error { rdsconn := meta.(*AWSClient).rdsconn tags := tagsFromMapRDS(d.Get("tags").(map[string]interface{})) createOpts := rds.CreateDBParameterGroupInput{ DBParameterGroupName: aws.String(d.Get("name").(string)), DBParameterGroupFamily: aws.String(d.Get("family").(string)), Description: aws.String(d.Get("description").(string)), Tags: tags, } log.Printf("[DEBUG] Create DB Parameter Group: %#v", createOpts) _, err := rdsconn.CreateDBParameterGroup(&createOpts) if err != nil { return fmt.Errorf("Error creating DB Parameter Group: %s", err) } d.Partial(true) d.SetPartial("name") d.SetPartial("family") d.SetPartial("description") d.Partial(false) d.SetId(*createOpts.DBParameterGroupName) log.Printf("[INFO] DB Parameter Group ID: %s", d.Id()) return resourceAwsDbParameterGroupUpdate(d, meta) }
func 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 }
// 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 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 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 resourceAwsLBCookieStickinessPolicyCreate(d *schema.ResourceData, meta interface{}) error { elbconn := meta.(*AWSClient).elbconn // Provision the LBStickinessPolicy lbspOpts := &elb.CreateLBCookieStickinessPolicyInput{ LoadBalancerName: aws.String(d.Get("load_balancer").(string)), PolicyName: aws.String(d.Get("name").(string)), } if v := d.Get("cookie_expiration_period").(int); v > 0 { lbspOpts.CookieExpirationPeriod = aws.Int64(int64(v)) } log.Printf("[DEBUG] LB Cookie Stickiness Policy opts: %#v", lbspOpts) if _, err := elbconn.CreateLBCookieStickinessPolicy(lbspOpts); err != nil { return fmt.Errorf("Error creating LBCookieStickinessPolicy: %s", err) } setLoadBalancerOpts := &elb.SetLoadBalancerPoliciesOfListenerInput{ LoadBalancerName: aws.String(d.Get("load_balancer").(string)), LoadBalancerPort: aws.Int64(int64(d.Get("lb_port").(int))), PolicyNames: []*string{aws.String(d.Get("name").(string))}, } log.Printf("[DEBUG] LB Cookie Stickiness create configuration: %#v", setLoadBalancerOpts) if _, err := elbconn.SetLoadBalancerPoliciesOfListener(setLoadBalancerOpts); err != nil { return fmt.Errorf("Error setting LBCookieStickinessPolicy: %s", err) } d.SetId(fmt.Sprintf("%s:%d:%s", *lbspOpts.LoadBalancerName, *setLoadBalancerOpts.LoadBalancerPort, *lbspOpts.PolicyName)) return nil }
func resourceMailgunDomainCreate(d *schema.ResourceData, meta interface{}) error { client := meta.(*mailgun.Client) opts := mailgun.CreateDomain{} opts.Name = d.Get("name").(string) opts.SmtpPassword = d.Get("smtp_password").(string) opts.SpamAction = d.Get("spam_action").(string) opts.Wildcard = d.Get("wildcard").(bool) log.Printf("[DEBUG] Domain create configuration: %#v", opts) domain, err := client.CreateDomain(&opts) if err != nil { return err } d.SetId(domain) log.Printf("[INFO] Domain ID: %s", d.Id()) // Retrieve and update state of domain _, err = resourceMailginDomainRetrieve(d.Id(), client, d) if err != nil { return err } return nil }
func resourceArmNetworkSecurityRuleCreate(d *schema.ResourceData, meta interface{}) error { client := meta.(*ArmClient) secClient := client.secRuleClient name := d.Get("name").(string) nsgName := d.Get("network_security_group_name").(string) resGroup := d.Get("resource_group_name").(string) source_port_range := d.Get("source_port_range").(string) destination_port_range := d.Get("destination_port_range").(string) source_address_prefix := d.Get("source_address_prefix").(string) destination_address_prefix := d.Get("destination_address_prefix").(string) priority := d.Get("priority").(int) access := d.Get("access").(string) direction := d.Get("direction").(string) protocol := d.Get("protocol").(string) armMutexKV.Lock(nsgName) defer armMutexKV.Unlock(nsgName) properties := network.SecurityRulePropertiesFormat{ SourcePortRange: &source_port_range, DestinationPortRange: &destination_port_range, SourceAddressPrefix: &source_address_prefix, DestinationAddressPrefix: &destination_address_prefix, Priority: &priority, Access: network.SecurityRuleAccess(access), Direction: network.SecurityRuleDirection(direction), Protocol: network.SecurityRuleProtocol(protocol), } if v, ok := d.GetOk("description"); ok { description := v.(string) properties.Description = &description } sgr := network.SecurityRule{ Name: &name, Properties: &properties, } resp, err := secClient.CreateOrUpdate(resGroup, nsgName, name, sgr) if err != nil { return err } d.SetId(*resp.ID) log.Printf("[DEBUG] Waiting for Network Security Rule (%s) to become available", name) stateConf := &resource.StateChangeConf{ Pending: []string{"Accepted", "Updating"}, Target: "Succeeded", Refresh: securityRuleStateRefreshFunc(client, resGroup, nsgName, name), Timeout: 10 * time.Minute, } if _, err := stateConf.WaitForState(); err != nil { return fmt.Errorf("Error waiting for Network Securty Rule (%s) to become available: %s", name, err) } return resourceArmNetworkSecurityRuleRead(d, meta) }
// resourceArmLocalNetworkGatewayRead goes ahead and reads the state of the corresponding ARM local network gateway. func resourceArmLocalNetworkGatewayRead(d *schema.ResourceData, meta interface{}) error { lnetClient := meta.(*ArmClient).localNetConnClient id, err := parseAzureResourceID(d.Id()) if err != nil { return err } name := id.Path["localNetworkGateways"] resGroup := id.ResourceGroup resp, err := lnetClient.Get(resGroup, name) if err != nil { if resp.StatusCode == http.StatusNotFound { d.SetId("") return nil } return fmt.Errorf("Error reading the state of Azure ARM local network gateway '%s': %s", name, err) } d.Set("gateway_address", resp.Properties.GatewayIPAddress) prefs := []string{} if ps := *resp.Properties.LocalNetworkAddressSpace.AddressPrefixes; ps != nil { prefs = ps } d.Set("address_space", prefs) 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 resourcePacketSSHKeyRead(d *schema.ResourceData, meta interface{}) error { client := meta.(*packngo.Client) key, _, err := client.SSHKeys.Get(d.Id()) if err != nil { err = friendlyError(err) // If the key is somehow already destroyed, mark as // succesfully gone if isNotFound(err) { d.SetId("") return nil } return err } d.Set("id", key.ID) d.Set("name", key.Label) d.Set("public_key", key.Key) d.Set("fingerprint", key.FingerPrint) d.Set("created", key.Created) d.Set("updated", key.Updated) return nil }
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 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 }
func resourceRemoteStateRead(d *schema.ResourceData, meta interface{}) error { backend := d.Get("backend").(string) config := make(map[string]string) for k, v := range d.Get("config").(map[string]interface{}) { config[k] = v.(string) } // Create the client to access our remote state log.Printf("[DEBUG] Initializing remote state client: %s", backend) client, err := remote.NewClient(backend, config) if err != nil { return err } // Create the remote state itself and refresh it in order to load the state log.Printf("[DEBUG] Loading remote state...") state := &remote.State{Client: client} if err := state.RefreshState(); err != nil { return err } var outputs map[string]string if !state.State().Empty() { outputs = state.State().RootModule().Outputs } d.SetId(time.Now().UTC().String()) d.Set("output", outputs) return nil }