Skip to content

Instantly share code, notes, and snippets.

@fabriziosalmi
Created November 29, 2024 17:29
Show Gist options
  • Save fabriziosalmi/cdfb9991e6a6a43eb00432c06fe7823a to your computer and use it in GitHub Desktop.
Save fabriziosalmi/cdfb9991e6a6a43eb00432c06fe7823a to your computer and use it in GitHub Desktop.
proxmox configuration via yaml and python

Proxmox API Integration Guide

This repository demonstrates the use of the Proxmox API for programmatically managing Proxmox environments. By leveraging the API, you can efficiently handle Proxmox nodes, containers (LXC), and virtual machines (VMs) in a secure, scalable, and maintainable manner. This guide provides an example of automating tasks like LXC and VM creation using Python.


Features

  • Supports LXC and VM Management: Provision containers and VMs with detailed configurations.
  • Centralized Configuration: YAML-based configuration simplifies management of multiple hosts and nodes.
  • Secure API Authentication: Compatible with both password and API token-based authentication.
  • Dynamic Node Selection: Automatically identifies and uses available Proxmox nodes.
  • Error Feedback and Handling: Includes basic checks for nodes and configurations.
  • Extensibility: Easily adaptable for additional tasks like backups, snapshots, or monitoring.

Prerequisites

  1. Proxmox VE environment with API access enabled.
  2. Python 3.6+ installed.
  3. Admin access to Proxmox to generate API tokens or passwords.

Installation

  1. Clone this repository:

    git clone https://github.com/your-repo/proxmox-api-integration.git
    cd proxmox-api-integration
  2. Install the required Python libraries:

    pip install proxmoxer requests pyyaml
  3. Ensure you have a valid YAML configuration file (see example below).


Configuration

Create a config.yaml file in the root directory. This file contains the Proxmox host details, API credentials, and VM/LXC configurations.

hosts:
  - api_url: "https://192.168.1.10:8006/api2/json"
    username: "root@pam"
    password: "yourpassword"  # Use this or API token below
    token_name: "apitoken"    # Optional: API token name
    token_secret: "token_secret"  # Optional: API token secret
    vms:
      - type: "lxc"
        vmid: 101
        name: "container1"
        template: "local:vztmpl/ubuntu-20.04-standard_20.04-1_amd64.tar.gz"
        cpu: 2
        memory: 2048
        disk: "10G"
        network_bridge: "vmbr0"
        ip: "192.168.100.10/24"
        gateway: "192.168.100.1"
      - type: "vm"
        vmid: 102
        name: "vm1"
        iso: "local:iso/debian.iso"
        cpu: 4
        memory: 8192
        disk: "50G"
        network_bridge: "vmbr0"
        ip: "dhcp"

Usage

Run the script to create the resources defined in your configuration file:

python script.py

Example Script

Below is the Python script for interacting with the Proxmox API:

from proxmoxer import ProxmoxAPI
import yaml

def create_lxc(proxmox, node, config):
    """Create an LXC container."""
    proxmox.nodes(node).lxc.create(
        vmid=config['vmid'],
        ostemplate=config['template'],
        hostname=config['name'],
        cores=config['cpu'],
        memory=config['memory'],
        rootfs=f"local:{config['disk']}",
        net0=f"name=eth0,bridge={config['network_bridge']},ip={config['ip']},gw={config['gateway']}",
        start=1
    )
    print(f"LXC {config['name']} created on {node}")

def create_vm(proxmox, node, config):
    """Create a VM."""
    proxmox.nodes(node).qemu.create(
        vmid=config['vmid'],
        name=config['name'],
        cores=config['cpu'],
        memory=config['memory'],
        net0=f"virtio,bridge={config['network_bridge']}",
        ide2=f"{config['iso']},media=cdrom",
        scsi0=f"local-lvm:{config['disk']}",
        boot="c",
        sockets=1,
        start=1
    )
    print(f"VM {config['name']} created on {node}")

def configure_host(host_config):
    """Configure Proxmox host."""
    proxmox = ProxmoxAPI(
        host_config['api_url'],
        user=host_config['username'],
        password=host_config.get('password'),
        token_name=host_config.get('token_name'),
        token_value=host_config.get('token_secret'),
        verify_ssl=False
    )
    nodes = proxmox.nodes.get()
    if not nodes:
        raise Exception(f"No nodes found in Proxmox at {host_config['api_url']}")

    # Use the first available node
    node = nodes[0]['node']
    for vm in host_config.get('vms', []):
        if vm['type'] == 'lxc':
            create_lxc(proxmox, node, vm)
        elif vm['type'] == 'vm':
            create_vm(proxmox, node, vm)
        else:
            print(f"Unsupported VM type: {vm['type']}")

def main():
    with open("config.yaml", "r") as file:
        config = yaml.safe_load(file)

    for host in config['hosts']:
        configure_host(host)

if __name__ == "__main__":
    main()

Advantages of Using the Proxmox API

  1. Stability: Abstracts underlying system commands, reducing compatibility issues with updates.
  2. Structured Responses: Detailed error messages and feedback for easier debugging.
  3. Scalability: Ideal for managing multiple nodes, VMs, and containers programmatically.
  4. Security: Avoids direct manipulation of sensitive files like SSH private keys.

Roadmap

  • Add support for Proxmox backups and snapshots.
  • Integrate monitoring tools using Proxmox metrics.
  • Extend support for high-availability configurations.
  • Implement better logging and error handling.

Contribution

Contributions are welcome! Please follow these steps:

  1. Fork the repository.
  2. Create a new branch for your feature or bugfix.
  3. Submit a pull request with a detailed description of your changes.

License

This project is licensed under the MIT License. See the LICENSE file for details.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment