func resourceAwsVPCEndpointCreate(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).ec2conn
	input := &ec2.CreateVpcEndpointInput{
		VpcId:       aws.String(d.Get("vpc_id").(string)),
		ServiceName: aws.String(d.Get("service_name").(string)),
	}

	if v, ok := d.GetOk("route_table_ids"); ok {
		list := v.(*schema.Set).List()
		if len(list) > 0 {
			input.RouteTableIds = expandStringList(list)
		}
	}

	if v, ok := d.GetOk("policy"); ok {
		policy, err := normalizeJsonString(v)
		if err != nil {
			return errwrap.Wrapf("policy contains an invalid JSON: {{err}}", err)
		}
		input.PolicyDocument = aws.String(policy)
	}

	log.Printf("[DEBUG] Creating VPC Endpoint: %#v", input)
	output, err := conn.CreateVpcEndpoint(input)
	if err != nil {
		return fmt.Errorf("Error creating VPC Endpoint: %s", err)
	}
	log.Printf("[DEBUG] VPC Endpoint %q created.", *output.VpcEndpoint.VpcEndpointId)

	d.SetId(*output.VpcEndpoint.VpcEndpointId)

	return resourceAwsVPCEndpointRead(d, meta)
}
func getImageIDFromConfig(computeClient *gophercloud.ServiceClient, d *schema.ResourceData) (string, 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 {
		return "", nil
	}

	if imageId := d.Get("image_id").(string); imageId != "" {
		return imageId, nil
	} else {
		// try the OS_IMAGE_ID environment variable
		if v := os.Getenv("OS_IMAGE_ID"); v != "" {
			return v, nil
		}
	}

	imageName := d.Get("image_name").(string)
	if imageName == "" {
		// try the OS_IMAGE_NAME environment variable
		if v := os.Getenv("OS_IMAGE_NAME"); v != "" {
			imageName = v
		}
	}

	if imageName != "" {
		imageId, err := images.IDFromName(computeClient, imageName)
		if err != nil {
			return "", err
		}
		return imageId, nil
	}

	return "", fmt.Errorf("Neither a boot device, image ID, or image name were able to be determined.")
}
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 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 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 resourceAWSEbsVolumeUpdate(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).ec2conn
	if _, ok := d.GetOk("tags"); ok {
		setTags(conn, d)
	}
	return resourceAwsEbsVolumeRead(d, meta)
}
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 getOptionalRegion(d *schema.ResourceData, config *Config) string {
	if res, ok := d.GetOk("region"); !ok {
		return config.Region
	} else {
		return res.(string)
	}
}
func resourceComputeSslCertificateCreate(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)

	project, err := getProject(d, config)
	if err != nil {
		return err
	}

	// Build the certificate parameter
	cert := &compute.SslCertificate{
		Name:        d.Get("name").(string),
		Certificate: d.Get("certificate").(string),
		PrivateKey:  d.Get("private_key").(string),
	}

	if v, ok := d.GetOk("description"); ok {
		cert.Description = v.(string)
	}

	op, err := config.clientCompute.SslCertificates.Insert(
		project, cert).Do()

	if err != nil {
		return fmt.Errorf("Error creating ssl certificate: %s", err)
	}

	err = computeOperationWaitGlobal(config, op, project, "Creating SslCertificate")
	if err != nil {
		return err
	}

	d.SetId(cert.Name)

	return resourceComputeSslCertificateRead(d, meta)
}
Exemplo n.º 10
0
func providerConfigure(d *schema.ResourceData) (interface{}, error) {
	config := Config{
		AccessKey:        d.Get("access_key").(string),
		SecretKey:        d.Get("secret_key").(string),
		Profile:          d.Get("profile").(string),
		CredsFilename:    d.Get("shared_credentials_file").(string),
		Token:            d.Get("token").(string),
		Region:           d.Get("region").(string),
		MaxRetries:       d.Get("max_retries").(int),
		DynamoDBEndpoint: d.Get("dynamodb_endpoint").(string),
		KinesisEndpoint:  d.Get("kinesis_endpoint").(string),
		Insecure:         d.Get("insecure").(bool),
	}

	endpointsSet := d.Get("endpoints").(*schema.Set)

	for _, endpointsSetI := range endpointsSet.List() {
		endpoints := endpointsSetI.(map[string]interface{})
		config.IamEndpoint = endpoints["iam"].(string)
		config.Ec2Endpoint = endpoints["ec2"].(string)
		config.ElbEndpoint = endpoints["elb"].(string)
	}

	if v, ok := d.GetOk("allowed_account_ids"); ok {
		config.AllowedAccountIds = v.(*schema.Set).List()
	}

	if v, ok := d.GetOk("forbidden_account_ids"); ok {
		config.ForbiddenAccountIds = v.(*schema.Set).List()
	}

	return config.Client()
}
func resourceCloudStackAffinityGroupCreate(d *schema.ResourceData, meta interface{}) error {
	cs := meta.(*cloudstack.CloudStackClient)

	name := d.Get("name").(string)
	affinityGroupType := d.Get("type").(string)

	// Create a new parameter struct
	p := cs.AffinityGroup.NewCreateAffinityGroupParams(name, affinityGroupType)

	// Set the description
	if description, ok := d.GetOk("description"); ok {
		p.SetDescription(description.(string))
	} else {
		p.SetDescription(name)
	}

	// If there is a project supplied, we retrieve and set the project id
	if err := setProjectid(p, cs, d); err != nil {
		return err
	}

	log.Printf("[DEBUG] Creating affinity group %s", name)
	r, err := cs.AffinityGroup.CreateAffinityGroup(p)
	if err != nil {
		return err
	}

	log.Printf("[DEBUG] Affinity group %s successfully created", name)
	d.SetId(r.Id)

	return resourceCloudStackAffinityGroupRead(d, meta)
}
func buildNetworks(d *schema.ResourceData, meta interface{}) (error, []*compute.NetworkInterface) {
	// Build up the list of networks
	networksCount := d.Get("network_interface.#").(int)
	networkInterfaces := make([]*compute.NetworkInterface, 0, networksCount)
	for i := 0; i < networksCount; i++ {
		prefix := fmt.Sprintf("network_interface.%d", i)

		source := "global/networks/default"
		if v, ok := d.GetOk(prefix + ".network"); ok {
			if v.(string) != "default" {
				source = v.(string)
			}
		}

		// Build the networkInterface
		var iface compute.NetworkInterface
		iface.Network = source

		accessConfigsCount := d.Get(prefix + ".access_config.#").(int)
		iface.AccessConfigs = make([]*compute.AccessConfig, accessConfigsCount)
		for j := 0; j < accessConfigsCount; j++ {
			acPrefix := fmt.Sprintf("%s.access_config.%d", prefix, j)
			iface.AccessConfigs[j] = &compute.AccessConfig{
				Type:  "ONE_TO_ONE_NAT",
				NatIP: d.Get(acPrefix + ".nat_ip").(string),
			}
		}

		networkInterfaces = append(networkInterfaces, &iface)
	}
	return nil, networkInterfaces
}
func resourceProfitBricksDatacenterCreate(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)
	profitbricks.SetAuth(config.Username, config.Password)

	datacenter := profitbricks.Datacenter{
		Properties: profitbricks.DatacenterProperties{
			Name:     d.Get("name").(string),
			Location: d.Get("location").(string),
		},
	}

	if attr, ok := d.GetOk("description"); ok {
		datacenter.Properties.Description = attr.(string)
	}
	dc := profitbricks.CreateDatacenter(datacenter)

	if dc.StatusCode > 299 {
		return fmt.Errorf(
			"Error creating data center (%s) (%s)", d.Id(), dc.Response)
	}
	d.SetId(dc.Id)

	log.Printf("[INFO] DataCenter Id: %s", d.Id())

	err := waitTillProvisioned(meta, dc.Headers.Get("Location"))
	if err != nil {
		return err
	}
	return resourceProfitBricksDatacenterRead(d, meta)
}
func resourceComputeTargetHttpProxyCreate(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)

	proxy := &compute.TargetHttpProxy{
		Name:   d.Get("name").(string),
		UrlMap: d.Get("url_map").(string),
	}

	if v, ok := d.GetOk("description"); ok {
		proxy.Description = v.(string)
	}

	log.Printf("[DEBUG] TargetHttpProxy insert request: %#v", proxy)
	op, err := config.clientCompute.TargetHttpProxies.Insert(
		config.Project, proxy).Do()
	if err != nil {
		return fmt.Errorf("Error creating TargetHttpProxy: %s", err)
	}

	err = computeOperationWaitGlobal(config, op, "Creating Target Http Proxy")
	if err != nil {
		return err
	}

	d.SetId(proxy.Name)

	return resourceComputeTargetHttpProxyRead(d, meta)
}
func resourceCloudStackLoadBalancerRuleRead(d *schema.ResourceData, meta interface{}) error {
	cs := meta.(*cloudstack.CloudStackClient)

	// Get the load balancer details
	lb, count, err := cs.LoadBalancer.GetLoadBalancerRuleByID(d.Id())
	if err != nil {
		if count == 0 {
			log.Printf("[DEBUG] Load balancer rule %s does no longer exist", d.Get("name").(string))
			d.SetId("")
			return nil
		}

		return err
	}

	d.Set("algorithm", lb.Algorithm)
	d.Set("public_port", lb.Publicport)
	d.Set("private_port", lb.Privateport)
	d.Set("ip_address_id", lb.Publicipid)

	// Only set network if user specified it to avoid spurious diffs
	_, networkID := d.GetOk("network_id")
	_, network := d.GetOk("network")
	if networkID || network {
		d.Set("network_id", lb.Networkid)
	}

	return nil
}
func resourcePostgreSQLExtensionCreate(d *schema.ResourceData, meta interface{}) error {
	c := meta.(*Client)
	c.catalogLock.Lock()
	defer c.catalogLock.Unlock()

	conn, err := c.Connect()
	if err != nil {
		return err
	}
	defer conn.Close()

	extName := d.Get(extNameAttr).(string)

	b := bytes.NewBufferString("CREATE EXTENSION ")
	fmt.Fprint(b, pq.QuoteIdentifier(extName))

	if v, ok := d.GetOk(extSchemaAttr); ok {
		fmt.Fprint(b, " SCHEMA ", pq.QuoteIdentifier(v.(string)))
	}

	if v, ok := d.GetOk(extVersionAttr); ok {
		fmt.Fprint(b, " VERSION ", pq.QuoteIdentifier(v.(string)))
	}

	query := b.String()
	_, err = conn.Query(query)
	if err != nil {
		return errwrap.Wrapf("Error creating extension: {{err}}", err)
	}

	d.SetId(extName)

	return resourcePostgreSQLExtensionReadImpl(d, meta)
}
Exemplo n.º 17
0
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] record create configuration: %#v", newRecord)

	recId, err := client.CreateRecord(d.Get("domain").(string), newRecord)

	if err != nil {
		return fmt.Errorf("Failed to create record: %s", err)
	}

	d.SetId(recId)
	log.Printf("[INFO] record ID: %s", d.Id())

	return resourceDNSimpleRecordRead(d, meta)
}
func resourceDigitalOceanFloatingIpUpdate(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*godo.Client)

	if d.HasChange("droplet_id") {
		if v, ok := d.GetOk("droplet_id"); ok {
			log.Printf("[INFO] Assigning the Floating IP %s to the Droplet %d", d.Id(), 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)
			}
		} else {
			log.Printf("[INFO] Unassigning the Floating IP %s", d.Id())
			action, _, err := client.FloatingIPActions.Unassign(d.Id())
			if err != nil {
				return fmt.Errorf(
					"Error Unassigning FloatingIP (%s): %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)
			}
		}
	}

	return resourceDigitalOceanFloatingIpRead(d, meta)
}
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 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)
}
Exemplo n.º 21
0
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 resourceAwsCloudWatchLogGroupUpdate(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).cloudwatchlogsconn

	name := d.Get("name").(string)
	log.Printf("[DEBUG] Updating CloudWatch Log Group: %q", name)

	if d.HasChange("retention_in_days") {
		var err error

		if v, ok := d.GetOk("retention_in_days"); ok {
			input := cloudwatchlogs.PutRetentionPolicyInput{
				LogGroupName:    aws.String(name),
				RetentionInDays: aws.Int64(int64(v.(int))),
			}
			log.Printf("[DEBUG] Setting retention for CloudWatch Log Group: %q: %s", name, input)
			_, err = conn.PutRetentionPolicy(&input)
		} else {
			log.Printf("[DEBUG] Deleting retention for CloudWatch Log Group: %q", name)
			_, err = conn.DeleteRetentionPolicy(&cloudwatchlogs.DeleteRetentionPolicyInput{
				LogGroupName: aws.String(name),
			})
		}

		if err != nil {
			return err
		}
	}

	return resourceAwsCloudWatchLogGroupRead(d, meta)
}
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
}
Exemplo n.º 24
0
func resourceAwsIamRoleCreate(d *schema.ResourceData, meta interface{}) error {
	iamconn := meta.(*AWSClient).iamconn

	var name string
	if v, ok := d.GetOk("name"); ok {
		name = v.(string)
	} else if v, ok := d.GetOk("name_prefix"); ok {
		name = resource.PrefixedUniqueId(v.(string))
	} else {
		name = resource.UniqueId()
	}

	request := &iam.CreateRoleInput{
		Path:                     aws.String(d.Get("path").(string)),
		RoleName:                 aws.String(name),
		AssumeRolePolicyDocument: aws.String(d.Get("assume_role_policy").(string)),
	}

	var createResp *iam.CreateRoleOutput
	err := resource.Retry(30*time.Second, func() *resource.RetryError {
		var err error
		createResp, err = iamconn.CreateRole(request)
		// IAM users (referenced in Principal field of assume policy)
		// can take ~30 seconds to propagate in AWS
		if isAWSErr(err, "MalformedPolicyDocument", "Invalid principal in policy") {
			return resource.RetryableError(err)
		}
		return resource.NonRetryableError(err)
	})
	if err != nil {
		return fmt.Errorf("Error creating IAM Role %s: %s", name, err)
	}
	return resourceAwsIamRoleReadResult(d, createResp.Role)
}
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
}
Exemplo n.º 26
0
func readBlockDevices(d *schema.ResourceData, instance *ec2.Instance, conn *ec2.EC2) error {
	ibds, err := readBlockDevicesFromInstance(instance, conn)
	if err != nil {
		return err
	}

	if err := d.Set("ebs_block_device", ibds["ebs"]); err != nil {
		return err
	}

	// This handles the import case which needs to be defaulted to empty
	if _, ok := d.GetOk("root_block_device"); !ok {
		if err := d.Set("root_block_device", []interface{}{}); err != nil {
			return err
		}
	}

	if ibds["root"] != nil {
		roots := []interface{}{ibds["root"]}
		if err := d.Set("root_block_device", roots); err != nil {
			return 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 resourceInstanceMetadata(d *schema.ResourceData) (*compute.Metadata, error) {
	m := &compute.Metadata{}
	mdMap := d.Get("metadata").(map[string]interface{})
	_, mapScriptExists := mdMap["startup-script"]
	dScript, dScriptExists := d.GetOk("metadata_startup_script")
	if mapScriptExists && dScriptExists {
		return nil, fmt.Errorf("Not allowed to have both metadata_startup_script and metadata.startup-script")
	}
	if dScriptExists {
		mdMap["startup-script"] = dScript
	}
	if len(mdMap) > 0 {
		m.Items = make([]*compute.MetadataItems, 0, len(mdMap))
		for key, val := range mdMap {
			v := val.(string)
			m.Items = append(m.Items, &compute.MetadataItems{
				Key:   key,
				Value: &v,
			})
		}

		// Set the fingerprint. If the metadata has never been set before
		// then this will just be blank.
		m.Fingerprint = d.Get("metadata_fingerprint").(string)
	}

	return m, nil
}
Exemplo n.º 29
0
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 resourceAwsApiGatewayRestApiCreate(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).apigateway
	log.Printf("[DEBUG] Creating API Gateway")

	var description *string
	if d.Get("description").(string) != "" {
		description = aws.String(d.Get("description").(string))
	}

	params := &apigateway.CreateRestApiInput{
		Name:        aws.String(d.Get("name").(string)),
		Description: description,
	}

	binaryMediaTypes, binaryMediaTypesOk := d.GetOk("binary_media_types")
	if binaryMediaTypesOk {
		params.BinaryMediaTypes = expandStringList(binaryMediaTypes.([]interface{}))
	}

	gateway, err := conn.CreateRestApi(params)
	if err != nil {
		return fmt.Errorf("Error creating API Gateway: %s", err)
	}

	d.SetId(*gateway.Id)

	if err = resourceAwsApiGatewayRestApiRefreshResources(d, meta); err != nil {
		return err
	}

	return resourceAwsApiGatewayRestApiRead(d, meta)
}