Created
June 1, 2022 13:53
-
-
Save Mahoney/c91dc09891dd30a7f5f1c77032a804e1 to your computer and use it in GitHub Desktop.
Add a new alias to an existing container from a container running within a docker network
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
#! /bin/sh | |
# Requires curl, jq & /var/run/docker.sock to be mounted into the container | |
set -eu | |
main() { | |
alias=$1 | |
container_id="$(hostname)" | |
original_network_config="$(original_network_config "$container_id")" | |
updated_network_config="$(add_alias "$original_network_config" "$alias")" | |
network_id="$(echo "$original_network_config" | jq -r '.NetworkID')" | |
disconnect_container "$container_id" "$network_id" | |
connect_container "$container_id" "$network_id" "$updated_network_config" | |
} | |
original_network_config() { | |
container_id=$1 | |
curl \ | |
-sS \ | |
--unix-socket /var/run/docker.sock \ | |
"http://v1.41/containers/$container_id/json" \ | |
| jq '.NetworkSettings.Networks | to_entries[0] | .value' | |
} | |
add_alias() { | |
original_network_config=$1 | |
alias=$2 | |
echo "$original_network_config" | jq '.Aliases += ["'"$alias"'"]' | |
} | |
disconnect_container() { | |
container_id=$1 | |
network_id=$2 | |
curl \ | |
-sS \ | |
-H 'Content-Type: application/json' \ | |
-d '{"Container": "'"$container_id"'"}' \ | |
--unix-socket /var/run/docker.sock \ | |
"http://v1.41/networks/$network_id/disconnect" | |
} | |
connect_container() { | |
container_id=$1 | |
network_id=$2 | |
updated_network_config=$3 | |
curl \ | |
-sS \ | |
-H 'Content-Type: application/json' \ | |
-d '{"Container": "'"$container_id"'", "EndpointConfig": '"$updated_network_config"'}' \ | |
--unix-socket /var/run/docker.sock \ | |
"http://v1.41/networks/$network_id/connect" | |
} | |
main "$@" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment