Initial commit

This commit is contained in:
Zhongwei Li
2025-11-30 08:47:38 +08:00
commit 18faa0569e
47 changed files with 7969 additions and 0 deletions

View File

@@ -0,0 +1,155 @@
# Ansible Proxmox Authentication
## API Token Setup
Create a dedicated Ansible user and API token on Proxmox:
```bash
# On Proxmox node
pveum user add ansible@pve
pveum aclmod / -user ansible@pve -role PVEAdmin
pveum user token add ansible@pve mytoken --privsep 0
```
**Note:** `--privsep 0` gives the token the same permissions as the user.
## Playbook Variables
### Direct in playbook (NOT recommended)
```yaml
vars:
proxmox_api_host: proxmox.example.com
proxmox_api_user: ansible@pve
proxmox_api_token_id: mytoken
proxmox_api_token_secret: "{{ vault_proxmox_token }}"
```
### Group vars with vault
```yaml
# group_vars/all.yml
proxmox_api_host: proxmox.example.com
proxmox_api_user: ansible@pve
proxmox_api_token_id: mytoken
# group_vars/secrets.yml (ansible-vault encrypted)
proxmox_api_token_secret: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
```
### Environment variables
```bash
export PROXMOX_HOST=proxmox.example.com
export PROXMOX_USER=ansible@pve
export PROXMOX_TOKEN_ID=mytoken
export PROXMOX_TOKEN_SECRET=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
```
```yaml
# In playbook
vars:
proxmox_api_host: "{{ lookup('env', 'PROXMOX_HOST') }}"
proxmox_api_user: "{{ lookup('env', 'PROXMOX_USER') }}"
proxmox_api_token_id: "{{ lookup('env', 'PROXMOX_TOKEN_ID') }}"
proxmox_api_token_secret: "{{ lookup('env', 'PROXMOX_TOKEN_SECRET') }}"
```
## Reusable Auth Block
Define once, reuse across tasks:
```yaml
vars:
proxmox_auth: &proxmox_auth
api_host: "{{ proxmox_api_host }}"
api_user: "{{ proxmox_api_user }}"
api_token_id: "{{ proxmox_api_token_id }}"
api_token_secret: "{{ proxmox_api_token_secret }}"
validate_certs: false # For self-signed certs
tasks:
- name: Create VM
community.general.proxmox_kvm:
<<: *proxmox_auth
node: joseph
vmid: 300
name: myvm
state: present
- name: Start VM
community.general.proxmox_kvm:
<<: *proxmox_auth
vmid: 300
state: started
```
## TLS Certificate Handling
### Self-signed certificates
```yaml
community.general.proxmox_kvm:
# ... auth params ...
validate_certs: false
```
### Custom CA
```bash
export SSL_CERT_FILE=/path/to/ca-bundle.crt
```
Or in ansible.cfg:
```ini
[defaults]
# For urllib3/requests
ca_cert = /path/to/ca-bundle.crt
```
## Minimum Required Permissions
For full VM/container management:
| Permission | Path | Purpose |
|------------|------|---------|
| VM.Allocate | / | Create VMs |
| VM.Clone | / | Clone templates |
| VM.Config.* | / | Modify VM config |
| VM.PowerMgmt | / | Start/stop VMs |
| VM.Snapshot | / | Create snapshots |
| Datastore.AllocateSpace | / | Allocate disk space |
| Datastore.Audit | / | List storage |
Or use the built-in `PVEAdmin` role for full access.
## Troubleshooting Auth Issues
```yaml
# Debug task to test connection
- name: Test Proxmox API connection
community.general.proxmox_kvm:
api_host: "{{ proxmox_api_host }}"
api_user: "{{ proxmox_api_user }}"
api_token_id: "{{ proxmox_api_token_id }}"
api_token_secret: "{{ proxmox_api_token_secret }}"
validate_certs: false
vmid: 100
state: current
register: result
ignore_errors: true
- name: Show result
ansible.builtin.debug:
var: result
```
Common errors:
| Error | Cause | Fix |
|-------|-------|-----|
| 401 Unauthorized | Bad token | Verify token ID format: `user@realm!tokenname` |
| 403 Forbidden | Insufficient permissions | Check user ACLs with `pveum user permissions ansible@pve` |
| SSL certificate problem | Self-signed cert | Set `validate_certs: false` |
| Connection refused | Wrong host/port | Verify API URL (port 8006) |

View File

