Ansible @ an efficient configuration management tool-ansible configure management-translation (4)

Source: Internet
Author: User
Do not reprint without written permission

Due to the long content in Chapter 3, I will divide it into several parts for translation.

Advanced PlaybooksSo far the playbooks that we have looked at are 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 be able to perform eventhe most complex deployments.Running operations in parallelBy default, Ansible will only fork up to five times, so it will only run an operationon five different machines at once. If you have a large number of machines, oryou have lowered this maximum fork value, then you may want to launch thingsasynchronously. Ansible's method for doing this is to launch the task and thenpoll for it to complete. This allows Ansible to start the job across all the requiredmachines while still using the maximum forks.To run an operation in parallel, use the async and poll keywords. The async keywordtriggers Ansible to run the job in parallel, and its value will be the maximum time thatAnsible will 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 an 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: 10You will notice that when you run the previous example on more than five machines,the yum module acts differently to the command module. The yum module will 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 on a port, you can start itwithout polling so that Ansible does not 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 that you are running takes an extremely long time to run, you cantell Ansible to wait for the job as long as it takes. To do this, set the value of asyncto 0 .You will want to use Ansible's polling in the following situations:?     You have a long-running task that may hit the timeout?     You need to run an operation across a large number of machines?     You have an operation for which you don't need to wait to completeThere are also a few situations where you should not use 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

The Playbook we encountered earlier is relatively simple. You only need to run some modules. However, ansible allows you to have more control when running playbook, allowing you to complete the most complex deployment tasks.

Run tasks in parallel

Ansible enables five threads at a time by default, so it can only operate on five machines at a time. If you have more than five machines or less than five threads, you may want to use Asynchronization. The ansible method is to poll each task until the task ends, so that absible can complete the tasks of all machines (more than five machines) with five threads.

To enable parallel, you need to use the async and poll keywords. The async keyword enables parallel, and its value is its maximum waiting time. Poll sets how often ansible checks whether a task is completed.

The following example updates all databases in a cluster at a time. The Code is as follows:

-Hosts: All
Tasks:
-Name: Install mlocate
Yum: Name = mlocate state = installed

-Name: Run updatedb
Command:/usr/bin/updatedb
Async: 300
Poll: 10

When you run this column, the yum operation runs on five machines and five machines, but the updatedb operation operates on all machines at a time and immediately returns the operation status information.

If you enable a daemon program and finally listen to a port, you can use the wait_for module described in the previous chapter instead of poll, in this way, you only need to set the value of poll to 0. If your operation may take a long time, we only need to tell ansible to wait, in this way, you only need to set Asyn to 0.

Applicable scenarios of Round Robin:

  • When your task needs to run for a long time and may time out
  • When the number of machines operated is large
  • When a task does not need to wait for it to return an end signal

Not applicable to async or Poll:

  • When your task is dependent on other tasks
  • Your task takes a short time

LoopingAnsible allows you to repeat a module several times with different input, forexample, if you had several files that should have similar permissions set. Thiscan save you a lot of repetition and allows you to iterate over facts and variables.To do this, you can use the with_items key on an action and set the value to the listof items that you are going to iterate over. This will create a variable for the modulecalled item , which will be set to each item in turn as your module is iterated over.Some modules such as yum will optimize this so that instead of doing a separatetransaction for each package, they will operate on all of them at once.Using with_items looks like this:tasks:- name: Secure config filesfile: path=/etc/{{ item }} mode=0600 owner=root group=rootwith_items:- my.cnf- shadow- fstabIn addition to looping over fixed items, or a variable, Ansible can also use whatare called 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 root 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- keys/*.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:?     Repeating a module many times with similar settings?     Iterating over all the values of a fact that is a list?     Used to create many files for later use with the assemble module to combineinto one large file?     Used with_fileglob to copy a directory of files using the glob patternmatching

Loop

Anisble can repeatedly run a module multiple times based on different inputs. For example, you can iterate on files with similar permission sets based on actual conditions and variable values.

Use the with_items keyword to define a loop and insert the expected data into a list as its value. This will generate a variable named item. When you review the list, the item will be assigned a value to each element in the list. Modules such as Yum will automatically optimize such operations, so you can use a loop to complete them all at once.

The loop mechanism is similar to 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 also use the lookup plug-in to use external data. For example, you want to upload all files that comply with the rules of an expression to the destination. In the following example, all files under the Public Key Directory are uploaded and merged to the authorized_keys file for 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 module is applicable to the following scenarios:

  • Repeat a module similar to the configuration many times.
  • When all values in the calendar page list (Fact based on actual conditions)
  • When you want to create many files and merge them into a large file using the Assemble module
  • When you use with_fileglob to copy all files in the directory that match the pattern

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 will only executethe module if they resolve to true . This can be handy if your servers use differentpackaging systems or have different filesystem layouts. It can also be 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 you provide a condition. If thecondition you set resolves to false , then the module will be skipped. The value thatyou assign to when is a Python expression. You can use any of the variables or factsavailable to you at this point.---- name: Install VIMhosts: alltasks:- name: Install VIM via yumyum: name=vim-enhanced state=installedwhen: ansible_os_family == "RedHat"<p>- name: Install VIM via aptapt: name=vim state=installedwhen: ansible_os_family == "Debian"</p>- name: Unexpected OS familydebug: msg="OS Family {{ ansible_os_family }} is notsupported" fail=yeswhen: not ansible_os_family == "RedHat" or ansible_os_family== "Debian"This feature can be used to pause at a particular point and wait for theuser intervention to continue. Normally when Ansible encounters anerror, it will simply stop what it is doing without running any handlers.With this feature, you can add the pause module with a condition on itthat triggers in unexpected situations. This way the pause module willbe ignored in a normal situation, but in unexpected circumstances it willallow the user to intervene and continue when it is safe to do so.The task would look like this:name: pause for unexpected conditionspause: prompt="Unexpected OS"when: ansible_os_family != "RedHat"There are numerous uses of skipping actions; here are a few suggestions:?     Working around differences in operating systems?     Prompting a user and only then performing actions that they request?     Improving performance by avoiding a module that you know won't changeanything but may take a while to do so?     Refusing to alter systems that have a particular file present?     Checking if custom written scripts have already been run

Conditional execution

Some modules such as copy provide the Skip ignore mechanism, and you can configure your own conditions to skip the execution of some modules. It is especially useful when your server uses different operating systems and file types. You can perform different tasks based on the value of the set_fact module.

Skip the execution of a module and useWhenThis keyword provides a condition. If the condition is false, skip the execution and use the python expression as its value, you can use any variable or any possible fact here.

The following example shows whether to use apt or yum to perform the installation Based on the operating system. When the OS information cannot be determined, a message is printed.


---
-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 can also add the pause module to allow the user to confirm and continue. The pause module will not be executed if it meets the conditions we set, the task is called only when exceptions occur and the user is requested to confirm the task. The Code is as follows:

Name: Pause for unexpected Conditions
Pause: prompt = "unexpected OS"
When: ansible_ OS _family! = "RedHat"

Applicable scenarios and suggestions for conditional execution:

  • When you want to operate on different operating systems
  • Prompt the user and then execute the operation request

  • When you execute a query task that requires a long time
  • Update prohibited when hard disk space exceeds the threshold
  • Check whether the custom script is running

Task delegationAnsible, by default, runs its tasks all at once on the configured machine. This is greatwhen you have a whole bunch of separate machines to configure, or if each of yourmachines is 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 delegation.Ansible can be configured to run a task on a different host than the one that is beingconfigured using the delegate_to key. The module will still run once for everymachine, but instead of running on the target machine, it will run on the delegatedhost. The facts available will be the ones applicable to the current host. Here, weshow a playbook that will use the get_url option to download the configurationfrom a bunch of web servers.---- name: Fetch configuration from all webservershosts: webserverstasks:- name: Get configget_url: dest=configs/{{ ansible_hostname }} force=yesurl=http://{{ ansible_hostname }}/diagnostic/configdelegate_to: localhostIf you are delegating to the localhost , 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 , then the delegation to localhost is implied. If we were tohave used this in the previous example, it would be slightly shorter and look like this:---- name: Fetch configuration 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 that is inthe inventory. Some other reasons why you might want to delegate are:? Removing a host from a load balancer before deployment? Changing DNS to direct traffic away from a server you are about to change? Creating an iSCSI volume on a storage device? Using an external server to check that access outside the network works

Task Delegation

Ansible executes tasks on the configured machine by default. It is useful when you have a large ticket machine that requires configuration or is accessible to every device. However, when you need to run the task on another ansible control machine, you need to use the task delegate.

You can use the delegate_to keyword to delegate tasks to other machines for running, and the available fact will also use the value on the delegated machine. The following example uses get_url to download configurations to all web servers:

---
-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 the local machine, you can also use the faster method local_action. The Code is as follows:

---
-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 assign a task to any machine on the device list. The following scenarios use the task assignment:

  • Delete a host from a server Load balancer cluster before deployment
  • Remove the corresponding DNS records before changing a host.
  • When an iSCSI volume is created on a storage device
  • When an external host is used to check whether the network egress is normal


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.