当前位置:网站首页>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
边栏推荐
猜你喜欢
随机推荐
目标管理【管理学之十四】
无法链接远程redis服务器(解决办法百分百)
状态模式 - Unity(有限状态机)
redis主从、哨兵主备切换搭建一步一步图解实现
L1-023 输出GPLT(Lua)
Establishment of solid development environment
MRS离线数据分析:通过Flink作业处理OBS数据
Problems encountered in Jenkins' release of H5 developed by uniapp
Examen des lois et règlements sur la sécurité de l'information
Solid function learning
Biped robot controlled by Arduino
字符串 - string(Lua)
命令模式 - Unity
Functions and usage of viewswitch
Vscode three configuration files about C language
Please insert the disk into "U disk (H)" & unable to access the disk structure is damaged and cannot be read
麒麟信安携异构融合云金融信创解决方案亮相第十五届湖南地区金融科技交流会
[video / audio data processing] Shanghai daoning brings you elecard download, trial and tutorial
MySQL index hit level analysis
什么是敏捷测试