I'm trying to create droplets with SSH key using the python-digitalocean library. For some reasons the ssh key is not attached to the newly created droplet.

Any idea what can I do ?

1 Answers

0
andrewsomething On

python-digitalocean accepts SSH keys in multiple formats when creating a new Droplet. One important thing to remember is that even if you are only adding one key, the attribute needs to be in list form.

Here's a quick example:

import os
import digitalocean

token = os.getenv('DO_TOKEN')
client = digitalocean.Manager(token=token)

keys = client.get_all_sshkeys()

droplet = digitalocean.Droplet(name='ssh-key-example-01',
                                     region='nyc3',
                                     size='s-1vcpu-1gb',
                                     image='ubuntu-18-04-x64',
                                     ssh_keys=[ keys[0], 3939600,
                                       'b6:2e:fa:ea:96:42:14:1b:62:e2:76:4b:6f:60:1a:e6'],
                                     token=token)

This example highlights the three forms that are accepted:

  • keys[0] is an SSHKey object that was retrieved using client.get_all_sshkeys()
  • 3939600 is the ID of an SSH key on my DigitalOcean account as an integer
  • b6:2e:fa:ea:96:42:14:1b:62:e2:76:4b:6f:60:1a:e6 is the fingerprint of an SSH key on my DigitalOcean account

If you'd like to add all of the keys on you account to a Droplet, the easiest way would be:

keys = client.get_all_sshkeys()

droplet = digitalocean.Droplet(name='ssh-key-example-01',
                               region='nyc3',
                               size='s-1vcpu-1gb',
                               image='ubuntu-18-04-x64',
                               ssh_keys=keys,
                               token=token)

This works since client.get_all_sshkeys() already returns them in a list.