Ansible lets you execute Linux commands across one or many servers securely and consistently. It uses SSH to connect to target hosts and run tasks defined in playbooks, making it ideal for automation without agents. You need Ansible installed on a control machine and SSH access to the target Linux servers—no special setup required on the targets beyond an SSH server and a Python interpreter (Python 2.7+ or 3.5+).

What You'll Need

  • A control machine (your local computer or a server) with Ansible installed (v2.9 or newer recommended)
  • One or more Linux target hosts (e.g., Ubuntu, CentOS, Debian) running an SSH server (sshd)
  • SSH access from the control machine to each target host—either via username/password or, preferably, SSH keys
  • Basic knowledge of Linux command-line syntax (e.g., ls, grep, systemctl)
  • A user account on the target hosts with sufficient privileges to run the commands (use become: yes for sudo if needed)

Step-by-Step

  1. Install Ansible on your control machine: On Ubuntu/Debian, run sudo apt update && sudo apt install ansible -y. On CentOS/RHEL, use sudo yum install epel-release && sudo yum install ansible -y. For macOS, use Homebrew: brew install ansible. Verify installation with ansible --version.
  2. Set up SSH key-based authentication (recommended for automation): Generate a key pair on your control machine with ssh-keygen -t ed25519 -C "ansible" (press Enter to accept defaults). Copy the public key to each target host with ssh-copy-id username@target_host, replacing username and target_host appropriately. Test connectivity with ssh username@target_host.
  3. Create an inventory file listing your target hosts: Make a file named hosts (or use /etc/ansible/hosts system-wide). Add lines like webserver1 ansible_host=192.168.1.10 user=ubuntu or group them: [webservers] 192.168.1.10 192.168.1.11. Save it in your working directory or the default Ansible inventory path.
  4. Write a simple playbook: Create a YAML file, e.g., run_command.yml. Define the hosts, user (if needed), and tasks. Example:
    ---
    - name: Run a Linux command on all webservers
      hosts: webservers
      become: yes
      tasks:
        - name: Check disk usage
          command: df -h
          register: disk_output
    
        - name: Display disk usage
          debug:
            var: disk_output.stdout_lines
    The command module runs raw shell commands securely (avoiding shell injection). Use shell only if you need pipes or redirections (e.g., shell: ps aux | grep nginx).
  5. Run the playbook: From your working directory, execute ansible-playbook -i hosts run_command.yml. Add -u username if your SSH user differs from your control machine user, or -k to prompt for SSH password (not recommended). For sudo, use -K to prompt for sudo password.
  6. Run ad hoc commands for quick tasks: For one-off commands without writing a playbook, use the ansible command. Example: ansible all -i hosts -m command -a "uptime". This runs uptime on all hosts in the inventory. Add -u ubuntu -b for user and privilege escalation.

Common Mistakes

  • Using shell unnecessarily: The command module is safer and more idempotent. Only use shell when you need shell features like pipes, redirections, or environment variables. Overusing shell risks non-portable or insecure playbooks.
  • Missing Python on target hosts: Ansible requires Python 2.7+ or 3.5+ on targets. Minimal images (e.g., Alpine Linux) often lack it. Install Python first with apt install python3 -y or use ansible_python_interpreter=/usr/bin/python3 in your inventory if Python is installed but not at /usr/bin/python.
  • Not handling privilege escalation properly: Commands like systemctl restart nginx require root. If you forget become: yes, the task will fail with Authorization denied. Always test with --check first: ansible-playbook --check -i hosts run_command.yml.
  • Ignoring command output: Running commands without capturing or reporting output makes debugging hard. Use register and debug to log results, especially for conditional tasks.
  • Hardcoding credentials or hosts: Avoid embedding passwords in playbooks. Use --ask-pass, SSH keys, or Ansible Vault for secrets. For hosts, use dynamic inventories (e.g., aws_ec2.yml) instead of static files for large environments.

Tips

  • Test with --diff: Add -C (check mode) and --diff to preview changes: ansible-playbook -i hosts --check --diff playbook.yml. This shows what would change without applying it.
  • Use async for long-running commands: Long tasks (e.g., large file transfers) may time out. Add async: 300 (seconds) and poll: 0 to run asynchronously, then check status later.
  • Group commands logically: Run related tasks together. Example: apt update and apt upgrade in one play to avoid partial states.
  • Validate output with failed_when: Define custom failure conditions. E.g., failed_when: "'error' in command_result.stderr