Ansible Playbook 完全指南:核心语法与实战

Ansible Playbook 核心语法详解:从基础到高级

什么是 Playbook

Playbook 是 Ansible 的核心配置文件,使用 YAML 格式编写,定义了一系列要执行的任务。Playbook 具有声明式、幂等性的特点,适合自动化运维场景。

Playbook 基本结构

---
- name: Playbook 名称
  hosts: 目标主机或组
  become: yes  # 是否提权
  vars:       # 变量定义
    var_name: var_value
  
  tasks:
    - name: 任务名称
      module_name:
        parameter: value
    
    - name: 另一个任务
      module_name:
        parameter: value
      when: condition  # 条件判断

Playbook 示例

---
- name: Install and configure Nginx
  hosts: webservers
  become: yes
  
  vars:
    nginx_port: 80
    document_root: /var/www/html
  
  tasks:
    - name: Update apt cache
      apt:
        update_cache: yes
        cache_valid_time: 3600
    
    - name: Install Nginx
      apt:
        name: nginx
        state: present
    
    - name: Copy Nginx configuration
      template:
        src: nginx.conf.j2
        dest: /etc/nginx/nginx.conf
      notify: Restart Nginx
  
  handlers:
    - name: Restart Nginx
      service:
        name: nginx
        state: restarted

Tasks(任务)

基本任务

tasks:
  - name: Copy file
    copy:
      src: /tmp/source.txt
      dest: /tmp/dest.txt
  
  - name: Install package
    apt:
      name: vim
      state: present

任务参数

tasks:
  - name: Task with multiple parameters
    yum:
      name: "{{ package_name }}"
      state: "{{ package_state }}"
      update_cache: yes
      disable_gpg_check: yes
  
  - name: Task with loop
    file:
      path: "/tmp/{{ item }}"
      state: directory
    loop:
      - dir1
      - dir2
      - dir3

Modules(模块)

常用模块

# 文件操作
tasks:
  - name: Copy file
    copy:
      src: local_file.txt
      dest: /remote/dest.txt
      owner: root
      group: root
      mode: '0644'
  
  - name: Create directory
    file:
      path: /tmp/mydir
      state: directory
      mode: '0755'
  
  - name: Delete file
    file:
      path: /tmp/old_file
      state: absent
# 软件包管理
tasks:
  # Debian/Ubuntu
  - name: Install package (APT)
    apt:
      name: nginx
      state: present
      update_cache: yes
  
  # CentOS/RHEL
  - name: Install package (YUM)
    yum:
      name: nginx
      state: present
  
  # 使用变量
  - name: Install multiple packages
    apt:
      name: "{{ packages }}"
      state: present
    vars:
      packages:
        - nginx
        - vim
        - curl
# 服务管理
tasks:
  - name: Start service
    service:
      name: nginx
      state: started
      enabled: yes
  
  - name: Stop service
    service:
      name: nginx
      state: stopped
  
  - name: Restart service
    service:
      name: nginx
      state: restarted
  
  - name: Reload service
    service:
      name: nginx
      state: reloaded
# 命令执行
tasks:
  - name: Execute shell command
    shell: echo "Hello World" > /tmp/hello.txt
  
  - name: Execute command with register
    command: whoami
    register: current_user
  
  - name: Display user
    debug:
      msg: "Current user: {{ current_user.stdout }}"
  
  - name: Execute command only when changed
    command: /opt/script.sh
    register: script_result
    changed_when: script_result.rc != 0

Handlers(处理器)

Handlers 是特殊的任务,只有在被任务 notify(通知)时才会执行,且在所有任务执行完成后统一执行。

---
- name: Handlers example
  hosts: webservers
  become: yes
  
  tasks:
    - name: Update Nginx config
      template:
        src: nginx.conf.j2
        dest: /etc/nginx/nginx.conf
      notify: Restart Nginx
    
    - name: Update website content
      copy:
        src: index.html
        dest: /var/www/html/index.html
      notify: Reload Nginx
  
  handlers:
    - name: Restart Nginx
      service:
        name: nginx
        state: restarted
    
    - name: Reload Nginx
      service:
        name: nginx
        state: reloaded

变量使用

定义变量

---
- name: Variables example
  hosts: all
  vars:
    app_name: myapp
    app_version: "1.0.0"
    app_config:
      port: 8080
      debug: false
  
  tasks:
    - name: Display variables
      debug:
        msg: |
          App Name: {{ app_name }}
          App Version: {{ app_version }}
          Port: {{ app_config.port }}

Facts(系统信息)

tasks:
  - name: Display OS information
    debug:
      msg: |
        OS Family: {{ ansible_os_family }}
        Distribution: {{ ansible_distribution }}
        Version: {{ ansible_distribution_version }}
        Architecture: {{ ansible_architecture }}

注册变量

tasks:
  - name: Check if file exists
    stat:
      path: /tmp/myfile
    register: file_info
  
  - name: Display file info
    debug:
      msg: "File exists: {{ file_info.stat.exists }}"
  
  - name: Create file if not exists
    file:
      path: /tmp/myfile
      state: touch
    when: not file_info.stat.exists

运行 Playbook

# 基本运行
ansible-playbook playbook.yml

# 指定 Inventory
ansible-playbook -i inventory.ini playbook.yml

# 检查语法
ansible-playbook --syntax-check playbook.yml

# 列出任务(不执行)
ansible-playbook --list-tasks playbook.yml

# 列出主机
ansible-playbook --list-hosts playbook.yml

# 限制目标主机
ansible-playbook -l webservers playbook.yml

# 从特定标签开始
ansible-playbook --start-at-task "Install Nginx" playbook.yml

# 并行执行(forks)
ansible-playbook -f 10 playbook.yml

# 详细输出
ansible-playbook -v playbook.yml

高级语法

Include 和 Import

# 动态包含(运行时)
tasks:
  - name: Include tasks
    include_tasks: tasks/setup.yml
    when: condition
  
  - name: Include variables
    include_vars: vars/config.yml

# 静态导入(解析时)
tasks:
  - name: Import tasks
    import_tasks: tasks/setup.yml
  
  - name: Import variables
    import_vars: vars/config.yml

Block(任务块)

tasks:
  - name: Block example
    block:
      - name: Install package
        apt:
          name: mypackage
          state: present
      
      - name: Configure service
        template:
          src: config.j2
          dest: /etc/mypackage/config.conf
    rescue:
      - name: Rollback
        apt:
          name: mypackage
          state: absent
    always:
      - name: Cleanup
        file:
          path: /tmp/install.log
          state: absent

最佳实践

  • 幂等性: 确保任务可以安全地多次执行
  • 模块化: 将复杂的 Playbook 拆分为 Roles
  • 命名规范: 使用清晰的名称描述任务和变量
  • 注释文档: 为复杂的逻辑添加注释
  • 版本控制: 将 Playbook 纳入 Git 管理

总结

Playbook 是 Ansible 的核心,掌握 Playbook 语法对于自动化运维至关重要。通过本文的学习,你已经掌握了 Playbook 的基本结构、任务定义、模块使用、Handlers、变量管理等知识。接下来可以深入学习变量、Roles、条件判断等内容。

发表回复

后才能评论