43 lines
1.6 KiB
Bash
Executable File
43 lines
1.6 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}"
|
|
|
|
IPS=("192.168.1.144" "192.168.1.23" "192.168.1.24")
|
|
|
|
echo "Using AWX at $AWX_HOST (inventory id $INV_ID)"
|
|
|
|
for ip in "${IPS[@]}"; do
|
|
name="host-$(echo "$ip" | tr '.' '-')"
|
|
vars=$(printf "ansible_host: %s\n" "$ip")
|
|
|
|
# URL-encode the name for query
|
|
encoded_name=$(jq -nr --arg s "$name" '$s|@uri')
|
|
|
|
echo "Processing $name -> $ip"
|
|
host_id=$(curl -sS -u "$AWX_USER:$AWX_PASS" "$AWX_HOST/api/v2/hosts/?name=$encoded_name&inventory=$INV_ID" | jq -r '.results[0].id // empty')
|
|
|
|
if [ -n "$host_id" ]; then
|
|
echo "Host exists (id=$host_id) — updating variables"
|
|
payload=$(jq -n --arg vars "$vars" '{variables:$vars}')
|
|
curl -sS -u "$AWX_USER:$AWX_PASS" -H "Content-Type: application/json" -X PATCH "$AWX_HOST/api/v2/hosts/$host_id/" -d "$payload" | jq .
|
|
else
|
|
echo "Host not found — creating"
|
|
payload=$(jq -n --arg name "$name" --arg inv "$INV_ID" --arg vars "$vars" '{name:$name, inventory:($inv|tonumber), variables:$vars}')
|
|
curl -sS -u "$AWX_USER:$AWX_PASS" -H "Content-Type: application/json" -X POST "$AWX_HOST/api/v2/hosts/" -d "$payload" | jq .
|
|
fi
|
|
|
|
echo
|
|
done
|
|
|
|
echo "Listing hosts in inventory $INV_ID:"
|
|
curl -sS -u "$AWX_USER:$AWX_PASS" "$AWX_HOST/api/v2/inventories/$INV_ID/hosts/?page_size=100" | jq '.results[] | {id: .id, name: .name, variables: .variables}'
|