include
编程的时候经常会调用其他代码模块的函数,当前比较火的Python 就是用关键字 import调用(或者叫做导入)模块。
在写shell脚本的时候我们也会you [. /path/test.sh] 的语法调用其他的shell脚本
在ansible-playbook中也有相应的调用,它是用关键字include来实现的
我们先写2个playbook,一个安装LAMP一个安装LNMP.
LAMP.yaml
---
- hosts: 192.168.233.167
remote_user: root
tasks:
- name: apt install LAMP
apt:
name: "{{ item }}"
state: present
loop:
- apache2
- mysql-server
- php-fpm
LNMP.yaml
---
- hosts: 192.168.233.167
remote_user: root
tasks:
- name: apt install LNMP
apt:
name: "{{ item }}"
state: present
loop:
- nginx
- mysql-server
- php-fpm
可以看到无论在LAMP或LNMP中都会安装mysql-server和php-fpm,因此我们把这2个任务放到一个单独的yaml文件中,再写一个install_mysql_php.yaml文件,内容如下:
- apt:
name: "{{ item }}"
state: present
loop:
- mysql-server
- php-fpm
或者你不用循环,直接写单独的2个任务,如下:
- apt:
name: mysql-server
state: present
- apt:
name: php-fpm
state: present
以上2种写法都可以,但是要注意一点,这个yaml文件只包含任务,可以理解为任务列表。
而我们之前写的LAMP.yaml和LNMP.yaml文件也要做相应的修改,修改后如下:
LAMP.yaml
---
- hosts: 192.168.233.167
remote_user: root
tasks:
- name: apt install LAMP
apt:
name: apache2
state: present
- include: install_mysql_php.yaml
LNMP.yaml
---
- hosts: 192.168.233.167
remote_user: root
tasks:
- name: apt install LNMP
apt:
name: nginx
state: present
- include: install_mysql_php.yaml
include和when结合是经常使用的,因为经常远程机器的系统都有不同发行版,有的是CentOS,有的是Ubuntu,有的是SUSE,而针对不同的发行版我们就要写不同的playbook,写法如下:
---
- hosts: 192.168.233.167
remote_user: root
tasks:
- include: centos.yml
when: ansible_os_family == "RedHat"
- include: ubuntu.yml
when: ansible_os_family == "Debian"
其实还有include_tasks、import_tasks也可以达到相同的调用效果,个人感觉一个include就够用了
好奇的同学可以到网上找相关资料研究一下。
本文暂时没有评论,来添加一个吧(●'◡'●)