Do not reprint without written permission
The third chapter is long, because, I will be divided into several parts to translate.
Advanced Playbooksso far the playbooks, we have looked at is simple and just run a number ofmodules in order. Ansible allows much more control over the execution of Yourplaybook. Using The following techniques, you should is able to perform eventhe most complex deployments. Running operations in Parallelby default, Ansible would only fork up to five times, so it'll only run an Operationon five Different machines at once. If you have a large number of machines, Oryou has lowered this maximum fork value, and then your may want to launch Thingsasyn chronously. Ansible ' s method for doing-launch the task and thenpoll for it to complete. This allows Ansible to start of the job across all the requiredmachines while still using the maximum forks. To run a operation in parallel, use the async and poll keywords. The async keywordtriggers Ansible to run the job in parallel, and its value would be the maximum time thatansible would wait For the command to complete. The value of poll indicates to ansiblehow often to poll to check if the command has been completed. If you wanted to run updatedb across a entire cluster of machines, it might look likethe following code:-hosts:alltasks :-Name:install mlocateyum:name=mlocate state=installed-name:run Updatedbcommand:/usr/bin/updatedbasync:300poll:10 You'll notice that if you run the previous example on + than five machines,the Yum module acts differently to the C Ommand module. The Yum module would run onthe first five machines, then the next five, and so on. The command module, However,will run across all the machines and indicate the status once complete. If your command starts a daemon that eventually listens to a port, you can start itwithout polling so that Ansible does no T check for it to complete. You can then carryon with other actions and check for completion later using the Wait_for module. Toconfigure Ansible to not wait for the job to complete, set the value of poll to 0. Finally, if the task is Running takes an extremely long time to run, you Cantell Ansible to wait for the job as long as it takes. To does this, set the value of Asyncto 0. You'll want to use Ansible's polling in the following situations:? you had a long-running task that May hits the timeout? need to run an operation across a large number of machines? You had an operation for which you don't need to wait to Completethere is also a few situations where you should not us E Async or poll:? If your job acquires locks that prevent other things from running?   ; You job only takes a short time to run
Advanced Palybook
Before we met the playbook are simpler, just need to execute some modules can be.
But Ansible agrees that you have a lot of other controls when you execute playbook, allowing you to complete the most complex deployment tasks.
Performing tasks in parallel
Ansible is enabled by default of 5 threads at a time, so it can only operate on 5 machines at a time. Assuming you have more than 5 machines, or fewer than 5 threads, you might want to end up with async. The Ansible method is to poll each task until the end of the task so that absible can complete the task of all machines (more than 5 machines) in the case of using 5 threads.
Enables parallelism. The 2 Keyword,asynckeyword with async and poll are required to enable parallelism, and its value is his maximum wait time. Poll sets ansible how often to check if the task is complete.
The following example, one-time update of a cluster of all the database, code such as the following:
-Hosts:all
Tasks
-Name:install Mlocate
Yum:name=mlocate state=installed
-Name:run UpdateDB
Command:/usr/bin/updatedb
async:300
Poll:10
When you do this, the Yum operation is performed on 5 machines with 5 machines, but the updatedb operation is a one-time operation of all machines and immediately returns operational status information.
Suppose you enable a daemon program. and will finally listen to a port, then you can not need to use poll polling, and use the Wait_for module described in the previous chapter. This will only need to set the value of poll to 0. Assume that your operation may be running for a very long time. Then we just need to tell ansible to wait and be able, so just set the Asyn to 0.
Applications for polling are:
- When your task needs to be executed for a very long time. And maybe time out.
- When the number of machines in operation is very large
- When a task, you do not need to wait for him to return to the end of the signal
For cases where async or poll is not applicable:
- When your mission has dependencies on other tasks.
- Your mission takes a very short time.
Loopingansible allows repeat a module several times with different input, forexample, if you had several files that Should has similar permissions set. Thiscan save you-a lot of repetition and allows-iterate over facts and variables. To does this, you can use the With_items key on a action and set the value to the Listof items is going to Iterat E over. This would create a variable for the modulecalled item, which'll be set to each item in turn as your module is iterated Over. Some modules such as Yum would optimize this so then instead of doing a separatetransaction for each package, they would ope them at once. Using With_items looks like this:tasks:-name:secure config filesfile:path=/etc/{{item}} mode=0600 owner=root Group=ro otwith_items:-my.cnf-shadow-fstabin addition to looping through fixed items, or a variable, Ansible can also use Whatare c Alled Lookup plugins. These plugins allow you to tell Ansible to fetch the datafrom somewhere externaLly. For example, you might want to upload all the files Thatmatch a particular pattern, and then upload them. In this example, we upload all the public keys in a directory and then assemble theminto an Authorized_keys file for the R Oot user.tasks: #1-name:make key Directory#2file:path=/root/.sshkeys ensure=directory mode=0700owner=root group=root# 3-name:upload public keys#4copy:src={{Item}} Dest=/root/.sshkeys mode=0600owner=root Group=root#5with_fileglob: #6-K eys/*.pub#7-name:assemble keys into Authorized_keys file#8assemble:src=/root/.sshkeys dest=/root/.ssh/authorized_ keysmode=0600 owner=root group=root#9repeating modules can be used in the following situations:? Repeat ing a module many times with similar settings? iterating over all the values of a fact that's a list?& nbsp; Used to create many files for later use with the Assemble module to combineinto one large FILE? &N Bsp used With_fileglob to copy a DirecTory of the files using the Glob patternmatching
Loop loop
Anisble can execute a module repeatedly based on different inputs, such as some files that have nearly the same permission set. You can iterate over them based on the actual situation and the value of the variable.
Use With_itemskeyword to define a loop. Insert the data you want into a list as its value.
This will generate a variable called item, and when you go through the list, item will be assigned to each of the elements in the list. Modules like Yum will also proactively optimize this operation, so you can use the loop once all is complete.
The loop mechanism resembles the following code:
Tasks
-Name:secure config files
file:path=/etc/{{Item}} mode=0600 owner=root Group=root
With_items:
-MY.CNF
-Shadow
-Fstab
In addition, anisble can use the lookup plugin to use external data, for example, if you want to upload all files that conform to an expression rule to the destination. In the following example. We upload all the files under the Public key folder and merge them into the Authorized_keys file to the root user.
Tasks
-Name:make Key Directory
File:path=/root/.sshkeys ensure=directory mode=0700
Owner=root Group=root
-Name:upload public keys
copy:src={{Item}} Dest=/root/.sshkeys mode=0600
Owner=root Group=root
With_fileglob:
-Keys/*.pub
-name:assemble keys into Authorized_keys file
Assemble:src=/root/.sshkeys Dest=/root/.ssh/authorized_keys
mode=0600 Owner=root Group=root
The repeating modules are available in the following scenarios:
- Repeating a configuration-like module very often
- When you have all the values in the list (according to fact)
- When you want to create very many files and then merge them into a large file with the Assemble module
- When using With_fileglob to copy all the pattern matching files under a folder
Conditional executionsome modules, such as the copy module, provide mechanisms to configure it to skipthe module. You can also configure your own skip conditions that would only executethe module if they resolve to true. This can is handy if your servers use differentpackaging systems or has different filesystem layouts. It can also is used with Theset_fact module to allow you to compute many different things. To skip a module, you can use the When key; This lets provide a condition. If thecondition you set resolves to false and then the module would be skipped. The value thatyou assign to was a Python expression. You can use any of the variables or factsavailable-to-Name:install vimhosts:alltasks:-name:inst All vim via yumyum:name=vim-enhanced state=installedwhen:ansible_os_family = = "RedHat" <p>-Name:install VIM via a Ptapt:name=vim state=installedwhen:ansible_os_family = = "Debian" </p>-name:unexpected os familydebug:msg= "OS Fa mily {{Ansible_os_family}} is notsupported "fail=yeswhen:not ansible_os_family = =" RedHat "or ansible_os_family==" Debian "this Feature can used to pause at a particular point and wait for theuser intervention to continue. Normally when Ansible encounters Anerror, it'll simply stop what it's doing without running any handlers. With this feature, you can add the Pause module with a condition to itthat triggers in unexpected situations. This is the pause module Willbe ignored in a normal situation, but unexpected circumstances it willallow the user to I Ntervene and continue when it's safe to do so. The task would look like This:name:pause for unexpected conditionspause:prompt= "unexpected OS" when:ansible_os_family! = "RedHat" There is numerous uses of skipping actions; Here is a few suggestions:? working around differences in operating systems? Prompt ing a user and only then performing the actions that they request? improving perFormance by avoiding a module so you know won ' t changeanything but could take a while to do so? Refusin G to alter systems that has a particular file present? Checking If custom written scripts have already been run
Conditional operation
Some of these modules, like copy, provide the skip ignore mechanism, and you can configure your own conditions to skip the operation of certain modules.
It is especially useful when your server uses different operating systems and file types.
You can do different things according to the value of the Set_fact module.
Skip the run of a module, use when this keyword to provide a condition, assume that the condition is false, skip run, use the Python expression as its value, here you can use whatever variable or whatever the possible fact.
The following example is based on the operating system to determine whether to use apt or yum to run the installation operation, when the OS information can not be determined, print a message.
---
-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"
-Name:unexpected OS Family
Debug:msg= "OS Family {{ansible_os_family}} is not
Supported "Fail=yes
When:not ansible_os_family = = "RedHat" or ansible_os_family
= = "Debian"
Based on this feature, we are also able to add the Pause module to allow the user to confirm to continue, in accordance with the conditions we set the normal circumstances. The pause module will not be run, it will be called only in exceptional cases and the user is asked to confirm to continue the task, code such as the following
Name:pause for unexpected conditions
pause:prompt= "Unexpected OS"
When:ansible_os_family! = "RedHat"
Scenarios and recommendations for conditions to run:
Task delegationansible, by default, runs it tasks all at once in the configured machine. This is greatwhen you has a whole bunch of separate machines to configure, or if each of yourmachines are responsible for Communicating its status to the other remote machines. However, if you need to perform an action on a different host than the one Ansible isoperating on, you can use a delegatio N.ansible can configured to run a task on a different host than the one that's beingconfigured using the delegate_to K ey. The module would still run once for Everymachine, but instead of running on the target machine, it'll run on the delegate Dhost. The facts available is the ones applicable to the current host. Here, WeShow a playbook that would use the Get_url option to download the Configurationfrom a bunch of the Web servers.----Nam E:fetch configuration from all webservershosts:webserverstasks:-name:get configget_url:dest=configs/{{ansible_hostn AME}} force=yesurl=http://{{Ansible_hostnamE}}/diagnostic/configdelegate_to:localhostif You is delegating to the localhost and you can use a shortcut when defining Theaction that automatically uses the local machine. If you define the key of the Actionline as local_action and then the delegation to localhost is implied. If We were tohave used this in the previous example, it would is slightly shorter and look like this:----Name:fetch conf Iguration from all webservershosts:webserverstasks:-name:get configlocal_action:get_url dest=configs/{{ansible_ Hostname}}.cfg url=http://{{Ansible_hostname}}/diagnostic/configdelegation is not limited to the local machine. You can delegate to any host, which is inthe inventory. Some Other reasons why do you might want to delegate is:? Removing a host from a load balancer before deployment? Changing DNS to direct traffic away from a server what is the change? Creating an ISCSI volume on a storage device? Using a external server to check that access outside the network works
Delegation of tasks
Ansible performs tasks on the configured machine by default and is useful when you have a lot of machines to configure or every device can reach.
But. When you need to perform a task on another ansible control machine, you need to use task delegation.
The ability to delegate tasks to other machines is performed using Delegate_tokeyword. The fact that is available at the same time will also use the value on the delegated machine. The following sample uses Get_url to all webserver to download the configuration:
---
-Name:fetch configuration from all webservers
Hosts:webservers
Tasks
-Name:get Config
get_url:dest=configs/{{Ansible_hostname}} force=yes
url=http://{{Ansible_hostname}}/diagnostic/config
Delegate_to:localhost
When you delegate to this machine, you can also use a faster way to local_action the code, such as the following:
---
-Name:fetch configuration from all webservers
Hosts:webservers
Tasks
-Name:get Config
Local_action:get_url dest=configs/{{Ansible_hostname
}}.cfg url=http://{{Ansible_hostname
}}/diagnostic/config
You can delegate tasks to the device list on the random machine, here are some of the delegated scenario tasks:
- When you deploy a host to remove from a load-balanced cluster
- After you make a change, delete the corresponding DNS record as a host
- When creating iSCSI as volume on a storage device
- When using an external host to detect if the network exits normal time
[email protected] An effective configuration management tool--ansible Configure management--translation (iv)