Running Ansible code means executing playbooks or ad-hoc commands to automate configuration, deployment, and task execution across managed nodes. This achieves consistent, repeatable infrastructure changes without manual intervention. To begin, you need Ansible installed on a control machine, SSH access to target hosts, and an inventory file defining those hosts.
What You'll Need
- A control machine (Linux or macOS; Windows requires WSL2)
- Ansible installed via pip or package manager (e.g.,
pip install ansible) - SSH access to target machines with key-based authentication recommended
- An inventory file (INI or YAML format) listing target hosts
- An Ansible playbook (YAML file) containing the tasks to run
- Basic understanding of YAML syntax and Linux command line
Step-by-Step
- Install Ansible on your control machine using your system’s package manager or pip. For example, on Ubuntu:
sudo apt update && sudo apt install ansible, or via pip:pip3 install ansible. Verify installation withansible --version. - Set up SSH key-based authentication from the control machine to each target host. Run
ssh-keygenif needed, then copy the public key withssh-copy-id user@target_host. Test connectivity withssh user@target_hostto ensure no password prompt. - Create an inventory file (e.g.,
inventory.ini) in INI format. Define groups and hosts:[webservers]web1.example.comweb2.example.com[dbservers]db1.example.com - Test connectivity to all hosts using the Ansible ping module:
ansible all -i inventory.ini -m ping. A successful response returnspongfrom each host. If any host fails, check SSH access, firewall rules, or inventory syntax. - Create a simple playbook (e.g.,
site.yml) to verify execution. Example:---- hosts: webserversbecome: yestasks:- name: Ensure Apache is installedapt:name: apache2state: presentSave this assite.yml. - Run the playbook using
ansible-playbook -i inventory.ini site.yml. Ansible will connect to each host, gather facts, and execute tasks in order. Output shows each task’s status: OK, changed, or failed. - For ad-hoc tasks, run commands directly. Example:
ansible webservers -i inventory.ini -m shell -a 'uptime'to check system load across all web servers. - Use
-vfor verbose output to see detailed connection and task execution info. Increase verbosity with-vvor-vvvfor debugging. - To limit execution to a subset of hosts, use
--limit:ansible-playbook -i inventory.ini site.yml --limit web1.example.com. - After execution, review the output. Ansible summarizes changes made. If a task reports
changed, the system state was modified.OKmeans no change was needed.
Common Mistakes
- Using password-based SSH without ssh-agent or sshpass, causing hangs or failures during automation.
- Incorrect inventory syntax, such as missing brackets, extra spaces, or using colons instead of semicolons in variable definitions.
- Forgetting to use
become: yeswhen tasks require root privileges, leading to permission errors. - Not validating YAML syntax in playbooks — a single misplaced space or incorrect indentation breaks the entire file.
- Running playbooks without testing connectivity first, wasting time on failed SSH connections.
- Assuming all modules work the same across distributions (e.g., using
apton CentOS). - Storing secrets like passwords in plain text within playbooks instead of using Ansible Vault.
Tips
- Always test playbooks in a staging environment before running on production systems.
- Use version control (e.g., Git) for inventory files, playbooks, and variables to track changes.
- Leverage Ansible roles to organize reusable configurations and promote modularity.
- Use
--checkor--diffflags to preview changes without applying them:ansible-playbook -i inventory.ini site.yml --check. - Organize inventory by function and environment (e.g.,
inventory/production/,inventory/staging/). - Enable fact caching to speed up repeated runs on large infrastructures.
- Use
ansible-lintto catch syntax issues and best practice violations before execution. - Document the purpose of each playbook and inventory file with comments in YAML using
#.
Troubleshooting
- SSH connection refused or timeout: Verify the target host is reachable via
pingandsshmanually. Check firewalls (e.g., ufw, firewalld) and ensure SSH daemon is running on port 22. - Authentication failed: Confirm the SSH key is added to
~/.ssh/authorized_keyson the target host. Usessh -v user@hostto debug the authentication process. - Module not found or unsupported: Ensure the target system has required dependencies (e.g., Python 3 for most modules). Some modules like
raworscripthave fewer dependencies. - YAML parsing error: Use
yamllintor an online YAML validator to check indentation and syntax. Remember that YAML uses spaces, not tabs. - Permission denied during become: Verify the user has sudo privileges without a password prompt, or configure
become_methodandbecome_userappropriately. - Task hangs indefinitely: This often indicates a missing SSH key or interactive prompt. Add
-vvvto see where it stalls. Ensure no sudo password is required. - Inconsistent results across runs: Check for idempotency issues in custom scripts or commands. Use
changed_whento define when a task should report change. - Inventory not loading: Verify the path to the inventory file is correct. Use
ansible-inventory -i inventory.ini --listto see how Ansible interprets it.
Frequently Asked Questions
Do I need to install Ansible on the target machines?
No, Ansible only needs to be installed on the control machine. Target machines require only SSH access and a compatible Python version (usually Python 2.7 or 3.5+).
Can I run Ansible on Windows?
Yes, but only through Windows Subsystem for Linux (WSL2). Native Windows is not supported as a control machine due to lack of POSIX compatibility.
What is the difference between ansible and ansible-playbook?
ansible runs ad-hoc commands against hosts. ansible-playbook executes a sequence of tasks defined in a YAML playbook for complex automation.
How do I handle secrets like passwords or API keys?
Use Ansible Vault to encrypt sensitive data. Create encrypted files with ansible-vault create and reference them in playbooks. Provide the vault password at runtime with --ask-vault-pass or a password file.
Can I run only specific tasks in a playbook?
Yes, use tags. Assign tags: to tasks, then run with --tags or skip with --skip-tags. Example: ansible-playbook site.yml --tags install,configure.
What happens if a task fails mid-playbook?
By default, Ansible stops execution on the first error. Use ignore_errors: yes on a task to continue, or max_fail_percentage to allow some failures before stopping.