Ansible (three) how to use variables

Using variables can simplify operations. In addition, ansible also provides variables that can be used to obtain information on the controlled host

Ordinary variable

Variable name requirements

There can be no spaces in the variable name, and no _characters other than underscore ( )

How to reference variables

To tasksquote a variable in, you need {{}}to enclose the variable. Note that there are spaces before and after the variable name.
When the variable name appears at the beginning of the line, you also need to use double quotation marks to enclose ""the entire line.
In some special cases, it may not be used {{}}. For example in the whencondition, or in debugthe varoptions of the module

vars: 
 user: joe
tasks:
 - name: use variables 
   user:
   name: "{{ user }}"
 - name: use variables in debug
   debug:
     var: user

The scope of the variable

When the same variable name appears in different levels, the variable value with the highest priority is used

  • Global variables
    are generally defined in the command line, playtake effect for all the commands, and have the highest priority
    ansible -e "user=root" -e "passwd=123"

  • play level variables
    in the playongoing definition, only the specified playvariables to take effect, a lower priority than global variables, higher than the level of the host
---
- name: a play
  vars:
    - user: root
  • Host-level variables are defined
    in inventoryfiles or specified variable files, and take effect for related hosts/host groups. The lowest priority.

    • inventoryDefine in the file

      # 主机级别的变量 直接将变量写在主机的后面
      servera user=root
      # 主机组级别的变量,使用[group:vars]进行定义
      [servers]
      servera
      serverb
      [servers:vars]
      user=root
    • Define in the variable file.
      Ansible will automatically look for the variable file in the current directory. The host variable file is in the hostvarsdirectory and the host group variable file is in the directory groups_vars.
      Create inventorya file with the same name as the host/host group defined in the specified directory, and the variables in the file will be applied to the corresponding host/host group

Variable matrix

If the value of a variable is a list, the value in the list is still a list, then it is called a variable matrix, similar pythonto the dictionary nested dictionary in

Definition method

users:
  bjones:
    first_name: Bob
    last_name: Jones
  acook:
    first_name: Anne
    last_name: Cook

Call method

It can be pythoncalled in a way similar to a Chinese dictionary
users['bjones']['first_name']
or in the following way. It is
users.bjones.first_name
recommended to use the first way. When the variable name contains keywords, the second way may cause errors

Several special variables

register variable

You can playbookassign taskthe running result to a variable during the running process, and taskoutput it in the follow-up , or perform different operations according to the result

# 示例,输出MySQL从库的同步状态
 - name: get slave status
   mysql_replication:
    login_user: root
    login_password: "{{ mysql_root_password }}"
    login_unix_socket: "{{ mysql_datadir }}/mysql.sock"
    login_port: "{{ mysql_port }}"
    mode: getslave
   register: slave_status

 - name: print slave status
   debug:
    msg: "Slave_IO: {{ slave_status.Slave_IO_Running }},Slave_SQL: {{ slave_status.Slave_SQL_Running }}"

facts variable

ansibleDuring execution playbook, the information of the controlled host will be collected by default, and this information is stored in factsvariables so that different operations can be performed according to the information of the controlled host.

Turn off variable collection in the playbook

---
- hosts: all
  gather_facts: no

Use adhoc to collect facts variables

ansible all -m setup

Facts variable content

factsVariables are jsonthe information of the controlled host saved in the format. The default includes IP, host name, disk, mount, CPU, memory and other information.
To query the factscontent of all variables, you can use ansible node1 -m setup > setup.jsonSave the variable to a file for viewing

Common facts variables

  • IPV4 address ansible_default_ipv4['address']
  • CPU name ansible_hostname
  • RAM ansible_memtotal_mb
  • Disk information ansible_devices
  • Mount information ansible_mounts

    Custom facts variable

    By default, the setupmodule will /etc/ansible/facts.dobtain user-defined variables from the folder on the host of the controlled node . File or script .factends with

# 自定义fact文件
# cat custom.fact 
[general]
package = httpd
service = httpd
state = started
enabled = true
# 调用自定义fact变量
# cat playbook.yml 
---
- name: Install Apache and starts the service
  hosts: webserver
  tasks:
    - name: Install the required package
      yum:
        name: "{{ ansible_facts['ansible_local']['custom']['general']['package'] }}"
        state: latest
    - name: Start the service
      service:
        name: "{{ ansible_facts['ansible_local']['custom']['general']['service'] }}"
        state: "{{ ansible_facts['ansible_local']['custom']['general']['state'] }}"
        enabled: "{{ ansible_facts['ansible_local']['custom']['general']['enabled'] }}"

magic variable

The magic variable is the content of the machine, including inventorythe content in the file

---
- hosts: localhost
  tasks:
   - name: print magic variables
     debug:
       var: hostvars['localhost']

Guess you like

Origin blog.51cto.com/13540167/2607068