Files
awx/scripts/try_usernames_awx.sh

60 lines
2.1 KiB
Bash
Executable File

#!/usr/bin/env bash
set -euo pipefail
# try_usernames_awx.sh
# Patch an existing AWX Machine credential (id 5) with candidate usernames
# and run an ad-hoc ping against the three static hosts until one succeeds.
AWX_HOST="${AWX_HOST:-http://192.168.49.2:30081}"
AWX_USER="${AWX_USER:-admin}"
AWX_PASS="${AWX_PASS:-Aase#1234!}"
CRED_ID="${CRED_ID:-5}"
INV_ID="${INV_ID:-2}"
USERS=(admin alex alexpolo ubuntu core ec2-user root ansible)
for u in "${USERS[@]}"; do
echo
echo "===> Trying username=$u"
TMPPATCH=$(mktemp)
# build JSON with a literal "$encrypted$" for ssh_key_data so AWX keeps the stored key
printf '{"inputs":{"username":"%s","ssh_key_data":"$encrypted$"}}' "$u" > "$TMPPATCH"
curl -sS -u "$AWX_USER:$AWX_PASS" -H "Content-Type: application/json" -X PATCH "$AWX_HOST/api/v2/credentials/$CRED_ID/" -d "$TMPPATCH" -o /tmp/patch_resp.json || true
jq -r '.name, .inputs.username' /tmp/patch_resp.json || cat /tmp/patch_resp.json
TMPADHOC=$(mktemp)
cat > "$TMPADHOC" <<JSON
{"inventory": $INV_ID, "credential": $CRED_ID, "module_name": "ping", "limit": "host-192-168-1-144,host-192-168-1-23,host-192-168-1-24"}
JSON
resp=$(curl -sS -u "$AWX_USER:$AWX_PASS" -H "Content-Type: application/json" -X POST "$AWX_HOST/api/v2/ad_hoc_commands/" -d @$TMPADHOC)
id=$(echo "$resp" | jq -r .id)
echo "Launched ad-hoc id=$id"
if [ -z "$id" ] || [ "$id" = "null" ]; then
echo "launch failed: $resp"
continue
fi
# poll
for i in $(seq 1 45); do
status=$(curl -sS -u "$AWX_USER:$AWX_PASS" "$AWX_HOST/api/v2/ad_hoc_commands/$id/" | jq -r '.status // ""')
echo -n "."
if [ "$status" != "running" ] && [ "$status" != "pending" ] && [ -n "$status" ]; then
break
fi
sleep 2
done
echo
echo "Status: $status"
events=$(curl -sS -u "$AWX_USER:$AWX_PASS" "$AWX_HOST/api/v2/ad_hoc_commands/$id/events/?page_size=500")
echo "$events" | jq -r '.results[] | "EVENT: \(.event) HOST: \(.host_name)\n\(.stdout)\n---"'
ok=$(echo "$events" | jq -r '.results[] | select(.event=="runner_on_ok") | .host_name' | wc -l)
if [ "$ok" -gt 0 ]; then
echo "SUCCESS with username=$u"
exit 0
fi
done
echo "None of the usernames worked"