Edits history of script submission #24086 for ' Save configuration (f5_bigip)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    async function connect(auth: RT.F5Bigip): Promise<{
      base: string
      headers: { [key: string]: string }
      release: () => Promise<void>
    }> {
      const base = auth.base_url.replace(/\/+$/, "")
      if (auth.auth_method === "basic") {
        return {
          base,
          headers: {
            Authorization: `Basic ${btoa(`${auth.username}:${auth.password}`)}`,
          },
          release: async () => {},
        }
      }
      const login = await fetch(`${base}/mgmt/shared/authn/login`, {
        method: "POST",
        headers: { "Content-Type": "application/json", Accept: "application/json" },
        body: JSON.stringify({
          username: auth.username,
          password: auth.password,
          loginProviderName: auth.login_provider_name || "tmos",
        }),
      })
      if (!login.ok) {
        throw new Error(`${login.status} ${await login.text()}`)
      }
      const token: string = (await login.json()).token.token
      return {
        base,
        headers: { "X-F5-Auth-Token": token },
        release: async () => {
          await fetch(
            `${base}/mgmt/shared/authz/tokens/${encodeURIComponent(token)}`,
            {
              method: "DELETE",
              headers: { "X-F5-Auth-Token": token },
            }
          )
        },
      }
    }
    
    /**
     * Save configuration
     * Save the running configuration to the stored configuration (tmsh save sys config), so changes made through the API survive a reboot.
     */
    export async function main(auth: RT.F5Bigip) {
      const f5 = await connect(auth)
      try {
        const response = await fetch(`${f5.base}/mgmt/tm/sys/config`, {
          method: "POST",
          headers: {
            ...f5.headers,
            "Content-Type": "application/json",
            Accept: "application/json",
          },
          body: JSON.stringify({ command: "save" }),
        })
    
        if (!response.ok) {
          throw new Error(`${response.status} ${await response.text()}`)
        }
    
        return await response.json()
      } finally {
        await f5.release()
      }
    }
    

    Submitted by hugo989 7 hours ago