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

Ansible Inventory: Hướng dẫn quản lý và tổ chức hệ thống máy chủ

Ansible Inventory là gì?

Ansible Inventory là một file hoặc tập hợp các file chứa danh sách các máy chủ (hosts) mà Ansible sẽ quản lý và thực thi các tác vụ automation. Inventory định nghĩa các node targets, cách nhóm chúng lại với nhau, và các biến (variables) liên quan đến từng host hoặc group.

Inventory có thể được viết dưới dạng INI format hoặc YAML format, và có thể là static (file cố định) hoặc dynamic (tạo động từ external sources như cloud providers).

Tại sao Ansible Inventory quan trọng?

  • Tổ chức hệ thống: Giúp phân loại và quản lý hàng trăm, thậm chí hàng nghìn servers một cách có hệ thống
  • Target cụ thể: Cho phép chạy playbooks trên các nhóm máy chủ cụ thể
  • Quản lý biến: Định nghĩa variables cho từng host hoặc group để customize behavior
  • Scalability: Dễ dàng mở rộng và maintain khi infrastructure phát triển
  • Tích hợp cloud: Hỗ trợ dynamic inventory từ AWS, Azure, GCP, và các cloud providers khác

Các loại Ansible Inventory

1. Static Inventory

Static inventory là file text cố định chứa danh sách hosts và groups.

INI Format

# File: inventory.ini

# Ungrouped hosts
mail.example.com

# Group webservers
[webservers]
web1.example.com
web2.example.com
192.168.1.10

# Group databases
[databases]
db1.example.com
db2.example.com

# Group với variables
[webservers:vars]
http_port=80
max_clients=200

# Nested groups (group of groups)
[production:children]
webservers
databases

[production:vars]
env=production

YAML Format

# File: inventory.yml

all:
  hosts:
    mail.example.com:
  children:
    webservers:
      hosts:
        web1.example.com:
        web2.example.com:
        192.168.1.10:
      vars:
        http_port: 80
        max_clients: 200
    databases:
      hosts:
        db1.example.com:
        db2.example.com:
    production:
      children:
        webservers:
        databases:
      vars:
        env: production

2. Dynamic Inventory

Dynamic inventory tự động lấy danh sách hosts từ external sources như cloud providers, CMDB, hoặc các hệ thống khác.

# Sử dụng AWS EC2 dynamic inventory
ansible-inventory -i aws_ec2.yml --list

# Sử dụng script Python để tạo dynamic inventory
ansible-playbook -i inventory_script.py playbook.yml

Cấu trúc và cú pháp Inventory

Host Patterns

# Single host
server1.example.com

# Host với port custom
server2.example.com:2222

# Host với alias
web ansible_host=192.168.1.10

# Range patterns
web[1:5].example.com  # web1, web2, web3, web4, web5
db-[a:c].example.com  # db-a, db-b, db-c

Groups và Nested Groups

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

[databases]
db1.example.com
db2.example.com

# Group of groups
[production:children]
webservers
databases

[staging:children]
staging_web
staging_db

Host và Group Variables

# Host variables
[webservers]
web1.example.com ansible_user=ubuntu ansible_port=22
web2.example.com ansible_user=centos ansible_port=2222

# Group variables
[webservers:vars]
http_port=80
https_port=443
nginx_version=1.18

Behavioral Inventory Parameters

Ansible cung cấp nhiều parameters để control connection behavior:

Parameter Mô tả Ví dụ
ansible_host Địa chỉ IP hoặc hostname thực tế ansible_host=192.168.1.10
ansible_port SSH port ansible_port=2222
ansible_user SSH username ansible_user=ubuntu
ansible_password SSH password (không khuyến khích) ansible_password=secret
ansible_ssh_private_key_file Private key path ansible_ssh_private_key_file=~/.ssh/id_rsa
ansible_connection Connection type ansible_connection=ssh hoặc local
ansible_python_interpreter Python path trên remote host ansible_python_interpreter=/usr/bin/python3
ansible_become Enable privilege escalation ansible_become=true
ansible_become_user User để escalate thành ansible_become_user=root

Ví dụ sử dụng Behavioral Parameters

