Help us shape the future of Go! Take the 2026 Go Developer Survey

proxmox

package module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 28, 2026 License: Apache-2.0 Imports: 19 Imported by: 6

README

Proxmox REST API Client for Go

Status: This project is under active development. Its API may change and breaking changes are possible. Do not use it in production yet.

go-proxmox-rest is a type-safe Go client for the Proxmox VE REST API. It follows patterns familiar to users of the Kubernetes Go client: resource clients provide clear methods such as Get, List, Create, Update, and Delete.

Features

  • API-token and username/password authentication
  • TLS, custom CA certificate, proxy, timeout, retry, and client-side load-balancing options
  • Fluent access to cluster, node, pool, and storage resources
  • Support for QEMU virtual machines, LXC containers, networking, storage, backups, firewall rules, HA, Ceph, replication, and tasks
  • An in-memory fake Proxmox API for tests, without a running Proxmox cluster

Quick start

Create a client with an API token. The URL must include the Proxmox API path:

package main

import (
	"context"
	"fmt"
	"log"
	"os"

	proxmox "github.com/sergelogvinov/go-proxmox-rest"
)

func main() {
	client, err := proxmox.New(
		proxmox.ClientConfig{},
		proxmox.WithURL(os.Getenv("PROXMOX_URL")),
		proxmox.WithTokenAuth(
			os.Getenv("PROXMOX_TOKEN_ID"),
			os.Getenv("PROXMOX_TOKEN_SECRET"),
		),
	)
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()

	version, err := client.Version(context.Background())
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Proxmox VE %s\\n", version.Version)
}

For username and password authentication, use proxmox.WithPasswordAuth("user@realm", "password") instead of WithTokenAuth. Password authentication creates and renews a Proxmox ticket when needed.

For development systems with a self-signed certificate, you can add proxmox.WithInsecure(true). Do not use this option in production. Prefer proxmox.WithCACert("/path/to/ca.pem") when you use a private certificate authority.

Using resources

The root client gives access to the main Proxmox API areas. For example:

ctx := context.Background()

pools, err := client.Pools().List(ctx)
if err != nil {
	log.Fatal(err)
}

vm, err := client.Nodes("pve1").Qemu().Status(ctx, 100)
if err != nil {
	log.Fatal(err)
}

container, err := client.Nodes("pve1").LXC().Status(ctx, 101)
if err != nil {
	log.Fatal(err)
}

tasks, err := client.Nodes("pve1").Tasks().List(ctx, nil)
if err != nil {
	log.Fatal(err)
}

Available API areas include:

  • client.Cluster() for cluster resources, jobs, backups, HA, firewall, Ceph, replication, mappings, and custom QEMU CPU models
  • client.Nodes("node") for node status and configuration, QEMU VMs, LXC containers, tasks, storage, networking, hardware, Ceph, and backups
  • client.Pools() for resource pools
  • client.Storage() for cluster storage configuration
  • client.Version(ctx) for the Proxmox VE version

Write operations that start a background task return a *task.Task handle. Wait on it, or inspect its status and log:

t, err := client.Nodes("pve1").Qemu().Start(ctx, 100, nil)
if err != nil {
	log.Fatal(err)
}

if err := t.Wait(ctx, &task.WaitOptions{Timeout: 5 * time.Minute}); err != nil {
	log.Fatal(err)
}

t.UPID() returns the task identifier. If all you have is a UPID string, client.Nodes("pve1").Tasks().Task(upid) gives you the same handle.

Testing with the fake API

The fakeapi package starts an in-memory HTTP server that behaves like a small Proxmox cluster. It is useful for testing code that uses this module without access to a real cluster.

func TestMyCode(t *testing.T) {
	cluster := fakeapi.NewCluster(t, fakeapi.WithNodes("pve1"))
	client := cluster.Client(t)

	// Use client as you would use a client connected to Proxmox VE.
	_ = client
}

Read the fake API design for its current behavior and limitations. Runnable examples are in the examples directory.

Projects using this module

License

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.


