The Ansible API allows you to interact programmatically with Ansible, enabling automation and integration with other systems. This module will cover the basics of using the Ansible API, including how to set it up, make requests, and handle responses.
Key Concepts
- RESTful API: Ansible Tower provides a RESTful API that allows you to interact with Ansible programmatically.
- Authentication: Secure access to the API using tokens or basic authentication.
- Endpoints: Specific URLs that represent different resources in Ansible Tower.
- HTTP Methods: Common methods include GET, POST, PUT, and DELETE to interact with the API.
Setting Up the Ansible API
Prerequisites
- Ansible Tower installed and running.
- API access enabled in Ansible Tower.
- An API token or user credentials for authentication.
Generating an API Token
- Log in to Ansible Tower.
- Navigate to User Settings.
- Generate a new API token.
Example: Generating an API Token
Replace <username>
, <password>
, and <ansible-tower-url>
with your actual credentials and URL.
Making API Requests
Basic Structure
- Base URL:
https://<ansible-tower-url>/api/v2/
- Headers: Include the
Authorization
header with your token. - Endpoints: Specific paths to resources, e.g.,
/projects/
,/inventories/
.
Example: Fetching Projects
Example: Creating a New Project
curl -H "Authorization: Bearer <your-api-token>" \ -H "Content-Type: application/json" \ -X POST \ -d '{ "name": "New Project", "description": "A new project created via API", "scm_type": "git", "scm_url": "https://github.com/your-repo.git" }' \ https://<ansible-tower-url>/api/v2/projects/
Handling Responses
Response Structure
- Status Code: Indicates the result of the request (e.g., 200 for success, 404 for not found).
- Body: JSON-formatted data representing the resource.
Example: Parsing a Response
import requests url = "https://<ansible-tower-url>/api/v2/projects/" headers = { "Authorization": "Bearer <your-api-token>" } response = requests.get(url, headers=headers) if response.status_code == 200: projects = response.json() for project in projects['results']: print(f"Project Name: {project['name']}") else: print(f"Failed to fetch projects: {response.status_code}")
Practical Exercises
Exercise 1: List All Job Templates
- Use the API to list all job templates in your Ansible Tower.
- Print the name and ID of each job template.
Solution:
import requests url = "https://<ansible-tower-url>/api/v2/job_templates/" headers = { "Authorization": "Bearer <your-api-token>" } response = requests.get(url, headers=headers) if response.status_code == 200: job_templates = response.json() for template in job_templates['results']: print(f"Job Template Name: {template['name']}, ID: {template['id']}") else: print(f"Failed to fetch job templates: {response.status_code}")
Exercise 2: Create a New Inventory
- Use the API to create a new inventory in your Ansible Tower.
- Verify the creation by listing all inventories.
Solution:
import requests # Create a new inventory url = "https://<ansible-tower-url>/api/v2/inventories/" headers = { "Authorization": "Bearer <your-api-token>", "Content-Type": "application/json" } data = { "name": "New Inventory", "description": "An inventory created via API", "organization": 1 # Replace with your organization ID } response = requests.post(url, headers=headers, json=data) if response.status_code == 201: print("Inventory created successfully.") else: print(f"Failed to create inventory: {response.status_code}") # Verify the creation response = requests.get(url, headers=headers) if response.status_code == 200: inventories = response.json() for inventory in inventories['results']: print(f"Inventory Name: {inventory['name']}, ID: {inventory['id']}") else: print(f"Failed to fetch inventories: {response.status_code}")
Common Mistakes and Tips
- Authentication Errors: Ensure your API token is valid and included in the
Authorization
header. - Endpoint Errors: Double-check the endpoint URLs and ensure they are correct.
- Data Format: Ensure the data sent in POST/PUT requests is correctly formatted as JSON.
Conclusion
In this module, you learned how to interact with the Ansible API, including setting up authentication, making requests, and handling responses. You also practiced creating and listing resources using the API. This knowledge allows you to integrate Ansible with other systems and automate tasks programmatically.
Ansible: From Beginner to Advanced
Module 1: Introduction to Ansible
Module 2: Ansible Basics
Module 3: Playbooks
- Introduction to Playbooks
- Writing Your First Playbook
- Playbook Structure
- Variables and Facts
- Conditionals and Loops
Module 4: Roles
Module 5: Advanced Playbook Techniques
Module 6: Ansible Galaxy
Module 7: Ansible Tower
- Introduction to Ansible Tower
- Installing Ansible Tower
- Using Ansible Tower
- Managing Projects and Inventories