[webservers]
web1.example.com ansible_host=10.0.1.10 ansible_user=ubuntu ansible_ssh_private_key_file=~/.ssh/web_key
web2.example.com ansible_host=10.0.1.11 ansible_user=centos ansible_port=2222
web3.example.com ansible_host=10.0.1.12 ansible_connection=local

[webservers:vars]
ansible_python_interpreter=/usr/bin/python3
ansible_become=true
ansible_become_user=root

Tổ chức Inventory với host_vars và group_vars

Để quản lý variables tốt hơn, nên tách variables ra các file riêng:

Cấu trúc thư mục

inventory/
├── hosts                  # Main inventory file
├── group_vars/
│   ├── all.yml           # Variables cho tất cả hosts
│   ├── webservers.yml    # Variables cho group webservers
│   └── databases.yml     # Variables cho group databases
└── host_vars/
    ├── web1.example.com.yml    # Variables cho host cụ thể
    └── db1.example.com.yml

Ví dụ nội dung files

inventory/hosts:

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

[databases]
db1.example.com
db2.example.com

inventory/group_vars/webservers.yml:

---
http_port: 80
https_port: 443
nginx_version: "1.18"
app_user: www-data

inventory/group_vars/all.yml:

---
ansible_user: ubuntu
ansible_become: true
ntp_server: time.google.com
dns_servers:
  - 8.8.8.8
  - 8.8.4.4

inventory/host_vars/web1.example.com.yml:

---
ansible_host: 192.168.1.10
server_id: web-01
max_connections: 500

Sử dụng Inventory trong thực tế

1. Kiểm tra Inventory

# List all hosts
ansible-inventory -i inventory/hosts --list

# List hosts trong group cụ thể
ansible-inventory -i inventory/hosts --list webservers

# Show inventory graph
ansible-inventory -i inventory/hosts --graph

# Show variables cho host cụ thể
ansible-inventory -i inventory/hosts --host web1.example.com

2. Chạy Ad-hoc Commands với Inventory

# Ping tất cả hosts
ansible all -i inventory/hosts -m ping

# Ping group cụ thể
ansible webservers -i inventory/hosts -m ping

# Chạy command trên specific hosts
ansible web1.example.com -i inventory/hosts -a "uptime"

# Sử dụng pattern
ansible "web*" -i inventory/hosts -m shell -a "df -h"

3. Sử dụng Inventory với Playbooks

# playbook.yml
---
- name: Configure webservers
  hosts: webservers
  become: true
  tasks:
    - name: Install nginx
      apt:
        name: nginx
        state: present
      when: ansible_os_family == "Debian"
# Chạy playbook với inventory
ansible-playbook -i inventory/hosts playbook.yml

# Chạy trên specific group
ansible-playbook -i inventory/hosts playbook.yml --limit webservers

# Chạy trên specific host
ansible-playbook -i inventory/hosts playbook.yml --limit web1.example.com

Dynamic Inventory với Cloud Providers

AWS EC2 Dynamic Inventory

aws_ec2.yml:

---
plugin: aws_ec2
regions:
  - us-east-1
  - us-west-2
filters:
  tag:Environment: production
  instance-state-name: running
keyed_groups:
  - key: tags.Role
    prefix: role
  - key: tags.Environment
    prefix: env
hostnames:
  - tag:Name
compose:
  ansible_host: public_ip_address
# List hosts từ AWS
ansible-inventory -i aws_ec2.yml --list

# Chạy playbook với AWS inventory
ansible-playbook -i aws_ec2.yml playbook.yml

Azure Dynamic Inventory

azure_rm.yml:

---
plugin: azure_rm
auth_source: auto
include_vm_resource_groups:
  - my-resource-group
keyed_groups:
  - prefix: tag
    key: tags

GCP Dynamic Inventory

gcp_compute.yml:

---
plugin: gcp_compute
projects:
  - my-gcp-project
auth_kind: serviceaccount
service_account_file: /path/to/credentials.json
keyed_groups:
  - key: labels.environment
    prefix: env

Best Practices cho Ansible Inventory

1. Tổ chức theo môi trường

inventory/
├── production/
│   ├── hosts
│   ├── group_vars/
│   └── host_vars/
├── staging/
│   ├── hosts
│   ├── group_vars/
│   └── host_vars/
└── development/
    ├── hosts
    ├── group_vars/
    └── host_vars/

2. Sử dụng meaningful group names

