Skip to content

Instantly share code, notes, and snippets.

@Skitionek
Created October 3, 2025 12:55
Show Gist options
  • Save Skitionek/8270497beb33d12a753348868b01b090 to your computer and use it in GitHub Desktop.
Save Skitionek/8270497beb33d12a753348868b01b090 to your computer and use it in GitHub Desktop.
Sync /etc/hosts with Azure vms adresses
#!/bin/bash
set -euo pipefail
# Configuration
HOSTS_FILE="/etc/hosts"
BACKUP_DIR="$HOME/.azure_hosts_backups"
AZURE_MARKER_START="# === AZURE VMs START ==="
AZURE_MARKER_END="# === AZURE VMs END ==="
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
log_info() {
echo -e "${GREEN}[INFO]${NC} $1"
}
log_warn() {
echo -e "${YELLOW}[WARN]${NC} $1"
}
log_error() {
echo -e "${RED}[ERROR]${NC} $1"
}
# Check if Azure CLI is installed
check_azure_cli() {
if ! command -v az &> /dev/null; then
log_error "Azure CLI is not installed. Please install it first."
exit 1
fi
}
# Check if user is logged in to Azure
check_azure_login() {
if ! az account show &> /dev/null; then
log_error "Not logged in to Azure. Please run 'az login' first."
exit 1
fi
}
# Create backup directory
create_backup_dir() {
mkdir -p "$BACKUP_DIR"
}
# Backup current hosts file
backup_hosts_file() {
local timestamp=$(date +"%Y%m%d_%H%M%S")
local backup_file="$BACKUP_DIR/hosts_backup_$timestamp"
if cp "$HOSTS_FILE" "$backup_file"; then
log_info "Hosts file backed up to: $backup_file"
else
log_error "Failed to backup hosts file"
exit 1
fi
}
# Get VM information from Azure
get_azure_vms() {
# Get all VMs with their public and private IPs
az vm list-ip-addresses --output json | jq -r '
.[] |
select(.virtualMachine.network.publicIpAddresses != null and (.virtualMachine.network.publicIpAddresses | length) > 0) |
.virtualMachine.name as $name |
.virtualMachine.network.publicIpAddresses[0].ipAddress as $public_ip |
(.virtualMachine.network.privateIpAddresses[0] // "") as $private_ip |
"\($public_ip)\t\($name)\t# Azure VM (Private: \($private_ip))"
' 2>/dev/null || {
log_error "Failed to fetch VM information from Azure"
exit 1
}
}
# Remove existing Azure VM entries from hosts file
remove_existing_azure_entries() {
local temp_file=$(mktemp)
# Remove content between markers (including markers)
awk "
BEGIN { skip = 0 }
/^$AZURE_MARKER_START/ { skip = 1; next }
/^$AZURE_MARKER_END/ { skip = 0; next }
!skip { print }
" "$HOSTS_FILE" > "$temp_file"
if mv "$temp_file" "$HOSTS_FILE"; then
log_info "Removed existing Azure VM entries from hosts file"
else
log_error "Failed to update hosts file"
exit 1
fi
}
# Add Azure VM entries to hosts file
add_azure_entries() {
local vm_entries="$1"
if [ -z "$vm_entries" ]; then
log_warn "No VMs with public IPs found in Azure"
return
fi
# Add markers and VM entries to hosts file
{
echo ""
echo "$AZURE_MARKER_START"
echo "$vm_entries"
echo "$AZURE_MARKER_END"
} >> "$HOSTS_FILE"
log_info "Added Azure VM entries to hosts file"
}
# Display summary
show_summary() {
local vm_count=$(echo "$1" | grep -c "^[0-9]" || echo "0")
log_info "Summary: Added $vm_count VM entries to $HOSTS_FILE"
if [ "$vm_count" -gt 0 ]; then
echo ""
echo "Added entries:"
echo "$1" | while IFS=$'\t' read -r ip name comment; do
echo " $ip -> $name"
done
fi
}
# Main function
main() {
log_info "Starting Azure VM hosts file update..."
# Preliminary checks
check_azure_cli
check_azure_login
# Check if we have write permissions to hosts file
if [ ! -w "$HOSTS_FILE" ]; then
log_error "No write permission to $HOSTS_FILE. Please run with sudo."
exit 1
fi
# Setup
create_backup_dir
backup_hosts_file
# Get VM information
log_info "Fetching VM information from Azure..."
vm_entries=$(get_azure_vms)
# Update hosts file
remove_existing_azure_entries
add_azure_entries "$vm_entries"
# Show results
show_summary "$vm_entries"
log_info "Azure VM hosts file update completed successfully!"
}
# Help function
show_help() {
cat << EOF
Usage: $0 [OPTIONS]
Update /etc/hosts file with Azure VM IP addresses and names.
OPTIONS:
-h, --help Show this help message
-d, --dry-run Show what would be added without modifying hosts file
REQUIREMENTS:
- Azure CLI installed and configured
- Logged in to Azure (az login)
- Write permission to /etc/hosts (run with sudo if needed)
- jq installed for JSON parsing
EXAMPLES:
# Update hosts file with Azure VMs
sudo $0
# See what would be added (dry run)
$0 --dry-run
EOF
}
# Handle command line arguments
case "${1:-}" in
-h|--help)
show_help
exit 0
;;
-d|--dry-run)
log_info "DRY RUN: Showing what would be added to hosts file"
check_azure_cli
check_azure_login
vm_entries=$(get_azure_vms)
if [ -n "$vm_entries" ]; then
echo ""
echo "Would add the following entries:"
echo "$vm_entries"
else
log_warn "No VMs with public IPs found"
fi
exit 0
;;
"")
main
;;
*)
log_error "Unknown option: $1"
show_help
exit 1
;;
esac
#!/bin/bash
set -euo pipefail
BACKUP_DIR="$HOME/.azure_hosts_backups"
HOSTS_FILE="/etc/hosts"
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m'
log_info() {
echo -e "${GREEN}[INFO]${NC} $1"
}
log_error() {
echo -e "${RED}[ERROR]${NC} $1"
}
# List available backups
list_backups() {
if [ ! -d "$BACKUP_DIR" ]; then
log_error "No backup directory found at $BACKUP_DIR"
exit 1
fi
local backups=($(ls -1t "$BACKUP_DIR"/hosts_backup_* 2>/dev/null || true))
if [ ${#backups[@]} -eq 0 ]; then
log_error "No backups found in $BACKUP_DIR"
exit 1
fi
echo "Available backups (newest first):"
for i in "${!backups[@]}"; do
local backup="${backups[$i]}"
local basename=$(basename "$backup")
local timestamp=$(echo "$basename" | sed 's/hosts_backup_//')
local readable_date=$(date -j -f "%Y%m%d_%H%M%S" "$timestamp" "+%Y-%m-%d %H:%M:%S" 2>/dev/null || echo "$timestamp")
echo " $((i+1)). $basename ($readable_date)"
done
echo ""
read -p "Select backup number to restore (1-${#backups[@]}): " selection
if [[ "$selection" =~ ^[0-9]+$ ]] && [ "$selection" -ge 1 ] && [ "$selection" -le ${#backups[@]} ]; then
selected_backup="${backups[$((selection-1))]}"
restore_backup "$selected_backup"
else
log_error "Invalid selection"
exit 1
fi
}
# Restore selected backup
restore_backup() {
local backup_file="$1"
if [ ! -f "$backup_file" ]; then
log_error "Backup file not found: $backup_file"
exit 1
fi
if [ ! -w "$HOSTS_FILE" ]; then
log_error "No write permission to $HOSTS_FILE. Please run with sudo."
exit 1
fi
if cp "$backup_file" "$HOSTS_FILE"; then
log_info "Successfully restored hosts file from: $(basename "$backup_file")"
else
log_error "Failed to restore backup"
exit 1
fi
}
# Main
case "${1:-}" in
-h|--help)
echo "Usage: $0"
echo "Restore /etc/hosts file from Azure VM update backups"
exit 0
;;
*)
list_backups
;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment