Ansible, an automated operation and maintenance tool: (2) Explanation and application of playbook scripts

Table of contents

One: playbook overview

1.1 Playbook introduction

1.2 Ansible playbook usage scenarios

1.3yaml basic grammar rules

1.4 data structures supported by yaml

1.5 example

Two: Variables in Inventory

2.1inventor variable parameters 

Three: playbook example 

3.1 Define a remote execution user for each task 

3.2 Specify the remote host to switch the user to execute the script 

3.3tasks ignores errors and forcefully returns success 

3.4 Execute scripts for multiple host nodes 

3.5 Handlers introduction

3.6 Introducing variables 

3.6.1 passed through the ansible command parameter -e

3.6.2 Define directly in yaml, or built-in variables 

3.6.3 Reference custom variables in the host list 

3.7 Condition testing 

3.7.1 Single condition judgment

3.7.2 Multi-condition judgment 

3.7.3 Group Condition Judgment 

3.7.4 Iteration

One: playbook overview

1.1 Playbook introduction

playbook is ansible script for configuring, deploying, and managing controlled nodes. Through the detailed description of the playbook, executing a series of tasks can make the remote host reach the expected state. The playbook is like a series of to-do-lists listed by the Ansible controller to the controlled node, and the controlled node must be completed. It can also be understood in this way. The literal meaning of playbook is the script. In reality, actors perform according to the script. In Ansible, this time, the computer performs the performance, installs, deploys applications, provides external services, and organizes the computer to handle various tasks. things.

A playbook is a script, which means that
multiple plays are organized and run in a playbook by calling the ansible module through the task.

The playbook itself consists of the following parts:

  • Tasks: Tasks, that is, certain operations completed by calling modules; the principle is the same as transactions, either executed together or not executed together.
  • Variables: variables; three scenarios for declaring variables: defined in the hosts file, defined in the script, and defined with -e in the command.
  • Templates: Templates; define the same format of templates to solve the problem that each service may be incompatible due to different formats.
  • Handlers: processors, when a certain condition is met, trigger the execution of the operation
  • Roles: roles; classify and execute tasks without interfering with each other

Core elements of Playbook:

  • Hosts: host group;
  • Tasks: task list;
  • Variables: variables, there are four setting methods;
  • Templates: a text file containing template syntax;
  • Handlers: tasks triggered by specific conditions;

1.2  Ansible playbook usage scenarios

  • For some simple tasks, ad-hoc commands can be used to solve problems conveniently, but sometimes a facility is too complex and requires a lot of operations, ad-hoc commands are not suitable for execution, and it is best to use playbook at this time.
  • Just like executing shell commands and writing shell scripts, it can also be understood as a batch task , but playbook has its own syntax format.
  • Using playbooks, you can easily reuse these codes and port them to different machines. Like functions, you can maximize the use of codes. As you use Ansible, you'll also find that most of the operations you handle are writing playbooks. You can write common applications into playbooks, and then manage the server will become very simple.

1.3yaml basic grammar rules

The playbook yaml syntax is a newline and two spaces, and - and: must be followed by a space

YAML: is a non-markup language. It is a language used to write configuration files, which is very concise and powerful;

YAML syntax is similar to other languages, and can also express data structures such as hash tables and scalars

The structure is displayed by spaces, and the configuration items in the sequence are represented by -; the key values ​​in the Map are separated by:; the extension of YAML is yaml

  1. Case Sensitive
  2. Use indentation to indicate hierarchical relationships
  3. Tabs are not allowed when indenting, only spaces are allowed
  4. The number of spaces indented is not important, as long as the elements of the same level are left-aligned

Grammar introduction:

  1. In a single file, three consecutive hyphens (---) can be used to distinguish multiple files. In addition, there are optional consecutive three dots ( ... ) used to indicate the end of the file
  2. The next line begins to write the content of the Playbook normally, it is generally recommended to write the function of the Playbook
  3. Use # to comment code
  4. Indentation must be uniform, spaces and tabs cannot be mixed
  5. The level of indentation must also be consistent. The same indentation represents the same level. The program distinguishes the configuration level by combining indentation with line breaks.
  6. The content of the YAML file is case-sensitive, and the value of k/v must be case-sensitive
  7. The value of k/v can be written in the same line or in a new line. peer use:separated
  8. v can be a string or another list
  9. A complete code block function requires a minimum of elements including name: task
  10. A name can only contain one task
  11. YAML file extensions are usually yml or yaml
hosts Define nodes, which can be groups
remote_user What user are you logging in as?
tasks is your task
become:yes Indicates switching users
become_user: mysql Indicates switching to the mysql user, used in conjunction with the previous one
- name: Give a name to the action performed below

1.4 data structures supported by yaml

  1. Object: a collection of key-value pairs, also known as mapping/hashes/dictionary
  2. Array: A set of values ​​arranged in order, also known as a sequence (sequence) / list (list)
  3. scalar: a single, indivisible value

1. Object: a collection of key-value pairs, also known as mapping (mapping) / hash (hashes) / dictionary (dictionary)
For example: name: Test Developer
     variable name: object name attribute

2. Array: A set of values ​​arranged in order, also known as sequence (sequence) / list (list)
For example: -Apple
     -Green

3. Scale: a single, indivisible value
For example: number: 17.50
     variable name: value

1.5 example

---
#安装与运行mysql服务
- hosts: node1
  remote_user: root
  tasks:
 
    - name: install mysql-server package
      yum: name=mysql-server state=present
    - name: starting mysqld service
      service: name=mysql state=started

Our file name should  end in .yml , like mysql.yml in our example above. Among them, there are three parts:

hosts: Use hosts to indicate which host or host group is used to run the following tasks. Each playbook must specify hosts, and hosts can also use wildcards. The host or host group is specified in the inventory list, you can use the system default /etc/ansible/hosts, or you can edit it yourself, add the -i option when running, and specify the location of the list. When running the inventory file, the --list-hosts option will display which hosts will participate in the execution of the task.

remote_user: Specify which user in the remote host to log in to the remote system. The user who executes the task in the remote system can be specified arbitrarily, or sudo can be used, but the user must have the authority to execute the corresponding task.

tasks: Specifies a series of actions to be performed by the remote host. The core of tasks is the module of ansible, and the usage of the module has been mentioned earlier. tasks contains the name and the module to be executed. The name is optional, just for the convenience of users to read, but it is recommended to add it. The module is required, and the corresponding parameters should also be given to the module.

templates: a text file containing template syntax;

Use ansible-playbook to run the playbook file, and get the following output information, which is in JSON format. And it is composed of different colors for easy identification. Generally speaking:

| Green means the execution is successful and the system remains as it is

| Yellow means that the system means that the system status has changed

| Red means that the execution failed and the error output is displayed

Execution has three steps:

  1. collect facts
  2. execute tasks
  3. report results

Two: Variables in Inventory

Inventory is a configuration file for Ansible to manage host information, which is equivalent to the function of the system HOSTS file, and is stored in /etc/ansible/hosts by default

The host list can be set manually or dynamically generated through Dynamic Inventory

Host list:

vi /etc/ansible/hosts
[webserver] #Use square brackets to set the group name
www1.example.org #Define the host to be monitored, here can be the host name or IP address
www2.example.org:2222 #Define after the colon Remote connection port, the default is port 22 of ssh

If there are hosts with similar names, you can use a list to identify each host

[webserver]
//[01:50]表示匹配从01到50,后面跟着内置变量,这里定义了ssh的访问的用户名和密码,用于免交互登录
www[01:50].example.org ansible_ssh_user=root ansible_ssh_pass=abc123
 
[dbbservers]
//[a:f]表示支持匹配a到f
db-[a:f].example.org

Variables in Inventory

1. Host variable

[webserver]
//定义变量http_port(开放的端口信息)和maxRequestsChild(最大进程数)
www1.magedu.com http_port=80 maxRequestsChild=808
www2.magedu.com http_port=8080 maxRequestsChild=909

2. Group variables

[servers:vars]
ntp_server=ntp.example.org
nfs_server=nfs.example.org

3. Group nesting 

[apache]
http1.example.org
http2.example.org
 
[nginx]
ngx1.example.org
ngx2.example.org
//定义一个组名,将刚才定义的两个组名放入,即webservers组包含apache组和nginx组的主机
[webservers]
apache
nginx

2.1inventor variable parameters 

parameter illustrate
ansible_ssh_host If the name of the remote host to be connected is different from the alias of the host you want to set, you can set it through this variable
ansible_ssh_port ss Port number, if it is not the default port number, set it by this variable
ansible_ssh_user default ssh username
ansible_ssh_pass ssh password (this way is not secure, we strongly recommend using --ask-pass or SSH keys)
ansible_ssh_private_key_file The private key file used by ssh, suitable for situations where there are multiple keys and you don't want to use SSH agent
ansible_ssh_common_args This setting is appended to the default command line for sftp, scp and ssh
ansible_sftp_extra_args This setting is appended to the default sftp command line
ansible_scp_extra_args This setting is appended to the default scp command line
ansible_ssh_extra_args This setting is appended to the default ssh command line
ansible_ssh_pipelining Determines whether to use SSH piping. This can be overridden in ansible.cfg to get the setting
ansible_shell_type The shell type of the target system. By default, the command is executed using sh syntax, which can be set to csh or fish
ansible_python_interpreter The python path of the target host, applicable to the situation: there are multiple pythons in the system, or the command path is not "/usr/bin/python"
ansible_*_interpreter The * here can be an interpreter of ruby ​​or perl or other languages, which is similar to ansible_python_interpreter
ansible_shell_executable This will set the shell that the ansible controller will use on the target machine, overriding the configuration in ansible.cfg, which defaults to /bin/sh

Three: playbook example 

Introduction to Basic Commands

格式:
ansible-playbook [yaml文件名]
例如:ansible-playbook ping.yml
参数:-k(–ask-pass) 用来交互输入ssh密码
     -K(-ask-become-pass) 用来交互输入sudo密码
     -u 指定用户
 
补充命令:
ansible-playbook XXXX.yaml --syntax-check   #检查yaml文件的语法是否正确
ansible-playbook XXXX.yaml --list-task      #检查tasks任务
ansible-playbook XXXX.yaml --list-hosts     #检查生效的主机
ansible-playbook XXXX.yaml --start-at-task='ensure apache is at the latest version'  #指定从某个task开始运行
parameter illustrate
-k(-ask-pass) Used to enter the ssh password interactively
-K(-ask-become-pass) Used to interactively enter the sudo password
-u designated user
-e import variable value

Introduction to hosts and users

 - hosts: webserver   #指定主机组,可以是一个或多个组
   remote_user: root  #指定远程主机执行的用户名

3.1 Define a remote execution user for each task 

cd /opt
vim 1.yaml
 
- hosts: mysql
  remote_user: root
  tasks:
  - name: test connection
    ping:
    remote_user: mysql    #指定远程主机执行tasks的运行用户为mysql
	
ansible mysql -m user -a 'name=mysql'
ansible mysql -m shell -a 'echo 123123 | passwd --stdin mysql'
ansible-playbook 1.yaml -k
123123

3.2 Specify the remote host to switch the user to execute the script 

vim 2.yaml
 
- hosts: mysql
  remote_user: root
  become: yes         
  become_user: mysql   
  tasks:
  - name: copy text
    copy: src=/etc/fstab dest=/home/mysql/fstab.bak
 
ansible-playbook 2.yaml

View the copied files on the mysql host

ls /home/mysql

Multiple hosts can be written in a yaml file, and multiple host groups can be defined

vim hosts.yaml
- hosts: webserver
  remote_user: root
  tasks:
   - name: create nginx group
     group: name=nginx system=yes gid=208
   - name: create nginx user
     user: name=nginx uid=208 group=nginx system=yes
- hosts: mysql
  remote_user: root
  tasks:
   - name: copy file to mysql
     copy: src=/etc/inittab dest=/opt/inittab.back

3.3tasks ignores errors and forcefully returns success 

1. The main part of Play is the task list. The tasks in the task list are executed on the hosts specified in hosts one by one in order, that is, the first task is completed on all hosts before starting. When running the playbook (executed from top to bottom), if a host fails to execute the task, the entire tasks will be rolled back, please correct the error in the playbook, and then re-execute, that is, the purpose of the task is to execute the module with the specified parameters, and in Variables can be used in module parameters, and the module is idempotent when executed, which means that multiple executions are safe because the result is certain.
2. Each task must have a name, so that when running the playbook, it can be well identified which task it belongs to from the task execution information output by it.
3. Define a task, the common format: "module: options" For example: yum: name =httpd
4. Among the built-in modules of ansible, the command module and the shell module do not need to use the key=value format

Error example: the task automatically stops when an error is encountered, and the apache service will not continue to install

vim 3.yaml
 
- hosts: webserver
  remote_user: root
  tasks:
  - name: stop selinux
    command: '/usr/sbin/setenforc 0'
  - name: install httpd
    yum: name=httpd
  - name: start httpd
    service: name=httpd state=started
 
ansible-playbook 3.yaml

Add ignore_errors: True to ignore errors, and continue to execute after an error is reported 

vim 3.yaml
 
- hosts: webserver
  remote_user: root
  tasks:
  - name: stop selinux
    command: '/usr/sbin/setenforc 0'
    ignore_errors: True
  - name: install httpd
    yum: name=httpd
  - name: start httpd
    service: name=httpd state=started
                                                   
ansible-playbook 3.yaml                       

3.4 Execute scripts for multiple host nodes 

vim 4.yaml
  
- hosts: webserver
  remote_user: root
  tasks:
  - name: remove httpd
    yum: name=httpd state=absent
 
- hosts: mysql
  remote_user: root
  tasks:
  - name: copy file
    copy: src=/etc/fstab dest=/opt/haha.txt

3.5 Handlers introduction

Handlers are also a list of tasks, which are no different from ordinary tasks.
The notify is performed by the notifier. If it is not notified, the Handlers will not be executed. If it is notified, the Handlers will be executed. No matter how many notifiers have notified, after all the tasks in the play are executed, the handlers will also be executed. will only be executed once

vim 5.yaml
 
- hosts: webserver
  remote_user: root
  tasks:
  - name: remove httpd
    yum: name=httpd state=absent
 
  - name: start firewalld
    service: name=firewalld state=started
 
  - name: setenforce 0 && install httpd
    command: '/usr/sbin/setenforce 0'
    notify:
    - step one
 
  - name: stop firewalld && start httpd
    service: name=firewalld state=stopped
    notify:
    - step two
 
  handlers:
 
  - name: step one
    yum: name=httpd
 
  - name: step two
    service: name=httpd state=started
 
 
ansible-playbook 5.yaml

3.6 Introducing variables 

There are three ways to introduce variables into playbook:

  1. passed through the ansible command parameter -e
  2. Define directly in yaml
  3. Refers to variables defined in the host manifest

3.6.1 passed through the ansible command parameter -e

执行命令: ansible-playbook a.yml -e "user=wangwu"
 
执行命令查看: ansible mysql -m command -a 'tail /etc/passwd'
vim 6_1.yaml
 
- hosts: mysql
  remote_user: root
  vars:
  - user:
  tasks:
  - name: add user
    user: name={
   
   {user}}
 
ansible-playbook 6_1.yaml -e "user=wangwu"
ansible mysql -a 'tail -1 /etc/passwd'

3.6.2 Define directly in yaml, or built-in variables 

vim 6_2.yaml
 
- hosts: mysql
  remote_user: root
  vars:
  - user: lisi
  tasks:
  - name: add user
    user: name={
   
   {user}}
 
ansible-playbook 6_2.yaml
ansible mysql -a 'tail -1 /etc/passwd'
vim 6_2.yaml
 
- hosts: mysql
  remote_user: root
  tasks:
  - name: copy file
    copy: content="{
   
   {ansible_all_ipv4_addresses}}" dest=/opt/vars.txt
 
ansible-playbook 6_2.yaml
ansible mysql -a 'ls /opt'
ansible mysql -a 'cat /opt/vars.txt'

3.6.3 Reference custom variables in the host list 

vim /etc/ansible/hosts
 
[webserver]
192.168.184.20
[mysql]
192.168.184.30  user=zhaoliu
 
vim 6_3.yaml
 
- hosts: mysql
  remote_user: root
  tasks:
  - name: add user
    user: name={
   
   {user}}
 
ansible-playbook 6_3.yaml
ansible mysql -a 'tail -1 /etc/passwd'

3.7 Condition testing 

If you need to use variables, facts (setup) or the execution results of previous tasks as a prerequisite for the execution of a task, you need to use conditional testing, which is used in conditional testing in Playbook. Add when clause after task to use conditional test: when clause supports jinjia2 expression or syntax

3.7.1 Single condition judgment

vim 7_1.yaml
 
 - hosts: mysql
   remote_user: root
   tasks:
     - name: "shutdown CentOS"
       command: /sbin/shutdown -h now
       when: ansible_distribution == "CentOS"
 
ansible-playbook 7_1.yaml

3.7.2 Multi-condition judgment 

vim 7_2.yaml
 
- hosts: mysql
  remote_user: root
  tasks:
  - name: "shut down CentOS 7 systems"
    command: /sbin/shutdown -r now
    when:
    - ansible_distribution == "CentOS"
    - ansible_distribution_major_version == "7"
 
ansible-playbook 7_2.yaml

3.7.3 Group Condition Judgment 

vim 7_3.yml
 
- hosts: mysql
  remote_user: root
  tasks:
  - name: "shut down CentOS 6 and Debian 7 systems"
    command: /sbin/shutdown -t now
    when: (ansible_distribution == "CentOS" and ansible_distribution_major_version == "6") or (ansible_distribution == "Debian" and ansible_distribution_major_version == "7")
 
ansible-playbook 7_3.yaml

3.7.4 Iteration

When there are tasks that need to be performed repeatedly, an iterative mechanism can be used. Its usage format is to define the content that needs to be iterated as an item variable reference, and specify the iteration through the with_items statement.

vim 7_5.yaml
 
- hosts: webserver
  remote_user: root
  tasks:
  - name: install
    yum: name={
   
   {item}} state=latest
    with_items:
    - httpd
    - rpcbind
    - nfs-utils
 
ansible-playbook 7_5.yaml
ansible webserver -a 'rpm -q httpd'
ansible webserver -a 'rpm -q rpcbind'
ansible webserver -a 'rpm -q nfs-utils'

You can also define item variables yourself 

vim 7_5.yaml
 
- hosts: webserver
  remote_user: root
  tasks:
  - name: add user && join group
    user: name={
   
   {item.x}} state=present group={
   
   {item.y}}
    with_items:
    - {x: 'qianqi', y: 'wheel'}
    - {x: 'sicong', y: 'root'}
 
ansible-playbook 7_5.yaml
ansible webserver -a 'tail -2 /etc/passwd'

Among them:
name indicates the name of the software package to be operated;
state indicates what operation to do;
present: default, means installation;
lastest: install the latest version;
absent: means delete.

Guess you like

Origin blog.csdn.net/ver_mouth__/article/details/126214769