@@ -0,0 +1,195 @@
# Ansible Proxmox Dynamic Inventory
Query Proxmox API for automatic inventory generation.
## Plugin Setup
### Requirements
```bash
pip install proxmoxer requests
ansible-galaxy collection install community.general
```
### Inventory File
Create `inventory/proxmox.yml`:
```yaml
plugin: community.general.proxmox
url: https://proxmox.example.com:8006
user: ansible@pve
token_id: mytoken
token_secret: "{{ lookup('env', 'PROXMOX_TOKEN_SECRET') }}"
validate_certs: false
# Include VMs and containers
want_facts: true
want_proxmox_nodes_ansible_host: false
# Filter by status
filters:
- status == "running"
# Group by various attributes
groups:
# By Proxmox node
node_joseph: proxmox_node == "joseph"
node_maxwell: proxmox_node == "maxwell"
node_everette: proxmox_node == "everette"
# By type
vms: proxmox_type == "qemu"
containers: proxmox_type == "lxc"
# By template naming convention
docker_hosts: "'docker' in proxmox_name"
pihole: "'pihole' in proxmox_name"
# Host variables from Proxmox
compose:
ansible_host: proxmox_agent_interfaces[0].ip-addresses[0].ip-address | default(proxmox_name)
ansible_user: "'ubuntu'"
proxmox_vmid: proxmox_vmid
proxmox_node: proxmox_node
```
### Enable in ansible.cfg
```ini
[inventory]
enable_plugins = community.general.proxmox, yaml, ini
```
## Testing Inventory
```bash
# List all hosts
ansible-inventory -i inventory/proxmox.yml --list
# Graph view
ansible-inventory -i inventory/proxmox.yml --graph
# Specific host details
ansible-inventory -i inventory/proxmox.yml --host myvm
```
## Common Patterns
### Filter by Tags
Proxmox 7+ supports VM tags:
```yaml
groups:
webservers: "'web' in proxmox_tags"
databases: "'db' in proxmox_tags"
production: "'prod' in proxmox_tags"
```
### Filter by VMID Range
```yaml
filters:
- vmid >= 200
- vmid < 300
groups:
dev_vms: proxmox_vmid >= 200 and proxmox_vmid < 300
prod_vms: proxmox_vmid >= 300 and proxmox_vmid < 400
```
### IP Address from QEMU Agent
Requires QEMU guest agent running in VM:
```yaml
compose:
# Primary IP from agent
ansible_host: >-
proxmox_agent_interfaces
| selectattr('name', 'equalto', 'eth0')
| map(attribute='ip-addresses')
| flatten
| selectattr('ip-address-type', 'equalto', 'ipv4')
| map(attribute='ip-address')
| first
| default(proxmox_name)
```
### Static + Dynamic Inventory
Combine with static inventory:
```bash
# inventory/
# static.yml # Static hosts
# proxmox.yml # Dynamic from Proxmox
ansible-playbook -i inventory/ playbook.yml
```
## Available Variables
Variables populated from Proxmox API:
| Variable | Description |
|----------|-------------|
| proxmox_vmid | VM/container ID |
| proxmox_name | VM/container name |
| proxmox_type | "qemu" or "lxc" |
| proxmox_status | running, stopped, etc. |
| proxmox_node | Proxmox node name |
| proxmox_pool | Resource pool (if any) |
| proxmox_tags | Tags (Proxmox 7+) |
| proxmox_template | Is template (bool) |
| proxmox_agent | QEMU agent enabled (bool) |
| proxmox_agent_interfaces | Network info from agent |
| proxmox_cpus | CPU count |
| proxmox_maxmem | Max memory bytes |
| proxmox_maxdisk | Max disk bytes |
## Caching
Enable caching for faster inventory:
```yaml
plugin: community.general.proxmox
# ... auth ...
cache: true
cache_plugin: jsonfile
cache_connection: /tmp/ansible_proxmox_cache
cache_timeout: 300 # 5 minutes
```
Clear cache:
```bash
rm -rf /tmp/ansible_proxmox_cache
```
## Troubleshooting
### No hosts returned
1. Check API connectivity:
```bash
curl -k "https://proxmox:8006/api2/json/cluster/resources" \
-H "Authorization: PVEAPIToken=ansible@pve!mytoken=secret"
```
2. Check filters aren't too restrictive - try removing them
3. Verify token permissions include `VM.Audit`
### QEMU agent data missing
- Agent must be installed and running in guest
- `want_facts: true` must be set
- May take a few seconds after VM boot
### Slow inventory queries
- Enable caching (see above)
- Use filters to reduce results
- Avoid `want_facts: true` if not needed

View File

