Site logo
Tác giả
  • avatar Nguyễn Đức Xinh
    Name
    Nguyễn Đức Xinh
    Twitter
Ngày xuất bản
Ngày xuất bản

Giới thiệu về Ansible: Tổng quan Configuration Management và Infrastructure Automation

Ansible là gì?

Ansible là một công cụ automation mã nguồn mở mạnh mẽ được sử dụng để quản lý cấu hình (configuration management), triển khai ứng dụng (application deployment), và tự động hóa các tác vụ IT (IT automation). Được phát triển bởi Michael DeHaan và ra mắt vào năm 2012, Ansible nhanh chóng trở thành một trong những công cụ phổ biến nhất trong thế giới DevOps nhờ tính đơn giản, hiệu quả và không cần agent.

Ansible hoạt động theo mô hình agentless, nghĩa là bạn không cần cài đặt bất kỳ phần mềm nào trên các máy chủ được quản lý (managed nodes). Thay vào đó, Ansible sử dụng SSH (Secure Shell) để kết nối và thực thi các lệnh từ xa, giúp việc triển khai và quản lý trở nên đơn giản và an toàn hơn.

Tại sao nên sử dụng Ansible?

1. Agentless Architecture - Không cần Agent

Một trong những ưu điểm lớn nhất của Ansible là kiến trúc agentless. Không giống như Puppet hay Chef yêu cầu cài đặt agent trên mỗi managed node, Ansible chỉ cần SSH và Python (thường đã có sẵn trên hầu hết các hệ thống Linux/Unix).

Lợi ích:

  • Dễ dàng triển khai: Không cần cài đặt và cấu hình agent trên hàng trăm hoặc hàng nghìn máy chủ
  • Giảm overhead: Không có process chạy liên tục trên managed nodes, tiết kiệm tài nguyên
  • Bảo mật tốt hơn: Ít surface attack hơn, không cần mở thêm ports hoặc services
  • Quản lý đơn giản: Không cần maintain agent versions và updates

2. Idempotency - Tính bất biến

Ansible được thiết kế với nguyên tắc idempotency, nghĩa là bạn có thể chạy cùng một playbook nhiều lần mà không lo lắng về việc thay đổi trạng thái hệ thống nếu nó đã ở trạng thái mong muốn.

Ví dụ:

- name: Ensure Apache is installed
  package:
    name: apache2
    state: present

Lệnh này sẽ chỉ cài đặt Apache nếu nó chưa được cài đặt. Nếu Apache đã có sẵn, Ansible sẽ bỏ qua task này. Điều này giúp bạn tự tin chạy playbook nhiều lần mà không sợ gây ra side effects.

3. Declarative Language - Ngôn ngữ khai báo

Ansible sử dụng YAML - một ngôn ngữ khai báo dễ đọc và dễ viết. Thay vì mô tả "cách làm" (imperative), bạn mô tả "trạng thái mong muốn" (declarative).

Ví dụ so sánh:

Imperative (Shell script):

if ! command -v apache2 &> /dev/null; then
    apt-get update
    apt-get install -y apache2
    systemctl start apache2
    systemctl enable apache2
fi

Declarative (Ansible):

- name: Install and start Apache
  package:
    name: apache2
    state: present
  service:
    name: apache2
    state: started
    enabled: yes

4. Học tập dễ dàng

Ansible có learning curve thấp hơn nhiều so với các công cụ khác:

  • Cú pháp đơn giản: YAML dễ đọc và viết hơn Ruby DSL (Chef) hoặc Puppet DSL
  • Tài liệu phong phú: Ansible có documentation rất tốt và cộng đồng lớn
  • Modules sẵn có: Hàng trăm modules được tích hợp sẵn cho các tác vụ phổ biến

5. Tích hợp tốt với Cloud và Containers

Ansible có khả năng tích hợp mạnh mẽ với:

  • Cloud providers: AWS, Azure, GCP, DigitalOcean, v.v.
  • Container platforms: Docker, Kubernetes, OpenShift
  • Virtualization: VMware, Hyper-V, KVM
  • Network devices: Cisco, Juniper, Arista

Use Cases của Ansible trong DevOps/Infrastructure

1. Configuration Management

Quản lý cấu hình hệ thống một cách nhất quán trên nhiều máy chủ:

Ví dụ use case:

  • Đảm bảo tất cả web servers có cùng cấu hình Apache/Nginx
  • Đồng bộ hóa cấu hình firewall rules
  • Quản lý user accounts và permissions
  • Cấu hình monitoring agents (Prometheus, Grafana)

2. Application Deployment

Tự động hóa quá trình triển khai ứng dụng:

Ví dụ use case:

  • Deploy web applications lên multiple servers
  • Rolling updates để tránh downtime
  • Blue-green deployments
  • Canary deployments cho testing

3. Infrastructure Provisioning

Tạo và quản lý infrastructure trên cloud:

Ví dụ use case:

  • Tạo EC2 instances trên AWS
  • Cấu hình VPC, security groups, load balancers
  • Setup database clusters (RDS, MongoDB)
  • Provision storage và backup solutions

