1. Overview
- playbookCompared with ad-hoc, it is a A completely different way of using ansible, similar to saltstack's state file. Ad-hoc cannot be used permanently, playbook can be used permanently.
- playbook is a list composed of one or more plays. The main function of play is to dress up the hosts that have been grouped into a group in advance through ansible. role defined by task.
- Fundamentally speaking, the so-called task is nothing more than a module that calls ansible. Organizing multiple plays into a playbook allows them to be combined to complete a certain task according to a pre-arranged mechanism.
Reference documentation: https://ansible-tran.readthedocs.io/en/latest/docs/playbooks.html
## For the basic introduction and environment deployment of #Ansible, please refer to my article: Ansible introduction and practical operation demonstration
## 2. Playbook core elements
- Hosts List of remote hosts executed
- TasksTask Set
- VarniablesBuilt-in variables or custom Variables call
- Templates in the playbook, that is, files using template syntax, such as configuration files, etc.
- Handlers is used in combination with notity. Operations triggered by specific conditions will only be executed if the conditions are met. Otherwise, they will not be executed.
- Tags Tags, specify a certain item Task execution is used to select and run part of the code in the playbook. 3. Playbook syntax (yaml)
- playbook uses
- yaml syntax format, suffix It can be yaml or yml. YAML (/ˈjæməl/) references many other languages, including: XML, C language, Python, Perl and the email format RFC2822, which was first published by Clark Evans in May 2001. language, Ingy döt Net and Oren Ben-Kiki are also co-designers of this language.
- YAML format is a file format similar to JSON. YAML is used for file configuration writing, and JSON is mostly used for development and design.
- 1) Introduction to YAML
1. The format of YAML is as follows
- The first line of the file should start with "--- ” (three hyphens), indicating the beginning of the YAML file.
- In the same line, the content after # indicates a comment, similar to shell, python and ruby.
- List elements in YAML begin with "-" and are followed by a space. What follows is the element content.
- Elements in the same list should maintain the same indentation, otherwise it will be treated as an error.
- The hosts, variables, roles, tasks and other objects in play are expressed by separating the key values with ":", and a space must be added after the ":".
- 2. Playbooks yaml configuration file explanation
Hosts:运行指定任务的目标主机 remoute_user:在远程主机上执行任务的用户; sudo_user: tasks:任务列表 tasks的具体格式: tasks: - name: TASK_NAME module: arguments notify: HANDLER_NAME handlers: - name: HANDLER_NAME module: arguments ##模块,模块参数: 格式如下: (1)action: module arguments (2) module: arguments 注意:shell和command模块后直接加命令,而不是key=value类的参数列表 handlers:任务,在特定条件下触发;接受到其他任务的通知时被触发;
3. Example
--- - hosts: web remote_user: root tasks: - name: install nginx##安装模块,需要在被控主机里加上nginx的源 yum: name=nginx state=present - name: copy nginx.conf##复制nginx的配置文件过去,需要在本机的/tmp目录下编辑nginx.conf copy: src=/tmp/nginx.conf dest=/etc/nginx/nginx.conf backup=yes notify: reload#当nginx.conf发生改变时,通知给相应的handlers tags: reloadnginx#打标签 - name: start nginx service#服务启动模块 service: name=nginx state=started tags: startnginx#打标签 handlers: - name: reload service: name=nginx state=restarted
2) variables variables
variables There are four ways to define variables. As follows:1. Facts: You can call it directly
There is a setup module in ansible. This module is implemented through the facts component, which is mainly a system of the node itself. Information, bios information, network, hard disk and other information. The variables here can also be directly called into the facts component. We can use thesetup module to obtain the facts, and then put them directly into our script to call them. 常用的几个参数: 搜索 自定义变量有两种方式 使用playbook定义变量,实例如下: 使用: 使用: 下面介绍roles会使用roles传递变量,小伙伴可以翻到下面看详解讲解。 可以在主机清单中定义,方法如下: 如果a"3",就将“test3”,写入到web组下被管控机的/opt/p1.yml中, 执行 执行 创建三个用户 执行 用户shy1的属组是group1,用户shy2的属组是group2,用户shy3的属组是group3 执行 该模板支持: 【示例】 使用 copy与template的区别 使用上场景:修改配置文件时 【示例】 正常情况时handlers是不会执行的 执行 一般情况下将roles写在/etc/ansible/roles中,也可以写在其他任意位置(写在其他位置要自己手动建立一个roles文件夹) 创建目录 【1】创建目录 【2】定义配置文件 先下载nginx rpm部署包 最后的目录结构如下: 执行ansible web -m setup
ansible_all_ipv4_addresses # ipv4的所有地址
ansible_all_ipv6_addresses # ipv6的所有地址
ansible_date_time # 获取到控制节点时间
ansible_default_ipv4 # 默认的ipv4地址
ansible_distribution # 系统
ansible_distribution_major_version # 系统的大版本
ansible_distribution_version # 系统的版本号
ansible_domain #系统所在的域
ansible_env #系统的环境变量
ansible_hostname #系统的主机名
ansible_fqdn #系统的全名
ansible_machine #系统的架构
ansible_memory_mb #系统的内存信息
ansible_os_family # 系统的家族
ansible_pkg_mgr # 系统的包管理工具
ansible_processor_cores #系统的cpu的核数(每颗)
ansible_processor_count #系统cpu的颗数
ansible_processor_vcpus #系统cpu的总个数=cpu的颗数*CPU的核数
ansible_python # 系统上的python
ansible web -m setup -a 'filter=*processor*'
2、用户自定义变量
ansible-playbook命令行中的 -e VARS,--extra-vars VARS,这样就可以直接把自定义的变量传入
---
- hosts: web
remote_user: root
tasks:
- name: install {{ rpmname }}
yum: name={{ rpmname }} state=present
- name: copy {{ rpmname }}.conf
copy: src=/tmp/{{ rpmname }}.conf dest=/etc/{{ rpmname }}/{{ rpmname }}.conf backup=yes
notify: reload
tags: reload{{ rpmname }}
- name: start {{ rpmname }} service
service: name={{ rpmname }} state=started
tags: start{{ rpmname }}
handlers:
- name: reload
service: name={{ rpmname }} state=restarted
ansible-playbook nginx.yml -e rpmname=keepalived
ansible-playbook nginx.yml --extra-vars rpmname=keepalived
##在playbook中定义变量如下:
vars:
- var1: value1
- var2: value2
---
- hosts: web
remote_user: root
vars:
- rpmname: keepalived
tasks:
- name: install {{ rpmname }}
yum: name={{ rpmname }} state=present
- name: copy {{ rpmname }}.conf
copy: src=/tmp/{{ rpmname }}.conf dest=/etc/{{ rpmname }}/{{ rpmname }}.conf backup=yes
notify: reload
tags: reload{{ rpmname }}
- name: start {{ rpmname }} service
service: name={{ rpmname }} state=started
tags: start{{ rpmname }}
handlers:
- name: reload
service: name={{ rpmname }} state=restarted
3、通过roles传递变量
4、 Host Inventory
#向不同的主机传递不同的变量
IP/HOSTNAME varaiable=value var2=value2
#向组中的主机传递相同的变量
[groupname:vars]
variable=value
3)流程控制
1、用when 来表示的条件判断
- hosts: web
remote_user: root#代表用root用户执行,默认是root,可以省略
tasks:
- name: createfile
copy: content="test3" dest=/opt/p1.yml
when: a=='3'
- name: createfile
copy: content="test4" dest=/opt/p1.yml
when: a=='4'
如果a"4",就将“test4”,写入到web组下被管控机的/opt/p1.yml中。# 语法校验
ansible-playbook--syntax-check p1.yml
#执行
ansible-playbook -e 'a="3"' p1.yml
2、标签(只执行配置文件中的一个任务)
- hosts: web
tasks:
- name: installnginx
yum: name=nginx
- name: copyfile
copy: src=/etc/nginx/nginx.conf dest=/etc/nginx/nginx.conf
tags: copyfile
- name: start
service: name=nginx static=restarted
# 语法校验
ansible-playbook--syntax-check p2.yml
#执行
ansible-playbook -t copyfile p2.yml
3、循环 with_items
- hosts: web
tasks:
- name: createruser
user: name={{ item }}
with_items:
- shy1
- shy2
- shy3
- name: creategroup
group: name={{ item }}
with_items:
- group1
- group2
- group3
#语法校验
ansible-playbook--syntax-check p3.yml
#执行
ansible-playbook p3.yml
4、循环嵌套(字典)
- hosts: web
tasks:
- name: creategroup
group: name={{item}}
with_items:
- group3
- group4
- group5
- name: createuser
user: name={{item.user}} group={{item.group}}
with_items:
- {'user': shy3,'group': group3}
- {'user': shy4,'group': group4}
- {'user': shy5,'group': group5}
#语法校验
ansible-playbook--syntax-check p4.yml
#执行
ansible-playbook p4.yml
4)模板 templates
字符串:使用单引号或双引号;
数字:整数,浮点数;
列表:[item1, item2, ...]
元组:(item1, item2, ...)
字典:{key1:value1, key2:value2, ...}
布尔型:true/false
算术运算:
+, -, *, /, //, %, **
比较操作:
==, !=, >, >=, <, <=
逻辑运算:
and, or, not
1、定义模板
usernginx; #设置nginx服务的系统使用用户
worker_processes{{ ansible_processor_vcpus }}; #工作进程数
error_log/var/log/nginx/error.log warn; #nginx的错误日志
pid/var/run/nginx.pid; #nginx启动时候的pid
events {
worker_connections1024; #每个进程允许的最大连接数
}
http { #http请求配置,一个http可以包含多个server
#定义 Content-Type
include /etc/nginx/mime.types;
default_typeapplication/octet-stream;
#日志格式 此处main与access_log中的main对应
#$remote_addr:客户端地址
#$remote_user:http客户端请求nginx认证的用户名,默认不开启认证模块,不会记录
#$timelocal:nginx的时间
#$request:请求method + 路由 + http协议版本
#status:http reponse 状态码
#body_bytes_sent:response body的大小
#$http_referer:referer头信息参数,表示上级页面
#$http_user_agent:user-agent头信息参数,客户端信息
#$http_x_forwarded_for:x-forwarded-for头信息参数
log_formatmain'$http_user_agent' '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
#访问日志,后面的main表示使用log_format中的main格式记录到access.log中
access_log/var/log/nginx/access.logmain;
#nginx的一大优势,高效率文件传输
sendfileon;
#tcp_nopush on;
#客户端与服务端的超时时间,单位秒
keepalive_timeout65;
#gzipon;
server { #http服务,一个server可以配置多个location
listen {{ nginxport }}; #服务监听端口
server_namelocalhost; #主机名、域名
#charset koi8-r;
#access_log/var/log/nginx/host.access.logmain;
location / {
root /usr/share/nginx/html; #页面存放目录
indexindex.html index.htm; #默认页面
}
#error_page404/404.html;
# 将500 502 503 504的错误页面重定向到 /50x.html
error_page 500 502 503 504/50x.html;
location = /50x.html { #匹配error_page指定的页面路径
root /usr/share/nginx/html; #页面存放的目录
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
#proxy_pass http://127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
#root html;
#fastcgi_pass 127.0.0.1:9000;
#fastcgi_indexindex.php;
#fastcgi_paramSCRIPT_FILENAME/scripts$fastcgi_script_name;
#includefastcgi_params;
#}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
#denyall;
#}
}
include /etc/nginx/conf.d/*.conf;
}
2、定义yaml编排
---
- hosts: web
remote_user: root
vars:
- rpmname: nginx
- nginxport: 8088
tasks:
- name: install {{ rpmname }}
yum: name={{ rpmname }} state=present
- name: copy {{ rpmname }}.conf
copy: src=/tmp/{{ rpmname }}.conf dest=/etc/{{ rpmname }}/{{ rpmname }}.conf backup=yes
notify: reload
tags: reload{{ rpmname }}
- name: start {{ rpmname }} service
service: name={{ rpmname }} state=started
tags: start{{ rpmname }}
handlers:
- name: reload
service: name={{ rpmname }} state=restarted
##使用reloadnginx标签,重新加载剧本
5)handlers(触发事件)
notify:触发
handlers:触发的动作
- hosts: web
tasks:
- name: installredis
yum: name=redis
- name: copyfile
template: src=redis.conf dest=/etc/redis.conf
tags: copyfile
notify: restart
- name: start
service: name=redis state=started
handlers:
- name: restart
service: name=redis
ansible-playbook -t copyfile p6.yml
6)roles
1、roles介绍与优势
2、目录结构
mkdir -pv ./{nginx,mysql,httpd}/{files,templates,vars,tasks,handlers,meta,default}
3、实战操作
mkdir -pv ./{nginx,mysql,httpd}/{files,templates,vars,tasks,handlers,meta,default}
# 下载地址:http://nginx.org/packages/centos/7/x86_64/RPMS/
wget http://nginx.org/packages/centos/7/x86_64/RPMS/nginx-1.18.0-1.el7.ngx.x86_64.rpm -O nginx/files/nginx-1.18.0-1.el7.ngx.x86_64.rpm
- name: cp
copy: src=nginx-1.18.0-1.el7.ngx.x86_64.rpm dest=/tmp/nginx-1.18.0-1.el7.ngx.x86_64.rpm
- name: install
yum: name=/tmp/nginx-1.18.0-1.el7.ngx.x86_64.rpm state=latest
- name: conf
template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf
tags: nginxconf
notify: new conf to reload
- name: start service
service: name=nginx state=started enabled=true
usernginx; #设置nginx服务的系统使用用户
worker_processes{{ ansible_processor_vcpus }}; #工作进程数
error_log/var/log/nginx/error.log warn; #nginx的错误日志
pid/var/run/nginx.pid; #nginx启动时候的pid
events {
worker_connections1024; #每个进程允许的最大连接数
}
http { #http请求配置,一个http可以包含多个server
#定义 Content-Type
include /etc/nginx/mime.types;
default_typeapplication/octet-stream;
#日志格式 此处main与access_log中的main对应
#$remote_addr:客户端地址
#$remote_user:http客户端请求nginx认证的用户名,默认不开启认证模块,不会记录
#$timelocal:nginx的时间
#$request:请求method + 路由 + http协议版本
#status:http reponse 状态码
#body_bytes_sent:response body的大小
#$http_referer:referer头信息参数,表示上级页面
#$http_user_agent:user-agent头信息参数,客户端信息
#$http_x_forwarded_for:x-forwarded-for头信息参数
log_formatmain'$http_user_agent' '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
#访问日志,后面的main表示使用log_format中的main格式记录到access.log中
access_log/var/log/nginx/access.logmain;
#nginx的一大优势,高效率文件传输
sendfileon;
#tcp_nopush on;
#客户端与服务端的超时时间,单位秒
keepalive_timeout65;
#gzipon;
server { #http服务,一个server可以配置多个location
listen {{ nginxport }}; #服务监听端口
server_namelocalhost; #主机名、域名
#charset koi8-r;
#access_log/var/log/nginx/host.access.logmain;
location / {
root /usr/share/nginx/html; #页面存放目录
indexindex.html index.htm; #默认页面
}
#error_page404/404.html;
# 将500 502 503 504的错误页面重定向到 /50x.html
error_page 500 502 503 504/50x.html;
location = /50x.html { #匹配error_page指定的页面路径
root /usr/share/nginx/html; #页面存放的目录
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
#proxy_pass http://127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
#root html;
#fastcgi_pass 127.0.0.1:9000;
#fastcgi_indexindex.php;
#fastcgi_paramSCRIPT_FILENAME/scripts$fastcgi_script_name;
#includefastcgi_params;
#}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
#denyall;
#}
}
include /etc/nginx/conf.d/*.conf;
}
nginxport: 9999
- name: new conf to reload
service: name=nginx state=restarted
- hosts: web
remote_user: root
roles:
- nginx
ansible-playbook roles.yml
The above is the detailed content of Ansible Playbook explanation and practical operation. For more information, please follow other related articles on the PHP Chinese website!

Python是一款非常有用的软件,可以根据需要用于许多不同的目的。Python可以用于Web开发、数据科学、机器学习等许多其他需要自动化处理的领域。它具有许多不同的功能,可以帮助我们执行这些任务。Python列表是Python的一个非常有用的功能之一。顾名思义,列表包含您希望存储的所有数据。它基本上是一组不同类型的信息。删除方括号的不同方法许多时候,用户会遇到列表项显示在方括号中的情况。在本文中,我们将详细介绍如何去掉这些括号,以便更好地查看您的列表。字符串和替换函数删除括号的最简单方法之一是在

如何在iOS17中的iPhone上制作GroceryList在“提醒事项”应用中创建GroceryList非常简单。你只需添加一个列表,然后用你的项目填充它。该应用程序会自动将您的商品分类,您甚至可以与您的伴侣或扁平伙伴合作,列出您需要从商店购买的东西。以下是执行此操作的完整步骤:步骤1:打开iCloud提醒事项听起来很奇怪,苹果表示您需要启用来自iCloud的提醒才能在iOS17上创建GroceryList。以下是它的步骤:前往iPhone上的“设置”应用,然后点击[您的姓名]。接下来,选择i

SolutionYes,Wecaninsertnullvaluestoalisteasilyusingitsadd()method.IncaseofListimplementationdoesnotsupportnullthenitwillthrowNullPointerException.Syntaxbooleanadd(Ee)将指定的元素追加到此列表的末尾。类型参数E −元素的运行时类型。参数e −要追加到此列表的元

在讨论差异之前,让我们先了解一下Python列表中的Del和Remove()是什么。Python列表中的Del关键字Python中的del关键字用于从List中删除一个或多个元素。我们还可以删除所有元素,即删除整个列表。示例使用del关键字从Python列表中删除元素#CreateaListmyList=["Toyota","Benz","Audi","Bentley"]print("List="

Python凭借其简单性和多功能性,已成为各种应用程序中最流行的编程语言之一。无论您是经验丰富的开发人员还是刚刚开始编码之旅,Python都提供了广泛的功能和库,使复杂的任务变得易于管理。在本文中,我们将探讨一个实际场景,Python可以通过自动执行基于列表创建多个目录的过程来帮助我们。通过利用Python内置模块和技术的强大功能,我们可以有效地处理此任务,而无需手动干预。在本教程中,我们将深入研究创建多个目录的问题,并为您提供使用Python解决该问题的不同方法。在本文结束时,我们的目标是为您

Vue是一款流行的JavaScript库,广泛应用于Web开发领域。在Vue中,我们可以很方便地实现各种组件和交互效果。其中,可折叠列表是一个比较实用的组件,它可以将列表数据分组,提高数据展示的可读性,同时又能够在需要展开具体内容时进行展开,方便用户查看详细信息。本文就将介绍如何使用Vue实现可折叠列表。准备工作在使用Vue实现可折叠列

List是JavaCollection接口的子接口。它是一种线性结构,按照顺序存储和访问每个元素。为了使用list的特性,我们使用实现了list接口的ArrayList和LinkedList类。在本文中,我们将创建一个ArrayList,并尝试随机选择该列表中的项目。在Java中随机选择列表中的项目的程序随机类别我们创建此类的对象来生成伪随机数。我们将自定义该对象并应用我们自己的逻辑从列表中选择任何随机项目。语法RandomnameOfObject=newRandom();Example1的翻译

花了这么长时间,但在iOS17中,Apple增加了对多个计时器的支持,并且还通过引入标签使在iPhone上管理多个计时器变得容易。没错。信不信由你,到目前为止,iPhone还没有包括设置多个持续计时器的功能。在iOS17,时钟应用程序最终可以设置多个计时器,这些计时器将同时运行,使您可以跟踪多件事,例如,这在烹饪包含多道菜的餐点时很方便。您不仅可以同时有多个计时器倒计时,还可以标记计时器,这有助于您在计时器列表中识别每个计时器。这样,您将始终知道哪个计时器与什么相关,并且可以保存自定义计时器,而


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Atom editor mac version download
The most popular open source editor

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