@@ -0,0 +1,202 @@
# Ansible Proxmox Gotchas
Common issues when using Ansible with Proxmox VE.
## 1. Token ID Format
**Wrong:**
```yaml
api_token_id: mytoken
```
**Correct:**
```yaml
api_token_id: mytoken # Just the token name, NOT user@realm!tokenname
```
The module combines `api_user` and `api_token_id` internally.
## 2. VMID Required for Most Operations
Unlike Terraform, you must always specify `vmid`:
```yaml
# Won't auto-generate VMID
- name: Create VM
community.general.proxmox_kvm:
# ... auth ...
vmid: 300 # REQUIRED - no auto-assignment
name: myvm
```
To find next available VMID:
```yaml
- name: Get cluster resources
ansible.builtin.uri:
url: "https://{{ proxmox_api_host }}:8006/api2/json/cluster/resources"
headers:
Authorization: "PVEAPIToken={{ proxmox_api_user }}!{{ proxmox_api_token_id }}={{ proxmox_api_token_secret }}"
validate_certs: false
register: resources
- name: Calculate next VMID
ansible.builtin.set_fact:
next_vmid: "{{ (resources.json.data | selectattr('vmid', 'defined') | map(attribute='vmid') | max) + 1 }}"
```
## 3. Node Parameter Required
Must specify which node to operate on:
```yaml
- name: Create VM
community.general.proxmox_kvm:
# ... auth ...
node: joseph # REQUIRED - which Proxmox node
vmid: 300
```
## 4. Clone vs Create
Cloning requires different parameters than creating:
```yaml
# CLONE from template
- name: Clone VM
community.general.proxmox_kvm:
# ... auth ...
node: joseph
vmid: 300
name: myvm
clone: tmpl-ubuntu-2404-standard # Template name or VMID
full: true
# CREATE new (less common)
- name: Create VM
community.general.proxmox_kvm:
# ... auth ...
node: joseph
vmid: 300
name: myvm
ostype: l26
scsihw: virtio-scsi-pci
bootdisk: scsi0
scsi:
scsi0: 'local-lvm:32,format=raw'
```
## 5. Async Operations
Large operations (clone, snapshot) can timeout. Use async:
```yaml
- name: Clone large VM
community.general.proxmox_kvm:
# ... auth ...
clone: large-template
vmid: 300
timeout: 600 # Module timeout
async: 900 # Ansible async timeout
poll: 10 # Check every 10 seconds
```
## 6. State Idempotency
`state: present` doesn't update existing VMs:
```yaml
# This WON'T change cores on existing VM
- name: Create/update VM
community.general.proxmox_kvm:
# ... auth ...
vmid: 300
cores: 4 # Ignored if VM exists
state: present
```
To modify existing VMs, use `proxmox_kvm` with `update: true` (Ansible 2.14+) or use the API directly.
## 7. Network Interface Format (LXC)
LXC containers use a specific JSON-like string format:
```yaml
# WRONG
netif:
net0:
bridge: vmbr0
ip: dhcp
# CORRECT
netif: '{"net0":"name=eth0,bridge=vmbr0,ip=dhcp"}'
# Multiple interfaces
netif: '{"net0":"name=eth0,bridge=vmbr0,ip=dhcp","net1":"name=eth1,bridge=vmbr12,ip=dhcp"}'
```
## 8. Disk Resize Only Grows
`proxmox_disk` resize only increases size:
```yaml
# This adds 20G to current size
- name: Grow disk
community.general.proxmox_disk:
# ... auth ...
vmid: 300
disk: scsi0
size: +20G # Relative increase
state: resized
# NOT possible to shrink
```
## 9. Template vs VM States
Templates don't support all states:
```yaml
# Can't start a template
- name: Start template
community.general.proxmox_kvm:
vmid: 100
state: started # FAILS - templates can't run
```
Convert template to VM first if needed.
## 10. Collection Version Matters
Module parameters change between versions. Check installed version:
```bash
ansible-galaxy collection list | grep community.general
```
Update if needed:
```bash
ansible-galaxy collection install community.general --upgrade
```
## 11. Cloud-Init Not Supported
Unlike Terraform's Proxmox provider, the Ansible modules have limited cloud-init support. For cloud-init VMs:
1. Clone template with cloud-init already configured
2. Use API calls to set cloud-init parameters
3. Or configure post-boot with Ansible
```yaml
# Workaround: Use URI module for cloud-init config
- name: Set cloud-init IP
ansible.builtin.uri:
url: "https://{{ proxmox_api_host }}:8006/api2/json/nodes/{{ node }}/qemu/{{ vmid }}/config"
method: PUT
headers:
Authorization: "PVEAPIToken={{ proxmox_api_user }}!{{ proxmox_api_token_id }}={{ proxmox_api_token_secret }}"
body_format: form-urlencoded
body:
ipconfig0: "ip=192.168.1.100/24,gw=192.168.1.1"
ciuser: ubuntu
validate_certs: false
```

View File

