#!/bin/bash # Default values DEFAULT_CORES=2 DEFAULT_RAM=2048 DEFAULT_SWAP=512 DEFAULT_STORAGE=8 DEFAULT_TEMPLATE="/var/lib/vz/template/cache/nixos_proxmox_lxc.tar.xz" # Function to display usage usage() { echo "Usage: $0 -n HOSTNAME_CONTAINER [-c CORES] [-m RAM] [-s SWAP] [-d STORAGE] [-i IP/DHCP]" echo "Options:" echo " -n HOSTNAME_CONTAINER Container hostname (required)" echo " -c CORES Number of CPU cores (default: $DEFAULT_CORES)" echo " -m RAM RAM in MB (default: $DEFAULT_RAM)" echo " -s SWAP Swap size in MB (default: $DEFAULT_SWAP)" echo " -d STORAGE Root filesystem size in GB (default: $DEFAULT_STORAGE)" echo " -i IP IP address in CIDR format or 'dhcp' (default: dhcp)" exit 1 } # Check if running as root if [ "$EUID" -ne 0 ]; then echo "Please run as root" exit 1 fi # Parse command line arguments while getopts "n:c:m:s:d:i:" opt; do case $opt in n) HOSTNAME_CONTAINER="$OPTARG" ;; c) CORES="$OPTARG" ;; m) RAM="$OPTARG" ;; s) SWAP="$OPTARG" ;; d) STORAGE="$OPTARG" ;; i) IP="$OPTARG" ;; *) usage ;; esac done # Check for required hostname if [ -z "$HOSTNAME_CONTAINER" ]; then echo "Error: Hostname is required" usage fi # Set defaults if not specified CORES=${CORES:-$DEFAULT_CORES} RAM=${RAM:-$DEFAULT_RAM} SWAP=${SWAP:-$DEFAULT_SWAP} STORAGE=${STORAGE:-$DEFAULT_STORAGE} IP=${IP:-"dhcp"} # Check if template exists if [ ! -f "$DEFAULT_TEMPLATE" ]; then echo "Error: NixOS template not found at $DEFAULT_TEMPLATE" exit 1 fi # Get next available CT ID NEXT_ID=$(pvesh get /cluster/nextid) # Prepare network config if [ "$IP" = "dhcp" ]; then NET_CONFIG="name=eth0,ip=dhcp,bridge=vmbr0" else NET_CONFIG="name=eth0,ip=$IP,bridge=vmbr0" fi # Create container echo "Creating NixOS container CT $NEXT_ID..." pct create "$NEXT_ID" "$DEFAULT_TEMPLATE" \ --hostname "$HOSTNAME_CONTAINER" \ --cores "$CORES" \ --memory "$RAM" \ --swap "$SWAP" \ --rootfs "local-lvm:${STORAGE}" \ --net0 "$NET_CONFIG" \ --unprivileged 1 \ --features "nesting=1" \ --start 1 # Get container's IPv4 address IP_ADDRESS=$(pct exec $NEXT_ID -- hostname -I | awk '{print $1}') if [ $? -eq 0 ]; then echo "Container $NEXT_ID created successfully" echo "Hostname: $HOSTNAME_CONTAINER" echo "Cores: $CORES" echo "RAM: $RAM MB" echo "Swap: $SWAP MB" echo "Storage: $STORAGE GB" echo "Network: $NET_CONFIG" # Only display IP if we got one if [ ! -z "$IP_ADDRESS" ]; then echo -e "${HOSTNAME_CONTAINER} is now deployed at ${GREEN}${IP_ADDRESS}${NC}" else echo "Warning: Could not retrieve IP address" fi else echo "Error: Failed to create container" exit 1 fi