跳转至

初识 Playbooks

学习内容:了解 Playbook 的语法和结构。创建简单的 Playbook 来执行基本任务。

官方 Playbook 指南: https://docs.ansible.com/ansible/latest/user_guide/playbooks.html

一、剧本语法

Ansible 剧本(Playbook) 是用 YAML (Yet Another Markup Language) 编写的。它定义了在托管节点上执行的任务。剧本包括以下几个主要部分:

  • 头部: 定义了剧本的名称、目标主机和用户。
  • 任务: 定义了具体要在目标主机上执行的操作。
  • 模块: Ansible 提供的功能单元,比如 copy, yum, service 等。

以下是一个基本的剧本语法结构:

---
- name: Install and start Apache
  hosts: webs
  become: yes

  tasks:
    - name: Ensure apache is installed
      apt:
        name: apache2
        state: present

    - name: Start apache service
      service:
        name: apache2
        state: started

解释:

  • ---:YAML 文件的起始标志。
  • name:定义整个剧本的名称。
  • hosts:指定该剧本应用到的主机组。
  • become:是否以超级用户权限执行任务。
  • tasks:任务部分,定义在目标主机上执行的具体操作。
  • yum 和 service 是模块,用来完成具体的任务。

二、 基本的剧本示例

编写一个简单的 Ansible Playbook 来安装 Apache HTTP Server 并启动它。

编写 Playbook 文件 (install_apache.yml):
---
- name: Install and start Apache
  hosts: webservers
  become: yes

  tasks:
    - name: Ensure apache is installed
      yum:
        name: httpd
        state: present

    - name: Start apache service
      service:
        name: httpd
        state: started

解释:

  • name: Install and start Apache:剧本的名称。
  • hosts: webservers:指定目标主机组是 webservers。你需要在 inventory 文件中定义这个组。
  • become: yes:使用root权限执行这些任务。
  • tasks:在这个剧本中有两个任务。
    • 任务一:Ensure apache is installed 使用 yum 模块安装 Apache (httpd) 软件包。
    • 任务二:Start apache service 使用 service 模块启动 Apache 服务。

三、使用 Ansible 命令运行剧本

运行 Ansible Playbook 需要使用 ansible-playbook 命令。下面是具体步骤:

1. 准备 Inventory 文件:

创建一个 Inventory 文件 (hosts) 来定义目标主机信息。

[webservers]
your_server_ip

2. 运行 Playbook:

使用 ansible-playbook 命令来执行上述的 Playbook。

ansible-playbook -i hosts install_apache.yml

3. 检验结果:

  • 确认 Playbook 执行成功。
  • 在目标主机上检查 Apache 是否已安装并正在运行。
# 如果使用的是 CentOS/RHEL
systemctl status httpd

运行效果示例:

$ ansible-playbook -i hosts install_apache.yml

PLAY [Install and start Apache] *******************************************************************

TASK [Gathering Facts] ****************************************************************************
ok: [your_server_ip]

TASK [Ensure apache is installed] *****************************************************************
changed: [your_server_ip]

TASK [Start apache service] ***********************************************************************
changed: [your_server_ip]

PLAY RECAP ***************************************************************************************
your_server_ip             : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0