Files
awx/scripts/add_static_hosts.sh

87 lines
3.0 KiB
Bash
Executable File

#!/usr/bin/env bash
set -euo pipefail
# add_static_hosts.sh
# Creates or updates static hosts in an AWX inventory via the AWX REST API.
# Usage:
# AWX_HOST=... AWX_USER=... AWX_PASS=... INV_ID=2 ./add_static_hosts.sh
AWX_HOST="${AWX_HOST:-http://192.168.49.2:30081}"
AWX_USER="${AWX_USER:-admin}"
AWX_PASS="${AWX_PASS:-Aase#1234!}"
INV_ID="${INV_ID:-2}"
# Define IPs here or pass via environment variable (comma-separated)
if [ -n "${IPS_CSV:-}" ]; then
IFS=',' read -r -a IPS <<< "$IPS_CSV"
else
IPS=("192.168.1.144" "192.168.1.23" "192.168.1.24")
fi
for cmd in curl jq mktemp; do
if ! command -v "$cmd" >/dev/null 2>&1; then
echo "ERROR: required command '$cmd' not found" >&2
exit 1
fi
done
echo "Using AWX at $AWX_HOST (inventory id $INV_ID)"
TMPDIR=$(mktemp -d)
cleanup() { rm -rf "$TMPDIR" || true; }
trap cleanup EXIT INT TERM
curl_auth() {
local method="$1" url="$2" datafile="${3:-}" outfile="${4:-/dev/stdout}"
local hdrs=( -H "Content-Type: application/json" )
if [ -n "${AWX_TOKEN:-}" ]; then
hdrs+=( -H "Authorization: Bearer ${AWX_TOKEN}" )
elif [ -n "${AWX_AUTH_HEADER:-}" ]; then
hdrs+=( -H "Authorization: ${AWX_AUTH_HEADER}" )
else
hdrs+=( -u "${AWX_USER}:${AWX_PASS}" )
fi
if [ -n "$datafile" ]; then
curl -sS -w "%{http_code}" "${hdrs[@]}" -X "$method" "$url" -d "@${datafile}" -o "$outfile" || true
else
curl -sS -w "%{http_code}" "${hdrs[@]}" -X "$method" "$url" -o "$outfile" || true
fi
}
for ip in "${IPS[@]}"; do
name="host-$(echo "$ip" | tr '.' '-')"
vars=$(printf "ansible_host: %s\n" "$ip")
echo "Processing $name -> $ip"
# Check existing host
encoded_name=$(jq -nr --arg s "$name" '$s|@uri')
out="$TMPDIR/host_query.json"
code=$(curl_auth GET "$AWX_HOST/api/v2/hosts/?name=$encoded_name&inventory=$INV_ID" "" "$out")
if [ "$code" -lt 200 ] || [ "$code" -ge 500 ]; then
echo "Warning: unexpected response ($code) from AWX when querying host $name" >&2
fi
host_id=$(jq -r '.results[0].id // empty' "$out")
if [ -n "$host_id" ]; then
echo "Host exists (id=$host_id) — updating variables"
payload="$TMPDIR/patch_payload.json"
jq -n --arg vars "$vars" '{variables:$vars}' > "$payload"
code=$(curl_auth PATCH "$AWX_HOST/api/v2/hosts/$host_id/" "$payload" "$TMPDIR/patch_resp.json")
echo "PATCH returned $code"; jq -M . "$TMPDIR/patch_resp.json" || true
else
echo "Host not found — creating"
payload="$TMPDIR/create_payload.json"
jq -n --arg name "$name" --arg inv "$INV_ID" --arg vars "$vars" '{name:$name, inventory:($inv|tonumber), variables:$vars}' > "$payload"
code=$(curl_auth POST "$AWX_HOST/api/v2/hosts/" "$payload" "$TMPDIR/create_resp.json")
echo "POST returned $code"; jq -M . "$TMPDIR/create_resp.json" || true
fi
echo
done
echo "Listing hosts in inventory $INV_ID:"
curl_auth GET "$AWX_HOST/api/v2/inventories/$INV_ID/hosts/?page_size=100" "" "$TMPDIR/list.json"
jq '.results[] | {id: .id, name: .name, variables: .variables}' "$TMPDIR/list.json" || true