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!
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
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
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
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.