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: yesfor sudo if needed)
Step-by-Step
- Install Ansible on your control machine: On Ubuntu/Debian, run
sudo apt update && sudo apt install ansible -y. On CentOS/RHEL, usesudo yum install epel-release && sudo yum install ansible -y. For macOS, use Homebrew:brew install ansible. Verify installation withansible --version. - 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 withssh-copy-id username@target_host, replacingusernameandtarget_hostappropriately. Test connectivity withssh username@target_host. - Create an inventory file listing your target hosts: Make a file named
hosts(or use/etc/ansible/hostssystem-wide). Add lines likewebserver1 ansible_host=192.168.1.10 user=ubuntuor group them:[webservers] 192.168.1.10 192.168.1.11. Save it in your working directory or the default Ansible inventory path. - Write a simple playbook: Create a YAML file, e.g.,
run_command.yml. Define the hosts, user (if needed), and tasks. Example:
The--- - 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_linescommandmodule runs raw shell commands securely (avoiding shell injection). Useshellonly if you need pipes or redirections (e.g.,shell: ps aux | grep nginx). - Run the playbook: From your working directory, execute
ansible-playbook -i hosts run_command.yml. Add-u usernameif your SSH user differs from your control machine user, or-kto prompt for SSH password (not recommended). For sudo, use-Kto prompt for sudo password. - Run ad hoc commands for quick tasks: For one-off commands without writing a playbook, use the
ansiblecommand. Example:ansible all -i hosts -m command -a "uptime". This runsuptimeon all hosts in the inventory. Add-u ubuntu -bfor user and privilege escalation.
Common Mistakes
- Using
shellunnecessarily: Thecommandmodule is safer and more idempotent. Only useshellwhen you need shell features like pipes, redirections, or environment variables. Overusingshellrisks 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 -yor useansible_python_interpreter=/usr/bin/python3in your inventory if Python is installed but not at/usr/bin/python. - Not handling privilege escalation properly: Commands like
systemctl restart nginxrequire root. If you forgetbecome: yes, the task will fail withAuthorization denied. Always test with--checkfirst:ansible-playbook --check -i hosts run_command.yml. - Ignoring command output: Running commands without capturing or reporting output makes debugging hard. Use
registeranddebugto 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--diffto preview changes:ansible-playbook -i hosts --check --diff playbook.yml. This shows what would change without applying it. - Use
asyncfor long-running commands: Long tasks (e.g., large file transfers) may time out. Addasync: 300(seconds) andpoll: 0to run asynchronously, then check status later. - Group commands logically: Run related tasks together. Example:
apt updateandapt upgradein one play to avoid partial states. - Validate output with
failed_when: Define custom failure conditions. E.g.,failed_when: "'error' in command_result.stderr