Ansible script - playbook script

1. Introduction to Ansible playbook

Playbooks is a mode different from using the Ansible command line execution mode, and its function is more powerful and flexible. In simple terms, playbook is a very simple configuration management and multi-host deployment system, unlike any existing model, which can be used as a basis for deploying complex applications. Playbook can be customized and configured, and can be executed in an orderly manner according to the specified operation steps, and supports synchronous and asynchronous modes. It is worth noting that the playbook is described and defined in the YAML format

1. playbook format

Playbooks are written in YAML language. The YAML language refers to many other languages, including: XML, C language, Python, Perl, etc. The MAL format is a file format similar to JSON, which is easy for human to understand and read, and easy to write at the same time. The following are the YAML formats commonly used in playbooks.

YMAL中的列表元素以”-”开头然后紧跟着一个空格,后面为元素内容。就像这样- host。
同一个列表中的元素应该保持相同的缩进。否则会被当做错误处理。
playbook中hosts,variables,roles,tasks等对象的表示方法都是键值中间以”:”分隔,”:”后面还要增加一个空格。
剧本以.yml后缀
yaml语法

2. Playbook components

  • Tasks: Tasks, that is, call ansible templates through tasks to organize multiple operations to run in a playbook
  • Variables: variables
  • Templates: Templates
  • Handlers: Processor, when the changed state condition is met, (notify) triggers the execution of the operation
  • Roles: role

Two, examples

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
##Ansible在执行完某个任务之后并不会立即去执行对应的handler,而是在当前play中所有普通任务都执行完后再去执行handler,这样的好处是可以多次触发notify,但最后只执行一次对应的handler,从而避免多次重启。
//运行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'     #指定从某个task开始运行
//定义、引用变量
- 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 test1.yaml -e "username=nginx"     #在命令行里定义变量
//指定远程主机sudo切换用户
---
- hosts: dbservers
  remote_user: zhangsan            
  become: yes	                 #2.6版本以后的参数,之前是sudo,意思为切换用户运行
  become_user: root              #指定sudo用户为root
执行playbook时:ansible-playbook test1.yml -k -K 
//when条件判断
在Ansible中,提供的唯一一个通用的条件判断是when指令,当when指令的值为true时,则该任务执行,否则不执行该任务。

//when一个比较常见的应用场景是实现跳过某个主机不执行任务或者只有满足条件的主机执行任务
vim test2.yaml
---
- hosts: all
  remote_user: root
  tasks:
   - name: shutdown host 
     command: /sbin/shutdown -r now
     when: ansible_default_ipv4.address == "192.168.80.12"      #when指令中的变量名不需要手动加上 {
    
    {}}
     when: inventory_hostname == "<主机名>"
	
ansible-playbook test2.yaml
//迭代
Ansible提供了很多种循环结构,一般都命名为with_items,作用等同于 loop 循环。
vim test3.yaml
---
- name: play1
  hosts: dbservers
  gather_facts: false
  tasks: 
    - name: create file
      file:
        path: "{
    
    {item}}"
        state: touch
      with_items: [ /opt/a, /opt/b, /opt/c, /opt/d ]


- name: play2
  hosts: dbservers
  gather_facts: false		
  vars:
    test:
    - /tmp/test1
    - /tmp/test2
    - /tmp/test3
    - /tmp/test4
  tasks: 
    - name: create directories
      file:
        path: "{
    
    {item}}"
        state: directory
      with_items: "{
    
    {test}}"
		
- name: play3
  hosts: dbservers
  gather_facts: false
  tasks:
    - 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 test3.yaml

3. Templates module

Jinja is a Python-based templating engine. The Template class is an important component of Jinja, which 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. First prepare a template template file with the suffix .j2, 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行,修改
  1. Modify the host inventory file and use the host variable to define a variable with the same variable name but different values
vim /etc/ansible/hosts       
[webservers]
192.168.80.11 http_port=192.168.80.11:80 server_name=www.accp.com:80 root_dir=/etc/httpd/htdocs

[dbservers]
192.168.80.12 http_port=192.168.80.12:80 server_name=www.benet.com:80 root_dir=/etc/httpd/htdocs
  1. 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

Four, tags module

You can define "tags" for one or some tasks in a playbook. When executing this playbook, use the –tags option through the ansible-playbook command to run only the specified tasks.
The playbook also provides a special tags for always. The effect is that when using always as the task of tags, 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"

vim dbhosts.yaml
---
- hosts: dbservers
  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


ansible-playbook dbhosts.yaml --tags="only"
//分别去两台被管理主机上去查看文件创建情况

5. Roles module

Roles are used to organize playbooks hierarchically and structurally. Roles can automatically load variable files, tasks and handlers according to the hierarchical structure. To use roles, you only need to use the include command in the playbook to import.
Simply put, roles is a mechanism that places variables, files, tasks, templates, and processors in separate directories and includes them easily. Roles is generally used in the scenario of building services based on the host, but it can also be used in scenarios such as building daemons. It is mainly used in scenarios where code reuse is high.

If we now have 3 managed hosts, the first one should be configured as httpd, the second one should be configured as haproxy server, and the third one should be configured as MySQL (mariadb) server. How do we define playbook?
The first play is used on the first host to build httpd, and the second play is used on the second host to build haproxy. These play definitions are cumbersome in the playbook, and are not conducive to modular calls in the future, and are not conducive to multiple calls. For example, a host was added later. The third host is both an httpd server and a haproxy server. We can only write the third play, which says to install httpd and haproxy. In this way, the code in the playbook is repeated.
In order to avoid code duplication, you can define a role called httpd, and a second role called haproxy, and use roles to implement code duplication.

//roles 的目录结构:
cd /etc/ansible/
tree roles/
roles/
├── web/    #相当于 playbook 中的 每一个 play 主题
│   ├── files/
│   ├── templates/
│   ├── tasks/
│   ├── handlers/
│   ├── vars/
│   ├── defaults/
│   └── meta/
└── db/
    ├── files/
    ├── templates/
    ├── tasks/
    ├── handlers/
    ├── vars/
    ├── defaults/
    └── meta/

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, and 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 that defines actions to be executed when conditions are triggered in this role.

  • vars
    This directory should contain a main.yml file that defines the variables used by this role.

  • defaults
    This directory should contain a main.yml file that sets default variables for the current role. These variables have the lowest priority of all available variables and can be easily overridden by any other variable. So we generally don't define variables here in production

  • meta
    This directory should contain a main.yml file that defines the metadata information of this role and its dependencies.

Steps to use roles in a playbook:

(1)创建以 roles 命名的目录
mkdir /etc/ansible/roles/ -p    #yum装完默认就有

(2)创建全局变量目录(可选)
mkdir /etc/ansible/group_vars/ -p
touch /etc/ansible/group_vars/all     #文件名自己定义,引用的时候注意

(3)在 roles 目录中分别创建以各角色名称命名的目录,如 httpd、mysql
mkdir /etc/ansible/roles/httpd
mkdir /etc/ansible/roles/mysql

(4)在每个角色命名的目录中分别创建files、handlers、tasks、templates、meta、defaults和vars目录,用不到的目录可以创建为空目录,也可以不创建
mkdir /etc/ansible/roles/httpd/{
    
    files,templates,tasks,handlers,vars,defaults,meta}
mkdir /etc/ansible/roles/mysql/{
    
    files,templates,tasks,handlers,vars,defaults,meta}

(5)在每个角色的 handlers、tasks、meta、defaults、vars 目录下创建 main.yml 文件,千万不能自定义文件名
touch /etc/ansible/roles/httpd/{
    
    defaults,vars,tasks,meta,handlers}/main.yml
touch /etc/ansible/roles/mysql/{
    
    defaults,vars,tasks,meta,handlers}/main.yml

(6)修改 site.yml 文件,针对不同主机去调用不同的角色
vim /etc/ansible/site.yml
---
- hosts: webservers
  remote_user: root
  roles:
     - httpd
- hosts: dbservers
  remote_user: root
  roles:
     - mysql
	 
(7)运行 ansible-playbook
cd /etc/ansible
ansible-playbook site.yml


示例:
mkdir /etc/ansible/roles/httpd/{
    
    files,templates,tasks,handlers,vars,defaults,meta} -p
mkdir /etc/ansible/roles/mysql/{
    
    files,templates,tasks,handlers,vars,defaults,meta} -p
mkdir /etc/ansible/roles/php/{
    
    files,templates,tasks,handlers,vars,defaults,meta} -p

touch /etc/ansible/roles/httpd/{
    
    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
------编写httpd模块------
写一个简单的tasks/main.yml
vim /etc/ansible/roles/httpd/tasks/main.yml
- name: install apache
  yum: name={
    
    {
    
    pkg}} state=latest
- name: start apache
  service: enabled=true name={
    
    {
    
    svc}} state=started
 
//定义变量:可以定义在全局变量中,也可以定义在roles角色变量中,一般定义在角色变量中
vim /etc/ansible/roles/httpd/vars/main.yml
pkg: httpd
svc: httpd

-------编写mysql模块-------
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

-------编写php模块-----
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

-----编写roles示例-----
vim /etc/ansible/site.yml
---
- hosts: webservers
  remote_user: root
  roles:
   - httpd
   - mysql
   - php


cd /etc/ansible
ansible-playbook site.yml

Guess you like

Origin blog.csdn.net/m0_74412260/article/details/131991131