Edits history of script submission #24076 for ' Set device variables (aruba_central_onprem)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    /**
     * Set device variables
     * Declaratively set the template variables of a device: reads the current variables, returns the diff and applies only the difference (nothing changes while dry_run is true). mode "merge" only sets the given keys; "replace" also removes keys not given (except _sys_*). For a device with no variables yet, _sys_lan_mac is required.
     */
    export async function main(
      auth: RT.ArubaCentralOnprem,
      device_serial: string,
      variables: { [key: string]: any },
      mode: "merge" | "replace" | undefined,
      dry_run: boolean = true
    ) {
      const dryRun = dry_run !== false
      const replace = mode === "replace"
      const token = await getAccessToken(auth, dryRun ? "read" : "all")
      const base = auth.base_url.replace(/\/+$/, "")
      const url = `${base}/configuration/v1/devices/${encodeURIComponent(device_serial)}/template_variables`
      const headers = {
        Authorization: `Bearer ${token}`,
        "Content-Type": "application/json",
        Accept: "application/json",
      }
    
      // 1. Read the current state
      const current = await fetch(url, {
        headers: { Authorization: headers.Authorization, Accept: headers.Accept },
      })
      if (!current.ok) {
        throw new Error(`${current.status} ${await current.text()}`)
      }
      const currentBody = (await current.json()) as {
        data?: { total?: number; variables?: { [key: string]: any } }
      }
      const existing: { [key: string]: any } = currentBody?.data?.variables ?? {}
      const intended: { [key: string]: any } = variables ?? {}
    
      // 2. Compute the difference
      const same = (a: any, b: any) => JSON.stringify(a) === JSON.stringify(b)
      const added: { [key: string]: any } = {}
      const changed: { [key: string]: { from: any; to: any } } = {}
      const removed: { [key: string]: any } = {}
      for (const [k, v] of Object.entries(intended)) {
        if (!(k in existing)) {
          added[k] = v
        } else if (!same(existing[k], v)) {
          changed[k] = { from: existing[k], to: v }
        }
      }
      if (replace) {
        for (const [k, v] of Object.entries(existing)) {
          if (!(k in intended) && !k.startsWith("_sys_")) {
            removed[k] = v
          }
        }
      }
      const diff = { added, changed, removed }
      const hasChanges =
        Object.keys(added).length +
          Object.keys(changed).length +
          Object.keys(removed).length >
        0
    
      const creating = Object.keys(existing).length === 0
      // _sys_serial and _sys_lan_mac are mandatory variable definitions (CoP "Managing Variable Files")
      if (creating && hasChanges && !intended._sys_lan_mac) {
        throw new Error(
          "device has no variables yet: include _sys_lan_mac (the device MAC address) to create them"
        )
      }
    
      if (!hasChanges || dryRun) {
        return { changed: hasChanges, diff, applied: false, dry_run: dryRun }
      }
    
      // 3. Apply only the difference, always with the device's _sys_* identifiers
      const sys = Object.fromEntries(
        Object.entries(existing).filter(([k]) => k.startsWith("_sys_"))
      )
      let method: "POST" | "PUT" | "PATCH"
      let payload: { [key: string]: any }
      if (creating) {
        // No variables yet: create them (PATCH/PUT reject a device without variables)
        method = "POST"
        payload = { _sys_serial: device_serial, ...intended }
      } else if (Object.keys(removed).length > 0) {
        // Removing keys needs a full replace
        method = "PUT"
        payload = { ...sys, ...intended }
      } else {
        method = "PATCH"
        payload = {
          ...sys,
          ...added,
          ...Object.fromEntries(Object.entries(changed).map(([k, c]) => [k, c.to])),
        }
      }
    
      const response = await fetch(url, {
        method,
        headers,
        body: JSON.stringify({
          total: Object.keys(payload).length,
          variables: payload,
        }),
      })
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
    
      return { changed: true, diff, applied: true, dry_run: false, method }
    }
    
    // OAuth grant mechanism documented for Central On-Premises (API Gateway > OAuth grant):
    // login -> authorization code -> access token. Tokens last 2 hours, so a fresh one is minted per run.
    async function getAccessToken(
      auth: RT.ArubaCentralOnprem,
      scope: "read" | "all"
    ): Promise<string> {
      const base = auth.base_url.replace(/\/+$/, "")
    
      const loginUrl = new URL(`${base}/oauth2/authorize/central/api/login`)
      loginUrl.searchParams.append("client_id", auth.client_id)
      const login = await fetch(loginUrl, {
        method: "POST",
        headers: { "Content-Type": "application/json", Accept: "application/json" },
        body: JSON.stringify({ username: auth.username, password: auth.password }),
      })
      if (!login.ok) {
        throw new Error(`login: ${login.status} ${await login.text()}`)
      }
      const cookies = login.headers.get("set-cookie") ?? ""
      const csrf = cookies.match(/csrftoken=([^;,\s]+)/)?.[1]
      const session = cookies.match(/session=([^;,\s]+)/)?.[1]
      if (!csrf || !session) {
        throw new Error(
          "login: response did not set the csrftoken and session cookies"
        )
      }
    
      const authorizeUrl = new URL(`${base}/oauth2/authorize/central/api`)
      authorizeUrl.searchParams.append("client_id", auth.client_id)
      authorizeUrl.searchParams.append("response_type", "code")
      authorizeUrl.searchParams.append("scope", scope)
      const authorize = await fetch(authorizeUrl, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Accept: "application/json",
          Cookie: `session=${session}`,
          "X-CSRF-Token": csrf,
        },
        body: JSON.stringify({ customer_id: auth.customer_id }),
      })
      if (!authorize.ok) {
        throw new Error(`authorize: ${authorize.status} ${await authorize.text()}`)
      }
      const { auth_code } = (await authorize.json()) as { auth_code: string }
    
      const tokenUrl = new URL(`${base}/oauth2/token`)
      tokenUrl.searchParams.append("client_id", auth.client_id)
      tokenUrl.searchParams.append("client_secret", auth.client_secret)
      tokenUrl.searchParams.append("grant_type", "authorization_code")
      tokenUrl.searchParams.append("code", auth_code)
      const token = await fetch(tokenUrl, {
        method: "POST",
        headers: { Accept: "application/json" },
      })
      if (!token.ok) {
        throw new Error(`token: ${token.status} ${await token.text()}`)
      }
      const { access_token } = (await token.json()) as { access_token: string }
      return access_token
    }
    

    Submitted by hugo989 7 hours ago