1. Playbooks overview and example operations
1. Composition of playbooks
playbooks themselves consist of the following parts
(1) Tasks: Tasks, that is, calling ansible templates through tasks to organize multiple operations to run in a playbook
(2) Variables: variables
(3) Templates: Templates
(4) Handlers: Processor, when the changed status condition is met, (notify) triggers the execution operation
(5) Roles: roles
2. Operation example one:
2.1 Write yaml file, also known as playbook
vim test1.yaml
--- #yaml文件以---开头,以表明这是一个yaml文件,可省略
- name: first play #定义一个play的名称,可省略
gather_facts: false #设置不进行facts信息收集,这可以加快执行速度,可省略
hosts: webservers #指定要执行任务的被管理主机组,如多个主机组用冒号分隔
remote_user: root #指定被管理主机上执行任务的用户
tasks: #定义任务列表,任务列表中的各任务按次序逐个在hosts中指定的主机上执行
- name: test connection # 自定义任务名称
ping: #使用 module: [options] 格式来定义一个任务
- name: disable selinux
command: '/sbin/setenforce 0' #command模块和shell模块无需使用key=value格式
ignore_errors: True #如执行命令的返回值不为0,就会报错,tasks停止,可使用ignore_errors忽略失败的任务
- name: disable firewalld
service: name=firewalld state=stopped #使用 module: options 格式来定义任务,option使用key=value格式
- name: install httpd
yum: name=httpd state=latest
- name: install configuration file for httpd
copy: src=/opt/httpd.conf dest=/etc/httpd/conf/httpd.conf #这里需要一个事先准备好的/opt/httpd.conf文件
notify: "restart httpd" #如以上操作后为changed的状态时,会通过notify指定的名称触发对应名称的handlers操作
- name: start httpd service
service: enabled=true name=httpd state=started
handlers: #handlers中定义的就是任务,此处handlers中的任务使用的是service模块
- name: restart httpd #notify和handlers中任务的名称必须一致
service: name=httpd state=restarted
1
##Ansible在执行完某个任务之后并不会立即去执行对应的handler,而是在当前play中所有普通任务都执行完后再去执行handler,这样的好处是可以多次触发notify,但最后只执行一次对应的handler,从而避免多次重启。
2.2 Modify the configuration file and put it in the /opt/ directory
vim httpd.conf #在/opt/目录下放入修改之后的配置文件
#42行,指定端口
Listen 8080
#95行,指定域名
ServerName www.ly.com:8080
2.3 Run playbook
ansible-playbook test1.yaml
//补充参数:
-k(–ask-pass):用来交互输入ssh密码
-K(-ask-become-pass):用来交互输入sudo密码
-u:指定用户
ansible-playbook test1.yaml --syntax-check #检查yaml文件的语法是否正确
ansible-playbook test1.yaml --list-task #检查tasks任务
ansible-playbook test1.yaml --list-hosts #检查生效的主机
ansible-playbook test1.yaml --start-at-task='install httpd' #从指定任务开始运行
3. Operation Example 2: Define and reference variables
- name: second play
hosts: dbservers
remote_user: root
vars: #定义变量
- groupname: mysql #格式为 key: value
- username: nginx
tasks:
- name: create group
group: name={
{groupname}} system=yes gid=306 #使用 {
{key}} 引用变量的值
- name: create user
user: name={
{username}} uid=306 group={
{groupname}}
- name: copy file
copy: content="{
{ansible_default_ipv4}}" dest=/opt/vars.txt #在setup模块中可以获取facts变量信息
ansible-playbook test2.yaml -e "username=nginx"
4. Operation example three: Specify the remote host sudo to switch users
---
- hosts: dbservers
remote_user: zhangsan
become: yes #2.6版本以后的参数,之前是sudo,意思为切换用户运行
become_user: root #指定sudo用户为root
执行playbook时:ansible-playbook test3.yml -K <密码>
5. Operation example four: when condition judgment
In Ansible, the only general conditional judgment provided is the when instruction. When the value of the when instruction is true, the task is executed, otherwise the task is not executed.
//when a common application scenario is to skip a certain host and not execute the task or only the host that meets the conditions executes the task
vim test4.yaml
---
- hosts: all
remote_user: root
tasks:
- name: shutdown host
command: /sbin/shutdown -r now
when: ansible_default_ipv4.address == "192.168.229.80" #when指令中的变量名不需要手动加上 {
{}}
或
when: inventory_hostname == "<主机名>"
ansible-playbook test4.yaml
6. Operation examples: Five: Iteration
Ansible provides many loop structures, generally named with_items, which are equivalent to loop loops.
vim test5.yaml
---
- name: play5
hosts: dbservers
gather_facts: false
tasks:
- name: create directories ##创建目录。目录名使用with_items里的循环
file:
path: "{
{item}}" ##由于值是{
{....}} ,所以为了防止被认为是字典,要加上双引号.
state: directory
with_items: #等同于 loop:
- /tmp/test1
- /tmp/test2
- name: add users ###使用循环创建用户,并添加附加组
user: name={
{item.name}} state=present groups={
{item.groups}}
with_items:
- name: test1
groups: wheel
- name: test2
groups: root
或
with_items:
- {name:'test1', groups:'wheel'}
- {name:'test2', groups:'root'}
ansible-playbook test5.yaml
2. Playbook module
1. Templates module
Jinja is a Python-based template engine. The Template class is an important component of Jinja. It can be regarded as a compiled template file, used to generate target text and pass Python variables to the template to replace the tags in the template.
1.1. First prepare a template file with .j2 as the suffix and set the referenced variables.
cp /etc/httpd/conf/httpd.conf /opt/httpd.conf.j2
vim /opt/httpd.conf.j2
Listen {
{http_port}} #42行,修改
ServerName {
{server_name}} #95行,修改
DocumentRoot "{
{root_dir}}" #119行,修改 <Directory "{
{root_dir}}"> #131修改 配置目录访问权限
1.2. Modify the host manifest file and use host variables to define a variable with the same name but different values.
vim /etc/ansible/hosts
[webservers]
192.168.2.200 http_port=192.168.2.200:80 server_name=www.xkq.com:80 root_dir=/etc/httpd/htdocs
[dbservers]
192.168.2.77 http_port=192.168.2.77:80 server_name=www.wy.com:80 root_dir=/etc/httpd/htdocs
1.3.Write playbook
vim apache.yaml
---
- hosts: all
remote_user: root
vars:
- package: httpd
- service: httpd
tasks:
- name: install httpd package
yum: name={
{package}} state=latest
- name: install configure file
template: src=/opt/httpd.conf.j2 dest=/etc/httpd/conf/httpd.conf #使用template模板
notify:
- restart httpd
- name: create root dir
file: path=/etc/httpd/htdocs state=directory
- name: start httpd server
service: name={
{service}} enabled=true state=started
handlers:
- name: restart httpd
service: name={
{service}} state=restarted
ansible-playbook apache.yaml
1.4 Create a test web page
ansible 192.168.2.200 -m shell -a "echo 'this is xkq' > /etc/httpd/htdocs/index.html" #制作网页测试文件
ansible 192.168.2.77 -m shell -a "echo 'this is wy' > /etc/httpd/htdocs/index.html"
curl http://192.168.2.200 #登录访问查看
2. tags module
You can define "tags" for one or more tasks in a playbook. When executing this playbook, use the --tags option with the ansible-playbook command to run only the specified tasks.
The playbook also provides a special tags for always. The function is that when using the always tags task, no matter which tags are executed, the tags defined with always will be executed.
vim webhosts.yaml
---
- hosts: webservers
remote_user: root
tasks:
- name: Copy hosts file
copy: src=/etc/hosts dest=/opt/hosts
tags:
- only #可自定义
- name: touch file
file: path=/opt/testhost state=touch
tags:
- always #表示始终要运行的代码
ansible-playbook webhosts.yaml --tags="only"
3. Roles module
In order to organize Playbooks hierarchically and structuredly, Ansible uses roles. Roles can automatically load variable files, tasks, handlers, etc. according to the hierarchical structure. Simply put, roles place variables, files, tasks, modules, and processors in separate directories, and they can be easily included. Roles are generally used in scenarios where services are built based on hosts, but they can also be used in scenarios such as building daemons.
3.1 Directory structure of roles:
cd /etc/ansible/
tree roles/
roles/
├── web/
│ ├── files/
│ ├── templates/
│ ├── tasks/
│ ├── handlers/
│ ├── vars/
│ ├── defaults/
│ └── meta/
└── db/
├── files/
├── templates/
├── tasks/
├── handlers/
├── vars/
├── defaults/
└── meta/
3.2 Explanation of the meaning of each directory in roles
●files
are used to store files called by the copy module or script module.
●templates
is used to store jinjia2 templates. The template module will automatically search for jinjia2 template files in this directory.
●tasks
This directory should contain a main.yml file, which is used to define the task list of this role. This file can use include to include other task files located in this directory.
●handlers
This directory should contain a main.yml file, which is used to define the actions to be performed when conditions are triggered in this role.
●vars
This directory should contain a main.yml file to define the variables used by this role.
●defaults
This directory should contain a main.yml file, which is used to set default variables for the current role.
●meta
This directory should contain a main.yml file that defines the special settings of this role and its dependencies.
3.3 Steps to use roles in a playbook:
(1) Create a directory named after roles
mkdir /etc/ansible/roles/ -p #yum装完默认就有
(2) Create a global variable directory (optional)
mkdir /etc/ansible/group_vars/ -p
touch /etc/ansible/group_vars/lnmp #文件名自己定义,引用的时候注意
(3) Create directories with commands with each role name in the roles directory, such as nginx, mysql, php
mkdir /etc/ansible/roles/nginx
mkdir /etc/ansible/roles/mysql
mkdir /etc/ansible/roles/php
(4) Create files, handlers, tasks, templates, meta, defaults and vars directories in the directory of each role command. Unused directories can be created as empty directories or not created at all.
mkdir /etc/ansible/roles/nginx/{files,templates,tasks,handlers,vars,defaults,meta}
mkdir /etc/ansible/roles/mysql/{files,templates,tasks,handlers,vars,defaults,meta}
mkdir /etc/ansible/roles/php/{files,templates,tasks,handlers,vars,defaults,meta}
(5) Create the main.yml file in the handlers, tasks, meta, defaults, and vars directories of each role. Do not customize the file name.
touch /etc/ansible/roles/nginx/{defaults,vars,tasks,meta,handlers}/main.yml
touch /etc/ansible/roles/mysql/{defaults,vars,tasks,meta,handlers}/main.yml
touch /etc/ansible/roles/php/{defaults,vars,tasks,meta,handlers}/main.yml
(6) Modify the site.yml file to call different roles for different hosts
vim /etc/ansible/site.yml
---
- hosts: webservers
remote_user: root
roles:
- nginx
- mysql
- php
(7) Run ansible-playbook
cd /etc/ansible
ansible-playbook site.yml
3. Application of roles in LNMP
Continue with the above experimental steps
1. Write nginx module
Write a simple tasks/main.yml
vim /etc/ansible/roles/nginx/tasks/main.yml
- name: install nginx
yum: name={
{pkg}} state=latest
- name: start
service: enabled=true name={
{svc}} state=started
//Define variables: They can be defined in global variables or in roles role variables. They are generally defined in role variables.
vim /etc/ansible/roles/nginx/vars/main.yml
pkg: nginx
svc: nginx
Here we define it in the role variable
2. Write mysql module
vim /etc/ansible/roles/mysql/tasks/main.yml
- name: install mysql
yum: name={
{pkg}} state=latest
- name: start mysql
service: enabled=true name={
{svc}} state=started
vim /etc/ansible/roles/mysql/vars/main.yml
pkg:
- mariadb
- mariadb-server
svc: mariadb
3. Write php module
vim /etc/ansible/roles/php/tasks/main.yml
- name: install php
yum: name={
{pkg}} state=latest
- name: start php-fpm
service: enabled=true name={
{svc}} state=started
vim /etc/ansible/roles/php/vars/main.yml
pkg:
- php
- php-fpm
svc: php-fpm
4. Write role examples
vim /etc/ansible/site.yml
---
- hosts: webservers
remote_user: root
roles:
- httpd
- mysql
- php
cd /etc/ansible
ansible-playbook site.yml