Create and delete Digital Ocean droplet with curl
Franz Wong
Posted on September 23, 2023
Assumed you have already get the Digital Ocean API key and SSH key.
digitalocean_token="<your API key>"
ssh_key="<your ssh key fingerprint>"
Create a droplet
Let's create a droplet. You can find values of available regions, size, distro images from https://slugs.do-api.dev/
droplet_name="<your droplet name>"
region="nyc1"
size="s-1vcpu-512mb-10gb"
image="ubuntu-22-04-x64"
# Create droplet
curl -s -X POST \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ${digitalocean_token}" \
-d '{"name":"'"${droplet_name}"'","region":"'"${region}"'","size":"'"${size}"'","image":"'"${image}"'","ssh_keys":["'"${ssh_key}"'"],"backups":false,"ipv6":false,"monitoring":false}' \
"https://api.digitalocean.com/v2/droplets"
Get droplet status
We can get the status and wait until it becomes active
.
curl -s -X GET \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ${digitalocean_token}" \
"https://api.digitalocean.com/v2/droplets?name=${droplet_name}" | jq -r '.droplets[].status'
Get the IP address
After it is provisioned, we can get the public IP address.
droplet_ip=$(curl -s -X GET \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ${digitalocean_token}" \
"https://api.digitalocean.com/v2/droplets?name=${droplet_name}" | jq -r '.droplets[].networks.v4[] | select(.type == "public") | .ip_address')
# Login to droplet
ssh -i "${your_ssh_key_path}" root@${droplet_ip}
Delete droplet
After we've done with the droplet, delete it to prevent from charging money.
# Get droplet id
droplet_id=$(curl -s -X GET \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ${digitalocean_token}" \
"https://api.digitalocean.com/v2/droplets?name=${droplet_name}" | jq -r '.droplets[].id')
# Delete droplet
curl -s -X DELETE \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ${digitalocean_token}" \
"https://api.digitalocean.com/v2/droplets/${droplet_id}"
# It should return no droplet details if it is deleted
curl -s -X GET \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ${digitalocean_token}" \
"https://api.digitalocean.com/v2/droplets?name=${droplet_name}"
💖 💪 🙅 🚩
Franz Wong
Posted on September 23, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
devchallenge A Hacktoberfest 2024 Journey: Insights from a First-Time Project Maintainer
November 4, 2024