Proxmox® is a registered trademark of Proxmox Server Solutions GmbH.

Documentation

Overview

Package proxmox provides a type-safe Go client for the Proxmox VE REST API, built on top of resty with a fluent resource-chaining API.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsNotFound

func IsNotFound(err error) bool

IsNotFound reports whether the error indicates that the requested resource (or a required Proxmox binary) was not found: a 404, a 500 whose message or per-field errors say so (Proxmox reports most missing guests and configs that way), or a missing task.

func IsRateLimited

func IsRateLimited(err error) bool

IsRateLimited reports whether the error is a 429 or a Proxmox "SlowDown" response.

func IsUnexpected

func IsUnexpected(err error) bool

IsUnexpected reports whether the error is a 5xx from the Proxmox API.

Types

type APIError

type APIError = apierr.APIError

APIError represents a Proxmox API error response. It is defined in internal/apierr, alongside the classification behind the Is* helpers below, so packages that cannot import this one classify errors the same way.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is the Proxmox VE API client.

func New

func New(cfg ClientConfig, opts ...Option) (*Client, error)

New builds a Client from the given config, applying the options on a copy (last one wins). Either a base URL or a load balancer must be provided.

func (*Client) Close

func (c *Client) Close() error

Close releases the underlying resources held by the client.

func (*Client) Cluster

func (c *Client) Cluster() *cluster.Client

Cluster returns a client for the cluster API section (/cluster).

func (*Client) Create

func (c *Client) Create(ctx context.Context, path string, out any, params map[string]string) error

Create performs a POST request with form-encoded params.

func (*Client) CreateValues

func (c *Client) CreateValues(ctx context.Context, path string, out any, params url.Values) error

