Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

AnsibleJob.ps1 - improved to coding guidelines. #3

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
159 changes: 123 additions & 36 deletions AnsibleJob.ps1
Original file line number Diff line number Diff line change
@@ -1,69 +1,156 @@
function Get-AnsibleJob
{
[CmdletBinding()]
Param (
param(
[Parameter(ValueFromPipelineByPropertyName=$true)]
[int]$id
[int]$ID
)

if ($id)
{
$Return = Invoke-GetAnsibleInternalJsonResult -ItemType "jobs" -Id $id
}
Else
{
$Return = Invoke-GetAnsibleInternalJsonResult -ItemType "jobs"
if ($ID) {
$result = Invoke-GetAnsibleInternalJsonResult -ItemType "jobs" -Id $ID;
} else {
$result = Invoke-GetAnsibleInternalJsonResult -ItemType "jobs";
}


if (!($Return))
{
#Nothing returned from the call
Return
if (!$result) {
# Nothing returned from the call.
return $null;
}
$returnobj = @()
foreach ($jsonorg in $return)
$returnObjs = @();
foreach ($jsonorg in $result)
{
#Shift back to json and let newtonsoft parse it to a strongly named object instead
$jsonorgstring = $jsonorg | ConvertTo-Json
$org = $JsonParsers.ParseToJob($jsonorgstring)
$returnobj += $org; $org = $null
# Shift back to json and let newtonsoft parse it to a strongly named object instead.
$jsonorgstring = $jsonorg | ConvertTo-Json;
$org = $JsonParsers.ParseToJob($jsonorgstring);
$returnObjs += $org;
$org = $null;

}
#return the things
$returnobj

# Return the job(s).
$returnObjs;
}

function Invoke-AnsibleJob
{
[CmdletBinding()]
Param (
[Parameter(ValueFromPipelineByPropertyName=$true,Mandatory=$true,ParameterSetName='ByObj')]
param(
[Parameter(ValueFromPipelineByPropertyName=$true,Mandatory=$true,Position=0,ParameterSetName='ByObj')]
[AnsibleTower.JobTemplate]$JobTemplate,

[Parameter(ValueFromPipelineByPropertyName=$true,Mandatory=$true,ParameterSetName='ById')]
[int]$id
[Parameter(ValueFromPipelineByPropertyName=$true,Mandatory=$true,Position=0,ParameterSetName='ById')]
[int]$ID
)

if ($JobTemplate)
{
$ThisJobTemplate = $JobTemplate
$id = $ThisJobTemplate.id
$ID = $ThisJobTemplate.id
}
Else
{
$ThisJobTemplate = Get-AnsibleJobTemplate -id $id
$ThisJobTemplate = Get-AnsibleJobTemplate -id $ID;
}


if (!$ThisJobTemplate) {Write-Error "No Job template with id $id"; return}
if (!$ThisJobTemplate) {
throw ("Job template with id [{0}] not found" -f $ID);
}

Write-Verbose "Submitting job from template $id"
$result = Invoke-PostAnsibleInternalJsonResult -ItemType "job_templates" -itemId $id -ItemSubItem "jobs"
$JobId = $result.id
Write-Verbose "Starting job with jobid $jobid"
$result = Invoke-PostAnsibleInternalJsonResult -ItemType "jobs" -itemId $JobId -ItemSubItem "start"
$job = get-ansibleJob -id $JobId
$job
Write-Verbose ("Creating job from job template [{0}]" -f $ID);
$result = Invoke-PostAnsibleInternalJsonResult -ItemType "job_templates" -itemId $id -ItemSubItem "jobs";
$JobID = $result.id;
Write-Verbose ("Starting job with id [{0}]" -f $JobID);
$result = Invoke-PostAnsibleInternalJsonResult -ItemType "jobs" -itemId $JobId -ItemSubItem "start";
Get-AnsibleJob -ID $JobId
}

function Wait-AnsibleJob
{
<#
.SYNOPSIS
Waits for an Ansible job to finish.

.DESCRIPTION
Waits for an Ansible job to finish by monitoring the 'finished' property of the job.
Every Interval the job details are requested and while 'finished' is empty the job is considered to be still running.
When the job is finished, the function returns. The caller must analyse the job state and/or result.
Inspect the status, failed and result_output properties for more information on the job result.

If the Timeout has expired an exception is thrown.

.PARAMETER Job
The Job object as returned by Get-AnsibleJob or Invoke-AnsibleJobTemplate.

.PARAMETER ID
The job ID.

.PARAMETER Timeout
The timeout in seconds to wait for the job to finish.

.PARAMETER Interval
The interval in seconds at which the job status is inspected.

.EXAMPLE
$job = Invoke-AnsibleJobTemplate 'Demo Job Template'
Wait-AnsibleJob -ID $job.id

Starts a new job for job template 'Demo Job Template' and then waits for the job to finish. Inspect the $job properties status, failed and result_stdout for more details.

.EXAMPLE
$job = Invoke-AnsibleJobTemplate 'Demo Job Template' | Wait-AnsibleJob -Interval 1

Starts a new job for job template 'Demo Job Template' and then waits for the job to finish by polling every second. Inspect the $job properties status, failed and result_stdout for more details.

.EXAMPLE
$job = Invoke-AnsibleJobTemplate 'Demo Job Template' | Wait-AnsibleJob -Interval 5 -Timeout 60

Starts a new job for job template 'Demo Job Template' and then waits for the job to finish by polling every 5 seconds. If the job did not finish after 60 seconds, an exception is thrown.
Inspect the $job properties status, failed and result_stdout for more details.

.OUTPUTS
The job object.
#>
[CmdletBinding(DefaultParameterSetName='Job')]
param(
[Parameter(ValueFromPipelineByPropertyName=$true,Mandatory=$true,Position=0,ParameterSetName='Job')]
[AnsibleTower.Job]$Job,

[Parameter(ValueFromPipelineByPropertyName=$true,Mandatory=$true,Position=0,ParameterSetName='ID')]
[int]$ID,

[int]$Timeout = 3600,
[int]$Interval = 3
)

if ($ID) {
$Job = Get-AnsibleJob -id $ID;
if (!$Job) {
throw ("Failed to get job with id [{0}]" -f $ID)
}
}

Write-Verbose ("Waiting for job [{0}] to finish..." -f $Job.id);
$startDate = Get-Date;
$finished = $false;
while (!$finished)
{
if (![string]::IsNullOrEmpty($Job.finished)) {
Write-Verbose ("Job [{0}] finished." -f $Job.id);
$finished = $true;
} else {
$timeSpan = New-TimeSpan -Start $startDate -End (Get-Date);
Write-Verbose ("Waiting for job [{0}] to finish. Job status is [{1}]. Elapsed time is [{2}] seconds." -f $Job.id,$Job.status,[math]::Round($timeSpan.TotalSeconds));
if ($timeSpan.TotalSeconds -ge $Timeout) {
throw ("Timeout waiting for job [{0}] to finish" -f $Job.id);
}

Write-Verbose ("Sleeping [{0}] seconds..." -f $Interval);
sleep -Seconds $Interval
}
$Job = Get-AnsibleJob -id $Job.id;
}

# Return the job object.
$Job
}
168 changes: 131 additions & 37 deletions AnsibleJobTemplate.ps1
Original file line number Diff line number Diff line change
@@ -1,75 +1,169 @@
function Get-AnsibleJobTemplate
function Get-AnsibleJobTemplateID
{
<#
.SYNOPSIS
.SYNOPSIS
Gets the job template ID from a job template name.

.EXAMPLE
Get-AnsibleJobTemplateID -Name 'Demo Job Template'

Gets one or multiple Job Templates
.EXAMPLE
'Demo Job Template' | Get-AnsibleJobTemplateID

.OUTPUTS
The job ID.
#>

[CmdletBinding()]
param(
[Parameter(Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,Position=0)]
[string]$Name
)

# We should be passing a search term here, prevents from passing all jobs via the REST call.
(Get-AnsibleJobTemplate | ? { $_.name -eq $Name }).id
}

function Get-AnsibleJobTemplate
{
<#
.SYNOPSIS
Gets one or all job templates.

.EXAMPLE
Get-AnsibleJobTemplate

Gets all job templates.

.EXAMPLE
Get-AnsibleJobTemplate | where { $_.project -eq 4 }

Gets all job templates that belong to project ID 4.

.EXAMPLE
Get-AnsibleJobTemplate 'Demo Job Template'

Gets details about job template named 'Demo Job Template'.

.EXAMPLE
$jobTemplate = Get-AnsibleJobTemplate -ID 5

.OUPUTS
Strongly typed job template object(s).
#>
[CmdletBinding(DefaultParameterSetName='Name')]
Param (
[Parameter(ValueFromPipelineByPropertyName=$true)]
[int]$id
[Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,Position=0,ParameterSetName='Name')]
[string]$Name,

[Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,Position=0,ParameterSetName='ID')]
[int]$ID
)

if ($id)
{
$Return = Invoke-GetAnsibleInternalJsonResult -ItemType "job_templates" -Id $id
if ($Name) {
$ID = Get-AnsibleJobTemplateID -Name $Name
if (!$ID) {
throw ("Failed to get the ID for job template named [{0}]" -f $Name)
}
}
Else
{
$Return = Invoke-GetAnsibleInternalJsonResult -ItemType "job_templates"

if ($ID) {
$return = Invoke-GetAnsibleInternalJsonResult -ItemType "job_templates" -Id $ID
} else {
$return = Invoke-GetAnsibleInternalJsonResult -ItemType "job_templates"
}


if (!($Return))
if (!$return)
{
#Nothing returned from the call
Return
# Nothing returned from the call
return
}
$returnobj = @()

$returnObjs = @()
foreach ($jsonorg in $return)
{
#Shift back to json and let newtonsoft parse it to a strongly named object instead
# Shift back to json and let newtonsoft parse it to a strongly named object instead
$jsonorgstring = $jsonorg | ConvertTo-Json
$org = $JsonParsers.ParseToJobTemplate($jsonorgstring)
$returnobj += $org; $org = $null
$returnObjs += $org;
$org = $null

}
#return the things
$returnobj
$returnObjs
}


function Invoke-AnsibleJobTemplate
{
<#
.SYNOPSIS
.SYNOPSIS
Runs an Ansible job template.

.PARAMETER Name
Name of the Ansible job template.

Invokes an Ansible Job Template
.PARAMETER ID
ID of the Ansible job template.

.EXAMPLE
.PARAMETER Data
Any additional data to be supplied to Tower in order to run the job template. Most common is "extra_vars".
Supply a normal Powershell hash table. It will be converted to JSON. See the examples for more information.

Connect-AnsibleTower -Credential (get-credential) -TowerUrl "https://mytower" -DisableCertificateVerification
$jobtemplate = get-ansibleJobTemplate -id 5
$jobtemplate | Invoke-AnsibleJobTemplate
.EXAMPLE
Invoke-AnsibleJobTemplate -Name 'Demo Job Template'

Runs a job for job template named 'Demo Job Template'.

.EXAMPLE
$job = Invoke-AnsibleJobTemplate -ID 5

Runs a job for job template with ID 5.

.EXAMPLE
$jobTemplateData = @{
"extra_vars" = @{
'var1' = 'value1';
'var2' = 'value2';
};
}
$job = Invoke-AnsibleJobTemplate -Name 'My Ansible Job Template' -Data $jobTemplateData

Launches job template named 'My Ansible Job Template' and passes extra variables for the job to run with.

.OUTPUTS
Strongly typed job object.
#>

[CmdletBinding()]
[CmdletBinding(DefaultParameterSetName='Name')]
Param (
[Parameter(ValueFromPipelineByPropertyName=$true,Mandatory=$true)]
[int]$id
)
[Parameter(Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,Position=0,ParameterSetName='Name')]
[string]$Name,

$ThisJobTemplate = Get-AnsibleJobTemplate -id $id
[Parameter(Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,Position=0,ParameterSetName='ID')]
[int]$ID,

if (!$ThisJobTemplate) {Write-Error "No Job template with id $id"; return}

$result = Invoke-PostAnsibleInternalJsonResult -ItemType "job_templates" -itemId $id -ItemSubItem "jobs"
$JobId = $result.id
$job = get-ansibleJob -id $JobId
$job
}
[Object]$Data
)

if ($Name) {
$ID = Get-AnsibleJobTemplateID -Name $Name
if (!$ID) {
throw ("Failed to get the ID for job template named [{0}]" -f $Name)
}
}

$params = @{
ItemType = 'job_templates';
itemId = $ID;
ItemSubItem = 'launch';
};
if ($Data) {
$params.Add('InputObject', $Data);
}
$result = Invoke-PostAnsibleInternalJsonResult @params;
if (!$result -and !$result.id) {
throw ("Failed to start job for job template ID [{0}]" -f $ID);
}
Get-AnsibleJob -id $result.id
}
Binary file modified AnsibleTower.psd1
Binary file not shown.
Loading