API not returning expected results.

Hi.

I’m working on a PowerShell script that will email the failed results of a job.

I’m trying to use the API to get the last _job then get the results of that job. But I’m stuck getting the last_job.

Using the web browser I can see what I need at https://AWX.company.local/api/v2/job_templates/?name=HealthCheckWinRMPing,

but the same URL doesn’t do anything when run from PowerShell or from Postman, both return 200 OK, and empty results.

I can’t see what I’m doing wrong.

<## AWX/Tower settings
$awxUrl = “https://AWX.company.local
$jobTemplateName = “HealthCheckWinRMPing”
$apiUsername = “APITEST”
$apiPassword = “”
$clientId = “”
$clientSecret = “”

Email settings

$smtpServer = “SERVER”
$smtpPort = 25
$smtpUsername = “”
$smtpPassword = “”
$emailFrom = “email@company.com
$emailTo = “email@company.com
#>

[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}

Authenticate and obtain access token

$authUrl = “$awxUrl/api/o/token/”
$authBody = @{
“grant_type” = “password”
“username” = $apiUsername
“password” = $apiPassword
}
$authHeaders = @{
“Content-Type” = “application/x-www-form-urlencoded”
“Authorization” = “Basic " + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(”${clientId}:${clientSecret}"))
}

#Authentication Headers
Write-Output “Authentication Headers”
$authHeaders | Format-List | Out-String | Write-Output
write-output “Auth URL: $authUrl”
$authResponse = Invoke-RestMethod -Method Post -Uri $authUrl -Headers $authHeaders -Body $authBody
$accessToken = $authResponse.access_token

Get the Job Template

$jobTemplateListUrl = “$awxUrl/api/v2/job_templates/?name=$([System.Web.HttpUtility]::UrlEncode($jobTemplateName))”
Write-verbose “Job Template Name: $jobTemplateName”
write-output “Template URL: $jobTemplateListUrl”
$jobTemplateListHeaders = @{
“Authorization” = “Bearer $accessToken”
“Content-Type” = “application/json”
}

$jobTemplateListResponse = Invoke-RestMethod -Method GET -Uri $jobTemplateListUrl -Headers $jobTemplateListHeaders
$jobTemplateListResponse.results[0].id

Print job template response for debugging

$jobTemplateListResponse | Format-List | Out-String | Write-Output

Check if last_job is not null before accessing its ID

if($null -ne $jobTemplateListResponse.results[0].summary_fields.last_job) {
$lastJobId = $jobTemplateListResponse.results[0].summary_fields.last_job.id
} else {
Write-Output “No last_job found in job template response.”
exit
}

Get the job events for the last job

$jobEventsUrl = “$awxUrl/api/v2/jobs/$lastJobId/job_events/”
$jobEventsHeaders = @{
“Authorization” = “Bearer $accessToken”
“Content-Type” = “application/json”
}
$jobEventsResponse = Invoke-RestMethod -Method GET -Uri $jobEventsUrl -Headers $jobEventsHeaders

Filter the events for failed or unreachable hosts and format them for the email body

$emailBody = “”
$failedEvents = $jobEventsResponse.results | Where-Object { $.failed -eq $true -or $.event -eq ‘runner_unreachable’ }
foreach ($event in $failedEvents) {
$hostName = $event.host_name
$errorMessage = $event.event_data.res.msg
$emailBody += “${hostName}: $errorMessage`n”
}

Format the email subject

$emailSubject = “$jobTemplateName - Job # $lastJobId - $($jobTemplateListResponse.results[0].created)”

Send the email

$mailMessage = New-Object System.Net.Mail.MailMessage
$mailMessage.From = $emailFrom
$mailMessage.To.Add($emailTo)
$mailMessage.Subject = $emailSubject
$mailMessage.Body = $emailBody

SMTP settings

$smtpClient = New-Object System.Net.Mail.SmtpClient($smtpServer, $smtpPort)
$smtpClient.EnableSsl = $false
#$smtpClient.Credentials = New-Object System.Net.NetworkCredential($smtpUsername, $smtpPassword)

Send the email

try {
$smtpClient.Send($mailMessage)
} catch {
Write-Error “Failed to send email: $_”
}

Please advise if you can.

Thank you

Greg

Lets start with what could be the obvious, are you logging into AWX as a different user when hitting the API vs the console? i.e. could it be a permissions issue?

-The AWX Team

Thank you for your response.
I have configured the user and Normal user and Super User and this has not helped. I have also made the user a member of a team with User + Read on the Project and Execute + Read on the Job Template. and none of this made any difference.

G

do you have access to a linux machine? if so can you get an equivalent curl command to work against the API?

I’m not familiar with powershell, but can you print the raw http requests that powershell is submitting in this case?

are you able to make any requests to the API server successfully, or only this one request is failing?

AWX Team

the issue was the name variable was not returning data

$jobTemplateListUrl = “$awxUrl/api/v2/job_templates/?name=$([System.Web.HttpUtility]::UrlEncode($jobTemplateName))”

I replace this with search and it worked.

Thanks you.