当前位置:网站首页>Ansible learning summary (9) -- ansible loop, condition judgment, trigger, processing failure and other task control use summary
Ansible learning summary (9) -- ansible loop, condition judgment, trigger, processing failure and other task control use summary
2022-07-07 17:40:00 【Technology d life】
One 、 Simple cycle
Use loop Format of assignment list :
loop: ## Assignment list
- value1
- value2
- ...
{
{item}} ## Iteration variable name
stay playbook Use in
vim user.yml
---
- name: create user
hosts: server2
tasks:
- name: create user
user:
name: "{
{item}}" ## Iteration variable name
state: present
loop: ## Assignment list
- user1
- user2
- user3
User setup succeeded
Defining variables
vim user_list.yml
---
USERS: ## Defining variables
- user1
- user2
- user3
To write yaml file
vim user.yml
---
- name: create user
hosts: server2
vars_files: ./user_list.yml
tasks:
- name: create user
user:
name: "{
{item}}"
state: absent
remove: yes
loop:
"{
{USERS}}" ## There is no need to add... When assigning values here -
Delete user succeeded
Two 、 Circular hash or dictionary list
Give different services different states
Example : by server3 Host setup user , And give the password ( The password here must be encrypted , Use rhel8
Of openssl passwd -6
Encrypt the password ).
vim user.yml
---
- name: create user
hosts: server3
tasks:
- name: create user
user:
name: "{
{ item.user }}"
password: "{
{ item.passwd }}"
state: present
loop:
- user: user1
passwd: "$6$P2MmG.dGe59uEe0R$SVmq6oojHWvYVK.BZhmL7pWjb7zVKRkUM.Rp2kFbLtl7jS570ZClaVPRZkX9BtfkqlLLCbTrlG7a04YRi/wz3."
- user: user2
passwd: "$6$YZcSU4GwSVBnw.ro$wQ0fAO9lB2M1Nwu9tVyBoGiEV/qOzQGBY.UHw2pQiq0GEjYpNW3c2FtG/wWZ0iVpqZi.iCo1x18LjpJg9tGTK/"
- user: user3
passwd: "$6$lqv/hz7ynndCR9NR$BmhKzFUsW4XzP9x9eAXv782gYBnxWUGFnh1qYExYwof5PSPk36GnlDKjjeygCSohM0cpncmk.1mkljEAgX3FQ1"
Test connection :
3、 ... and 、 conditional
Both conditions are met at the same time
when:
- Conditions 1
- Conditions 2
One of the conditions
when:
- Conditions 1 or Conditions 2
# It can also be expressed as
when:
- Conditions 1
or
Conditions 2
Example : Check whether the file exists (ignore_errors: yes
: When the file does not exist , The system will determine the failure , no return value , Add this parameter to ignore the error ).
vim exist.yml
---
- name: test
hosts: demo
tasks:
- name: test
shell: test -e /mnt/file ## Use shell The module detects whether the file exists
ignore_errors: yes
register: OUTPUT ## Register the results to OUTPUT Variable
- name: show message
debug:
msg: /mnt/file is exist
when: OUTPUT.rc == 0 ## Output result rc Part of it is 0, File exists
- name: show message
debug:
msg: /mnt/file is not exist
when: OUTPUT.rc == 1 ## Output result rc Part of it is 1, file does not exist
stay server4 Create... On the host /mnt/file
, stay server2 and server3 Do not create , perform yaml file
Definition of condition judgment
Example : Add disks , Use conditional statements to detect the disk ( by server2 Add disk to host )
adopt ansible Statement can detect
ansible server2 -m shell -a "fdisk -l /dev/vdb"
To write yaml file , Detect the presence of vdb disk
vim vdb.yml
---
- name: test
hosts: demo
tasks:
- name: show message
debug:
msg: /dev/vdb is exist
when:
- ansible_facts['devices']['vdb'] is defined ##vdb In existence
- inventory_hostname in "server2" ##hostname by server2 when , The above conditions must be met at the same time
- name: show message
debug:
msg: /dev/vdb is not find
when:
- ansible_facts['devices']['vdb'] is not defined
or
inventory_hostname not in "server2" ##vdb Does not exist or hostname Not for server2 when , You can also write a line
perform yaml file , Get the results
3、 ... and 、 trigger
notify
: Trigger triggers when a change is encounteredhandlers
handlers
: The action performed after the trigger is triggered
Example : Installation and downloading vsftpd And modify the access home directory ( To write yaml file )
vim vsftpd.yml
---
- name: vsftpd
hosts: server4
tasks:
- name: install vsftpd
yum:
name: vsftpd
state: present
- name: start vsftpd
service:
name: vsftpd
state: started
enabled: yes
notify:
- firewalld ## When vsftpd The service is set to start automatically , Trigger firewalld modular
- name: vsftpd.conf
lineinfile:
path: /etc/vsftpd/vsftpd.conf
line: "anon_root=/mnt" ## Modify access home directory
regexp: "^anon_root" ## Replaced line
backrefs: no ## Replace when matching , No match, then , Add a line at the end of the file
notify:
- restart vsftpd ## When the file is replaced , Trigger the module to restart the service
handlers: ## Triggered module , Pay attention to the relationship between here and tasks alignment
- name: firewalld
firewalld:
service: ftp
state: enabled
permanent: yes
immediate: yes
- name: restart vsftpd
service:
name: vsftpd
state: restarted
perform yaml file
stay server4 Of /mnt/file
Add content to , Anonymous access testing
Four 、 Handling failed tasks
ignore_errors
effect : When play When a task fails, it will terminate (ignore_errors: yes
The task failure will be ignored and the following tasks will continue to run )
Example : Install a non-existent service
vim ignore.yml
---
- name: ignore_errors
hosts: server3
tasks:
- name: install haha
yum:
name: haha
state: present
ignore_errors: yes ## Ignore mistakes
- name: debug
debug:
msg: heloo lll
force_handlers
effect : When the task fails play If terminated, the trigger process will also be called
Example : Install a non-existent service , Task failed play There will still be triggers after termination ( Pay attention to removal ignore_errors: yes Interference of )
vim force.yml
---
- name: force_handlers
hosts: server3
force_handlers: yes ## After the task fails, it still triggers
tasks:
- name: hostname
shell:
hostname
register: info ## Use registered variables
notify:
- debug
- name: install haha
yum:
name: haha
state: present
handlers:
- name: debug
debug:
msg: "{
{ info['stdout'] }}" ## Show variables info The output variable of
changed_when
effect : Controls when a task reports that it has made changes , Suppress changes
Example : test changed_when: true
vim changed.yml
---
- name: test
hosts: server4
tasks:
- name: install vsftpd
yum:
name: vsftpd
state: present
changed_when: true ## When detected vsftpd After installation ( Whether just installed or previously installed ), The report has changed
server4 Of vsftpd Has been installed before , Should be displayed in green , But it's yellow here
Example : test changed_when: false
vim changed.yml
---
- name: test
hosts: server4
tasks:
- name: remove vsftpd
yum:
name: vsftpd
state: absent
changed_when: false ## When detected vsftpd When uninstalled , The report does not change
Uninstall... Here vsftpd, There should be a change to yellow , But it's green
failed_when
effect : When the conditions are met, the mandatory task fails , But it doesn't change the behavior of the task itself
Example : create file , Report errors , But the essence has been established
vim failed.yml
---
- name: test
hosts: server2
tasks:
- name: touch file
file:
path: /mnt/failedfile
state: touch
failed_when: true ## An error is reported after the file is created
But the actual file was created successfully
example : Create a file in a directory that does not exist , But report success
vim failed.yml
---
- name: test
hosts: server2
tasks:
- name: touch file
file:
path: /mnt/haha/linuxfile
state: touch
failed_when: false ## No error is reported when the file is not created
Naturally, the file was not created
block
block
: Define the tasks to runrescue
: Define whenblock
The task that runs after a failed task appears in the sentencealways
: Define the tasks that will eventually run independently
Example 1: here /mnt/file
There is
vim block.yml
---
- name: test
hosts: server4
tasks:
- name: check file
block:
- name: test
shell: test -e /mnt/file
- name: debug
debug:
msg: /mnt/file is exist
rescue:
- name: debug
debug:
msg: /mnt/file is not exist
always:
- name:
debug:
msg: good night!
therefore block There is no failure in the sentence , So it won't execute rescue modular
Example 2: here /mnt/file
non-existent , Re execution block.yml
, because block There is a failure in the sentence , So execute rescue modular
边栏推荐
- swiper左右切换滑块插件
- 做软件测试 掌握哪些技术才能算作 “ 测试高手 ”?
- Pytorch中自制数据集进行Dataset重写
- 本周小贴士#141:注意隐式转换到bool
- 《世界粮食安全和营养状况》报告发布:2021年全球饥饿人口增至8.28亿
- Devops' operational and commercial benefits Guide
- With the latest Alibaba P7 technology system, mom doesn't have to worry about me looking for a job anymore
- 麒麟信安加入宁夏商用密码协会
- 跟奥巴马一起画方块(Lua)
- 企业即时通讯软件是什么?它有哪些优势呢?
猜你喜欢
<代码随想录二刷>链表
Cartoon | who is the first ide in the universe?
网络攻防复习篇
Face recognition attendance system based on Baidu flying plasma platform (easydl)
Supplementary instructions to relevant rules of online competition
使用OneDNS完美解决办公网络优化问题
serachview的功能和用法
【分布式理论】(二)分布式存储
Devops' operational and commercial benefits Guide
麒麟信安中标国网新一代调度项目!
随机推荐
基于百度飞浆平台(EasyDL)设计的人脸识别考勤系统
自动化测试:Robot FrameWork框架大家都想知道的实用技巧
The computer cannot add a domain, and the Ping domain name is displayed as the public IP. What is the problem? How to solve it?
What is cloud computing?
PLC: automatically correct the data set noise, wash the data set | ICLR 2021 spotlight
Dragging the custom style of Baidu map to the right makes the global map longitude 0 unable to be displayed normally
做软件测试 掌握哪些技术才能算作 “ 测试高手 ”?
Matplotlib绘制三维图形
YARN Capacity Scheduler容量调度器(超详细解读)
actionBar 导航栏学习
A tour of grpc:03 - proto serialization / deserialization
【网络攻防原理与技术】第5章:拒绝服务攻击
Functions and usage of viewflipper
目标管理【管理学之十四】
Functions and usage of ratingbar
Several best practices for managing VDI
麒麟信安操作系统衍生产品解决方案 | 存储多路径管理系统,有效提高数据传输可靠性
第二十四届中国科协湖南组委会调研课题组一行莅临麒麟信安调研考察
[video / audio data processing] Shanghai daoning brings you elecard download, trial and tutorial
LeetCode 890(C#)