-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdocker-hosts
executable file
·48 lines (40 loc) · 1.08 KB
/
docker-hosts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#!/bin/bash
HOSTS_FILE="/etc/hosts"
START_MARK="##### START DOCKER #####"
END_MARK="##### END DOCKER #####"
clear_hosts() {
START_LINE=$(grep -n "$START_MARK" $HOSTS_FILE | cut -d ':' -f 1)
END_LINE=$(grep -n "$END_MARK" $HOSTS_FILE | tail -n 1 | cut -d ':' -f 1)
if [ -z $START_LINE ] || [ -z $END_LINE ]; then
echo "Nothing to clear."
return 0
fi
echo "Deleting from $START_LINE to $END_LINE lines"
sed -i "${START_LINE},${END_LINE}d" $HOSTS_FILE
}
add_hosts() {
echo -e "$START_MARK" >> $HOSTS_FILE
CONTAINERS=$(docker ps --format="{{.ID}}")
for CUR in $CONTAINERS; do
HOSTS=$(docker inspect --format '{{range .NetworkSettings.Networks}}{{.IPAddress}} {{join .DNSNames " "}}{{printf "\n"}}{{end}}' $CUR)
echo -e "$HOSTS" >> $HOSTS_FILE
done
echo -e "$END_MARK" >> $HOSTS_FILE
}
case "$1" in
add)
echo -e "Adding hosts..."
add_hosts
;;
replace)
echo -e "Replacing..."
clear_hosts
add_hosts
;;
clear)
echo "Clearing..."
clear_hosts
;;
*)
echo -e "Usage: docker-hosts add|replace|clear"
esac