Ansible playbook cài đặt và cấu hình Nginx (idempotent)
🎯 Mục tiêu: Viết playbook YAML idempotent cài Nginx, deploy file cấu hình từ template, bật service — chạy nhiều lần không gây lỗi.
🧰 Công cụ / nền tảng: ansible (pip install ansible), SSH key, Linux target (Ubuntu 22.04 hoặc WSL2), VS Code.
📦 Chuẩn bị: Cài Ansible trên control node; chuẩn bị SSH key và user có sudo trên managed node (có thể dùng localhost với connection: local).
▶️ Các bước (CLI):
# 1. Cài Ansible
pip install ansible
# 2. Tạo cấu trúc project
mkdir ansible-nginx && cd ansible-nginx
# 3. inventory.ini
cat > inventory.ini << 'EOF'
[webservers]
web1 ansible_host=127.0.0.1 ansible_connection=local ansible_user=root
EOF
# 4. Template Nginx config: templates/nginx.conf.j2
mkdir -p templates
cat > templates/nginx.conf.j2 << 'EOF'
server {
listen {{ nginx_port | default(80) }};
server_name {{ server_name | default('_') }};
root /var/www/html;
index index.html;
location / { try_files $uri $uri/ =404; }
}
EOF
# 5. Playbook
cat > site.yml << 'EOF'
---
- name: Configure Nginx webserver
hosts: webservers
become: true
vars:
nginx_port: 80
server_name: "lab.local"
tasks:
- name: Install Nginx
ansible.builtin.apt:
name: nginx
state: present
update_cache: true
- name: Deploy Nginx config from template
ansible.builtin.template:
src: templates/nginx.conf.j2
dest: /etc/nginx/sites-available/lab.conf
owner: root
group: root
mode: '0644'
notify: Reload Nginx
- name: Enable site (symlink)
ansible.builtin.file:
src: /etc/nginx/sites-available/lab.conf
dest: /etc/nginx/sites-enabled/lab.conf
state: link
- name: Ensure Nginx is started and enabled
ansible.builtin.service:
name: nginx
state: started
enabled: true
- name: Create default index page
ansible.builtin.copy:
content: "Deployed by Ansible on {{ inventory_hostname }}
"
dest: /var/www/html/index.html
mode: '0644'
handlers:
- name: Reload Nginx
ansible.builtin.service:
name: nginx
state: reloaded
EOF
# 6. Chạy playbook lần 1
ansible-playbook -i inventory.ini site.yml -v
# 7. Chạy lại lần 2 (kiểm tra idempotency)
ansible-playbook -i inventory.ini site.yml
# 8. Kiểm tra
curl -s http://localhost/ | grep Ansible
✅ Kết quả mong đợi: Lần 1: output có changed ở các task install/config. Lần 2: tất cả task đều ok (0 changed) — idempotency đạt. curl http://localhost/ trả về HTML chứa "Deployed by Ansible".
🧹 Cleanup: ansible-playbook -i inventory.ini site.yml -e "state=absent" hoặc apt remove nginx -y.