예제 #1
0
func (p *digitalOceanProvider) Create(host providers.Host) error {
	var sshKey godo.DropletCreateSSHKey
	if strings.Contains(host.Keyname, ":") {
		sshKey.Fingerprint = host.Keyname
	} else {
		id, err := strconv.Atoi(host.Keyname)
		if err != nil {
			return err
		}
		sshKey.ID = id
	}
	droplet, _, err := p.client.Droplets.Create(&godo.DropletCreateRequest{
		Name:   host.Name,
		Region: host.Region,
		Size:   host.Flavor,
		Image: godo.DropletCreateImage{
			Slug: host.Image,
		},
		SSHKeys:  []godo.DropletCreateSSHKey{sshKey},
		UserData: host.Userdata,
	})
	if err != nil {
		return err
	}
	for {
		droplet, _, err = p.client.Droplets.Get(droplet.ID)
		if droplet != nil && droplet.Status == "active" {
			return nil
		}
		if err != nil {
			return err
		}
		time.Sleep(1 * time.Second)
	}
}
func resourceDigitalOceanDropletCreate(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*godo.Client)

	// Build up our creation options
	opts := &godo.DropletCreateRequest{
		Image: godo.DropletCreateImage{
			Slug: d.Get("image").(string),
		},
		Name:   d.Get("name").(string),
		Region: d.Get("region").(string),
		Size:   d.Get("size").(string),
	}

	if attr, ok := d.GetOk("backups"); ok {
		opts.Backups = attr.(bool)
	}

	if attr, ok := d.GetOk("ipv6"); ok {
		opts.IPv6 = attr.(bool)
	}

	if attr, ok := d.GetOk("private_networking"); ok {
		opts.PrivateNetworking = attr.(bool)
	}

	if attr, ok := d.GetOk("user_data"); ok {
		opts.UserData = attr.(string)
	}

	// Get configured ssh_keys
	sshKeys := d.Get("ssh_keys.#").(int)
	if sshKeys > 0 {
		opts.SSHKeys = make([]godo.DropletCreateSSHKey, 0, sshKeys)
		for i := 0; i < sshKeys; i++ {
			key := fmt.Sprintf("ssh_keys.%d", i)
			sshKeyRef := d.Get(key).(string)

			var sshKey godo.DropletCreateSSHKey
			// sshKeyRef can be either an ID or a fingerprint
			if id, err := strconv.Atoi(sshKeyRef); err == nil {
				sshKey.ID = id
			} else {
				sshKey.Fingerprint = sshKeyRef
			}

			opts.SSHKeys = append(opts.SSHKeys, sshKey)
		}
	}

	log.Printf("[DEBUG] Droplet create configuration: %#v", opts)

	droplet, _, err := client.Droplets.Create(opts)

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

	// Assign the droplets id
	d.SetId(strconv.Itoa(droplet.ID))

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

	_, err = WaitForDropletAttribute(d, "active", []string{"new"}, "status", meta)
	if err != nil {
		return fmt.Errorf(
			"Error waiting for droplet (%s) to become ready: %s", d.Id(), err)
	}

	return resourceDigitalOceanDropletRead(d, meta)
}