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

  1. 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 with ansible --version.
  2. Set up SSH key-based authentication from the control machine to each target host. Run ssh-keygen if needed, then copy the public key with ssh-copy-id user@target_host. Test connectivity with ssh user@target_host to ensure no password prompt.
  3. Create an inventory file (e.g., inventory.ini) in INI format. Define groups and hosts: [webservers] web1.example.com web2.example.com [dbservers] db1.example.com
  4. Test connectivity to all hosts using the Ansible ping module: ansible all -i inventory.ini -m ping. A successful response returns pong from each host. If any host fails, check SSH access, firewall rules, or inventory syntax.
  5. Create a simple playbook (e.g., site.yml) to verify execution. Example: --- - hosts: webservers become: yes tasks: - name: Ensure Apache is installed apt: name: apache2 state: present Save this as site.yml.
  6. 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.
  7. 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.
  8. Use -v for verbose output to see detailed connection and task execution info. Increase verbosity with -vv or -vvv for debugging.
  9. To limit execution to a subset of hosts, use --limit: ansible-playbook -i inventory.ini site.yml --limit web1.example.com.
  10. After execution, review the output. Ansible summarizes changes made. If a task reports changed, the system state was modified. OK means 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: yes when 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 apt on 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 --check or --diff flags 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-lint to 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 ping and ssh manually. 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_keys on the target host. Use ssh -v user@host to 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 raw or script have fewer dependencies.
  • YAML parsing error: Use yamllint or 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_method and become_user appropriately.
  • Task hangs indefinitely: This often indicates a missing SSH key or interactive prompt. Add -vvv to 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_when to 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 --list to 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.