 ansible进阶技巧
ansible进阶技巧
  # ansible进阶技巧
在实际工作中,一个完整的项目往往是很多功能的组合体,如果将所有的功能写在一个Playbook中会存在问题,如:代码耦合程度高;Playbook过长而维护成本巨大;Playbook过于臃肿而缺乏灵活性等。为解决如上问题,可以:
- 使用Includes引用Playbook的YML文件;
- 用Roles改造已有的Includes代码;
- 使用Templates结合Jinja生成配置模板等。
# 1. Include
Includes在Ansible中主要起引用功能,可以引用YML、Vars、Handlers、Files也同样支持。
# 1.1. include
Ansible Navigator (opens new window)
Ansible Automation Platform - 功能构成 (opens new window)
假设共有A、B、C、D、E、F这6个Project(项目),但均需使用 Restart Nginx Process(重启nginx进程)功能,此时,我们可以把 Restart Nginx Process 功能作为单独的Playbook文件独立出来,以方便其他项目引用。
RestartNginxProcess.yml的配置如下:
---
- name: Restart Nginx Process
  ansible.builtin.service:
    state: restarted
    name: nginx
1
2
3
4
5
6
2
3
4
5
6
其他文件引用RestartNginxProcess.yml:
---
- name: This playbook deploys the whole application stack in this site.
  hosts: localhost
  remote_user: root
  gather_facts: false
  tasks:
    - name: A Project command
      ansible.builtin.command: A Project command
    - name: Restart Nginx Process
      include:
        RestartNginxProcess.yml          # 引用RestartNginxProcess.yml文件
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# 1.2. include Handler
上次更新: 2024/05/11, 03:55:33
