'How to be notified when a droplet is active after its creation

I'm working on an automation script with the DO API and Ansible. I can create a lot of droplets but how to know if the created droplets has been active?

The first (naive) approach uses the following process:

A. Create droplet with the Digital Ocean API
B. Call the API to get the created droplet informations
    1. is active ?
        yes : 
        no : go to B

In the best world, after the droplet creation, I will be notified (like a webhook executed when the droplet creation is finished). Is it possible?



Solution 1:[1]

For the first approach, DigitalOcean's API also returns Action items. These can be used to check the status of different actions you take. The returned json looks like:

{
  "action": {
    "id": 36804636,
    "status": "completed",
    "type": "create",
    "started_at": "2014-11-14T16:29:21Z",
    "completed_at": "2014-11-14T16:30:06Z",
    "resource_id": 3164444,
    "resource_type": "droplet",
    "region": "nyc3",
    "region_slug": "nyc3"
  }
}

Here is a quick example of how they can be used:

import os, time
import requests

token = os.getenv('DO_TOKEN')
url = "https://api.digitalocean.com/v2/droplets"

payload = {'name': 'example.com', 'region': 'nyc3', 'size': '512mb', "image": "ubuntu-14-04-x64"}
headers = {'Authorization': 'Bearer {}'.format(token)}

r = requests.post(url, headers=headers, json=payload)

action_url = r.json()['links']['actions'][0]['href']

r = requests.get(action_url, headers=headers)
status = r.json()['action']['status']

while status != u'completed':
    print('Waiting for Droplet...')
    time.sleep(2)
    r = requests.get(action_url, headers=headers)
    status = r.json()['action']['status']

print('Droplet ready...')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 andrewsomething