Automating Proxmox Container Management with Ansible
Managing a growing homelab or server fleet manually is inefficient. If you're running multiple LXC containers on Proxmox, it makes sense to automate basic setup and maintenance. In this post, I'll show how to create an Ansible workflow that dynamically discovers containers, builds an inventory, and runs tasks like apt update
, setting a default shell, and more.
Step 1: Dynamic Inventory with Proxmox
Start by querying Proxmox for a list of running containers. You can use a small Python script or shell script to generate a dynamic Ansible inventory.
Here's a quick and dirty example using pct
:
#!/bin/bash
# save as generate_inventory.sh
echo "[lxc]"
for id in $(pct list | awk 'NR>1 {print $1}'); do
ip=$(pct exec $id -- hostname -I | awk '{print $1}')
name=$(pct exec $id -- hostname)
echo "$name ansible_host=$ip ansible_user=root"
done
Make it executable:
chmod +x generate_inventory.sh
Run it like this to feed directly into Ansible:
ansible -i <(./generate_inventory.sh) lxc -m ping
Or you can redirect the output to a static file:
./generate_inventory.sh > inventory.ini
Step 2: Ansible Playbook for Container Setup
Now let's create a playbook that performs common setup steps.
# lxc_setup.yml
- name: Configure LXC containers
hosts: lxc
become: yes
tasks:
- name: Update apt cache and upgrade packages
apt:
update_cache: yes
upgrade: dist
- name: Install common packages
apt:
name:
- curl
- vim
- sudo
state: present
- name: Change default shell to bash
user:
name: "{{ ansible_user }}"
shell: /bin/bash
- name: Ensure .bashrc is present
copy:
src: ./dotfiles/bashrc
dest: /root/.bashrc
owner: root
group: root
mode: '0644'
📝 Tip: You can create a
dotfiles/bashrc
file with your custom shell config.
Step 3: Run It All
Once your inventory is ready and your playbook is defined, run it:
ansible-playbook -i inventory.ini lxc_setup.yml
Or directly with the dynamic inventory script:
ansible-playbook -i <(./generate_inventory.sh) lxc_setup.yml
Conclusion
This setup saves a ton of time when managing multiple containers in a homelab or test environment. You can extend the playbook to configure SSH keys, install Docker, or set up monitoring agents—whatever you need. The key is building automation into your workflow early so you can scale without stress.
Let me know if you'd like a downloadable repo or if I should turn this into a role-based structure next!