This article contains modules
- error
- tags
- handlers
- when
- register
- debug
- with_items
- include and roles
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Module error
- Ansible-playbook's handling of errors
-the default judgment is $?. If the value is not 0, stop execution
-but in some cases we need to ignore the error and continue execution
-for example, create a cache directory, and then restart apache
---
- hosts: web1
tasks:
- shell: mkdir /tmp/cache
- name: reload httpd
service:
name: httpd
state: restarted
- Error handling method
--ignore_errors: the way to deal with errors-
True means ignore the error and continue execution
-False means stop execution when encountering an error
-Default False
-Handling method:
- name: run some command
shell: /usr/bin/somecommand
ignore_error: True
Module tags
- tags: Define a call tag for the specified task
- Use format:
– name: NAME
– module: arguments
–tags:TAG_ID - How to call playbook
--t TAGS, --tags= TAGS - Modify the yml of httpd configuration
tasks: - copy: src: httpd.conf dest: /etc/httpd/conf/httpd.conf - template: src: index.html dest: /var/www/html/index.html owner: apache group: apache mode: 0644
- Set tags
- name: modify index.html copy: src: index.html dest: /var/www/html/index.html owner: apache group: apache mode: 0644 tags: update_index
- Call flag
ansible-playbook conf.yml -t update_index
Module handlers
- Actions taken when the resource of interest changes
- The notify action can be used to be triggered at the end of each play, so as to avoid performing the specified operation every time when multiple changes occur, and instead only perform the specified operation once after all changes have occurred.
- The operations listed in notify are called handlers, that is, notify calls the operations defined in the handler
- Apache was installed earlier, the httpd configuration file was modified, and the configuration file was reloaded to make the service take effect
- Use handlers to achieve
handlers:
- name: reload httpd
service:
name: httpd
state: restarted
- Combined with the previous example, use handlers
tasks:
- name: modify httpd.conf
copy:
src: httpd.conf
dest: /etc/httpd/conf/httpd.conf
tags: update_conf
notify: reload httpd
handlers:
- name: reload httpd
service:
name: httpd
state: restarted
!!!Precautions:
– Notify calls the string defined by the name of the handler segment, which must be consistent, otherwise the trigger effect will not be achieved
. When multiple tasks trigger the same notify, the same service will only be triggered once
. Notify can trigger multiple conditions. The production environment often involves a scenario where a configuration file changes and several services need to be restarted. The handler is very suitable for use here
-combined with vars, very common service management scripts can be written
Exercises for the error/tags/handlers module
- Install Apache software configuration file
- Reload the configuration file for the service to take effect
- Use handlers to achieve
Step 1: error
The playbook is executed in order from top to bottom. If an error is reported, the following commands will not be executed. If you want to solve it, you can use ignoring_errors:True (using this, there will be an error message telling you to ignore the error, continue to execute the following command)
[root@manger ansible]# vim error.yml
---
- hosts: web
remote_user: root
tasks:
- shell: mkdir /tmp/cache
- name: ReStart service httpd
service:
name: httpd
state: restarted
- name: run some command
shell: /usr/bin/somecommand
ignore_errors: True
[root@ansible ansible]# ansible-playbook error.yml
Step 2: tags define a call identifier for the specified task
[root@manger ansible]# vim adhttp.yml
---
- hosts: cache
remote_user: root
tasks:
- copy:
src: /root/httpd.conf
dest: /etc/httpd/conf/httpd.conf
owner: apache
group: apache
mode: 0644
tags: syncconf
[root@manger ansible]# ansible-playbook tags.yml -t syncconf
[root@manger ansible]# vim handers.yml
---
- hosts: cache
remote_user: root
tasks:
- copy:
src: /root/httpd.conf
dest: /etc/httpd/conf/httpd.conf
owner: apache
group: apache
mode: 0644
tags: syncconf
notify:
- restart httpd
handlers:
- name: restart httpd
service:
name: httpd
state: restarted
[root@manger ansible]# ansible-playbook handers.yml
Module when
- Some suits need to trigger an operation after meeting specific conditions, or terminate a certain behavior under specific conditions. This suit requires conditional judgment. When is the best choice to solve this problem. System variables in remote Facts are used as conditions of when, which can be viewed through the setup module
- examples of when:
tashs:
- name: somecommand
command: somecommand
when: expr
- An example of using when
---
- name: Install VIM
hosts: all
tasks:
- name: Install VIM via yum
yum: name=vim-enhanced state=installed
when: ansible_os_family == "RedHat"
- name: Install VIM via apt
apt: name=vim state=installed
when: ansible_os_family == "Debian"
Module register
- register
-Sometimes we need more complicated examples, such as judging the execution result of the previous command to process the subsequent operations. At this time, we need the register module to save the return status of the previous command and call it later- command: test command register: result - command: run command when: result
- Advanced variable registration
-judge the return value of the result of running the command
-when the system load exceeds a certain value, it is suitable for special processing
---
- hosts: web
remote_user: root
tasks:
- shell: uptime | awk '{
printf("%.2f",$(NF-2))}'
register: result
- service:
name: httpd
state: stopped
when: result.stdout | float >0.7
debugging
Module debug
- The debug module can output more detailed information at runtime to help us troubleshoot
---
- hosts: web
remote_user: root
tasks:
- shell: uptime | awk '{
printf("%.2f",$(NF-2))}'
register: result
- service:
name: httpd
state: stopped
when: result.stdout| float >0.7
- debug: var=result
with_items
- with_items is a playbook standard loop, which can be used to iterate a list or dictionary, and
get the value of each iteration through { (item)}
-for example, create multiple users
---
- hosts: web1
remote_user: root
tasks:
- name: add users
user: group=wheel password={
{
'123456' |password_hash('sha512')}} name={
{
item}}
with_items:["a1","a2","a3","a4"]
- with_items advanced
-define different groups for different users
---
- hosts: web2
remote_user:root
tasks:
- name: add users
user:group={
{
item.group}} password={
{
'123456 '| password_hash('sha512')}} name={
{
item.name}}
with_items:
- {
name: 'a1',group: 'root'}
- {
name: 'a2',group: 'root'}
- {
name: 'a3',group: 'wheel'}
- {
name: 'a4',group: 'wheel'}
Module include and roles
- When writing a playbook, as the project becomes larger and larger, the playbook becomes more and more complex, and the modification is also very troublesome. At this time, you can put some play, task or handler in other files, and it is a good choice to include it through the include command.
tasks:
- include: tasks/setup.yaml
- include: tasks/user.yml user=a1 # users.yml 中可以通过{
{ user }} 来使用这个变量
handlers:
- include: handler/handlers.yml
-
Roles are like an enhanced version of include, which can introduce files and directories of a project
-
Generally required directory levels are
– vars: variable layer
–tasks: task layer
–handlers: trigger condition
–files: file
– template: template
– default: default, the lowest priority -
If a play contains a role called "x", then
---
- hosts: host_group
roles:
- x
– X/tasks/main.yml
– x/vars/main.yml
– x/handlers/main.yml
– x/... …/main.yml
– will be automatically added to this play
Troubleshooting method (debugging)
- Check grammar
]# ansible-playbook --syntax-check playbook.yaml
- Test run
]#ansible-playbook -C playbook.yaml
--Display affected hosts --list-hosts --Display
working tasks --list-tasks
--Display tags that will be run --list-tags
Exercise: Stop the Apache service with too high system load
- Step 1: Stop the Apache service whose system load is too high
1) When the system load exceeds 0.7, turn off httpd
[root@manager ansible]# vim when.yml
---
- hosts: cache
remote_user: root
tasks:
- shell: uptime | awk '{
printf("%.2f\n",$(NF-2))}'
register: result
- service:
name: httpd
state: stopped
when: result.stdout|float > 0.7
[root@manager ansible]# ansible-playbook when.yml
- Step 2: with_items standard loop
1) with_item creates multiple users
[root@manager ansible]# vim adduser.yml
---
- hosts: web2
remote_user: root
tasks:
- name: add users
user: group=wheel password={
{
'123456' | password_hash('sha512')}} name={
{
item}}
with_items: ["a1", "a2", "a3", "a4"]
[root@manager ansible]# ansible-playbook adduser.yml
2) Define different groups for different users
[root@manager ansible]# vim adduser1.yml
---
- hosts: web2
remote_user: root
tasks:
- name: add users
user: group={
{
item.group}} password={
{
'123456' | password_hash('sha512')}} name={
{
item.name}}
with_items:
- {
name: 'a1', group: 'root'}
- {
name: 'a2', group: 'root'}
- {
name: 'a3', group: 'wheel'}
- {
name: 'a4', group: 'wheel'}
[root@manager ansible]# ansible-playbook adduser1.yml
3) Include and roles
When writing a playbook, as the project becomes larger and larger, the playbook becomes more and more complex. You can put some play, task or handler in other files. It is a good choice
to include it. Roles are like an enhanced version of include, which can introduce files and directories of a project.
Generally, the required directory level is
vars: variable layer
tasks: task level
handlers: trigger condition
files: file
template: template
default: default, the lowest priority
...
tasks:
- include: tasks/setup.yml
- include: tasks/users.yml user=plj
//users.yml 中可以通过{
{
user }}来使用这些变量
handlers:
- include: handlers/handlers.yml
Step 3: Debug detection
[root@manager ansible]# ansible-playbook --syntax-check http.yml //检测语法
root@manager ansible]# ansible-playbook http.yml --list-tasks
//显示要执行的工作
[root@manager ansible]# vim debug.yml
---
- hosts: cache
remote_user: root
tasks:
- shell: uptime |awk '{
printf("%f\n",$(NF-2))}'
register: result
- service:
name: httpd
state: stopped
when: result.stdout|float > 0.7
- name: Show debug info
debug: var=result
[root@manager ansible]# ansible-playbook debug.yml //运行