如何在Node.js脚本中通过API端点创建Ansible Tower Job Template
Got it, let's walk through exactly how to create an Ansible Tower (now AWX) Job Template using its API in a Node.js script. I'll break this down into actionable steps with code examples so you can follow along easily.
Before you start, make sure you have these ready:
- A running Ansible Tower/AWX instance with API access enabled
- A valid API Token for your Tower user (you can generate this in Tower's UI under User Settings > Tokens)
- Node.js installed on your machine (v14+ recommended)
- IDs (or names) of the resources you want to link to the Job Template:
- Inventory (where your target hosts live)
- Project (contains your Ansible playbooks)
- Credentials (for accessing hosts, if needed)
We'll use axios for making HTTP requests to the Tower API—it's simpler than native fetch for handling JSON and auth. Install it via npm:
npm install axios
Let's build the script step by step. We'll use async/await for cleaner async code.
2.1 Configure Core Variables
First, define your Tower instance details and Job Template parameters:
const axios = require('axios'); // Tower API configuration const TOWER_URL = 'https://your-tower-instance.com/api/v2'; const API_TOKEN = 'your-api-token-here'; // Job Template parameters (customize these!) const JOB_TEMPLATE_DETAILS = { name: 'My New Job Template', description: 'Template for deploying web servers', inventory: 1, // Replace with your inventory ID project: 2, // Replace with your project ID playbook: 'deploy-web.yml', // Path to your playbook in the project credentials: [3], // Array of credential IDs (leave empty if not needed) enabled: true, allow_simultaneous: false };
2.2 Add Authentication Header
Tower uses Bearer token auth. Create a reusable headers object:
const headers = { 'Authorization': `Bearer ${API_TOKEN}`, 'Content-Type': 'application/json' };
2.3 (Optional) Fetch Resource IDs by Name
If you don't know the IDs of your inventory/project/credentials, you can fetch them via the API. Here's a helper function to get an inventory ID by name:
async function getInventoryIdByName(inventoryName) { try { const response = await axios.get(`${TOWER_URL}/inventories/?name=${encodeURIComponent(inventoryName)}`, { headers }); if (response.data.count > 0) { return response.data.results[0].id; } throw new Error(`Inventory "${inventoryName}" not found`); } catch (error) { console.error('Error fetching inventory ID:', error.message); process.exit(1); } }
You can create similar functions for projects and credentials by changing the endpoint to /projects/ or /credentials/.
2.4 Create the Job Template
Now write the main function to send the POST request to create the template:
async function createJobTemplate() { try { // Optional: If using names instead of IDs, uncomment these lines // const inventoryId = await getInventoryIdByName('My Production Inventory'); // JOB_TEMPLATE_DETAILS.inventory = inventoryId; const response = await axios.post( `${TOWER_URL}/job_templates/`, JOB_TEMPLATE_DETAILS, { headers } ); console.log('Job Template created successfully!'); console.log('Template ID:', response.data.id); console.log('Template URL:', `${TOWER_URL}/job_templates/${response.data.id}/`); } catch (error) { console.error('Failed to create Job Template:'); if (error.response) { // Tower returns detailed error messages in the response console.error('Status:', error.response.status); console.error('Error Details:', error.response.data); } else { console.error('Error Message:', error.message); } process.exit(1); } } // Run the function createJobTemplate();
Save the script as create-job-template.js, then run it:
node create-job-template.js
If everything works, you'll see a success message with the template ID. You can also verify the template exists in your Tower UI under Templates > Job Templates.
- 401 Unauthorized: Double-check your API token is valid and has the correct permissions.
- 400 Bad Request: Missing required fields (like
name,inventory, orproject) or invalid resource IDs. Check the error details in the response. - 403 Forbidden: Your user doesn't have permission to create Job Templates or access the linked resources.
- Connection Errors: Ensure your Tower instance is reachable from your machine and the API endpoint is correct.
内容的提问来源于stack exchange,提问作者Shreya Sood

