Question

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

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!


Submit an answer


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!

Sign In or Sign Up to Answer

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.

Bobby Iliev
Site Moderator
Site Moderator badge
October 27, 2024
Accepted Answer

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

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

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.