@@ -0,0 +1,232 @@
# Ansible Proxmox Modules
Proxmox VE management via `community.general` collection.
## Collection Setup
```bash
ansible-galaxy collection install community.general
```
## Core Modules
### proxmox (LXC Containers)
```yaml
- name: Create LXC container
community.general.proxmox:
api_host: proxmox.example.com
api_user: ansible@pve
api_token_id: mytoken
api_token_secret: "{{ proxmox_token_secret }}"
node: joseph
vmid: 200
hostname: mycontainer
ostemplate: local:vztmpl/ubuntu-22.04-standard_22.04-1_amd64.tar.zst
storage: local-lvm
cores: 2
memory: 2048
disk: 10
netif: '{"net0":"name=eth0,bridge=vmbr0,ip=dhcp"}'
state: present
- name: Start container
community.general.proxmox:
api_host: proxmox.example.com
api_user: ansible@pve
api_token_id: mytoken
api_token_secret: "{{ proxmox_token_secret }}"
node: joseph
vmid: 200
state: started
- name: Stop container
community.general.proxmox:
# ... auth params ...
vmid: 200
state: stopped
force: true # Force stop if graceful fails
- name: Remove container
community.general.proxmox:
# ... auth params ...
vmid: 200
state: absent
```
### proxmox_kvm (VMs)
```yaml
- name: Create VM from template
community.general.proxmox_kvm:
api_host: proxmox.example.com
api_user: ansible@pve
api_token_id: mytoken
api_token_secret: "{{ proxmox_token_secret }}"
node: joseph
vmid: 300
name: myvm
clone: tmpl-ubuntu-2404-standard
full: true # Full clone (not linked)
storage: local-lvm
format: raw
timeout: 500
- name: Start VM
community.general.proxmox_kvm:
# ... auth params ...
node: joseph
vmid: 300
state: started
- name: Stop VM (ACPI shutdown)
community.general.proxmox_kvm:
# ... auth params ...
vmid: 300
state: stopped
force: false # Graceful ACPI
- name: Force stop VM
community.general.proxmox_kvm:
# ... auth params ...
vmid: 300
state: stopped
force: true
- name: Current state (running/stopped/present/absent)
community.general.proxmox_kvm:
# ... auth params ...
vmid: 300
state: current
register: vm_state
```
### proxmox_template
```yaml
- name: Convert VM to template
community.general.proxmox_template:
api_host: proxmox.example.com
api_user: ansible@pve
api_token_id: mytoken
api_token_secret: "{{ proxmox_token_secret }}"
node: joseph
vmid: 100
state: present # Convert to template
- name: Delete template
community.general.proxmox_template:
# ... auth params ...
vmid: 100
state: absent
```
### proxmox_snap
```yaml
- name: Create snapshot
community.general.proxmox_snap:
api_host: proxmox.example.com
api_user: ansible@pve
api_token_id: mytoken
api_token_secret: "{{ proxmox_token_secret }}"
vmid: 300
snapname: before-upgrade
description: "Snapshot before major upgrade"
vmstate: false # Don't include RAM
state: present
- name: Rollback to snapshot
community.general.proxmox_snap:
# ... auth params ...
vmid: 300
snapname: before-upgrade
state: rollback
- name: Remove snapshot
community.general.proxmox_snap:
# ... auth params ...
vmid: 300
snapname: before-upgrade
state: absent
```
### proxmox_nic
```yaml
- name: Add NIC to VM
community.general.proxmox_nic:
api_host: proxmox.example.com
api_user: ansible@pve
api_token_id: mytoken
api_token_secret: "{{ proxmox_token_secret }}"
vmid: 300
interface: net1
bridge: vmbr12
model: virtio
tag: 12 # VLAN tag
state: present
- name: Remove NIC
community.general.proxmox_nic:
# ... auth params ...
vmid: 300
interface: net1
state: absent
```
### proxmox_disk
```yaml
- name: Add disk to VM
community.general.proxmox_disk:
api_host: proxmox.example.com
api_user: ansible@pve
api_token_id: mytoken
api_token_secret: "{{ proxmox_token_secret }}"
vmid: 300
disk: scsi1
storage: local-lvm
size: 50G
format: raw
state: present
- name: Resize disk
community.general.proxmox_disk:
# ... auth params ...
vmid: 300
disk: scsi0
size: +20G # Increase by 20G
state: resized
- name: Detach disk
community.general.proxmox_disk:
# ... auth params ...
vmid: 300
disk: scsi1
state: absent
```
## State Reference
| Module | States |
|--------|--------|
| proxmox (LXC) | present, started, stopped, restarted, absent |
| proxmox_kvm | present, started, stopped, restarted, absent, current |
| proxmox_template | present, absent |
| proxmox_snap | present, absent, rollback |
| proxmox_nic | present, absent |
| proxmox_disk | present, absent, resized |
## Common Parameters
All modules share these authentication parameters:
| Parameter | Description |
|-----------|-------------|
| api_host | Proxmox hostname/IP |
| api_user | User (format: user@realm) |
| api_token_id | API token name |
| api_token_secret | API token value |
| validate_certs | Verify TLS (default: true) |
| timeout | API timeout seconds |