There are some common Ansible modules that use frequently, more details please refer to Ansible online document.
How to organize the ansible files structure, see this best practice.
play strategy
There are several play strategies in ansible:
1 | - hosts: all |
The default is linear strategy with 5 forks parallelism.
gather_facts
https://docs.ansible.com/ansible/latest/collections/ansible/builtin/gather_facts_module.html Variables related to remote systems are called facts.
This module is automatically called by playbooks to gather useful variables about remote hosts that can be used in playbooks.
1 | - hosts: all |
For example, I can use ansible_memtotal_mb
and ansible_processor_vcpus
(processor number in /proc/cpuinfo) to config other daemons, they are both
facts
from remote machine:
1 | jvm_heap_size: "{{ ansible_memtotal_mb // 2 | int }}m" |
Here is an case about using ansible internal variable to get machine memory size: https://www.redhat.com/sysadmin/configuration-verification-ansible Then we can use it for example to calculate and set heap size used for ES.
magic variables
Variables related to Ansible are called magic variables. For example: hostvars
,groups
and inventory_hostname
.
add_host
Dynamically create host and group just like inventory file for later play use.
1 | - name: Add host to group 'just_created' with variable foo=42 |
Delegation
https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_delegation.html Delegate tasks to different machine or group, for example localhost, etc.
There is also a shorthand syntax that you can use on a per-task basis:
local_action
, the same as delegate_to: 127.0.0.1
:
1 |
|
serial
This keyword is useful when doing rolling upgrade or patching.
You can also set maximum failure percentage to abort play during the batch execution:
1 |
|
run_once
Run task only on the first host in the batch, for example, setting on ES cluster
master. Here provides other options like delegate_to
and
when: inventory_hostname == webservers[0]
.
retry block
By the time Ansible does not support retry block, but there is another workaround to implement this useful feature, for instance, to make group of tasks atomic, see this post:
1 | - name: Group of tasks that are tightly coupled |
K8s management
挺有意思,看看这篇文章 和Helm做了一下比较:
Use Ansible on k8s management:
uri
1 | # PUT method and get response to result |
pause
https://docs.ansible.com/ansible/latest/modules/pause_module.html
Pauses playbook execution for a set amount of time, or until a prompt is acknowledged. All parameters are optional. The default behavior is to pause with a prompt.
The pause module integrates into async/parallelized playbooks without any special considerations (see Rolling Updates). When using pauses with the serial playbook parameter (as in rolling updates) you are only prompted once for the current group of hosts.
Useful when debug certain task to see the execution result:
1 | # just pause |
skip
Sometimes I need to skip tasks on some machines with prompt confirmation, how to do this?
It seems there is no skip
module in ansible, but we have workaroud, see this
issue.
You can also apply tag
and condition.
debug
https://docs.ansible.com/ansible/latest/modules/debug_module.html This module prints statements during execution and can be useful for debugging variables or expressions without necessarily halting the playbook.
Useful for debugging together with the when:
directive.
1 | ## Example that prints return information from the previous task |
fail
https://docs.ansible.com/ansible/latest/modules/fail_module.html This module fails the progress with a custom message. It can be useful for bailing out when a certain condition is met using when.
More error handling see: https://docs.ansible.com/ansible/latest/user_guide/playbooks_error_handling.html
1 | - name: check async task status |
copy
https://docs.ansible.com/ansible/latest/modules/copy_module.html
The copy module copies a file from the local or remote machine to a location on
the remote machine (depends on the condition). 和template类似, 如果task下面有files
文件夹, 在不指定src路径的时候, eg: src: xxx.txt
, 会从files文件夹里copy.
Use the fetch
module to copy files from remote locations to the local box.
If you need variable interpolation in copied files, use the template
module.
Using a variable in the content field will result in unpredictable output.
1 | # {{ baseDir }}/registry-certs/tls.crt is in control machine |
NOTE that
mode: '0400'
must use 4 digits, such as0644
instead of644
, otherwise you write sticky bit. See ansible copy make sticky bit.
fetch
https://docs.ansible.com/ansible/latest/collections/ansible/builtin/fetch_module.html This module works like copy, but in reverse. It is used for fetching files from remote machines and storing them locally in a file tree, organized by hostname.
Files that already exist at dest will be overwritten if they are different than the src.
1 | # fetched file is marked by the remote hostname |
template
https://docs.ansible.com/ansible/latest/modules/template_module.html 这个module在统一设置配置文件时很常用, 或者可以用来初始化 script template 中的参数, 然后传递 到各个host去运行.
Templates are processed by the Jinja2
templating language.
Documentation on the template formatting can be found in the
Template Designer Documentation.
Usually we have the ansible role structure:
1 | roles/ |
When template works it picks source file from role’s templates/
folder.
If the template file contains jinja2 placeholder, it will be interpolated.
1 | # Copy from control machine to target nodes |
Besides the jinja2 built-in filters: https://jinja.palletsprojects.com/en/latest/templates/#list-of-builtin-filters There are Ansible supplies: https://ansible-docs.readthedocs.io/zh/stable-2.0/rst/playbooks_filters.html#jinja2-filters
Some useful cases:
- remove quotes: using
regex_replace("\"", "")
, or using slice cutxxx[1:-2]
shell
https://docs.ansible.com/ansible/latest/modules/shell_module.html
It is almost exactly like the command
module but runs the command through a
shell (/bin/sh
) on the remote node.
1 | # the symbol | is a Yaml formater |
command
https://docs.ansible.com/ansible/latest/modules/command_module.html
The command
module takes the command name followed by a list of
space-delimited arguments. The given command will be executed on all selected
nodes.
The command(s) will not be processed through the shell
, so variables like
$HOME
and operations like “<”, “>”, “|”, “;” and “&” will not work. Use the
shell module if you need these features.
1 | - name: return motd to registered var |
service
https://docs.ansible.com/ansible/latest/modules/service_module.html Controls services on remote hosts. Supported init systems include BSD init, OpenRC, SysV, Solaris SMF, systemd, upstart.
1 | - name: Start service httpd, if not started |
sysctl
https://docs.ansible.com/ansible/2.9/modules/sysctl_module.html
Managing entries in sysctl.conf
file:
1 | - sysctl: |
systemd
https://docs.ansible.com/ansible/latest/modules/systemd_module.html
More dedicated then service
module, controls systemd services on remote hosts.
1 | - name: Enable and start docker |
file
Set attributes of files, symlinks or directories. Alternatively, remove files, symlinks or directories.
1 | - name: Create a directory if it does not exist |
replace
https://docs.ansible.com/ansible/latest/collections/ansible/builtin/replace_module.html
1 | # Remember to escape regex character |
lineinfile
https://docs.ansible.com/ansible/latest/modules/lineinfile_module.html
If you use sed
in command module, you will get warning, you can disable the
warning by add warn: false
or use lineinfile
module.
This module ensures a particular line is in a file, or replace an existing line using a back-referenced regular expression.
This is primarily useful when you want to change a single line in a file only.
See the replace
module if you want to change multiple, similar lines or check
blockinfile
if you want to insert/update/remove a block of lines in a file.
For other cases, see the copy or template modules.
1 | # remove |
NOTE that if run multiple times, only the first time take effect! it will not remove or insert duplicates.
mount
https://docs.ansible.com/ansible/latest/modules/mount_module.html
This module controls active and configured mount points in /etc/fstab
For /etc/exports
(nfs server side config), no dedicated module for it.
1 | - name: Edit /etc/fstab file to mount share directory |
asynchronous
https://docs.ansible.com/ansible/latest/user_guide/playbooks_async.html By default task in playbook blocks, this may not always be desirable, or you may be running operations that take longer than the SSH timeout.
This module can be use to create progress bar for long time task.
Notice that async task can only be accessed in the same playbook.
1 |
|
ini_file
1 | - name: "Add override config file for xxx service" |
synchronize
The rsync command wrapper.
loop
https://docs.ansible.com/ansible/latest/user_guide/playbooks_loops.html
需要注意的是在有嵌套循环时,要rename default item
, for example, below loop is a
inner loop, rename the loop var to inner_item
, otherwise you get warning
message:
1 | # main.yml |
variables
- inventory_hostname
- groups
- jinjia2 template
}}``` 1
2
3
4
5
6
7
8
9
10
11
If the vars expresson is long, can modify it into multipe lines:
```yaml
# using > instead of |, > will ignore the line return ane assemble the
# multi-line into one line.
result: >
"{{ ((groups['data'] | length) == 0
and (groups['data_hot'] | length) == 0
and (groups['data_warm'] | length) == 0)
| ternary('it is OK', 'bad!')
}}"
conditional
- when clause
1 | ## 不是每个module都支持creates的 |