Report this

What is the reason for this report?

How to Set Up a DigitalOcean Droplet with a Specific SSH Key Using Terraform?

Posted on October 26, 2024

I’m new to using Terraform and am trying to create a Droplet that automatically includes a specific SSH key I already have on my account. I have the SSH key fingerprint, but I’m not sure how to add it to the Droplet configuration in my Terraform script.

Could someone provide an example of how to reference an existing SSH key for a new Droplet in Terraform? Any pointers would be much appreciated!



This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Hi there,

To use an existing SSH key with a new Droplet in Terraform, you can use the digitalocean_ssh_key data source to reference the key by name and then pass the id of the key to your Droplet configuration.

First, retrieve the SSH key with the digitalocean_ssh_key data source:

data "digitalocean_ssh_key" "example" {
  name = "example" # Replace "example" with the actual name of your SSH key in DigitalOcean
}

Then, in your Droplet configuration, include the key by referencing its ID:

resource "digitalocean_droplet" "web" {
  name   = "example-droplet"
  region = "nyc3"
  size   = "s-1vcpu-1gb"
  image  = "ubuntu-20-04-x64"

  # Reference the existing SSH key
  ssh_keys = [data.digitalocean_ssh_key.example.id]
}

This will ensure that the specified SSH key is added to the new Droplet, allowing you to SSH into it securely.

For more details, you can check out the Terraform DigitalOcean Provider documentation on SSH keys.

Let me know if this helps or if you have further questions!

- Bobby

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.