Skip to content

Instantly share code, notes, and snippets.

@erikaheidi
Created May 15, 2019 09:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save erikaheidi/a4f8a53f1bc311b7f2402bb49fd5b681 to your computer and use it in GitHub Desktop.
Save erikaheidi/a4f8a53f1bc311b7f2402bb49fd5b681 to your computer and use it in GitHub Desktop.
Dynamically generates an Ansible inventory based on your DigitalOcean droplets
<?php
####################################
# Dynamic Inventory Build Script
# usage: php doin.php > inventory
####################################
$DO_API_TOKEN = 'YOUR_DIGITALOCEAN_API_TOKEN';
$GROUP_NAME = 'servers';
$endpoint = "https://api.digitalocean.com/v2/droplets";
$headers[] = "Content-type: application/json";
$headers[] = "Authorization: Bearer $DO_API_TOKEN";
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_HTTPHEADER => $headers,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => $endpoint,
]);
$response = json_decode(curl_exec($curl), true);
curl_close($curl);
$hosts = [];
foreach ($response['droplets'] as $droplet) {
$hosts[] = inventoryHost($droplet['name'], $droplet['networks']['v4'][0]['ip_address']);
}
printInventory($GROUP_NAME, $hosts);
function inventoryHost($alias, $host)
{
return sprintf("%s ansible_host=%s\n", $alias, $host);
}
function printInventory($groupName, array $hosts)
{
$inventory = sprintf("[%s]\n", $groupName);
foreach ($hosts as $host) {
$inventory .= $host;
}
$inventory .= sprintf("\n[all:vars]\nansible_python_interpreter=/usr/bin/python3\n");
echo $inventory;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment