Building Virtual Machines in Proxmox with Ansible
In today's short and sweet #100DaysToOffload (post 005!), I would like to show off an #ansible playbook for creating VMs in #proxmox.
I wrote this playbook several weeks ago when I was trying to stretch the limits of what I could do with Ansible. It would be much better to do this with #opentofu or #terraform but I thought this was a fun exercise.
A few ways I would improve this playbook:
- Add all the hard coded variables to a prompt, ENV vars, or maybe a vault
- Check to see if the
vmid
exists before attempting to build the machine - Add more descriptive output when the play is done
In the future, I'd like to try to pull this off with #pulumi as well.
---
- name: Create Fedora Server VM with demo user
hosts: localhost
gather_facts: yes
vars:
proxmox_host: "IP OR HOSTNAME"
vars_prompt:
- name: proxmox_user
prompt: "Proxmox username (e.g., root@pam)"
private: no
- name: proxmox_password
prompt: "Proxmox password"
private: yes
tasks:
- name: Read SSH public key
slurp:
src: "{{ ansible_env.HOME }}/.ssh/id_rsa.pub"
register: ssh_key
- name: Create Fedora VM
community.general.proxmox_kvm:
api_host: "{{ proxmox_host }}"
api_user: "{{ proxmox_user }}"
api_password: "{{ proxmox_password }}"
node: "NODE NAME HERE"
name: "fedora-demo-server"
vmid: 120
memory: 4096
cores: 2
cpu: "host"
ostype: "l26"
agent: enabled=1
net:
net0: "virtio,bridge=vmbr0"
virtio:
virtio0: "local-lvm:32"
ide:
ide2: "local:iso/Fedora-Server-netinst-x86_64-41-1.4.iso,media=cdrom"
serial:
serial0: "socket"
vga: "serial0"
boot: "order=ide2;virtio0"
bootdisk: "virtio0"
ciuser: "demo"
cipassword: "demo123"
citype: "nocloud"
ipconfig:
ipconfig0: "ip=dhcp"
sshkeys: "{{ ssh_key.content | b64decode | trim }}"
state: present
- name: Start VM
community.general.proxmox_kvm:
api_host: "{{ proxmox_host }}"
api_user: "{{ proxmox_user }}"
api_password: "{{ proxmox_password }}"
node: "NODE NAME HERE"
vmid: 120
state: started