4. Orchestration

Điều phối các tác vụ phức tạp trên nhiều hệ thống:

Ví dụ use case:

  • Zero-downtime deployments với load balancer integration
  • Database migrations với backup và rollback
  • Multi-tier application deployments (web → app → database)
  • Disaster recovery procedures

5. Security Compliance

Đảm bảo tuân thủ các tiêu chuẩn bảo mật:

Ví dụ use case:

  • Hardening systems theo CIS benchmarks
  • Audit và remediation security vulnerabilities
  • Enforce security policies across infrastructure
  • Compliance reporting (PCI-DSS, HIPAA, SOC 2)

6. Continuous Integration/Continuous Deployment (CI/CD)

Tích hợp vào pipeline CI/CD:

Ví dụ use case:

  • Automated testing environments
  • Infrastructure as Code (IaC) validation
  • Post-deployment verification
  • Automated rollback on failures

Kiến trúc và các thành phần của Ansible

Control Node vs Managed Nodes

Control Node:

  • Máy chủ nơi Ansible được cài đặt và chạy
  • Nơi bạn viết và thực thi playbooks
  • Có thể là laptop, server, hoặc CI/CD runner

Managed Nodes:

  • Các máy chủ được quản lý bởi Ansible
  • Không cần cài đặt Ansible
  • Chỉ cần SSH access và Python (thường có sẵn)

Các thành phần chính

1. Inventory (Hàng tồn kho)

File chứa danh sách các managed nodes, có thể là static hoặc dynamic:

Static Inventory (INI format):

[web_servers]
web1.example.com
web2.example.com

[db_servers]
db1.example.com

Static Inventory (YAML format):

all:
  children:
    web_servers:
      hosts:
        web1.example.com:
        web2.example.com:
    db_servers:
      hosts:
        db1.example.com:

2. Playbooks

File YAML chứa các plays và tasks để mô tả automation workflow:

---
- name: Configure web servers
  hosts: web_servers
  become: yes
  tasks:
    - name: Install Apache
      package:
        name: apache2
        state: present

3. Modules

Các đoạn code Python thực thi các tác vụ cụ thể. Ansible có hàng trăm built-in modules:

  • System modules: package, service, user, group
  • File modules: copy, template, file, lineinfile
  • Cloud modules: ec2_instance, gcp_compute_instance
  • Network modules: uri, get_url

4. Tasks

Các đơn vị công việc nhỏ nhất trong Ansible, mỗi task gọi một module:

- name: Ensure Nginx is installed
  package:
    name: nginx
    state: present

5. Plays

Tập hợp các tasks được thực thi trên một nhóm hosts:

- name: Setup web server
  hosts: web_servers
  tasks:
    - name: Install Nginx
      package:
        name: nginx
        state: present

6. Roles

Cách tổ chức playbooks và các file liên quan để tái sử dụng:

roles/
  nginx/
    tasks/
      main.yml
    handlers/
      main.yml
    templates/
      nginx.conf.j2
    vars/
      main.yml

So sánh với Terraform

Quan trọng: Terraform và Ansible thường được sử dụng cùng nhau, không phải thay thế nhau.

Ansible:

  • ✅ Configuration Management
  • ✅ Application Deployment
  • ✅ Orchestration
  • ✅ Tốt cho managing existing infrastructure

Terraform:

  • ✅ Infrastructure Provisioning
  • ✅ Infrastructure as Code
  • ✅ State Management
  • ✅ Tốt cho creating new infrastructure

Best Practice:

  • Terraform: Tạo và quản lý infrastructure (servers, networks, storage)
  • Ansible: Cấu hình và deploy applications lên infrastructure đã có

Ví dụ workflow:

  1. Terraform tạo EC2 instances, VPC, security groups
  2. Ansible cấu hình OS, cài đặt software, deploy applications

Infrastructure as Code (IaC) với Ansible

IaC là gì?

Infrastructure as Code là phương pháp quản lý và provisioning infrastructure thông qua code thay vì thao tác thủ công. Ansible là một công cụ quan trọng trong ecosystem IaC.

Lợi ích của IaC

  1. Version Control: Infrastructure được versioned như code
  2. Reproducibility: Có thể tạo lại infrastructure giống hệt nhau
  3. Consistency: Đảm bảo tất cả environments giống nhau
  4. Documentation: Code là documentation
  5. Collaboration: Team có thể review và contribute
  6. Disaster Recovery: Dễ dàng rebuild infrastructure

Ansible trong IaC Ecosystem

┌─────────────────────────────────────────┐
│         Infrastructure Layer            │
├─────────────────────────────────────────┤
│  Terraform / CloudFormation / Pulumi    │  ← Provisioning
│  (Tạo infrastructure)                   │
└─────────────────────────────────────────┘
              ↓
