API not returning expected results.

77 views
Skip to first unread message

Gregory Machin

unread,
May 15, 2023, 11:34:35 PM5/15/23
to AWX Project
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
$jobTemplateName = "HealthCheckWinRMPing"
$apiUsername = "APITEST"
$apiPassword = ""
$clientId = ""
$clientSecret = ""

# Email settings
$smtpServer = "SERVER"
$smtpPort = 25
$smtpUsername = ""
$smtpPassword = ""
$emailFrom = "em...@company.com"
$emailTo = "em...@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





AWX Project

unread,
May 17, 2023, 2:55:38 PM5/17/23
to AWX Project
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

Gregory Machin

unread,
May 18, 2023, 6:40:40 PM5/18/23
to awx-p...@googlegroups.com
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

--
You received this message because you are subscribed to a topic in the Google Groups "AWX Project" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/awx-project/O5InhVoJkRw/unsubscribe.
To unsubscribe from this group and all its topics, send an email to awx-project...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/awx-project/b86bcffc-cf53-4b9c-a3e1-724e047a556fn%40googlegroups.com.

AWX Project

unread,
May 19, 2023, 1:26:37 PM5/19/23
to AWX Project
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

Gregory Machin

unread,
May 22, 2023, 10:09:39 PM5/22/23
to awx-p...@googlegroups.com
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. 

Reply all
Reply to author
Forward
0 new messages