Ansible Automation Ops Guide: From Configuration Management to Application Deployment

Ansible is an automation tool maintained by Red Hat, known for its simplicity. It requires no agent on target machines, executing tasks via SSH.

1. Installation and Basic Concepts

# 安装
pip install ansible

# 验证
ansible --version

核心概念:

Concept Description
Control Node Machine running Ansible
Managed Node Target machine to manage
Inventory Host清单
Playbook YAML task剧本
Module Performs specific operations

2. Inventory Configuration

# hosts.ini
[web]
web1.example.com
web2.example.com

[db]
db1.example.com

[all:vars]
ansible_user=deploy
ansible_python_interpreter=/usr/bin/python3

3. Playbook Example

---
- name: Configure Web Servers
  hosts: web
  become: yes
  vars:
    nginx_port: 80

  tasks:
    - name: Install Nginx
      apt:
        name: nginx
        state: present
        update_cache: yes

    - name: Copy Nginx config
      template:
        src: nginx.conf.j2
        dest: /etc/nginx/sites-available/default
      notify: restart nginx

    - name: Start Nginx
      service:
        name: nginx
        state: started
        enabled: yes

  handlers:
    - name: restart nginx
      service:
        name: nginx
        state: restarted

4. Role Organization

Organize Playbooks into reusable Roles:

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

5. Use Cases

Scenario Solution
Server initialization Install software, configure SSH, set timezone
App deployment Git pull, build, restart services
Configuration management Manage Nginx, MySQL, Redis configs
Security hardening Firewall rules, Fail2ban, SSH hardening