Ansible Playbook编写教程

1. 什么是Ansible Playbook

Ansible Playbook是Ansible的核心组件,用于定义自动化任务的配置、部署和管理流程。它使用YAML语法编写,通过声明式的方式描述系统的期望状态。Playbook可以包含多个play,每个play针对一组主机执行一系列任务,实现高效、可重复的IT自动化。

2. Playbook基础结构

一个基本的Ansible Playbook包含以下关键元素:

名称:描述Playbook的功能

主机:指定任务执行的目标主机

变量:定义可复用的配置参数

任务:实际要执行的操作步骤

处理器:在任务变化时触发的操作

下面是一个简单的Web服务器部署Playbook示例:

---
- name: Install and configure Apache
  hosts: webservers
  become: yes

  vars:
    http_port: 80
    max_clients: 200

  tasks:
    - name: Install Apache package
      ansible.builtin.apt:
        name: apache2
        state: present
        update_cache: yes

    - name: Start Apache service
      ansible.builtin.service:
        name: apache2
        state: started
        enabled: yes

    - name: Deploy custom configuration
      ansible.builtin.template:
        src: templates/apache2.conf.j2
        dest: /etc/apache2/apache2.conf
      notify:
        - Restart Apache

  handlers:
    - name: Restart Apache
      ansible.builtin.service:
        name: apache2
        state: restarted

发表回复

后才能评论