How do I create a droplet and capture its id to a variable?

  • Posted May 24, 2016
  • API

I’m looking to automate as much as possible. I’m using curl to create a droplet. How can I capture the assigned id and save to a variable so that I can then issue other commands where I need this id?

Regards, GH.


This comment has been deleted

Submit an 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.

When you create a Droplet via the API, you receive a JSON response containing information about the Droplet. You can use the jq tool to parse that response and extract the specific value you want by piping the output to it. You can also assign it a variable at the same time. You could do it like this:

droplet_id=`curl -X POST -H "Content-Type: application/json" -H "Authorization: Bearer $DO_TOKEN" \
    -d '{"name":"example","region":"nyc3","size":"512mb","image":"ubuntu-14-04-x64"}' \
    "" | jq`

Running echo $droplet_id will return the Droplet’s ID if the request was successful.

When you create a droplet via the API an event id for the creation process is returned. You can then poll the events endpoint for that event’s status and once complete, the droplet’s ID. That ID can then be used against the droplet endpoint to gather other details like IP addresses, etc.

Because the IPs and other details are only assigned once the droplet is created they cannot be polled directly from the creation event.