┌─────────────────────────────────────────┐
│      Configuration & Deployment         │
├─────────────────────────────────────────┤
│  Ansible / Puppet / Chef                │  ← Configuration
│  (Cấu hình và deploy)                   │
└─────────────────────────────────────────┘
              ↓
┌─────────────────────────────────────────┐
│         Application Layer               │
├─────────────────────────────────────────┤
│  Kubernetes / Docker Swarm              │  ← Orchestration
│  (Container orchestration)              │
└─────────────────────────────────────────┘

Các tính năng nâng cao của Ansible

1. Ansible Vault

Bảo mật sensitive data như passwords, API keys:

# Encrypt file
ansible-vault encrypt secrets.yml

# Decrypt và edit
ansible-vault edit secrets.yml

# Sử dụng trong playbook
- name: Use encrypted variable
  debug:
    var: db_password
  vars:
    db_password: "{{ vault_db_password }}"

2. Ansible Galaxy

Thư viện roles và collections từ community:

# Cài đặt role từ Galaxy
ansible-galaxy install geerlingguy.nginx

# Sử dụng trong playbook
- hosts: web_servers
  roles:
    - geerlingguy.nginx

3. Dynamic Inventory

Tự động discover hosts từ cloud providers:

# AWS EC2 dynamic inventory
ansible-inventory -i aws_ec2.yml --list

# Sử dụng trong playbook
ansible-playbook -i aws_ec2.yml playbook.yml

4. Ansible Tower / AWX

Enterprise solution với web UI, RBAC, scheduling:

  • AWX: Open-source version
  • Ansible Tower: Commercial version (nay là Red Hat Ansible Automation Platform)

Tính năng:

  • Web-based UI
  • Role-based access control (RBAC)
  • Job scheduling
  • Workflow automation
  • Audit logs
  • Integration với CI/CD

5. Collections

Cách mới để tổ chức và phân phối Ansible content:

# Cài đặt collection
ansible-galaxy collection install community.aws

# Sử dụng module từ collection
- name: Create EC2 instance
  community.aws.ec2_instance:
    name: web-server
    image_id: ami-12345

Khi nào nên sử dụng Ansible?

✅ Nên sử dụng Ansible khi:

  1. Bạn mới bắt đầu với automation

    • Learning curve thấp
    • Tài liệu phong phú
    • Community hỗ trợ tốt
  2. Cần giải pháp agentless

    • Không thể cài agent trên managed nodes
    • Security policies nghiêm ngặt
    • Temporary environments (containers, cloud instances)
  3. Cần orchestration

    • Multi-tier deployments
    • Complex workflows
    • Integration với nhiều systems
  4. Infrastructure nhỏ đến trung bình

    • Vài chục đến vài trăm servers
    • Không cần pull model
  5. Team đa dạng về kỹ năng

    • YAML dễ đọc cho cả non-developers
    • Không cần biết programming language

❌ Có thể cân nhắc công cụ khác khi:

  1. Infrastructure cực lớn

    • Hàng nghìn nodes
    • Có thể cần Puppet với pull model
  2. Cần real-time execution

    • Event-driven automation
    • Có thể cần SaltStack
  3. Chỉ cần infrastructure provisioning

    • Tạo servers, networks
    • Có thể chỉ cần Terraform
  4. Team đã có expertise với công cụ khác

    • Nếu đã dùng Puppet/Chef thành công
    • Cân nhắc tiếp tục với công cụ hiện tại

Prerequisites và yêu cầu

Kiến thức cần có

  1. Linux/Unix basics: Command line, File system, Permissions, Services
  2. SSH: Key-based authentication, SSH config, Remote execution
  3. YAML (cơ bản): Syntax, Indentation, Lists và dictionaries
  4. Python (tùy chọn): Hữu ích cho viết custom modules, Không bắt buộc cho beginners

Yêu cầu hệ thống

Control Node:

  • Linux, macOS, hoặc Windows (với WSL)
  • Python 3.8+
  • SSH client

Managed Nodes:

  • SSH access
  • Python 2.7+ hoặc Python 3.5+ (Python 3 được khuyến nghị)
  • Sudo/root access (cho các tác vụ cần quyền)

Tổng kết

Ansible là một công cụ mạnh mẽ và linh hoạt cho automation và configuration management. Với kiến trúc agentless, cú pháp YAML đơn giản, và ecosystem phong phú, Ansible đã trở thành lựa chọn hàng đầu cho nhiều DevOps teams.

Điểm mạnh chính:

  • ✅ Agentless architecture
  • ✅ Idempotency built-in
  • ✅ Learning curve thấp
  • ✅ Tích hợp tốt với cloud và containers
  • ✅ Community lớn và tài liệu phong phú

Trong các bài học tiếp theo, chúng ta sẽ:

  1. Cài đặt và cấu hình Ansible
  2. Tìm hiểu về Inventory
  3. Chạy ad-hoc commands
  4. Viết playbooks đầu tiên
  5. Làm việc với variables, templates, và nhiều hơn nữa

Hãy sẵn sàng để bắt đầu hành trình từ zero đến hero với Ansible!