#!/usr/bin/env bash set -euo pipefail usage() { cat <<'EOF' Usage: ZBX_URL=https://zabbix.example.com ZBX_TOKEN=xxxx \ scripts/export.sh [--force] [ ...] Specifying multiple template names exports them into a single YAML file. To include linked templates, list their names explicitly. Environment variables: ZBX_URL Zabbix URL (for example, https://zabbix.example.com) ZBX_TOKEN API token EOF } force=0 if [[ "${1:-}" == "--force" ]]; then force=1 shift fi if [[ $# -lt 2 ]]; then usage exit 1 fi out="$1" shift names=("$@") if [[ -z "${ZBX_URL:-}" || -z "${ZBX_TOKEN:-}" ]]; then echo "ERROR: Set ZBX_URL and ZBX_TOKEN." >&2 exit 1 fi command -v curl >/dev/null 2>&1 || { echo "ERROR: curl is required." >&2 exit 1 } command -v jq >/dev/null 2>&1 || { echo "ERROR: jq is required." >&2 exit 1 } api_url="${ZBX_URL%/}" if [[ "$api_url" != */api_jsonrpc.php ]]; then api_url="$api_url/api_jsonrpc.php" fi if [[ -e "$out" && $force -eq 0 ]]; then echo "ERROR: Output already exists: $out (use --force to overwrite)" >&2 exit 1 fi api_call() { local payload="$1" curl -sS --fail-with-body \ -H "Authorization: Bearer ${ZBX_TOKEN}" \ -H 'Content-Type: application/json' \ -d "$payload" \ "$api_url" } ids=() for name in "${names[@]}"; do payload="$(jq -n --arg name "$name" '{ jsonrpc: "2.0", method: "template.get", params: { output: ["templateid", "host"], filter: {host: $name} }, id: 1 }')" if ! response="$(api_call "$payload")"; then echo "ERROR: API request failed: $api_url" >&2 exit 1 fi if jq -e '.error' >/dev/null 2>&1 <<<"$response"; then echo "ERROR: template.get failed: $name" >&2 jq -r '.error.data // .error.message' <<<"$response" >&2 exit 1 fi id="$(jq -r '.result[0].templateid // empty' <<<"$response")" if [[ -z "$id" ]]; then echo "ERROR: Template not found: $name" >&2 exit 1 fi ids+=("$id") echo "Resolved: $name -> $id" >&2 done ids_json="$(printf '%s\n' "${ids[@]}" | jq -R . | jq -s .)" payload="$(jq -n --argjson ids "$ids_json" '{ jsonrpc: "2.0", method: "configuration.export", params: { options: {templates: $ids}, format: "yaml" }, id: 1 }')" if ! response="$(api_call "$payload")"; then echo "ERROR: API request failed: $api_url" >&2 exit 1 fi if jq -e '.error' >/dev/null 2>&1 <<<"$response"; then echo "ERROR: configuration.export failed" >&2 jq -r '.error.data // .error.message' <<<"$response" >&2 exit 1 fi yaml="$(jq -r '.result' <<<"$response")" mkdir -p "$(dirname "$out")" printf '%s\n' "$yaml" > "$out" echo "Created: $out"