fix: clean orphan Proxmox cloud-init volumes
This commit is contained in:
@@ -94,6 +94,60 @@ jobs:
|
|||||||
if: steps.plan.outcome == 'failure'
|
if: steps.plan.outcome == 'failure'
|
||||||
run: exit 1
|
run: exit 1
|
||||||
|
|
||||||
|
- name: Cleanup orphan Proxmox cloud-init volumes
|
||||||
|
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
python3 - <<'PY'
|
||||||
|
import os
|
||||||
|
import ssl
|
||||||
|
import urllib.error
|
||||||
|
import urllib.parse
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
endpoint = os.environ["TF_VAR_proxmox_endpoint"].strip().removesuffix("/api2/json").rstrip("/")
|
||||||
|
token_id = os.environ["TF_VAR_proxmox_api_token_id"]
|
||||||
|
token_secret = os.environ["TF_VAR_proxmox_api_token_secret"]
|
||||||
|
insecure = os.environ.get("TF_VAR_proxmox_insecure", "false").lower() == "true"
|
||||||
|
node = "flex"
|
||||||
|
storage = "Flash"
|
||||||
|
vm_ids = [200, 201, 202, 210, 211, 212, 213, 214]
|
||||||
|
context = ssl._create_unverified_context() if insecure else None
|
||||||
|
headers = {"Authorization": f"PVEAPIToken={token_id}={token_secret}"}
|
||||||
|
|
||||||
|
def request(method, path):
|
||||||
|
req = urllib.request.Request(
|
||||||
|
f"{endpoint}/api2/json{path}",
|
||||||
|
method=method,
|
||||||
|
headers=headers,
|
||||||
|
)
|
||||||
|
return urllib.request.urlopen(req, context=context, timeout=30)
|
||||||
|
|
||||||
|
def vm_exists(vmid):
|
||||||
|
try:
|
||||||
|
request("GET", f"/nodes/{node}/qemu/{vmid}/status/current").close()
|
||||||
|
return True
|
||||||
|
except urllib.error.HTTPError as err:
|
||||||
|
if err.code == 404:
|
||||||
|
return False
|
||||||
|
raise
|
||||||
|
|
||||||
|
for vmid in vm_ids:
|
||||||
|
if vm_exists(vmid):
|
||||||
|
print(f"VM {vmid} exists; keeping cloud-init volume")
|
||||||
|
continue
|
||||||
|
|
||||||
|
volume = urllib.parse.quote(f"{storage}:vm-{vmid}-cloudinit", safe="")
|
||||||
|
try:
|
||||||
|
request("DELETE", f"/nodes/{node}/storage/{storage}/content/{volume}").close()
|
||||||
|
print(f"Deleted orphan cloud-init volume for VM {vmid}")
|
||||||
|
except urllib.error.HTTPError as err:
|
||||||
|
if err.code == 404:
|
||||||
|
print(f"No orphan cloud-init volume for VM {vmid}")
|
||||||
|
continue
|
||||||
|
raise
|
||||||
|
PY
|
||||||
|
|
||||||
- name: Terraform Apply
|
- name: Terraform Apply
|
||||||
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
|
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
|
||||||
working-directory: terraform
|
working-directory: terraform
|
||||||
|
|||||||
Reference in New Issue
Block a user