ansible manage fact and loop and conditional tasks

Manage facts and cycles and conditional tasks

Fact profile

Ansible is actually a variable that ansible automatically detects on the managed host. The fact contains host related information that can be used like regular variables, conditions, loops in play, or any other statement that depends on the values collected from the managed host.

Some of the facts collected for managed hosts may include:

Host name

Kernel version

Network interface

IP address

Operating system version

Various environmental variables

Number of CPU s

Memory provided or available

Free disk space

With the help of facts, the state of the managed host can be easily retrieved and the operation to be performed can be determined according to the state. For example:

You can restart the server by running the conditional task based on the fact that it contains the current kernel version of the managed host

MySQL configuration files can be customized based on available memory through fact reporting

You can set the IPv4 address used in the configuration file based on the value of the fact

Usually, each play will automatically run the setup module to collect facts before performing the first task.

One way to view the facts collected for the managed host is to run a collection of facts and use the debug module to display ansible_ Short playbook of facts variable value.

View host information:

Method 1: use the step module to display all the fact information

[root@localhost ansible]# ansible http -m setup
192.168.240.40 | SUCCESS => {
    "ansible_facts": {
        "ansible_all_ipv4_addresses": [
            "192.168.240.40"
        ],
        "ansible_all_ipv6_addresses": [
            "fe80::b0aa:5d3b:1352:b7cb"
        ],
······
discovered_interpreter_python": "/usr/libexec/platform-python",
        "gather_subset": [
            "all"
        ],
        "module_setup": true
    },
    "changed": false
}

Method 2: use variables to display fact information

[root@localhost ansible]# cat shishi.yml  #Use ansible_facts variable
---
- name: fact
  hosts: 192.168.240.40
  tasks: 
    - name: facts
      debug: 
        var: ansible_facts

[root@localhost ansible]# ansible-playbook shishi.yml 	#test

PLAY [fact] *******************************************************************************************************************************************************************************************************

TASK [Gathering Facts] ********************************************************************************************************************************************************************************************
ok: [192.168.240.40]