# Good
[web_frontend]
[api_backend]
[database_primary]
[database_replica]

# Avoid
[group1]
[servers]
[misc]

3. Leverage group hierarchy

[web_tier1]
web1.example.com
web2.example.com

[web_tier2]
web3.example.com
web4.example.com

[web:children]
web_tier1
web_tier2

[production:children]
web
database
cache

4. Không lưu sensitive data trong inventory

# BAD - Không làm thế này
[databases]
db1.example.com ansible_user=root ansible_password=secret123

# GOOD - Sử dụng Ansible Vault
[databases]
db1.example.com ansible_user=dbadmin
# Encrypt sensitive variables
ansible-vault encrypt inventory/group_vars/databases/vault.yml

5. Document inventory structure

# inventory/hosts
# Inventory cho Production Environment
# Updated: 2025-11-17
# Owner: DevOps Team

[webservers]
# Frontend web servers - Load balanced
web1.example.com  # Primary
web2.example.com  # Secondary

[databases]
# PostgreSQL database cluster
db1.example.com   # Master
db2.example.com   # Replica

6. Sử dụng consistent naming conventions

# Environment-Role-Number pattern
prod-web-01.example.com
prod-web-02.example.com
prod-db-01.example.com
staging-web-01.example.com
staging-db-01.example.com

So sánh Static vs Dynamic Inventory

Tiêu chí Static Inventory Dynamic Inventory
Cấu hình File text cố định (INI/YAML) Script hoặc plugin tự động query
Cập nhật Manual edit file Tự động sync với source
Use case Infrastructure ổn định, ít thay đổi Cloud environments, autoscaling
Complexity Đơn giản, dễ hiểu Phức tạp hơn, cần configuration
Performance Nhanh, không có overhead Có overhead khi query external sources
Maintenance Cần update manual khi infrastructure thay đổi Tự động reflect changes
Best for On-premise servers, small teams Cloud-native, large dynamic infrastructure

Troubleshooting Inventory Issues

1. Verify inventory syntax

# Check inventory có valid không
ansible-inventory -i inventory/hosts --list

# Show detailed output
ansible-inventory -i inventory/hosts --list -vvv

2. Test connectivity

# Test SSH connection đến all hosts
ansible all -i inventory/hosts -m ping

# Test với verbose mode
ansible all -i inventory/hosts -m ping -vvv

# Test specific group
ansible webservers -i inventory/hosts -m ping

3. Debug variables

# Show tất cả variables cho một host
ansible-inventory -i inventory/hosts --host web1.example.com --yaml

# Show variables cho group
ansible-inventory -i inventory/hosts --list --yaml | grep -A 20 webservers

4. Common errors và solutions

Error: "Failed to connect to the host via ssh"

# Check SSH connectivity
ssh -i ~/.ssh/key.pem ubuntu@web1.example.com

# Verify ansible_user và ansible_host đúng
ansible-inventory -i inventory/hosts --host web1.example.com

Error: "Unable to parse inventory file"

# Validate YAML syntax
yamllint inventory/hosts.yml

# Validate INI syntax
ansible-inventory -i inventory/hosts --list

Tổng kết

Ansible Inventory là nền tảng của mọi automation workflow trong Ansible. Việc hiểu rõ cách tổ chức, quản lý và tối ưu hóa inventory sẽ giúp bạn:

  • Quản lý infrastructure một cách có hệ thống và scalable
  • Target đúng hosts/groups cho từng automation task
  • Tổ chức variables một cách maintainable
  • Tích hợp dễ dàng với cloud providers và external systems
  • Giảm thiểu errors và tăng reliability

Trong bài học tiếp theo, chúng ta sẽ tìm hiểu về Running Ad-Hoc Commands - cách chạy các lệnh nhanh trên managed hosts mà không cần viết playbooks.

Bài tập thực hành

  1. Tạo một static inventory với 3 groups: webservers, databases, và monitoring
  2. Định nghĩa host_vars và group_vars cho từng group
  3. Sử dụng behavioral parameters để customize SSH connections
  4. Chạy ansible-inventory commands để verify cấu hình
  5. Test connectivity đến all hosts bằng ping module
  6. (Advanced) Setup một dynamic inventory cho AWS EC2 hoặc cloud provider khác

Tài liệu tham khảo