Ansible Cheatsheet
~1 min read
DevOpsansibleautomationdevopsconfiguration-management
Installation
# Install Ansible
pip install ansible-core # Core only
pip install ansible # Full with extras
# Verify installation
ansible --version
ansible-galaxy --version
Inventory Management
# hosts.ini
[webservers]
web01.example.com
web02.example.com
web03.example.com
[dbservers]
db01.example.com
db02.example.com
# \[all:vars\]
# ansible_user=ubuntu
# ansible_ssh_private_key_file=~/.ssh/id_rsa
# ansible_python_interpreter=/usr/bin/python3
# \[webservers:vars\]
# http_port=80
# inventory.yaml (YAML format)
webservers:
hosts:
web01.example.com:
http_port: 80
web02.example.com:
http_port: 80
vars:
ansible_user: ubuntu
dbservers:
hosts:
db01.example.com:
db02.example.com:
all:
children:
webservers:
dbservers:
vars:
ansible_python_interpreter: /usr/bin/python3
Basic Commands
# Check connectivity
ansible all -i hosts.ini -m ping
# Run ad-hoc command
ansible webservers -i hosts.ini -m shell -a "uptime"
# Copy file
ansible all -i hosts.ini -m copy -a "src=/tmp/file dest=/tmp/file"
# Install package
ansible webservers -i hosts.ini -m apt -a "name=nginx state=present"
# Gather facts
ansible all -i hosts.ini -m setup
Playbook Structure
# playbook.yaml
---
- name: Configure Web Server
hosts: webservers
become: yes
vars:
http_port: 80
server_name: example.com
tasks:
- name: Update apt cache
ansible.builtin.apt:
update_cache: yes
cache_valid_time: 3600
- name: Install nginx
ansible.builtin.apt:
name: nginx
state: present
- name: Configure nginx
ansible.builtin.template:
src: nginx.conf.j2
dest: /etc/nginx/nginx.conf
owner: root
group: root
mode: "0644"
notify: Restart nginx
handlers:
- name: Restart nginx
ansible.builtin.service:
name: nginx
state: restarted
Common Modules
File Operations
- name: Create directory
ansible.builtin.file:
path: /var/www/html
state: directory
mode: "0755"
owner: www-data
- name: Copy file
ansible.builtin.copy:
src: /local/file
dest: /remote/file
mode: "0644"
- name: Template file (Jinja2)
ansible.builtin.template:
src: config.j2
dest: /etc/app/config.conf
mode: "0644"
- name: Download file
ansible.builtin.get_url:
url: https://example.com/file.tar.gz
dest: /tmp/file.tar.gz
mode: "0644"
Package Management
# Debian/Ubuntu
- name: Install package
ansible.builtin.apt:
name: nginx
state: present
update_cache: yes
- name: Install multiple packages
ansible.builtin.apt:
name:
- nginx
- python3-pip
- git
state: present
- name: Remove package
ansible.builtin.apt:
name: nginx
state: absent
# RHEL/CentOS
- name: Install package (yum)
ansible.builtin.yum:
name: nginx
state: present
# Alpine
- name: Install package (apk)
community.general.apk:
name: nginx
state: present