Skip to content

Instantly share code, notes, and snippets.

@juhokuu
Last active April 2, 2016 09:58
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 juhokuu/3acebb58312b45e6c779cb3cb9df16b6 to your computer and use it in GitHub Desktop.
Save juhokuu/3acebb58312b45e6c779cb3cb9df16b6 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
# Author: juhokuu
#
# Dumb script to manage port mappings between a LXD
# host and containers.
#
# $PATH has to include jq (a JSON processor https://stedolan.github.io/jq/),
# nc (netcat with support for UNIX-domain sockets), awk, iptables, and sort.
PORTMAPS=(
# <guest name> <host port> <guest port>
container01 8081 80
container02 8082 80
container03 8083 80
container04 8084 80
container05 8085 80
container06 8086 80
)
GUEST_INTERFACE="eth0"
HOST_NAT_INTERFACE="eth0"
LXD_SOCKET_PATH="/var/lib/lxd/unix.socket"
RESPONSE_HEADER_LINES=5
LXD_NET_REGEX='10\.0\..\..*'
for bin in jq awk nc iptables sort; do
type $bin &>/dev/null || {
printf "You need '$bin' in your \$PATH.\n"; exit 1; }
done
get_ip() {
request="GET /1.0/containers/${1}/state HTTP/1.1\nUser-Agent: meh\n"
request+="Host: localhost\nAccept: */*\n\n"
# Connect to LXD API and parse the output for the IP
# addr of $GUEST_INTERFACE
# (see https://github.com/lxc/lxd/blob/master/doc/rest-api.md)
printf "$request" | nc -U "$LXD_SOCKET_PATH" |\
awk "NR > $RESPONSE_HEADER_LINES" |\
jq -c ".metadata.network.${GUEST_INTERFACE}.addresses[].address" 2>/dev/null |\
awk "/$LXD_NET_REGEX/"
}
# Delete all prior rules by this script to ensure the PORTMAPS
# array and IPT rules stay in sync
iptables -t nat -L --line-number | awk '/08gsg209g/ {print $1}' |\
sort -nr | while read rule; do iptables -t nat -D PREROUTING $rule; done
for ((i=0; i<$(( ${#PORTMAPS[@]} - 1 )); i+=3)); do
ip_addr=$(get_ip ${PORTMAPS[$i]})
# If 'jq' spat out what at least appears like an IP then run IPT
# NOTE: This will APPEND rules after your current rules!
[[ $ip_addr =~ [0-9]*\.[0-9]*\.[0-9]*\.[0-9]* ]] && \
iptables -t nat -A PREROUTING -p tcp \
-i "$HOST_NAT_INTERFACE" --dport ${PORTMAPS[$i+1]} \
-j DNAT --to-destination "${ip_addr//\"/}":${PORTMAPS[$i+2]} \
-m comment --comment 'LXD: port forward /08gsg209g/'
done
iptables -t nat -L PREROUTING --line-numbers
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment