A
cd ..
DevOps

Ansible Basics

Run commands and deploy configurations with Ansible automation.

2025-09-21
ansible, automation, devops

Install Ansible

# Ubuntu/Debian
sudo apt install ansible

# macOS
brew install ansible

Check version

ansible --version

Basic inventory file

Create hosts:

[webservers]
web1.example.com
web2.example.com

[databases]
db1.example.com

Ping all hosts

ansible all -i hosts -m ping

Run command on all hosts

ansible all -i hosts -a "uptime"

Run with sudo

ansible all -i hosts -b -a "apt update"

Target specific group

ansible webservers -i hosts -a "systemctl status nginx"

Copy file to remote hosts

ansible all -i hosts -m copy -a "src=/local/file.txt dest=/remote/file.txt"

Install package

ansible webservers -i hosts -m apt -a "name=nginx state=present" -b

Restart service

ansible webservers -i hosts -m service -a "name=nginx state=restarted" -b

Basic playbook

Create playbook.yml:

---
- hosts: webservers
  become: yes
  tasks:
    - name: Install nginx
      apt:
        name: nginx
        state: present
    
    - name: Start nginx
      service:
        name: nginx
        state: started
        enabled: yes

Run playbook

ansible-playbook -i hosts playbook.yml

Dry run (check mode)

ansible-playbook -i hosts playbook.yml --check

Run with verbose output

ansible-playbook -i hosts playbook.yml -v

Limit to specific hosts

ansible-playbook -i hosts playbook.yml --limit web1.example.com

Use vault for secrets

ansible-vault create secrets.yml

Run playbook with vault

ansible-playbook -i hosts playbook.yml --ask-vault-pass

List all hosts

ansible all -i hosts --list-hosts

Gather facts

ansible all -i hosts -m setup

Was this useful?

Share with your team

Browse More