Table of contents
Loop cycle based on external variables
By magic variables, fact variables as conditions
Use the variable of the script execution result as a condition
Handle failed tasks ignore_errors
The handler force_handlers corresponding to the task that failed to enforce
Specifies the condition failed_when for task failure
Handle error tasks via Ansible block
Ansible Loop cycle
Use loop statements in the playbook to perform tasks in batches (such as creating users in batches, installing applications in batches, etc.)
Define the list of elements to be looped in the loop keyword, and then extract the list of elements in the loop sequentially by fixing the variable name item
Simple Loop
创建用户admin1和admin2
---
- name: create users with loop
hosts: web
tasks:
- name: create user
user:
name: "{
{ item }}"
loop:
- admin1
- admin2
Loop loop in array list mode
创建普通用户admin1,系统用户admin2
---
- name: create users with loop
hosts: web
tasks:
- name: create user
user:
name: "{
{ item.user }}"
group: "{
{ item.shell }}"
loop:
- user: admin1
shell: /bin/bash
- user: admin2
shell: /sbin/nologin
Loop loop in dictionary mode
创建普通用户admin1,系统用户admin2
---
- name: create users with loop
hosts: web
tasks:
- name: create user
user:
name: "{
{ item.name }}"
shell: "{
{ item.shell }}"
loop:
- { name: "admin1" , shell: "/bin/bash" }
- { name: "admin2" , shell: "/sbin/nologin" }
Loop cycle based on external variables
创建普通用户admin1,系统用户admin2
定义变量文件
vim user.yml
users:
- name: admin1
shell: /bin/bash
- name: admin2
shell: /sbin/nologin
定义剧本
vim create_user.yml
---
- name: create users with loop
hosts: web
vars_files:
- user.yml
tasks:
- name: create user
user:
name: "{
{ item.name }}"
shell: "{
{ item.shell }}"
state: present
loop: "{
{ user }}"
Ansible's When Judgment
The judgment statement can be defined by the when keyword. Only when the judgment statement succeeds will the task of this module be executed, and it will not be executed if the condition is not met.
When judgment statement format
when: keep up with the judgment expression
comparison operator
== Whether both sides are equal
!= Whether both sides are not equal
: compare the size, the value on the left is greater than the value on the right
< compares the size, the value on the left is less than the value on the right
= Compare size, the value on the left is greater than or equal to the value on the right
<= compares the size, the value on the left is less than or equal to the value on the right
Logical Operators
and logic and; only when they are satisfied can they succeed
or Logical or; as long as one of the conditions is met, it succeeds
not Logical negative; negates the expression
() combines multiple expressions together (all expressions in the combination must be satisfied at the same time)
By magic variables, fact variables as conditions
If the host belongs to a host in the web host group in the inventory, install httpd (invenrtory_hostname is a magic variable)
--- - name: yum hosts: all tasks: - name: install httpd yum: name: httpd state: latest when: inventory_hostname in groups.web
If the host has an IPv4 address, install httpd (ansible_facts is the fact variable)
--- - name: yum hosts: all tasks: - name: install httpd yum: name: httpd state: latest when: ansible_facts['default_ipv4']['address'] is defined
Use the variable of the script execution result as a condition
Take the rc variable as an example
When installing a software package through a script, there will be an rc variable in the execution result, and the rc variable has two values of 0 and 1
If rc=0, it means that the installation package already exists or did not exist before but the installation is successful
If rc=1, it means that the installation package does not exist and the installation fails
The execution result can be defined in a variable through the register keyword, and then the value corresponding to the rc variable in this variable can be extracted as a judgment condition (the execution result can also be displayed through the debug module)
安装httpd,并显示执行结果;如果主机上已经存在httpd,则删除httpd --- - name: install hosts: all tasks: - name: install httpd yum: name: httpd state: present register: result - name: debug debug: var: result - name: renove httpd yum: name: httpd state: absent when: result.rc == 0
Ansible handler
Ansible handlers are tasks that are triggered in response to other tasks, and the triggered tasks are handlers
Only when the response task is executed and takes effect on the managed node (the execution result is yellow), the handler will be triggered; and the handler will run after all tasks in the playbook are completed
handlers element
The handlers element belongs to the list at the same level as tasks, and is used to define handlers
Wait for the result of task execution in tasks to be changed (yellow) to trigger notify, and then call the task corresponding to this notify under handlers
notify element
The notify element is used as a trigger for handlers, defined in a certain piece of code in tasks, and juxtaposed with the module
example
当httpd和phpinfo安装成功后,开启httpd和phpinfo服务 --- - name: httpd hosts: web tasks: - name: install httpd yum: name: httpd state: present notify: - start httpd handlers: - name: start httpd service: name: httpd state: started
Precautions
The order in which handlers are executed is only related to the order in which playbooks are defined, not the order in which handlers configure notifications
The name of - name in handlers needs to be consistent with the name defined by notify
Handlers will only be triggered when called with a notify statement
The handler will be executed after all the normal tasks of the playbook are executed
The tasks in the handler will only be executed sequentially, even if a task in the handler is notified multiple times
Ansible handles failed tasks
Handle failed tasks ignore_errors
When the execution of the ansibke task fails, the execution of the playbook is aborted and all subsequent tasks are skipped
Sometimes you want to ignore the error here even when the task fails, and continue to execute subsequent tasks. At this time, you need to configure ignore_error:yes to achieve it (the ignore_error element is parallel to the module)
Precautions
Not all errors can be ignored, only when the execution success or failure of the task is not related to the subsequent tasks.
example
当php安装失败后继续执行mariadb的安装 --- - name: install hosts: server tasks: - name: install php yum: name: php state: present ignore_errors: yes - name: isntall mariadb yum: name: mariadb tate: present ignore_errors: yes
The handler force_handlers corresponding to the task that failed to enforce
If the executed task on the host fails, the handler for this task will no longer run
At this time, it can be realized by force_handlers: yes , even if the response task corresponding to notify fails to execute, the handler corresponding to nottify will continue to be executed (even if the task fails, notify will be called to trigger handlers)
force_handlers are at the same level as tasks
example
--- - name: httpd hosts: web force_handlers: yes tasks: - name: install httpd yum: name: httpd state: present notify: - start httpd handlers: - name: start httpd service: name: httpd state: started
Specifies the condition failed_when for task failure
Use failed_when to specify the conditions for task failure; that is, artificially specify the conditions for the failure of this task, and turn the normal task into a failed task (if the conditions defined by failed_when are met, it will be judged that the task execution failed)
Notice
Task execution failure does not necessarily mean that there is an error in the task (it may also be artificial)
example
如果主机属于ftp组,则显示bug模块的内容,然后中止任务 --- - name: httpd hosts: all tasks: - name: deubg debug: msg: "hostname is not web" when: inventory_hostname in groups['ftp'] failed_when: inventory_hostname in groups['ftp'] - name: copy copy: content: "Welcome to { { ansible_facts.hostname }}" dest: /var/www/index.html
Handle error tasks via Ansible block
In the playbook, tasks can be logically grouped by blocks, and error handling can be realized
The block block can be combined with rescue and always statements to implement error handling
block is at the same level as when, rescue, and always, and is located under tasks
If any task in the block block fails, execute the tasks in its rescue to proceed
block , rescue, always concepts
block: Define the main task to be run (if any task in the block fails, the tasks in the rescue will be executed sequentially)
rescue: defines the task to run when the task defined in the block clause fails
always: defines tasks that are always run independently, regardless of the success or failure of the tasks defined in the block and rescue clauses
The block task is successfully executed → go directly to the task in the always (do not execute the task corresponding to the rescue)
Block task execution failed → go to the task in rescue → go to the task in always
example
对vdc磁盘分区,分为1500m(如果磁盘无法分为1500m则分为800m),最后将磁盘格式化为ext4格式 --- - name: create /dev/vdc hosts: web tasks: - name: block block: - name: create vdc1 1000MiB parted: device: /dev/vdc number: 1 state: present part_end: 1000MiB rescue: - name: create vdc 500MiB parted: device: /dev/vdc number: 1 state: present part_end: 500MiB always: - name: create ext4 filesystem: fstype: ext4 dev: /dev/vdc1