Created
January 28, 2020 17:18
-
-
Save rajeshisnepali/7d6420677bf74f94a1fdfe05e055537a to your computer and use it in GitHub Desktop.
modify /etc/hosts [docker container networks]
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
#!/usr/bin/env bash | |
#format = sudo manage-etc-hosts.sh <docker_webserver_container_name> <domain> | |
set -eu | |
if [ "$EUID" -ne 0 ] | |
then echo "Please run as root" | |
exit | |
fi | |
# PATH TO YOUR HOSTS FILE | |
: ${ETC_HOSTS="/etc/hosts"} | |
# DEFAULT IP FOR HOSTNAME | |
DEFAULT_IP=127.0.0.1 | |
VERBOSE=true | |
function remove() { | |
local HOSTNAME=$1 | |
local HOST_REGEX="\(\s\+\)${HOSTNAME}\s*$" | |
local HOST_LINE="$(grep -e "${HOST_REGEX}" ${ETC_HOSTS})" | |
if [ -n "${HOST_LINE}" ]; then | |
[ ${VERBOSE} == true ] && echo "${HOSTNAME} Found in your ${ETC_HOSTS}, Removing now..." | |
sed -i -e "s/${HOST_REGEX}/\1/g" -e "/^[^#][0-9\.]\+\s\+$/d" ${ETC_HOSTS} | |
else | |
[ ${VERBOSE} == true ] && echo "${HOSTNAME} was not found in your ${ETC_HOSTS}"; | |
fi | |
} | |
function add() { | |
local HOSTNAME=$1 | |
local IP=${2:-${DEFAULT_IP}} | |
local HOST_REGEX="\(\s\+\)${HOSTNAME}\s*$" | |
local HOST_LINE="$(grep -e "${HOST_REGEX}" ${ETC_HOSTS})" | |
if [ -n "${HOST_LINE}" ]; then | |
[ ${VERBOSE} == true ] && echo "${HOSTNAME} already exists : ${HOST_LINE}" | |
else | |
[ ${VERBOSE} == true ] && echo "Adding ${HOSTNAME} to your ${ETC_HOSTS}"; | |
echo -e "${IP}\t${HOSTNAME}" >> ${ETC_HOSTS} | |
[ ${VERBOSE} == true ] && echo -e "${HOSTNAME} was added succesfully \n ${HOST_LINE}"; | |
# nscd -i hosts | |
fi | |
} | |
function modify-host() { | |
ip="$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $1)" | |
remove $2 | |
add $2 $ip | |
} | |
# Execute | |
$@ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment