-
-
Save genothomas/f1ff35348eee542368e1ebdf978886d9 to your computer and use it in GitHub Desktop.
Dynamically generates an Ansible inventory based on your DigitalOcean droplets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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