//native
/**
* Launch job template
* Launch a job template. extra_vars, limit and inventory are applied only when the template prompts for them on launch (ask_variables_on_launch, ask_limit_on_launch, ask_inventory_on_launch); otherwise the controller ignores them and lists them in ignored_fields. Returns the new job, whose id is in job.
*/
export async function main(
auth: RT.Awx,
job_template_id: number,
extra_vars: { [key: string]: any } | undefined,
limit: string | undefined,
inventory: number | undefined
) {
const url = new URL(
`${apiRoot(auth)}/job_templates/${job_template_id}/launch/`
)
const body: { [key: string]: any } = {}
if (typeof extra_vars === "string") {
// An API or AI caller may already pass the YAML/JSON string form.
if (extra_vars !== "") body.extra_vars = extra_vars
} else if (extra_vars != null && Object.keys(extra_vars).length > 0) {
// Sent as a JSON string, the form the launch docs and awxkit use.
body.extra_vars = JSON.stringify(extra_vars)
}
if (limit != null && limit !== "") {
body.limit = limit
}
if (inventory != null) {
body.inventory = inventory
}
const response = await fetch(url, {
method: "POST",
headers: {
Authorization: authorization(auth),
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify(body),
})
if (!response.ok) {
throw new Error(`${response.status} ${await response.text()}`)
}
return await response.json()
}
function apiRoot(auth: RT.Awx) {
const path = (auth.api_path || "/api/v2").replace(/^\/+|\/+$/g, "")
// Tolerate a base_url pasted with the API path already on it.
const base = auth.base_url
.replace(/\/+$/, "")
.replace(new RegExp(`/${path}$`), "")
return `${base}/${path}`
}
function authorization(auth: RT.Awx) {
if (auth.token) {
return `Bearer ${auth.token}`
}
if (auth.username) {
const bytes = new TextEncoder().encode(
`${auth.username}:${auth.password ?? ""}`
)
return `Basic ${btoa(String.fromCharCode(...bytes))}`
}
throw new Error(
"The AWX resource needs either a token or a username and password"
)
}
Submitted by hugo989 3 hours ago