diff --git a/README.md b/README.md index d97ddd9..3d78282 100644 --- a/README.md +++ b/README.md @@ -1 +1,11 @@ -# lxc-iptag \ No newline at end of file +# lxc-iptag + +lxc-iptag is a simple script to add ip tags to LXC containers. + +![](./img/pve-lxc-iptag.png) + +## Installation + +```sh +curl -sL https://github.com/gitsang/lxc-iptag/raw/main/install.sh | sudo bash +``` diff --git a/img/pve-lxc-iptag.png b/img/pve-lxc-iptag.png new file mode 100644 index 0000000..4b06b2a Binary files /dev/null and b/img/pve-lxc-iptag.png differ diff --git a/install.sh b/install.sh new file mode 100644 index 0000000..93018ae --- /dev/null +++ b/install.sh @@ -0,0 +1,5 @@ +#!/bin/bash + +curl -sL https://github.com/gitsang/lxc-iptag/releases/download/v1.0.0/lxc-iptag -o /usr/local/bin/lxc-iptag +cp lxc-iptag /usr/local/bin +cp lxc-iptag.service /lib/systemd/system/ diff --git a/lxc-iptag b/lxc-iptag new file mode 100755 index 0000000..9a25f68 --- /dev/null +++ b/lxc-iptag @@ -0,0 +1,53 @@ +#!/bin/bash + +is_valid_ipv4() { + local ip=$1 + local regex="^([0-9]{1,3}\.){3}[0-9]{1,3}$" + + if [[ $ip =~ $regex ]]; then + IFS='.' read -r -a parts <<< "$ip" + for part in "${parts[@]}"; do + if ! [[ $part =~ ^[0-9]+$ ]] || ((part < 0 || part > 255)); then + return 1 + fi + done + return 0 + else + return 1 + fi +} + +main() { + while true; do + # Set the IP tags for all LXC containers + lxc_name_list=$(pct list 2>/dev/null | grep -v VMID | awk '{print $1}') + for lxc_name in ${lxc_name_list}; do + new_tags=() + + # Get tags + old_tags=$(pct config ${lxc_name} | grep tags | awk '{print $2}' | sed 's/;/ /g') + for old_tag in ${old_tags}; do + if is_valid_ipv4 ${old_tag}; then + continue + fi + new_tags+=("${old_tag}") + done + + # Get the valid IPv4s + ips=$(lxc-info -n ${lxc_name} -i | awk '{print $2}') + for ip in ${ips}; do + if is_valid_ipv4 ${ip}; then + new_tags+=("${ip}") + fi + done + + # Set the tags + joined_tags=$(IFS=';'; echo "${new_tags[*]}") + echo "Setting ${lxc_name} tags to ${joined_tags}" + pct set ${lxc_name} -tags "${joined_tags}" + done + sleep 60 + done +} + +main diff --git a/lxc-iptag.service b/lxc-iptag.service new file mode 100644 index 0000000..08b0c5a --- /dev/null +++ b/lxc-iptag.service @@ -0,0 +1,11 @@ +[Unit] +Description=Start lxc-iptag service +After=network.target + +[Service] +Type=simple +ExecStart=/usr/local/bin/lxc-iptag +Restart=always + +[Install] +WantedBy=multi-user.target