Skip to content

Instantly share code, notes, and snippets.

@senz
Created April 25, 2016 08:12
Show Gist options
  • Save senz/16780db7e4c762a018e8e60b6efd85d0 to your computer and use it in GitHub Desktop.
Save senz/16780db7e4c762a018e8e60b6efd85d0 to your computer and use it in GitHub Desktop.
Ansible dynamic inventory for docker-machine written in PHP
#!/usr/bin/php
<?php
/**
* Created by IntelliJ IDEA.
* User: senz
* Date: 24.04.16
* Time: 14:54
*/
$opts = getopt('', [
"list",
"host:"
]);
if ($argc < 2 || $argc > 3) {
fwrite(STDERR, "Invalid argument count\n");
exit(1);
}
if (count($opts) != 1) {
fwrite(STDERR, "Only one argument must be passed\n");
exit(1);
}
$machineName = getenv("DOCKER_MACHINE_NAME");
$hostString = getenv("DOCKER_HOST");
$certPath = getenv("DOCKER_CERT_PATH");
if (!$machineName || !$hostString || !$certPath) {
fwrite(STDERR,
<<<TXT
This script requires env vars:
DOCKER_MACHINE_NAME
DOCKER_HOST
DOCKER_CERT_PATH
And optional GROUPS_FILE with json describing groups attributes
(see https://docs.ansible.com/ansible/developing_inventory.html)
TXT
);
exit(1);
}
$sshPrivateKey = $certPath . DIRECTORY_SEPARATOR . "id_rsa";
$parsedHost = parse_url($hostString);
$host = $parsedHost['host'];
$groupsFile = getenv("GROUPS_FILE");
$out = "";
if (isset($opts['list'])) {
if (!$groupsFile || !is_readable($groupsFile)) {
$out = "{}";
} else {
$content = file_get_contents($groupsFile);
$json = json_decode($content, true);
if (null === $json) {
fwrite(STDERR, "Groups files cannot be decoded\n");
exit(1);
} else {
$out = $content;
}
}
} elseif (isset($opts['host'])) {
if ($opts['host'] == $machineName) {
$json = [
"ansible_host" => $host,
"ansible_ssh_private_key_file" => $sshPrivateKey,
"ansible_user" => "docker",
];
$out = json_encode($json);
} else {
$out = "{}";
}
} else {
fwrite(STDERR, "Abnormal crap\n");
exit(1);
}
echo $out . "\n";
exit(0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment