Search code examples
node.jsoauth-2.0ansibleansible-tower

Ansible Tower API call using OAuth2 Token from Nodejs App


Can we call Ansible Tower Api by passing only Oauth2 token no username or password?

(Say I want to fetch my inventories from ansible tower by passing only Oauth2 token to my nodejs script. Is that possible?)

If yes, please share syntax of that script.

Script which i have used is giving me correct output but it is using credentials as username and password but i want to do the same task by passing only OAuth2 token(generating from my username and password)

var unirest = require('unirest');
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
var Request = unirest.get('http://<tower-host>/api/v2/inventories');

Request
   .auth({
    user: 'foo',
    pass: 'bar',
})
   .then(function (response) {
    var data = response.body;
    console.log(data);
  })

Solution

  • You can simply pass the authorization token in a header. Here's an example function:

    const fetch = require('node-fetch');
    function job_inventory(tower_url, token) {
        return fetch(tower_url+ "/api/v2/inventories", {
            method: "GET",
            headers: {
                "content-type": "application/json",
                "authorization": "Bearer " + token
            }
        });
    }