Add a stateful Proxmox API console and broad handler coverage beyond the
initial QEMU slice, backed by imported contracts for majors 6–9. - Implement durable handlers for access/auth, cluster, LXC, storage, HA, firewall, Ceph, SDN, ACME, notifications, pools, mapping, and node ops - Serve an interactive Web UI with catalog browsing, demo seed controls, and OpenAPI/help surfaces - Bundle PVE 6.4-15, 7.4-16, and 8.4.5 contract revisions alongside 9.2.3 - Support in-memory runtime contract Apply (POST /ui/api/contract/apply) so /version and /api2 routes follow the selected major until restart - Expand seed profiles (including demo-cluster), migrations 007–008, TLS gateway config, Compose/Makefile tooling, and compatibility evidence - Tighten .gitignore for macOS, hidden directories (.*/), and local secrets
This commit is contained in:
@@ -0,0 +1,27 @@
|
||||
# Runnable client cookbooks
|
||||
|
||||
Companion code for [docs/clients.md](../docs/clients.md).
|
||||
|
||||
## Prerequisites
|
||||
|
||||
```bash
|
||||
make up
|
||||
make seed PROFILE=small
|
||||
```
|
||||
|
||||
## Layout
|
||||
|
||||
| Path | Stack |
|
||||
|---|---|
|
||||
| `python/` | proxmoxer + requests |
|
||||
| `go/` | Go stdlib |
|
||||
| `java/` | Java 11+ HttpClient |
|
||||
| `perl/` | HTTP::Tiny |
|
||||
| `ansible/` | ansible-playbook |
|
||||
| `terraform/` | Terraform + Proxmox provider |
|
||||
| `pulumi/` | Pulumi (Python) |
|
||||
|
||||
Default node: **`pve01`**. Default token:
|
||||
`root@pam!automation=automation-secret`.
|
||||
|
||||
Guides: [docs/examples/](../docs/examples/overview.md).
|
||||
@@ -0,0 +1,2 @@
|
||||
[simulator]
|
||||
localhost ansible_connection=local
|
||||
@@ -0,0 +1,112 @@
|
||||
---
|
||||
# Lab cookbook against proxmox-api-simulator (HTTP :8006).
|
||||
# ansible-playbook -i inventory.ini playbook.yml
|
||||
|
||||
- name: Proxmox API simulator cookbook
|
||||
hosts: simulator
|
||||
gather_facts: false
|
||||
vars:
|
||||
pve_base: "http://localhost:8006/api2/json"
|
||||
pve_node: pve01
|
||||
pve_vmid: 116
|
||||
pve_token: "root@pam!automation=automation-secret"
|
||||
auth_header: "PVEAPIToken={{ pve_token }}"
|
||||
|
||||
tasks:
|
||||
- name: Read version
|
||||
ansible.builtin.uri:
|
||||
url: "{{ pve_base }}/version"
|
||||
headers:
|
||||
Authorization: "{{ auth_header }}"
|
||||
return_content: true
|
||||
register: version
|
||||
|
||||
- name: Show version
|
||||
ansible.builtin.debug:
|
||||
var: version.json
|
||||
|
||||
- name: Create QEMU guest
|
||||
ansible.builtin.uri:
|
||||
url: "{{ pve_base }}/nodes/{{ pve_node }}/qemu"
|
||||
method: POST
|
||||
headers:
|
||||
Authorization: "{{ auth_header }}"
|
||||
body_format: form-urlencoded
|
||||
body:
|
||||
vmid: "{{ pve_vmid }}"
|
||||
name: "ansible-{{ pve_vmid }}"
|
||||
cores: "1"
|
||||
memory: "512"
|
||||
return_content: true
|
||||
register: create
|
||||
|
||||
- name: Wait for create task
|
||||
ansible.builtin.uri:
|
||||
url: "{{ pve_base }}/nodes/{{ pve_node }}/tasks/{{ create.json.data | urlencode }}/status"
|
||||
headers:
|
||||
Authorization: "{{ auth_header }}"
|
||||
return_content: true
|
||||
register: create_status
|
||||
until: create_status.json.data.status == 'stopped'
|
||||
retries: 60
|
||||
delay: 1
|
||||
|
||||
- name: Start guest
|
||||
ansible.builtin.uri:
|
||||
url: "{{ pve_base }}/nodes/{{ pve_node }}/qemu/{{ pve_vmid }}/status/start"
|
||||
method: POST
|
||||
headers:
|
||||
Authorization: "{{ auth_header }}"
|
||||
return_content: true
|
||||
register: start
|
||||
|
||||
- name: Wait for start task
|
||||
ansible.builtin.uri:
|
||||
url: "{{ pve_base }}/nodes/{{ pve_node }}/tasks/{{ start.json.data | urlencode }}/status"
|
||||
headers:
|
||||
Authorization: "{{ auth_header }}"
|
||||
return_content: true
|
||||
register: start_status
|
||||
until: start_status.json.data.status == 'stopped'
|
||||
retries: 60
|
||||
delay: 1
|
||||
|
||||
- name: Stop guest
|
||||
ansible.builtin.uri:
|
||||
url: "{{ pve_base }}/nodes/{{ pve_node }}/qemu/{{ pve_vmid }}/status/stop"
|
||||
method: POST
|
||||
headers:
|
||||
Authorization: "{{ auth_header }}"
|
||||
return_content: true
|
||||
register: stop
|
||||
|
||||
- name: Wait for stop task
|
||||
ansible.builtin.uri:
|
||||
url: "{{ pve_base }}/nodes/{{ pve_node }}/tasks/{{ stop.json.data | urlencode }}/status"
|
||||
headers:
|
||||
Authorization: "{{ auth_header }}"
|
||||
return_content: true
|
||||
register: stop_status
|
||||
until: stop_status.json.data.status == 'stopped'
|
||||
retries: 60
|
||||
delay: 1
|
||||
|
||||
- name: Delete guest
|
||||
ansible.builtin.uri:
|
||||
url: "{{ pve_base }}/nodes/{{ pve_node }}/qemu/{{ pve_vmid }}"
|
||||
method: DELETE
|
||||
headers:
|
||||
Authorization: "{{ auth_header }}"
|
||||
return_content: true
|
||||
register: delete
|
||||
|
||||
- name: Wait for delete task
|
||||
ansible.builtin.uri:
|
||||
url: "{{ pve_base }}/nodes/{{ pve_node }}/tasks/{{ delete.json.data | urlencode }}/status"
|
||||
headers:
|
||||
Authorization: "{{ auth_header }}"
|
||||
return_content: true
|
||||
register: delete_status
|
||||
until: delete_status.json.data.status == 'stopped'
|
||||
retries: 60
|
||||
delay: 1
|
||||
@@ -0,0 +1,3 @@
|
||||
module example.com/proxmox-api-simulator-cookbook
|
||||
|
||||
go 1.22
|
||||
@@ -0,0 +1,97 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func env(k, def string) string {
|
||||
if v := os.Getenv(k); v != "" {
|
||||
return v
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
func main() {
|
||||
base := strings.TrimRight(env("PVE_BASE", "http://localhost:8006/api2/json"), "/")
|
||||
node := env("PVE_NODE", "pve01")
|
||||
vmid := env("PVE_VMID", "113")
|
||||
token := env("PVE_API_TOKEN", "root@pam!automation=automation-secret")
|
||||
auth := "PVEAPIToken=" + token
|
||||
|
||||
fmt.Printf("version: %v\n", call(base+"/version", "GET", auth, nil))
|
||||
upid := asString(call(base+"/nodes/"+node+"/qemu", "POST", auth, url.Values{
|
||||
"vmid": {vmid},
|
||||
"name": {"go-" + vmid},
|
||||
"cores": {"1"},
|
||||
"memory": {"512"},
|
||||
}))
|
||||
wait(base, node, auth, upid)
|
||||
upid = asString(call(base+"/nodes/"+node+"/qemu/"+vmid+"/status/start", "POST", auth, nil))
|
||||
wait(base, node, auth, upid)
|
||||
fmt.Printf("status: %v\n", call(base+"/nodes/"+node+"/qemu/"+vmid+"/status/current", "GET", auth, nil))
|
||||
upid = asString(call(base+"/nodes/"+node+"/qemu/"+vmid+"/status/stop", "POST", auth, nil))
|
||||
wait(base, node, auth, upid)
|
||||
upid = asString(call(base+"/nodes/"+node+"/qemu/"+vmid, "DELETE", auth, nil))
|
||||
wait(base, node, auth, upid)
|
||||
fmt.Println("ok")
|
||||
}
|
||||
|
||||
func wait(base, node, auth, upid string) {
|
||||
deadline := time.Now().Add(2 * time.Minute)
|
||||
for time.Now().Before(deadline) {
|
||||
status := call(base+"/nodes/"+node+"/tasks/"+url.PathEscape(upid)+"/status", "GET", auth, nil)
|
||||
if m, ok := status.(map[string]any); ok {
|
||||
if s, _ := m["status"].(string); s == "stopped" {
|
||||
return
|
||||
}
|
||||
}
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
}
|
||||
panic("timeout waiting for " + upid)
|
||||
}
|
||||
|
||||
func call(u, method, auth string, values url.Values) any {
|
||||
var body io.Reader
|
||||
if values != nil {
|
||||
body = strings.NewReader(values.Encode())
|
||||
}
|
||||
req, err := http.NewRequest(method, u, body)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
req.Header.Set("Authorization", auth)
|
||||
if values != nil {
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
}
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
b, _ := io.ReadAll(resp.Body)
|
||||
if resp.StatusCode >= 300 {
|
||||
panic(fmt.Sprintf("%s %s: %s", method, u, b))
|
||||
}
|
||||
var envelope struct {
|
||||
Data any `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(b, &envelope); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return envelope.Data
|
||||
}
|
||||
|
||||
func asString(v any) string {
|
||||
s, ok := v.(string)
|
||||
if !ok {
|
||||
panic(fmt.Sprintf("expected string UPID, got %#v", v))
|
||||
}
|
||||
return s
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.net.URLEncoder;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* Minimal Java 11+ cookbook against HTTP :8006 using an API token.
|
||||
*
|
||||
* javac Cookbook.java && java Cookbook
|
||||
*/
|
||||
public final class Cookbook {
|
||||
private static final HttpClient CLIENT = HttpClient.newHttpClient();
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
String base = env("PVE_BASE", "http://localhost:8006/api2/json");
|
||||
String node = env("PVE_NODE", "pve01");
|
||||
String vmid = env("PVE_VMID", "114");
|
||||
String token = env("PVE_API_TOKEN", "root@pam!automation=automation-secret");
|
||||
String auth = "PVEAPIToken=" + token;
|
||||
|
||||
System.out.println("version: " + data(get(base + "/version", auth)));
|
||||
String upid =
|
||||
data(
|
||||
form(
|
||||
base + "/nodes/" + node + "/qemu",
|
||||
auth,
|
||||
Map.of(
|
||||
"vmid", vmid,
|
||||
"name", "java-" + vmid,
|
||||
"cores", "1",
|
||||
"memory", "512")));
|
||||
waitTask(base, node, auth, upid);
|
||||
upid = data(form(base + "/nodes/" + node + "/qemu/" + vmid + "/status/start", auth, Map.of()));
|
||||
waitTask(base, node, auth, upid);
|
||||
System.out.println(
|
||||
"status: " + data(get(base + "/nodes/" + node + "/qemu/" + vmid + "/status/current", auth)));
|
||||
upid = data(form(base + "/nodes/" + node + "/qemu/" + vmid + "/status/stop", auth, Map.of()));
|
||||
waitTask(base, node, auth, upid);
|
||||
upid = data(delete(base + "/nodes/" + node + "/qemu/" + vmid, auth));
|
||||
waitTask(base, node, auth, upid);
|
||||
System.out.println("ok");
|
||||
}
|
||||
|
||||
private static void waitTask(String base, String node, String auth, String upid)
|
||||
throws Exception {
|
||||
long deadline = System.currentTimeMillis() + 120_000;
|
||||
String encoded = URLEncoder.encode(upid, StandardCharsets.UTF_8);
|
||||
while (System.currentTimeMillis() < deadline) {
|
||||
String body = get(base + "/nodes/" + node + "/tasks/" + encoded + "/status", auth);
|
||||
if (body.contains("\"status\":\"stopped\"") || body.contains("\"status\": \"stopped\"")) {
|
||||
return;
|
||||
}
|
||||
Thread.sleep(500);
|
||||
}
|
||||
throw new IllegalStateException("timeout waiting for " + upid);
|
||||
}
|
||||
|
||||
private static String env(String key, String def) {
|
||||
String value = System.getenv(key);
|
||||
return value == null || value.isBlank() ? def : value;
|
||||
}
|
||||
|
||||
private static String get(String uri, String auth) throws IOException, InterruptedException {
|
||||
return send(
|
||||
HttpRequest.newBuilder(URI.create(uri))
|
||||
.timeout(Duration.ofSeconds(60))
|
||||
.header("Authorization", auth)
|
||||
.GET()
|
||||
.build());
|
||||
}
|
||||
|
||||
private static String delete(String uri, String auth) throws IOException, InterruptedException {
|
||||
return send(
|
||||
HttpRequest.newBuilder(URI.create(uri))
|
||||
.timeout(Duration.ofSeconds(60))
|
||||
.header("Authorization", auth)
|
||||
.DELETE()
|
||||
.build());
|
||||
}
|
||||
|
||||
private static String form(String uri, String auth, Map<String, String> fields)
|
||||
throws IOException, InterruptedException {
|
||||
String body =
|
||||
fields.entrySet().stream()
|
||||
.map(
|
||||
e ->
|
||||
URLEncoder.encode(e.getKey(), StandardCharsets.UTF_8)
|
||||
+ "="
|
||||
+ URLEncoder.encode(e.getValue(), StandardCharsets.UTF_8))
|
||||
.collect(Collectors.joining("&"));
|
||||
return send(
|
||||
HttpRequest.newBuilder(URI.create(uri))
|
||||
.timeout(Duration.ofSeconds(60))
|
||||
.header("Authorization", auth)
|
||||
.header("Content-Type", "application/x-www-form-urlencoded")
|
||||
.POST(HttpRequest.BodyPublishers.ofString(body))
|
||||
.build());
|
||||
}
|
||||
|
||||
private static String send(HttpRequest request) throws IOException, InterruptedException {
|
||||
HttpResponse<String> response = CLIENT.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
if (response.statusCode() >= 300) {
|
||||
throw new IOException(response.statusCode() + ": " + response.body());
|
||||
}
|
||||
return response.body();
|
||||
}
|
||||
|
||||
/** Extract Proxmox envelope data when it is a JSON string UPID. */
|
||||
private static String data(String body) {
|
||||
String marker = "\"data\":\"";
|
||||
int start = body.indexOf(marker);
|
||||
if (start >= 0) {
|
||||
start += marker.length();
|
||||
int end = body.indexOf('"', start);
|
||||
if (end > start) {
|
||||
return body.substring(start, end);
|
||||
}
|
||||
}
|
||||
return body;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
#!/usr/bin/env perl
|
||||
use strict;
|
||||
use warnings;
|
||||
use HTTP::Tiny;
|
||||
use JSON qw(decode_json encode_json);
|
||||
|
||||
sub uri_escape {
|
||||
my ($value) = @_;
|
||||
$value =~ s/([^A-Za-z0-9\-\._~])/sprintf('%%%02X', ord($1))/eg;
|
||||
return $value;
|
||||
}
|
||||
|
||||
my $base = $ENV{PVE_BASE} // 'http://localhost:8006/api2/json';
|
||||
my $node = $ENV{PVE_NODE} // 'pve01';
|
||||
my $vmid = $ENV{PVE_VMID} // '115';
|
||||
my $token = $ENV{PVE_API_TOKEN} // 'root@pam!automation=automation-secret';
|
||||
my $auth = "PVEAPIToken=$token";
|
||||
my $http = HTTP::Tiny->new(timeout => 60);
|
||||
|
||||
sub api {
|
||||
my ($method, $path, $body) = @_;
|
||||
my %opts = (headers => { Authorization => $auth });
|
||||
if (defined $body) {
|
||||
$opts{headers}{'Content-Type'} = 'application/x-www-form-urlencoded';
|
||||
$opts{content} = $body;
|
||||
}
|
||||
my $res = $http->request($method, "$base$path", \%opts);
|
||||
die "$method $path failed: $res->{status} $res->{content}\n" unless $res->{success};
|
||||
my $json = decode_json($res->{content});
|
||||
return $json->{data};
|
||||
}
|
||||
|
||||
sub wait_task {
|
||||
my ($upid) = @_;
|
||||
my $deadline = time + 120;
|
||||
while (time < $deadline) {
|
||||
my $status = api('GET', "/nodes/$node/tasks/" . uri_escape($upid) . '/status');
|
||||
return if ref $status eq 'HASH' && ($status->{status} // '') eq 'stopped';
|
||||
select(undef, undef, undef, 0.5);
|
||||
}
|
||||
die "timeout waiting for $upid\n";
|
||||
}
|
||||
|
||||
print "version: ", encode_json(api('GET', '/version')), "\n";
|
||||
my $upid = api('POST', "/nodes/$node/qemu", "vmid=$vmid&name=perl-$vmid&cores=1&memory=512");
|
||||
wait_task($upid);
|
||||
$upid = api('POST', "/nodes/$node/qemu/$vmid/status/start");
|
||||
wait_task($upid);
|
||||
print "status: ", encode_json(api('GET', "/nodes/$node/qemu/$vmid/status/current")), "\n";
|
||||
$upid = api('POST', "/nodes/$node/qemu/$vmid/status/stop");
|
||||
wait_task($upid);
|
||||
$upid = api('DELETE', "/nodes/$node/qemu/$vmid");
|
||||
wait_task($upid);
|
||||
print "ok\n";
|
||||
@@ -0,0 +1,2 @@
|
||||
requires 'HTTP::Tiny';
|
||||
requires 'JSON';
|
||||
@@ -0,0 +1,3 @@
|
||||
name: proxmox-api-simulator
|
||||
runtime: python
|
||||
description: Lab cookbook against proxmox-api-simulator
|
||||
@@ -0,0 +1,88 @@
|
||||
"""Pulumi lab program: create/start/stop/delete a VM on the simulator via HTTP API.
|
||||
|
||||
This uses a dynamic Pulumi Resource that wraps REST calls so the cookbook works
|
||||
even when a Proxmox native provider is unavailable. Prefer HTTPS gateway +
|
||||
token; default here is HTTP :8006 for simpler local TLS handling.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
import pulumi
|
||||
import requests
|
||||
|
||||
config = pulumi.Config()
|
||||
base = config.get("base") or "http://localhost:8006/api2/json"
|
||||
node = config.get("node") or "pve01"
|
||||
vmid = int(config.get("vmid") or "118")
|
||||
token = config.get_secret("token") or "root@pam!automation=automation-secret"
|
||||
headers = {"Authorization": f"PVEAPIToken={token}"}
|
||||
|
||||
|
||||
def api(method: str, path: str, data: dict[str, Any] | None = None) -> Any:
|
||||
response = requests.request(
|
||||
method,
|
||||
f"{base}{path}",
|
||||
headers=headers,
|
||||
data=data,
|
||||
timeout=60,
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json().get("data")
|
||||
|
||||
|
||||
def wait_task(upid: str) -> None:
|
||||
deadline = time.time() + 120
|
||||
while time.time() < deadline:
|
||||
status = api("GET", f"/nodes/{node}/tasks/{upid}/status")
|
||||
if status and status.get("status") == "stopped":
|
||||
return
|
||||
time.sleep(0.5)
|
||||
raise TimeoutError(upid)
|
||||
|
||||
|
||||
class SimulatorVm(pulumi.ComponentResource):
|
||||
def __init__(self, name: str, opts: pulumi.ResourceOptions | None = None) -> None:
|
||||
super().__init__("simulator:index:Vm", name, None, opts)
|
||||
|
||||
def create(_):
|
||||
version = api("GET", "/version")
|
||||
upid = api(
|
||||
"POST",
|
||||
f"/nodes/{node}/qemu",
|
||||
{
|
||||
"vmid": vmid,
|
||||
"name": f"pulumi-{vmid}",
|
||||
"cores": 1,
|
||||
"memory": 512,
|
||||
},
|
||||
)
|
||||
wait_task(upid)
|
||||
upid = api("POST", f"/nodes/{node}/qemu/{vmid}/status/start")
|
||||
wait_task(upid)
|
||||
return {
|
||||
"version": json.dumps(version),
|
||||
"vmid": str(vmid),
|
||||
"status": json.dumps(api("GET", f"/nodes/{node}/qemu/{vmid}/status/current")),
|
||||
}
|
||||
|
||||
result = pulumi.Output.from_input(None).apply(create)
|
||||
self.version = result.apply(lambda d: d["version"])
|
||||
self.vmid = result.apply(lambda d: d["vmid"])
|
||||
self.status = result.apply(lambda d: d["status"])
|
||||
self.register_outputs(
|
||||
{
|
||||
"version": self.version,
|
||||
"vmid": self.vmid,
|
||||
"status": self.status,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
vm = SimulatorVm("cookbook-vm")
|
||||
pulumi.export("version", vm.version)
|
||||
pulumi.export("vmid", vm.vmid)
|
||||
pulumi.export("status", vm.status)
|
||||
@@ -0,0 +1,2 @@
|
||||
requests>=2.31
|
||||
pulumi>=3.0.0
|
||||
@@ -0,0 +1,85 @@
|
||||
#!/usr/bin/env python3
|
||||
"""proxmoxer cookbook against the local HTTPS gateway."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
|
||||
from proxmoxer import ProxmoxAPI
|
||||
|
||||
|
||||
def wait_task(proxmox: ProxmoxAPI, node: str, upid: str, timeout: float = 120.0) -> None:
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
status = proxmox.nodes(node).tasks(upid).status.get()
|
||||
if status.get("status") == "stopped":
|
||||
exitstatus = status.get("exitstatus", "")
|
||||
if exitstatus not in ("OK", "ok", None, ""):
|
||||
# Proxmox uses exitstatus "OK" on success; accept empty for lab.
|
||||
if str(exitstatus).upper() != "OK":
|
||||
raise RuntimeError(f"task failed: {status}")
|
||||
return
|
||||
time.sleep(0.5)
|
||||
raise TimeoutError(upid)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
host = os.environ.get("PVE_HOST", "localhost")
|
||||
port = int(os.environ.get("PVE_PORT", "8007"))
|
||||
user = os.environ.get("PVE_USER", "root@pam")
|
||||
node = os.environ.get("PVE_NODE", "pve01")
|
||||
vmid = int(os.environ.get("PVE_VMID", "110"))
|
||||
|
||||
token_name = os.environ.get("PVE_TOKEN_NAME")
|
||||
token_value = os.environ.get("PVE_TOKEN_VALUE")
|
||||
if token_name and token_value:
|
||||
proxmox = ProxmoxAPI(
|
||||
host,
|
||||
user=user,
|
||||
token_name=token_name,
|
||||
token_value=token_value,
|
||||
port=port,
|
||||
verify_ssl=False,
|
||||
)
|
||||
else:
|
||||
proxmox = ProxmoxAPI(
|
||||
host,
|
||||
user=user,
|
||||
password=os.environ.get("PVE_PASSWORD", "secret"),
|
||||
port=port,
|
||||
verify_ssl=False,
|
||||
)
|
||||
|
||||
print("version:", proxmox.version.get())
|
||||
print("nodes:", proxmox.nodes.get())
|
||||
print("qemu:", proxmox.nodes(node).qemu.get())
|
||||
|
||||
upid = proxmox.nodes(node).qemu.post(
|
||||
vmid=vmid,
|
||||
name=f"cookbook-{vmid}",
|
||||
cores=1,
|
||||
memory=512,
|
||||
)
|
||||
print("create:", upid)
|
||||
wait_task(proxmox, node, upid)
|
||||
|
||||
upid = proxmox.nodes(node).qemu(vmid).status.start.post()
|
||||
print("start:", upid)
|
||||
wait_task(proxmox, node, upid)
|
||||
print("status:", proxmox.nodes(node).qemu(vmid).status.current.get())
|
||||
|
||||
upid = proxmox.nodes(node).qemu(vmid).status.stop.post()
|
||||
print("stop:", upid)
|
||||
wait_task(proxmox, node, upid)
|
||||
|
||||
upid = proxmox.nodes(node).qemu(vmid).delete()
|
||||
print("delete:", upid)
|
||||
wait_task(proxmox, node, upid)
|
||||
print("ok")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,102 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Raw requests cookbook against HTTP :8006."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
import requests
|
||||
|
||||
BASE = os.environ.get("PVE_BASE", "http://localhost:8006/api2/json")
|
||||
NODE = os.environ.get("PVE_NODE", "pve01")
|
||||
VMID = int(os.environ.get("PVE_VMID", "111"))
|
||||
TOKEN = os.environ.get(
|
||||
"PVE_API_TOKEN",
|
||||
"root@pam!automation=automation-secret",
|
||||
)
|
||||
|
||||
|
||||
def api(
|
||||
method: str,
|
||||
path: str,
|
||||
*,
|
||||
headers: dict[str, str] | None = None,
|
||||
data: dict[str, Any] | None = None,
|
||||
) -> Any:
|
||||
response = requests.request(
|
||||
method,
|
||||
f"{BASE}{path}",
|
||||
headers=headers,
|
||||
data=data,
|
||||
timeout=60,
|
||||
)
|
||||
response.raise_for_status()
|
||||
body = response.json()
|
||||
return body.get("data", body)
|
||||
|
||||
|
||||
def wait_task(headers: dict[str, str], upid: str, timeout: float = 120.0) -> None:
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
status = api("GET", f"/nodes/{NODE}/tasks/{upid}/status", headers=headers)
|
||||
if status.get("status") == "stopped":
|
||||
return
|
||||
time.sleep(0.5)
|
||||
raise TimeoutError(upid)
|
||||
|
||||
|
||||
def with_token() -> dict[str, str]:
|
||||
return {"Authorization": f"PVEAPIToken={TOKEN}"}
|
||||
|
||||
|
||||
def with_ticket() -> dict[str, str]:
|
||||
data = api(
|
||||
"POST",
|
||||
"/access/ticket",
|
||||
data={
|
||||
"username": os.environ.get("PVE_USER", "root@pam"),
|
||||
"password": os.environ.get("PVE_PASSWORD", "secret"),
|
||||
},
|
||||
)
|
||||
return {
|
||||
"Cookie": f"PVEAuthCookie={data['ticket']}",
|
||||
"CSRFPreventionToken": data["CSRFPreventionToken"],
|
||||
}
|
||||
|
||||
|
||||
def cookbook(headers: dict[str, str], label: str) -> None:
|
||||
print(label, "version:", api("GET", "/version", headers=headers))
|
||||
print(label, "qemu:", api("GET", f"/nodes/{NODE}/qemu", headers=headers))
|
||||
upid = api(
|
||||
"POST",
|
||||
f"/nodes/{NODE}/qemu",
|
||||
headers=headers,
|
||||
data={"vmid": VMID, "name": f"req-{VMID}", "cores": 1, "memory": 512},
|
||||
)
|
||||
wait_task(headers, upid)
|
||||
upid = api("POST", f"/nodes/{NODE}/qemu/{VMID}/status/start", headers=headers)
|
||||
wait_task(headers, upid)
|
||||
print(
|
||||
label, "status:", api("GET", f"/nodes/{NODE}/qemu/{VMID}/status/current", headers=headers)
|
||||
)
|
||||
upid = api("POST", f"/nodes/{NODE}/qemu/{VMID}/status/stop", headers=headers)
|
||||
wait_task(headers, upid)
|
||||
upid = api("DELETE", f"/nodes/{NODE}/qemu/{VMID}", headers=headers)
|
||||
wait_task(headers, upid)
|
||||
print(label, "ok")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
cookbook(with_token(), "token")
|
||||
# second VMID for ticket path
|
||||
global VMID
|
||||
VMID = int(os.environ.get("PVE_VMID_TICKET", "112"))
|
||||
cookbook(with_ticket(), "ticket")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,2 @@
|
||||
proxmoxer>=2.3,<3
|
||||
requests>=2.31
|
||||
@@ -0,0 +1,64 @@
|
||||
terraform {
|
||||
required_version = ">= 1.5.0"
|
||||
required_providers {
|
||||
proxmox = {
|
||||
source = "bpg/proxmox"
|
||||
version = "~> 0.66"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
provider "proxmox" {
|
||||
endpoint = var.endpoint
|
||||
api_token = var.api_token
|
||||
insecure = var.insecure
|
||||
}
|
||||
|
||||
variable "endpoint" {
|
||||
type = string
|
||||
description = "Simulator HTTPS gateway, e.g. https://localhost:8007"
|
||||
default = "https://localhost:8007"
|
||||
}
|
||||
|
||||
variable "api_token" {
|
||||
type = string
|
||||
description = "PVE API token USER@REALM!TOKENID=SECRET"
|
||||
default = "root@pam!automation=automation-secret"
|
||||
sensitive = true
|
||||
}
|
||||
|
||||
variable "insecure" {
|
||||
type = bool
|
||||
description = "Skip TLS verify for the local self-signed gateway certificate"
|
||||
default = true
|
||||
}
|
||||
|
||||
variable "node_name" {
|
||||
type = string
|
||||
default = "pve01"
|
||||
}
|
||||
|
||||
variable "vmid" {
|
||||
type = number
|
||||
default = 117
|
||||
}
|
||||
|
||||
# Provider resource schemas evolve — adjust attribute names to the provider
|
||||
# version you pin. This file is a lab starting point against the simulator.
|
||||
resource "proxmox_virtual_environment_vm" "cookbook" {
|
||||
name = "tf-cookbook-${var.vmid}"
|
||||
node_name = var.node_name
|
||||
vm_id = var.vmid
|
||||
|
||||
cpu {
|
||||
cores = 1
|
||||
}
|
||||
|
||||
memory {
|
||||
dedicated = 512
|
||||
}
|
||||
|
||||
agent {
|
||||
enabled = false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
# Optional overrides — copy to terraform.tfvars if needed.
|
||||
# endpoint = "https://localhost:8007"
|
||||
# api_token = "root@pam!automation=automation-secret"
|
||||
# node_name = "pve01"
|
||||
# vmid = 117
|
||||
Reference in New Issue
Block a user