TASK [facts] ******************************************************************************************************************************************************************************************************
ok: [192.168.240.40] => {
    "ansible_facts": {
        "all_ipv4_addresses": [
            "192.168.240.40"
······
"userspace_architecture": "x86_64",
        "userspace_bits": "64",
        "virtualization_role": "guest",
        "virtualization_type": "VMware"
    }
}

PLAY RECAP ********************************************************************************************************************************************************************************************************
192.168.240.40             : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

The following table shows some facts that may be collected from managed nodes and can be used in playbook:
Example of Ansible fact

factvariable
Short host nameansible_facts['hostname']
Fully qualified domain nameansible_facts['fqdn']
IPv4 addressansible_facts['default_ipv4']['address']
Name list of all network interfacesansible_facts['interfaces']
/Size of dev/vda1 disk partitionansible_facts['devices']['vda']['partitions']['vda1']['size']
DNS server listansible_facts['dns']['nameservers']
Currently running kernel versionansible_facts['kernel']

If the value of a variable is of hash / dictionary type, two syntax can be used to get its value. For example:

  • ansible_facts ['default_ipv4'] ['address'] can also be written as ansible_facts.default_ipv4.address
  • ansible_facts ['DNS'] [' nameservers'] can also be written as ansible_facts.dns.nameservers

When using facts in playbook, Ansible dynamically replaces the variable name of facts with the corresponding value

[root@localhost ansible]# cat shishi.yml 	#Get IP and hostname
---
- name: fact
  hosts: 192.168.240.40
  tasks: 
    - name: facts
      debug: 
        msg: >
          {{ansible_facts.default_ipv4.address}} is {{ansible_facts.fqdn}}

[root@localhost ansible]# ansible-playbook shishi.yml 	#see

PLAY [fact] *******************************************************************************

TASK [Gathering Facts] ********************************************************************
ok: [192.168.240.40]

TASK [facts] ******************************************************************************
ok: [192.168.240.40] => {
    "msg": "192.168.240.40 is localhost.localdomain\n"
}

PLAY RECAP ********************************************************************************
192.168.240.40             : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

Ansible facts are injected as variables

In ansible2 Before 5, the fact was that it was prefixed with the string ansible_ Single variable injection, not as ansible_ Part of the facts variable is injected. For example, ansible_facts ['distribution '] facts will be called ansible_distribution.

Many older playbook s still use the fact that variables are injected instead of ansible_ Create a new syntax for the namespace under the facts variable. We can use temporary commands to run the setup module to display the values of all facts in this form.

Comparison of selected Ansible fact names

ansible_facts formOld fact variable form
ansible_facts['hostname']ansible_hostname
ansible_facts['fqdn']ansible_fqdn
ansible_facts['default_ipv4']['address']ansible_default_ipv4['address']
ansible_facts['interfaces']ansible_interfaces
ansible_facts['devices']['vda']['partitions']['vda1']['size']ansible_devices['vda']['partitions']['vda1']['size']
ansible_facts['dns']['nameservers']ansible_dns['nameservers']
ansible_facts['kernel']ansible_kernel

At present, Ansible recognizes both the new fact naming system (using ansible_facts) and the old "fact injected as a separate variable" naming system before 2.5.

Insert in the * * [default] section of the Ansible configuration file_ facts_ as_ Set the vars parameter to False * * to turn off the old naming system. The default setting is currently True.

inject_ facts_ as_ The default value of vars may be changed to False in future versions of Ansible. If set to False, only the new * * Ansible can be used_ facts.*** The naming system references Ansible facts. Therefore, it is suggested that we should adapt to this way from the beginning.

Turn off fact collection

Sometimes we don't want to collect facts for play. The reasons for this may be:

Not prepared to use any facts

Hope to speed up play

You want to reduce the load caused by play on the managed host

The managed host cannot run the setup module for some reason

You need to install some prerequisite software before collecting facts

For the above reasons, we may want to turn off the fact collection function permanently or temporarily. To disable the fact collection function for play, you can turn gather_ The facts keyword is set to no.

[root@localhost ansible]# cat shishi.yml 
---
- name: fact
  hosts: 192.168.240.40
  gather_facts: no
  tasks: 
    - name: facts
      debug: 
        msg: >
          {{ansible_facts.default_ipv4.address}} is {{ansible_facts.fqdn}}

Even if gather is set for play_ Facts: No, you can also manually collect facts at any time by running a task using the setup module

[root@localhost ansible]# cat shishi.yml 
---
- name: fact
  hosts: 192.168.240.40
  gather_facts: no
  tasks: 
    - name: facts
      setup: 
    - name: debug
      debug: 
        msg: >
          {{ansible_facts.default_ipv4.address}} is {{ansible_facts.fqdn}}

Create custom facts

In addition to using the facts captured by the system, we can also customize the facts and store them locally on each managed host. These facts are consolidated into a standard list of facts collected when the setup module runs on the managed host. They enable the managed host to provide arbitrary variables to Ansible to adjust the behavior of play.

Custom facts can be defined in static files. The format can be INI files or JSON. They can also be executable scripts that generate JSON output, just like dynamic manifest scripts.

With custom facts, we can define specific values for the managed host for play to populate the configuration file or run tasks conditionally. Dynamic custom facts allow you to programmatically determine the values of these facts at play runtime, and even determine which facts to provide.

By default, the setup module starts from * * / etc / ansible / facts Load custom facts in the files and scripts in the D directory. The name of each file or script must be in The end of fact * * can only be used. The dynamic custom fact script must output the fact in JSON format and must be an executable file.

Static custom fact file written in INI format. A custom fact file in INI format contains a top-level value defined by a part, followed by a key value pair for the fact to be defined

[root@localhost facts.d]# cat best.fact 
[packages]
web_package = httpd
db_package = mariadb-server

[users]
user1 = joe
user2 = jane

[root@localhost ansible]# ansible 192.168.240.40 -m setup|less #Check whether it is added successfully
                "packages": {
                    "db_package": "mariadb-server",
                    "web_package": "httpd"
                },

Use magic variables

Some variables are not facts or configured through the setup module, but are also automatically set by Ansible. These magic variables can also be used to obtain information related to a specific managed host.

Magic variableexplain
hostvarsA variable that contains a managed host and can be used to get the value of a variable of another managed host. If facts have not been collected for the managed host, it will not contain the facts for that host.
group_namesLists all groups to which the currently managed host belongs
groupsLists all groups and hosts in the list
inventory_hostnameContains the host name of the currently managed host configured in the manifest. For various reasons, it may be different from the host name reported in the fact

Loop and conditional tasks

Iterative tasks using loops

By using loops, the task of using the first mock exam is not necessary. For example, instead of writing five tasks to ensure that there are five users, they just need to write one task to iterate over a list of five users to ensure that they all exist.

Ansible supports iterative tasks on a set of projects using the loop keyword. Loops can be configured to repeat tasks using items in the list, the contents of files in the list, a generated sequence of numbers, or a more complex structure.

If you do not use loops, you will use the user module twice to create two users, and if you create more, you will use more

---
- name: no loop
  hosts: 192.168.240.40
  tasks: 
    - name: user
      user: 
        name: ppp
        uid: 9090
   
    - name: user2
      user:
        name: qqq
        uid: 8080

After use cycle

---
- name: yes loop
  hosts: 192.168.240.40
  tasks: 
    - name: user
      user: 
        name: "{{ item }}"
        
      loop:
        - ooo
        - www   

You can provide the list used by loop through a variable. In the following example, the variable liu contains a list of services that need to be running.

---
- name: no loop
  hosts: 192.168.240.40
  vars: 
    liu:
      - jjj
      - yyy
  tasks: 
    - name: user
      user: 
        name: "{{ item }}"
      loop: "{{ liu }}"

Circular hash or dictionary list

The loop list does not need to be a simple list of values. In the following example, each item in the list is actually a hash or dictionary. Each hash or dictionary in the example has two keys, name and groups. The value of each key in the current item loop variable can be passed through item Name and item Groups variable.

---
- name: no loop
  hosts: 192.168.240.40
  tasks: 
    - name: user
      user: 
        name: "{{ item.name }}"
        uid: "{{ item.uid }}"
      loop: 
        - name: ddd
          uid: 12212
        - name: sss
          uid: 34354

Circular keywords for earlier styles

In Ansible2 Before 5, most playbooks used different loop syntax. Multiple cyclic keywords are provided with the prefix whth_, Followed by the name of the Ansible lookup plug-in. This circular syntax is common in existing playbooks, but may be deprecated at some point in the future.

Circular keyworddescribe
with_itemsThe behavior is the same as the loop keyword of a simple list, such as a string list or a hash / dictionary list. But different from loop, if it is with_items provides a list of lists, which will be flattened into a single-level list. The loop variable item holds the list items used during each iteration.
with_fileThis keyword requires a list of control node file names. The loop variable item saves the contents of the corresponding file in the file list during each iteration.
with_sequenceThis keyword does not require a list, but requires parameters to generate a list of values from a sequence of numbers. The loop variable item saves the value of a generated item in the generated sequence during each iteration.
---
- name: no loop
  hosts: 192.168.240.40
  vars: 
    liu:
      - jjj
      - yyy
  tasks: 
   - name: "with_items"
    debug:
      msg: "{{ item }}"
    with_items: "{{ liu }}"

From ansible2 Starting with 5, it is recommended to write a loop using the loop keyword

Use the Register variable with Loop

The register keyword can also capture the output of a circular task. The following code snippet shows the structure of the register variable in a circular task:

---
- name:
  hosts: 192.168.240.40
  tasks:
    - name: loop rcho task
      shell: "echo you is item: {{ item }}"
      loop:
        - ddd
        - sss
      register: echo_results

    - name: show echo_results
      debug:
        var: echo_results

The playbook has been modified so that the second task iterates over this list

---
- name: 
  hosts: 192.168.240.40
  tasks: 
    - name: loop rcho task
      shell: "echo you is item: {{ item }}"
      loop: 
        - ddd
        - sss
      register: echo_results

    - name: show echo_results
      debug:
        msg: "STDOUT FROM previous task: {{ item.stdout  }}"
      loop: "{{  echo_results['results'] }}"

Run tasks conditionally

Ansible can use conditions to perform tasks or play when specific conditions are met. For example, a condition can be used to determine the available memory on the managed host before ansible installs or configures the service.

We can use conditions to distinguish different managed hosts and assign functional roles according to their conditions. Playbook variables, registered variables, and Ansible facts can all be tested by conditions. You can use operators that compare strings, numeric data, and Boolean values.

The following scenarios illustrate the use of conditions in Ansible:

You can define a hard limit (such as min_memory) in the variable and compare it with the available memory on the managed host.

Ansible can capture and evaluate the output of a command to determine whether a task has been completed before performing further operations. For example, if a program fails, it will pass through batch processing.

The Ansible fact can be used to determine the managed host network configuration and determine the template file to send (such as network binding or relay).

You can evaluate the number of CPU s to determine how to properly tune a Web server.

Compare the registered variables with predefined variables to determine whether the service has changed. For example, test MD5 of the service configuration file to verify and see if the service has changed.

Conditional task syntax

The when statement is used to run a task conditionally. It takes the condition to be tested as the value. If the conditions are met, run the task. If the conditions are not met, the task is skipped.

One of the simplest conditions that can be tested is whether a boolean variable is True or False

---
- name: 
  hosts: 192.168.240.40
  vars: 
    run_my_task: true	#If it is true, the creation is successful; if it is false, it will not be created
  tasks: 
    - name: create user
      user: 
        name: iii
      when: run_my_task
      

Tests whether liuq variables have values. If there is a value, use the value of liuq as the name of the package to be installed. If the liuq variable is not defined, the task is skipped and no errors are displayed.

---
- name: 
  hosts: 192.168.240.40
  vars: 
    liuq: opop
  tasks: 
    - name: create user
      user: 
        name: "{{ liuq }}"
      when: run_my_task
      when: liuq is defined

Operations that can be used by processing conditions

Indentation of the when statement. Since the when statement is not a module variable, it must be indented to the highest level of the task and placed outside the module.

The task is a YAML hash / dictionary, and the when statement is just another key in the task, just like the name of the task and the module it uses. The usual practice is to put any possible when keyword after the task name and module (and module parameters).

operationExample
Equal to (value is string)ansible_machine == "x86_64"
Equal to (value is numeric)max_memory == 512
less thanmin_memory < 128
greater thanmin_memory > 256
Less than or equal tomin_memory <= 256
Greater than or equal tomin_memory >= 512
Not equal tomin_memory != 512
Variable existsmin_memory is defined
Variable does not existmin_memory is not defined
The boolean variable is true. 1. True or yes evaluates to truememory_available
The boolean variable is False. 0, False, or no evaluate to Falsenot memory_available
The value of the first variable exists as the value in the list of the second variableansible_distribution in supported_distros
                          | min_memory != 512                         |

|Variable exists | min_memory is defined |
|Variable does not exist | min_memory is not defined |
|The boolean variable is true. 1. True or yes evaluates to True | memory_available |
|The boolean variable is False. 0, False, or no evaluate to False | not memory_available |
|The value of the first variable exists as the value | ansible in the list of the second variable_ distribution in supported_ distros |

Keywords: Linux

Added by dc519 on Thu, 20 Jan 2022 08:15:50 +0200