CreateValues performs a POST request with url.Values params, which (unlike Create's map[string]string) support multiple values under the same key. Used only by endpoints with a genuine Proxmox "array"-typed parameter (see doValues).

func (*Client) Delete

func (c *Client) Delete(ctx context.Context, path string, out any, params map[string]string) error

Delete performs a DELETE request.

func (*Client) Get

func (c *Client) Get(ctx context.Context, path string, out any, params map[string]string) error

Get performs a GET request and decodes the response envelope into out.

func (*Client) Nodes

func (c *Client) Nodes(node string) *nodes.Client

Nodes returns a client scoped to the given node's API section (/nodes/{node}).

func (*Client) Patch

func (c *Client) Patch(ctx context.Context, path string, out any, params map[string]string) error

Patch performs a PATCH request with form-encoded params.

func (*Client) Pools

func (c *Client) Pools() *pools.Client

Pools returns a client for the pools API section (/pools).

func (*Client) Storage

func (c *Client) Storage() *storage.Client

Storage returns a client for the storage API section (/storage).

func (*Client) ToRESTConfig

func (c *Client) ToRESTConfig() ClientConfig

ToRESTConfig returns a copy of the client's configuration suitable for use with the REST client. Modifications to the returned config do not affect the original client.

func (*Client) Update

func (c *Client) Update(ctx context.Context, path string, out any, params map[string]string) error

Update performs a PUT request with form-encoded params.

func (*Client) UpdateValues

func (c *Client) UpdateValues(ctx context.Context, path string, out any, params url.Values) error

UpdateValues performs a PUT request with url.Values params, which (unlike Update's map[string]string) support multiple values under the same key. Used only by endpoints with a genuine Proxmox "array"-typed parameter (see doValues).

func (*Client) Upload

func (c *Client) Upload(ctx context.Context, path string, out any, fields map[string]string, fieldName, fileName string, file io.Reader) error

Upload performs a multipart/form-data POST request: fields are sent as ordinary form fields and file is streamed as the part named fieldName, with fileName carried as that part's Content-Disposition filename. Used only by endpoints that accept a raw file upload (e.g. nodes/{node}/storage/{storage}/upload) rather than form-encoded params.

The multipart body is built by hand instead of via resty's SetMultipartFormData/SetFileReader, which always streams the body through an io.Pipe with no Content-Length, forcing Transfer-Encoding: chunked. pveproxy rejects that on upload endpoints with "501 chunked transfer encoding not supported", so the exact body size is computed up front (buffering file into memory only if it doesn't support io.Seeker) and set via SetContentLength.

The multipart-framing technique — write the fields and the file part's header into a buffer, close the writer to finalize the closing boundary, then splice file's content in at the recorded header offset — matches other Proxmox Go clients doing the same non-chunked upload (e.g. luthermonson/go-proxmox's Client.UploadReader), rather than reconstructing the closing boundary by hand.

func (*Client) Version

func (c *Client) Version(ctx context.Context) (*Version, error)

Version retrieves the version information of the Proxmox VE server.

type ClientConfig

type ClientConfig struct {
	BaseURL     string
	Token       string
	TokenSecret string
	Username    string
	Password    string
	UserAgent   string
	Proxy       string

	Insecure bool
	// CACerts sets the trusted CA bundle(s); see WithCACert.
	CACerts []string
	// contains filtered or unexported fields
}

ClientConfig holds the configuration for a Client. All fields are private and can only be set through functional options (see Option).

func (ClientConfig) ToRESTConfig

func (c ClientConfig) ToRESTConfig() ClientConfig

ToRESTConfig returns a copy of the config, safe to mutate without affecting the original.

type Option

type Option func(*ClientConfig)

Option mutates a ClientConfig. Options are the only way to populate the private config fields; the last applied option wins.

func WithBasePath

func WithBasePath(p string) Option

WithBasePath sets the API path prefix (e.g. /api2/json) explicitly, overriding any path extracted from the URL. It is used when a load balancer is configured, since LB endpoints carry no path information.

func WithCACert

func WithCACert(paths ...string) Option

WithCACert adds the path(s) to one or more PEM CA bundles to trust. Supplying any CA replaces the system trust store rather than adding to it, so a cluster fronted by a VIP/ingress certificate that differs from its nodes' own CA-signed certificates (a split trust chain) needs both: WithCACert(vipCA, pveCA). WithCACert can also be called multiple times; each call appends to the previously configured bundles rather than replacing them.

func WithInsecure

func WithInsecure(skip bool) Option

WithInsecure controls whether TLS certificate verification is skipped.

func WithLoadBalancer

func WithLoadBalancer(lb resty.LoadBalancer) Option

WithLoadBalancer sets a custom resty.LoadBalancer implementation, overriding the single base URL.

func WithLogger

func WithLogger(l resty.Logger) Option

WithLogger sets the resty logger.

func WithPasswordAuth

func WithPasswordAuth(username, password string) Option

WithPasswordAuth enables ticket/password authentication. The realm is included in the username (e.g., "root@pam").

func WithProxy

func WithProxy(p string) Option

WithProxy sets an optional proxy URL.

func WithRetryCount

func WithRetryCount(n int) Option

WithRetryCount sets the number of auto-retries (default 3).

func WithRetryMaxWaitTime

func WithRetryMaxWaitTime(d time.Duration) Option

WithRetryMaxWaitTime sets the cap on backoff wait (default 30s).

func WithRetryWaitTime

func WithRetryWaitTime(d time.Duration) Option

WithRetryWaitTime sets the initial backoff wait per retry (default 500ms).

func WithRoundRobin

func WithRoundRobin(urls ...string) Option

WithRoundRobin distributes requests across the given API endpoints round-robin style. The endpoints ignore the API path prefix To redefine the default API path, use WithBasePath

func WithSRVWeightedRoundRobin

func WithSRVWeightedRoundRobin(service, proto, domain, scheme string) Option

WithSRVWeightedRoundRobin resolves SRV records and load balances across the discovered endpoints. Since SRV records carry no path, requests are prefixed with the default API path (/api2/json) To redefine the default API path, use WithBasePath

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets the per-request timeout (default 5m).

func WithTokenAuth

func WithTokenAuth(tokenID, secret string) Option

WithTokenAuth enables API token authentication. tokenID has the form user@realm!tokenid.

func WithURL

func WithURL(u string) Option

WithURL sets the API endpoint, e.g. https://10.0.0.1:8006/api2/json If the URL contains a path component, it is saved as the base path and prepended to request paths when a load balancer is used.

func WithUserAgent

func WithUserAgent(ua string) Option

WithUserAgent sets a custom User-Agent header.

func WithWeightedRoundRobin

func WithWeightedRoundRobin(hosts ...*resty.Host) Option

WithWeightedRoundRobin distributes requests across the given hosts proportionally to their weights. Since hosts carry no path, requests are prefixed with the default API path (/api2/json) To redefine the default API path, use WithBasePath

type Session

type Session struct {
	Username            string `json:"username,omitempty" url:"username,omitempty"`
	Ticket              string `json:"ticket,omitempty" url:"ticket,omitempty"`
	CSRFPreventionToken string `json:"CSRFPreventionToken,omitempty" url:"CSRFPreventionToken,omitempty"`
	Cap                 any    `json:"cap,omitempty" url:"cap,omitempty"`
	ClusterName         string `json:"clustername,omitempty" url:"clustername,omitempty"`
}

Session holds the ticket-based authentication data returned by POST /access/ticket.

type Version

type Version struct {
	// Release is the version string, e.g. "8.2.2".
	Release string `json:"release,omitempty" url:"release,omitempty"`
	// Version is the Proxmox VE version string, e.g. "8.2.2".
	Version string `json:"version,omitempty" url:"version,omitempty"`
	// Repoid is the git commit hash of the running pve-manager.
	Repoid string `json:"repoid,omitempty" url:"repoid,omitempty"`
}

Version contains the Proxmox VE version information.

Directories

Path Synopsis
Package cluster provides access to the Proxmox VE cluster API (GET/POST endpoints under /cluster).
Package cluster provides access to the Proxmox VE cluster API (GET/POST endpoints under /cluster).
backup
Package backup provides access to the Proxmox VE cluster-wide vzdump backup job API (endpoints under /cluster/backup).
Package backup provides access to the Proxmox VE cluster-wide vzdump backup job API (endpoints under /cluster/backup).
ceph
Package ceph provides access to the Proxmox VE cluster-wide Ceph API (endpoints under /cluster/ceph).
Package ceph provides access to the Proxmox VE cluster-wide Ceph API (endpoints under /cluster/ceph).
firewall
Package firewall provides access to the Proxmox VE cluster firewall API (endpoints under /cluster/firewall).
Package firewall provides access to the Proxmox VE cluster firewall API (endpoints under /cluster/firewall).
ha
Package ha provides access to the Proxmox VE cluster high-availability API (endpoints under /cluster/ha).
Package ha provides access to the Proxmox VE cluster high-availability API (endpoints under /cluster/ha).
jobs
Package jobs provides access to the Proxmox VE cluster-wide job API (endpoints under /cluster/jobs).
Package jobs provides access to the Proxmox VE cluster-wide job API (endpoints under /cluster/jobs).
mapping
Package mapping provides access to the Proxmox VE cluster-wide hardware mapping API (endpoints under /cluster/mapping): PCI, USB and directory mappings that let a guest reference a logical device name instead of a node-specific path, resolved per node by the mapping's entries.
Package mapping provides access to the Proxmox VE cluster-wide hardware mapping API (endpoints under /cluster/mapping): PCI, USB and directory mappings that let a guest reference a logical device name instead of a node-specific path, resolved per node by the mapping's entries.
qemu
Package qemu provides access to the Proxmox VE cluster-wide QEMU API (endpoints under /cluster/qemu): available CPU flags and custom CPU model definitions.
Package qemu provides access to the Proxmox VE cluster-wide QEMU API (endpoints under /cluster/qemu): available CPU flags and custom CPU model definitions.
replication
Package replication provides access to the Proxmox VE cluster-wide storage replication job API (endpoints under /cluster/replication).
Package replication provides access to the Proxmox VE cluster-wide storage replication job API (endpoints under /cluster/replication).
examples
fakeapi command
Package main demonstrates the fakeapi package (see docs/fakeapi.md): an in-memory, HTTP-level stand-in for a Proxmox VE cluster, driven through an ordinary *proxmox.Client exactly as if it were pointed at a real cluster.
Package main demonstrates the fakeapi package (see docs/fakeapi.md): an in-memory, HTTP-level stand-in for a Proxmox VE cluster, driven through an ordinary *proxmox.Client exactly as if it were pointed at a real cluster.
version command
Package main demonstrates how to use the Proxmox VE API client to retrieve the version information.
Package main demonstrates how to use the Proxmox VE API client to retrieve the version information.
Package fakeapi is an in-memory, HTTP-level stand-in for a Proxmox VE cluster, for exercising this module's own client code (and downstream consumers of it) without a live cluster.
Package fakeapi is an in-memory, HTTP-level stand-in for a Proxmox VE cluster, for exercising this module's own client code (and downstream consumers of it) without a live cluster.
internal
apierr
Package apierr is the single place that decides what a Proxmox API error means.
Package apierr is the single place that decides what a Proxmox API error means.
firewall
Package firewall is the single implementation of the Proxmox VE firewall resource tree (rules, aliases, IP sets and their entries, options, refs and the log), parameterised by the tree's base path.
Package firewall is the single implementation of the Proxmox VE firewall resource tree (rules, aliases, IP sets and their entries, options, refs and the log), parameterised by the tree's base path.
params
Package params provides a reflection-based encoder/decoder that converts between option structs and the flat form parameters / JSON responses used by the Proxmox API.
Package params provides a reflection-based encoder/decoder that converts between option structs and the flat form parameters / JSON responses used by the Proxmox API.
property
Package property converts Proxmox comma-separated property strings to and from tagged Go structs.
Package property converts Proxmox comma-separated property strings to and from tagged Go structs.
Package nodes provides access to the Proxmox VE per-node API (endpoints under /nodes/{node}).
Package nodes provides access to the Proxmox VE per-node API (endpoints under /nodes/{node}).
capabilities
Package capabilities provides access to the Proxmox VE per-node capability-discovery API (endpoints under /nodes/{node}/capabilities): available QEMU CPU models/flags, machine types, and migration capabilities.
Package capabilities provides access to the Proxmox VE per-node capability-discovery API (endpoints under /nodes/{node}/capabilities): available QEMU CPU models/flags, machine types, and migration capabilities.
ceph
Package ceph provides access to the Proxmox VE per-node Ceph service API (endpoints under /nodes/{node}/ceph): the basic service-lifecycle operations — cluster status, start/stop/restart, the list of installable Ceph releases, and the Ceph log — folded directly onto Client rather than behind an accessor.
Package ceph provides access to the Proxmox VE per-node Ceph service API (endpoints under /nodes/{node}/ceph): the basic service-lifecycle operations — cluster status, start/stop/restart, the list of installable Ceph releases, and the Ceph log — folded directly onto Client rather than behind an accessor.
hardware
Package hardware provides access to the Proxmox VE per-node hardware detection API (endpoints under /nodes/{node}/hardware), local PCI and USB device inventories.
Package hardware provides access to the Proxmox VE per-node hardware detection API (endpoints under /nodes/{node}/hardware), local PCI and USB device inventories.
lxc
Package lxc provides access to the Proxmox VE per-node LXC container API (endpoints under /nodes/{node}/lxc/{vmid}).
Package lxc provides access to the Proxmox VE per-node LXC container API (endpoints under /nodes/{node}/lxc/{vmid}).
lxc/firewall
Package firewall provides access to the Proxmox VE per-guest LXC firewall API (endpoints under /nodes/{node}/lxc/{vmid}/firewall): rules, aliases, IP sets, options, the firewall log, and reference lookups.
Package firewall provides access to the Proxmox VE per-guest LXC firewall API (endpoints under /nodes/{node}/lxc/{vmid}/firewall): rules, aliases, IP sets, options, the firewall log, and reference lookups.
network
Package network provides access to the Proxmox VE per-node network configuration API (endpoints under /nodes/{node}/network).
Package network provides access to the Proxmox VE per-node network configuration API (endpoints under /nodes/{node}/network).
qemu
Package qemu provides access to the Proxmox VE per-node QEMU guest API (endpoints under /nodes/{node}/qemu/{vmid}).
Package qemu provides access to the Proxmox VE per-node QEMU guest API (endpoints under /nodes/{node}/qemu/{vmid}).
qemu/agent
Package agent provides access to the Proxmox VE per-guest QEMU Guest Agent API (endpoints under /nodes/{node}/qemu/{vmid}/agent).
Package agent provides access to the Proxmox VE per-guest QEMU Guest Agent API (endpoints under /nodes/{node}/qemu/{vmid}/agent).
qemu/firewall
Package firewall provides access to the Proxmox VE per-guest QEMU firewall API (endpoints under /nodes/{node}/qemu/{vmid}/firewall): rules, aliases, IP sets, options, the firewall log, and reference lookups.
Package firewall provides access to the Proxmox VE per-guest QEMU firewall API (endpoints under /nodes/{node}/qemu/{vmid}/firewall): rules, aliases, IP sets, options, the firewall log, and reference lookups.
replication
Package replication provides access to the Proxmox VE per-node replication status API (endpoints under /nodes/{node}/replication): the runtime status and logs of storage replication jobs whose guest runs on that node.
Package replication provides access to the Proxmox VE per-node replication status API (endpoints under /nodes/{node}/replication): the runtime status and logs of storage replication jobs whose guest runs on that node.
storage
Package storage provides access to the Proxmox VE per-node storage API (endpoints under /nodes/{node}/storage): each storage's status on that node, its content (volumes), and backup retention pruning.
Package storage provides access to the Proxmox VE per-node storage API (endpoints under /nodes/{node}/storage): each storage's status on that node, its content (volumes), and backup retention pruning.
tasks
Package tasks provides access to the Proxmox VE per-node task API (endpoints under /nodes/{node}/tasks): the node's task history, and a single task's log/status/stop/wait addressed by its UPID string.
Package tasks provides access to the Proxmox VE per-node task API (endpoints under /nodes/{node}/tasks): the node's task history, and a single task's log/status/stop/wait addressed by its UPID string.
vzdump
Package vzdump provides access to the Proxmox VE per-node backup API (endpoints under /nodes/{node}/vzdump): creating an on-demand backup job, reading the node's configured backup defaults, and extracting a guest's configuration from an existing backup archive.
Package vzdump provides access to the Proxmox VE per-node backup API (endpoints under /nodes/{node}/vzdump): creating an on-demand backup job, reading the node's configured backup defaults, and extracting a guest's configuration from an existing backup archive.
Package pools provides access to the Proxmox VE pool API (endpoints under /pools).
Package pools provides access to the Proxmox VE pool API (endpoints under /pools).
Package storage provides access to the Proxmox VE storage API (endpoints under /storage).
Package storage provides access to the Proxmox VE storage API (endpoints under /storage).
Package task is the handle for a Proxmox VE background task (a worker identified by a UPID) and the client-side logic for following one: its status, log, stop, and Wait, a blocking helper that polls until the task finishes (Proxmox has no server-side "block until done" endpoint of its own).
Package task is the handle for a Proxmox VE background task (a worker identified by a UPID) and the client-side logic for following one: its status, log, stop, and Wait, a blocking helper that polls until the task finishes (Proxmox has no server-side "block until done" endpoint of its own).
Package types holds wire-format types shared by sibling API subpackages that cannot import each other (see the dependency-direction rule in docs/design.md §2): a plain leaf package with no dependency on the root package or on any subpackage, so both sides of a shared shape can import it without creating a cycle.
Package types holds wire-format types shared by sibling API subpackages that cannot import each other (see the dependency-direction rule in docs/design.md §2): a plain leaf package with no dependency on the root package or on any subpackage, so both sides of a shared shape can import it without creating a cycle.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL