Chapter 4, very important playbook script writing

When an article requires readers to chew slowly, it can be understood after combining it with practical operations.

1. Preliminary introduction to the playbook module

Take a simple playbook as an example to illustrate yamlthe basic grammar

  1. yaml file - - - 开头to indicate that it is a yaml language file, just like commonly used shell script files declare that #!/bin/bash it is a shell script file at the beginning. But even if you don't start with - - -, it will have no effect.
  2. Use "#" as a comment in yaml, you can comment the entire line, or you can comment the content starting with "#" in the line.
  3. Strings in yaml usually don't need any quotes, even if they contain some special characters. But there are situations where quotation marks are necessary " ", the most common being 在引⽤变量when.

When a single variable needs to be called separately, it must be quoted

4. The writing format of Boolean values
​​(we generally use yes or NO) can also be expressed in true/false. In fact, the Boolean value type in the playbook is very flexible and can be divided into two cases:

(1) Parameters of the module (included with the system): At this time, the boolean value is directly parsed by ansible as a string. Accept yes/on/1/true/no/of f /0/false and other parameters, which are then parsed by ansible. For example update_cache=yes in the above example.

(2) Non-module parameters: At this time, the boolean value is parsed by the yaml interpreter, which completely follows the yaml syntax. Accepts true/yes/on/y/f alse/no/off /n case insensitive. For example gpgcheck=no and enabled=True above. It is recommended to follow the official specification of ansible. The boolean parameters of modules adopt yes/no, and the boolean parameters of non-modules adopt True/False

5. The content of the playbook

  • Each play operation should contain one hosts(必须存在) and one tasks值(when the role value sometimes does not exist), (unless the second play is defined).

  • hosts defines inventory(主机清单)the hosts to be controlled, and tasks defines a series of task task lists, such as calling various modules. These tasks are executed one at a time in sequence, until all the filtered hosts have executed the task before moving to the next task to perform the same operation.

  • It should be noted that although only the filtered hosts (which will read the list by default) will execute the corresponding task, all hosts (here all hosts refer to those hosts specified by the hosts option) will receive the same task command, after all hosts receive the command,ansible主控端会筛选某些主机并将命令打包为.py的脚本,并通过ssh在远程执⾏任务。

6. Judgment result rules
can be judged based on each execution of the command

changed=2 controlled node changed
unreachable=0 controlled=node unreachable (number appears).

YAML dictionary (commonly used)
The key/value pairs used in YAML are also called dictionaries, hashes, or associative arrays. In key/value pairs, keys and values ​​are separated by separators consisting of colons and spaces. For example
:

 name: 
 svcrole 
 svcservice: http 
 svcport: 80  

Dictionaries can also be represented using inline block format, where multiple key/value pairs are enclosed in curly braces and separated by commas and spaces

  • {name: svcrole, svcservice: http, svcport: 80}

7. YAML list

  • In YAML, lists are similar to arrays in other programming languages. To represent a set of list items, use a dash followed by a space as the prefix of each list item, in a row-by-row method hosts: - server1 - server2
    list Inline blocks can also be used.
    Multiple list items are enclosed in square brackets and separated by commas and spaces hosts: [server1, server2]

8. The pre-execution of the playbook uses
ansible-playbook to run the script, and -C tests the running results. It does not actually execute the task, but only simulates it.

[student@server ansible]$ ansible-playbook aa.yml -C

YAML syntax and playbook writing
Playbook runs by accumulating modules one by one

insert image description here

Ansible's playbook uses yaml syntax, which simply implements the event description in json format. Before learning ansible playbook, it is necessary to sort out the grammatical format and reference method of yaml.

The basic writing ansible-docis similar to the template in the help document

yaml list:
need to end with yml suffix name
and write in yaml dictionary (this is the most commonly used)

Two, playbook operation example

1. Build a warehouse demonstration

[student@server ansible]$ vim aa.yml
---
- name: test              //某个横杠和冒号都需要接空格
 Hosts : node1           //定义自己的主机名
 tasks:                //任务清单
	- name:  mount cdrom            //自定义子目录中的名字
      mount:
	    src: /dev/cdrom
		dath: /mnt
		fstype: iso9660
		state: mounted


   - name: set repo1    //每个子模块下面需要缩进2字符
     yum_repository:
       file: server
       name: aa
       description: aa1
       baseurl: file:///mnt/BaseOS
       enabled: yes
       gpgcheck: no
       
   - name: set repo2
     yum_repository:
       file: server
       name: bb
       description: bb1
       baseurl: file:///mnt/AppStream
       enabled: yes
       gpgcheck: no
  • Direct input and automatic alignment
    Every time: a space is required after the newline input

//Run the command.
It should be noted that when an error occurs in a node in the middle, the following programs will not run

[student@server ansible]$ ansible-playbook aa.yml 

PLAY [test] ********************************************************************

TASK [Gathering Facts] *********************************************************
ok: [node1]

TASK [mount cdrom] *************************************************************
ok: [node1]

TASK [set repo1] ***************************************************************
changed: [node1]

TASK [set repo2] ***************************************************************
changed: [node1]

PLAY RECAP *********************************************************************
node1                      : ok=4    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

2. Install httpd instance

Example 1:
1. Install httpd

//server本机安装
[root@server html]# systemctl restart httpd
[root@server html]# systemctl enable --now httpd
Created symlink /etc/systemd/system/multi-user.target.wants/httpd.service → /usr/lib/systemd/system/httpd.service.
[root@server html]# ss -antl | grep httpd
[root@server html]# ss -antl | grep 80
LISTEN 0      128          0.0.0.0:80        0.0.0.0:* 
//防火墙处于关闭中
[root@server html]# systemctl status firewalld
● firewalld.service - firewalld - dynamic firewall daemon
   Loaded: loaded (/usr/lib/systemd/system/firewalld.service; disabled; vendor>
   Active: inactive (dead) 
[root@node1 www]# cat /var/www/html/index.html 
my name is liutianyang

后映射软连接就有了
[root@node1 www]# pwd
/www
[root@node1 www]# cat index.html 
my name is liutianyang

2、	开机自启
3、	给/var/www/html目录创建软链接/www

[student@server ansible]$ cat aa.yml 
---
- name: test
  hosts: node1
  tasks: 
   - name: mount cdrom
     mount: 
       src: /dev/cdrom
       path: /mnt
       fstype: iso9660
       state: mounted

   - name: set repo1                //定义好第一个yum源
     yum_repository: 
       file: server
       name: aa
       description: aa1
       baseurl: file:///mnt/BaseOS
       enabled: yes
       gpgcheck: no

   - name: set repo2              //定义第二个
     yum_repository: 
       file: server
       name: bb
       description: bb1
       baseurl: file:///mnt/AppStream
       enabled: yes
       gpgcheck: no

   - name: install httpd         //为node1安装httpd
     yum: 
       name: httpd
       statr: present

   - name: create link         //将本机的httpd网页存放目录映射为受控机的/www
     file: 
       src: /var/www/html
       dest: /www
       state: link

name: get file    //定义拉取
     get_url:
       url: http://servera.example.com/index.html
       dest: /www

   - name: set selinux context     //这里由于是映射,需要修改数值
     sefcontext: 
       target: /www/index.html    //受控机绝对路径
       setype: httpd_sys_content_t     //设置的值

   - name: apply context     //在次刷新数值
     shell: 
       cmd: restorecon -Rv /www/index.html

- name: modify apache config     //将其受控主机默认网页访问目录改为自己映射的/www
     replace: 
       path: /etc/httpd/conf/httpd.conf
       regexp: DocumentRoot "/var/www/html" 
       replace: DocumentRoot "/www"     //替换


   - name: modify apache config2
     replace: 
       path: /etc/httpd/conf/httpd.conf
       regexp: <Directory "/var/www">
       replace: <Directory "/www">

   - name: restart httpd      //将apache设为开机自启动
     service: 
       name: httpd
       state: restarted
       enabled: yes

   - name: set firewalld for http     //添加http放行防火墙规则
     firewalld: 
       service: httpd
       state: enabled
       permanent: yes

When running the script, an error may be reported due to our careless typo
//The subdirectory-name used at this time will come in handy (know there is a mistake at a glance)
insert image description here

//It turned out that the firewall rules in the configuration file were marked as httpd
insert image description here

//success

The default battle point that has been replaced here is similar to the proxy module
[root@node1 html]# vim /etc/httpd/conf/httpd.conf
DocumentRoot “/www”
<Directory “/www”>

4. Download from http://server.example.com/index.html to /www
5. Can visit the web site, documentroot is /www

[student@server ansible]$ curl http://node1
my name is liutianyang

2. Conditional judgment usage

Example 2:

notify handlers用法(当完成….任务时,则进行….任务)
[root@server ansible]# cat test.yml 
---
- name: this is a test playbook
hosts: node1
tasks: 
- name: create user1
   user: 
     name: user1
     state: present

  - name: create user2
    user: 
     name: user2
     state: present
    notify:               //当只有创建第二个user2时notify才会触发handlers程序去执行对应的任务
     - file3

 handlers:      //这里需与第一集目录相对应
  - name: file3      //指定file3如果user2创建则触发则执行命令,如果u2不触发则不会运行
    file: 
     path: /tmp/cy1
     state: touch
     mode: 0644

Example 3:
1. Write a script runtime.yml, which only operates on node1
2. Create user aa, which cannot be used for login, home directory /www
3. Create a file html in /www
4. Every time the script is executed , enter the current time of the system into the html file.
5. If the time in html changes, create a file in /tmp/kk

[student@ansible ~/ansible]$cat alone.yml
---
- name: time
hosts: node1
tasks:
- name: create user
user:
name: aa
shell: /sbin/nologin
home: /www
- name: create file
file:
path: /www/html
state: touch
- name: date
shell: date > /www/html
notify:
- kk
handlers:
- name: kk
file:
path: /tmp/kk
state: touch
[student@ansible ~/ansible]$ansible-playbook alone.yml
PLAY [time]
********************************************************************************************************
****
TASK [Gathering Facts]
*************************************************************************************************
ok: [node1]
TASK [create user]
*****************************************************************************************************
ok: [node1]
TASK [create file]
*****************************************************************************************************
changed: [node1]
TASK [date]
********************************************************************************************************
****
changed: [node1]
RUNNING HANDLER [kk]
***************************************************************************************************
changed: [node1]
PLAY RECAP
********************************************************************************************************
*****
node1 : ok=5 changed=3 unreachable=0 failed=0 skipped=0 rescued=0
ignored=

[root@node1 ~]# ls /tmp/
aa
ansible_setup_payload_d9nvajm5
b
d
ggg
hhh
kk

3. Examples of tags tags

Example: 4:
Tags usage: to tag tasks, a task can have multiple tags,
parameters -tto specify the task tags that need to be specified.
tags
l2
l3
are generally placed at the end of the template command and can be called directly at runtime

Note:
In fact, ansible also presets 5 special tags, which can be executed separately when executing some commands.
1. always: If this tag is added, it will be executed regardless of whether the command line specifies the task

tag:
-	 always

2. never: do not execute the label

	tag:
-	 never

3. tagged: use -t tagged during execution to only execute tasks with tags (tags)

[student@server ansible]$ ansible-playbook aa.yml -t tagged

4. Untagged: Use -t untagged during execution to only execute untagged tasks, including always tags

[student@server ansible]$ ansible-playbook aa.yml -t untagged

5. all: execute all tasks, default label.

6. Custom dictionary label:

Multiple tags can be used at the same time, need to be separated by ","
--tags package,service playbook.yml

Check the label type of tag
ansible-playbook –list-tags playbook.yml

//demonstration

[student@server ansible]$ cat test2.yml 
---
 - name: test playbook
  hosts: node1
  tasks: 
    - name: create user3
      user: 
        name: user3
        state: present
      tags: 
        - l1
        - l2 
    
    - name: create user4
      user:
        name: user4
        state: present
      tags: 
        - l2
        - l3

    - name: create user5
      user: 
        name: user5
        state: present
      tags: 
        - l3
        - l4

只执行l2标签的
[student@server ansible]$ ansible-playbook  test2.yml  -t  l2
  • ansible-playbook --skip-tags l1 test2.yml — skip l1, other executions, except never
  • ansible-playbook --tags always test2.yml -- only execute the always tag
  • ansible-playbook --tags tagged test2.yml --Execute tagged tasks, except never tags
  • ansible-playbook --tags untagged test2.yml --Execute untagged tasks, but always still execute
  • ansible-playbook --tags never test2.yml --Execute the never tag task, but always still execute

Text can add parameters

Writing:
Tags:
always

4. template module

Supplement: template module
1, the use method of the template module is basically the same as the copy module, but when the copy module copies files from the local ansible node to the controlled node, the content of the source file is what it is and cannot be changed; while using the template module to copy When using a file, the content of the source file can vary from one host to another.

2. When using the template module to write file variables on the server side, the extension of the file must be ".j2".

Example 1: Create a template file html.j2, the content of which is that
The 【受控主机的hostname】 address is 【IP地址】(需要随着受控主机的不同,文件的内容而发生变化)
each host will have its own fact variable

1、编辑文件html.j2
[student@server ansible]$ cat html.j2 
the {
   
   {ansible_fqdn}} address is {
   
   {ansible_ens160.ipv4.address}}

2. Write a playbook, copy the template file to the /tmp/ directory of the controlled host, and rename it to html

[student@server ansible]$ vim a.yml
---
- name: test
  hosts: node1,node2
  tasks:
    - name: cp html.j2
      template:
        src: /etc/ansible/html.j2
        dest: /tmp/html

3、执行该playbook
Ansible-playbook  a.yml


4、分别去node1和node2两台受控主机中去验证,变量验证成功
Node1: 
[root@node1 ~]# cat /tmp/html 
the node1.example.com address is 172.16.30.10
[root@node1 ~]# 

Node2:
[root@node2 ~]# cat /tmp/html 
the node2.example.com address is 172.16.30.20
[root@node2 ~]# 

6. Copy module

Example 5:
Copy module:
Create a playbook named /home/student/ansible/b.yml.
The playbook runs on all list hosts.
The content of the playbook is:
if the content of the /tmp/chenyu file of the controlled host is copied Replace it with the following:
On the hosts in the net host group, this line of text displays: chenyu
On the hosts in the hr host group, this line of text displays: cy123

[student@server ansible]$cat hosts
[net]
node1

[hr]        //主机组
node2

1、撰写剧本
[student@server ansible]$ vim b.yml
---
- name: test
  hosts: all
  tasks:
    - name: cp file
      copy:
        content: |      //判断当主机显示是那列hosts,则执行命令
          {
   
   % if "net" in group_names %}   //group…内置变量,if 则用来找清单中的主机组
          Chenyu                     //判断成功后则显示文本内容
          {
   
   % elif "hr" in group_names %}   
          cy123
          {
   
   % endif %}      //结束
        dest: /tmp/chenyu   //对受控主机的次目录进行执行

2、执行该剧本
Ansible-playbook  b.yml

3、验证:
Node1:
[root@node1 ~]# cat /tmp/chenyu 
chenyu
[root@node1 ~]# 

Node2:
[root@node2 ~]# cat /tmp/chenyu 
cy123
[root@node2 ~]# 

Guess you like

Origin blog.csdn.net/cxyxt/article/details/127549709