Edits history of script submission #23999 for ' Launch workflow job template (awx)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    /**
     * Launch workflow job template
     * Launch a workflow job template. extra_vars, limit and inventory are applied only when the workflow prompts for them on launch; otherwise the controller ignores them and lists them in ignored_fields. Returns the new workflow job, whose id is in workflow_job (use Get job with job_type workflow_job to follow it).
     */
    export async function main(
      auth: RT.Awx,
      workflow_job_template_id: number,
      extra_vars: { [key: string]: any } | undefined,
      limit: string | undefined,
      inventory: number | undefined
    ) {
      const url = new URL(
        `${apiRoot(auth)}/workflow_job_templates/${workflow_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