Skip to content

Instantly share code, notes, and snippets.

@am-
Created March 29, 2018 07:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save am-/6a5e34b5884974b19d02273db0517ec0 to your computer and use it in GitHub Desktop.
Save am-/6a5e34b5884974b19d02273db0517ec0 to your computer and use it in GitHub Desktop.
Script to update the hosts file according to the container names in a docker-compose setup
<?php
define('HOST_SUFFIX', '.local');
/**
* @return string[]
*/
function determineIpAddresses()
{
$lines = array_slice(explode(PHP_EOL, shell_exec('docker-compose ps')), 2, -1);
$ipAddresses = [];
foreach ($lines as $line) {
$container = explode(' ', $line, 2)[0];
$information = json_decode(shell_exec("docker inspect $container"), true)[0];
$ipAddresses[$container] = array_values($information['NetworkSettings']['Networks'])[0]['IPAddress'];
}
return $ipAddresses;
}
/**
* @param string[] $lines
* @param string[] $containers
* @return string[]
*/
function filterContainers($lines, $containers)
{
$hostSuffix = strlen(HOST_SUFFIX);
$filteredLines = [];
foreach ($lines as $line) {
if (substr($line, -$hostSuffix) !== HOST_SUFFIX) {
$filteredLines[] = $line;
continue;
}
$parts = preg_split('/[\t ]+/', $line);
$ipAddress = $parts[0];
$hosts = array_filter(array_slice($parts, 1));
foreach ($hosts as $index => $host) {
$container = substr($host, 0, -$hostSuffix);
if (in_array($container, $containers, true)) {
unset($hosts[$index]);
}
}
if ($hosts !== []) {
$filteredLines[] = buildHostLine($ipAddress, $hosts);
}
}
return $filteredLines;
}
/**
* @param string $ipAddress
* @param string[] $hosts
* @return string
*/
function buildHostLine($ipAddress, $hosts)
{
return $ipAddress . "\t" . implode(' ', $hosts);
}
/**
* @param string[] $ipAddresses
* @return string[]
*/
function generateHostLines($ipAddresses)
{
$lines = [];
foreach($ipAddresses as $container => $ipAddress) {
$lines[] = buildHostLine($ipAddress, [$container . HOST_SUFFIX]);
}
return $lines;
}
echo shell_exec('docker-compose start');
$ipAddresses = determineIpAddresses();
$filteredHostFile = filterContainers(file('/etc/hosts', FILE_IGNORE_NEW_LINES), array_keys($ipAddresses));
$lines = array_merge($filteredHostFile, generateHostLines($ipAddresses));
file_put_contents('/etc/hosts', implode(PHP_EOL, $lines) . PHP_EOL);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment