Ansible command line lets you run playbooks and ad-hoc tasks to automate configuration, deployment, and orchestration across remote systems without installing agents. You need Ansible installed on a control node and SSH access to target hosts.

What You'll Need

  • A control machine with Python 3.8 or later installed
  • Ansible installed via pip or system package manager (e.g., pip install ansible)
  • SSH access to all target hosts (key-based authentication recommended)
  • Inventory file defining your hosts and groups
  • Basic understanding of YAML for playbooks

Step-by-Step

  1. Verify Ansible is installed and accessible by running ansible --version. This confirms the installation and shows the version, configuration file path, and Python version in use.
  2. Create an inventory file (e.g., inventory.ini) listing your target hosts. Example:
    [webservers]
    host1.example.com
    host2.example.com
    [dbservers]
    host3.example.com
    Save the file and test connectivity with ansible all -i inventory.ini -m ping. A successful response returns "pong" from each host.
  3. Run a simple ad-hoc command to check system uptime across all hosts: ansible all -i inventory.ini -a "uptime". This executes the uptime module on each host and returns the output.
  4. Create a basic playbook (e.g., site.yml) to install Nginx on web servers:
    -
      hosts: webservers
      become: yes
      tasks:
        - name: Install Nginx
          apt:
            name: nginx
            state: present
        - name: Start and enable Nginx
          service:
            name: nginx
            state: started
            enabled: yes
    
    Save the file and run it with ansible-playbook -i inventory.ini site.yml. Ansible will connect to each host, install Nginx if missing, start the service, and enable it at boot.
  5. Use --check mode to preview changes before applying them: ansible-playbook -i inventory.ini site.yml --check. This runs the playbook in dry-run mode, showing what would be changed without modifying any systems.
  6. Limit execution to a subset of hosts using -l: ansible-playbook -i inventory.ini site.yml -l host1.example.com. This runs the playbook only on the specified host, useful for testing or targeted updates.
  7. Pass variables at runtime with -e: ansible-playbook -i inventory.ini site.yml -e "nginx_port=8080". This overrides any default variables in the playbook, allowing flexible deployments without editing files.
  8. Review execution output for errors. Ansible uses color-coded output: green for success, yellow for changed, red for failures. Check the RECAP section at the end for a summary of successes, failures, and skipped tasks per host.

Common Mistakes

  • Using password-based SSH without ssh-agent or sshpass, causing intermittent failures or hanging prompts. Always use key-based authentication for reliable automation.
  • Forgetting to use become: yes when tasks require root privileges, leading to permission errors during package installation or service management.
  • Misindenting YAML in playbooks, which Ansible interprets as structural errors. Use consistent 2-space indentation and validate syntax with ansible-playbook --syntax-check.
  • Running playbooks against the wrong inventory due to typos or missing -i flag, resulting in no hosts being targeted or unintended systems being modified.
  • Not quoting strings with special characters in ad-hoc commands (e.g., ansible all -a "echo $HOME"), causing local shell expansion instead of remote execution. Use single quotes to prevent local interpretation: -a 'echo $HOME'.

Tips

  • Use -v, -vv, or -vvv to increase verbosity and see detailed connection and task execution information, invaluable for debugging.
  • Organize inventory with groups and group_vars/host_vars directories to manage variables cleanly and avoid hardcoding values in playbooks.
  • Leverage Ansible modules over raw commands whenever possible (e.g., use yum or apt instead of command: yum install ...) for idempotency and better error handling.
  • Store sensitive data like passwords using Ansible Vault. Encrypt variables with ansible-vault create and decrypt at runtime with --ask-vault-pass or a vault password file.
  • Regularly update Ansible and dependencies to benefit from new modules, security fixes, and performance improvements. Check ansible --version after updates.

Troubleshooting

If commands fail, follow these steps in order:

  1. Verify SSH connectivity manually: ssh user@host. If this fails, check network access, SSH service status, and key permissions (chmod 600 ~/.ssh/id_rsa).
  2. Test with -vvv to see where the connection fails — common issues include missing Python on the target host or incorrect SSH port.
  3. Ensure the target host has Python 3 installed. Ansible requires Python 2.7 or 3.5+; if missing, install it via your distribution’s package manager or use the raw or script module for initial bootstrap.
  4. Check inventory syntax: invalid headers or missing newlines can cause hosts to be ignored. Use ansible-inventory -i inventory.ini --list to verify parsed inventory.
  5. If using become, confirm the user has sudo privileges without a password prompt (NOPASSWD in sudoers) or provide the password via --ask-become-pass.
  6. For module-specific errors (e.g., apt failures), run the command manually on the target to isolate whether it’s an Ansible or system issue.
  7. If playbooks hang, check for interactive prompts or missing dependencies; use -v to see if it’s waiting for input.

Frequently Asked Questions

Do I need to install Ansible on the target hosts?

No, Ansible is agentless and only requires installation on the control node. Targets need only SSH and a supported Python version.

Can I use Windows as a control node?

Ansible does not natively support Windows as a control node. Use Linux or macOS, or run Ansible inside a Windows Subsystem for Linux (WSL) environment.

What if my inventory contains hundreds of hosts?

Ansible scales well; use -f to control parallelism (e.g., -f 20 for 20 concurrent hosts) and consider splitting inventory or using dynamic inventory scripts for cloud environments.

How do I handle hosts with different SSH ports?

Define the port in the inventory: host.example.com:2222 or set ansible_port in host_vars. Ansible will use the specified port for each host.

Is it safe to run Ansible playbooks as root on the control node?

It’s not required and poses unnecessary risk. Run as a regular user with SSH key access to targets and sudo privileges where needed via become.

Can I run only specific tasks in a playbook?

Yes, use --tags to execute tasks tagged with specific labels (e.g., --tags "install,config") or --skip-tags to exclude others.