当前位置:网站首页>Priority analysis of list variables in ansible playbook and how to separate and summarize list variables

Priority analysis of list variables in ansible playbook and how to separate and summarize list variables

2022-06-13 07:01:00 The mountains and rivers are all right

Write it at the front


  • Um. , Study Ansible Advanced features , Organize this part of the notes
  • The content of the blog involves
    • Ansible ploybook Basic principles of variable definition in
    • Define the priority of variables in different positions Demo
    • How to decouple variables from lists
  • How to eat :
    • A lot of Demo, Therefore, it is suitable for collecting, reviewing and looking up variable priority
    • Need to have ansible Basics
    • Understand the basic structure of the role play
    • Able to use Ansible Solve practical problems
  • If you don't understand enough, please help me correct

In the evening , You sit under the eaves , Watching the sky slowly darken , My heart is lonely and desolate , Feel deprived of your life . I was a young man , But I'm afraid to live like this , Aging goes on . in my opinion , This is more terrible than death .-------- Wang Xiaobo


Manage manifest variables

Describe the basic principles of variables

stay Ansible in , Using variables , You can write Mission 、 Roles and playbook, Make them reusable and flexible . Variables can specify Configuration differences between different systems .ansilbe Variables can be set in many different places :

  • In the role of defaults and vars Directory
  • stay Host manifest file in , As Host variables or Group variable
  • stay Playbook Or a list of group_vars or host_vars In the variable file under the subdirectory
  • stay Play role or Mission in

When defining and managing variables in a project , Plan to follow the following principle

  • Keep it simple : Although many different ⽅ Formula definition Ansible Variable , But try to use only oneortwo different ways and define variables in only a few places .

  • Don't repeat : If ⼀ Group systems have the same configuration , Then organize them into ⼀ In groups , And in group_vars Set manifest variables for them in the files under the directory .

  • Organize variables in small readable files : If you have a large project with many host groups and variables , Please split the variable into multiple files .

Variable merging and priority

When defining the same variable in multiple ways ,Ansible A priority rule will be used to pick values for variables . Priority is discussed below From low to high

  • The configuration file (ansible.cfg)
  • Command line options
  • role defaults Variable
  • host and group Variable
  • Play Variable
  • Extra Variable ( Global variables

Let's briefly sort out these variables together :

The configuration file

The variables in the configuration file have the lowest priority , By means of ansible.cfg Provide one of KV The key/value pair , Let's look at one Demo

┌──[[email protected]]-[~/ansible]
└─$cat ansible.cfg | grep remote_user
remote_user=root
┌──[[email protected]]-[~/ansible]
└─$

In the configuration file here remote_user=root Is the remote user name to connect to the managed machine , Save the corresponding to ansible Medium ansible_user variable

┌──[[email protected]]-[~/ansible]
└─$ansible vms82.liruilongs.github.io -m debug -a 'var=ansible_user' -i ./inventorys/hosts
vms82.liruilongs.github.io | SUCCESS => {
    
    "ansible_user": "root"
}

Delete the variables in the configuration file ,

┌──[[email protected]]-[~/ansible]
└─$sed -i '/remote_user=root/d' ansible.cfg

When printing variables, you will be prompted that the variables have not been defined

┌──[[email protected]]-[~/ansible]
└─$ansible vms82.liruilongs.github.io -m debug -a 'var=ansible_user' -i ./inventorys/hosts
vms82.liruilongs.github.io | SUCCESS => {
    "ansible_user": "VARIABLE IS NOT DEFINED!"
}

You can also print normally after adding

┌──[[email protected]]-[~/ansible]
└─$sed '4a remote_user=root' ansible.cfg -i
┌──[[email protected]]-[~/ansible]
└─$ansible vms82.liruilongs.github.io -m debug -a 'var=ansible_user' -i ./inventorys/hosts
vms82.liruilongs.github.io | SUCCESS => {
    
    "ansible_user": "root"
}
┌──[[email protected]]-[~/ansible]
└─$

Of course, what we need to pay attention to here is , When the host list is not specified , By default ansible Files with suffixes are ignored

┌──[[email protected]]-[~/ansible]
└─$ansible-config  dump | grep -i inventory
DEFAULT_HOST_LIST(/root/ansible/ansible.cfg) = [u'/root/ansible/inventory']
DEFAULT_INVENTORY_PLUGIN_PATH(default) = [u'/root/.ansible/plugins/inventory', u'/usr/share/ansible/plugins/inventory']
INVENTORY_ANY_UNPARSED_IS_FAILED(default) = False
INVENTORY_CACHE_ENABLED(default) = False
INVENTORY_CACHE_PLUGIN(default) = None
INVENTORY_CACHE_PLUGIN_CONNECTION(default) = None
INVENTORY_CACHE_PLUGIN_PREFIX(default) = ansible_facts
INVENTORY_CACHE_TIMEOUT(default) = 3600
INVENTORY_ENABLED(default) = ['host_list', 'script', 'auto', 'yaml', 'ini', 'toml']
INVENTORY_EXPORT(default) = False
INVENTORY_IGNORE_EXTS(default) = {
    {
    (BLACKLIST_EXTS + ( '.orig', '.ini', '.cfg', '.retry'))}}
INVENTORY_IGNORE_PATTERNS(default) = []
INVENTORY_UNPARSED_IS_FAILED(default) = False
VARIABLE_PRECEDENCE(default) = ['all_inventory', 'groups_inventory', 'all_plugins_inventory', 'all_plugins_play', 'groups_plugins_inventory', 'groups_plugins_play']
┌──[[email protected]]-[~/ansible]
└─$

Command line options :

Can be passed to on the command line ansible-playbook The option to ( Not -e ) With lowest priority . Here we mainly talk about defining variables through other parameters , Still use what we defined before ansible_user Variable

┌──[[email protected]]-[~/ansible]
└─$ansible all -m debug -a "var=ansible_user"
vms82.liruilongs.github.io | SUCCESS => {
    
    "ansible_user": "root"
}
┌──[[email protected]]-[~/ansible]
└─$ansible all -m debug -a "var=ansible_user" -u liruilong
vms82.liruilongs.github.io | SUCCESS => {
    
    "ansible_user": "liruilong"
}

Of course, what needs to be noted here is that it is executed through temporary commands debug modular . The managed machine is not connected by default , So no error will be reported here , our sanheyiwuyang A user is a user that is not defined by the managed machine .

┌──[[email protected]]-[~/ansible]
└─$ansible all -m debug -a "var=ansible_user" -u sanheyiwuyang
vms82.liruilongs.github.io | SUCCESS => {
    
    "ansible_user": "sanheyiwuyang"
}
┌──[[email protected]]-[~/ansible]
└─$

role default value :

role_name/defaults/ The default value set by the role in the file has a very low priority . Relative to... In the role vars Variables in the directory , Will be covered defaults A variable's value . Here we still use remote_user This variable

First, create a new role

┌──[[email protected]]-[~/ansible]
└─$ansible-galaxy init vars_demo --init-path=roles
- Role vars_demo was created successfully
┌──[[email protected]]-[~/ansible]
└─$ansible-galaxy list | grep var
- vars_demo, (unknown version)

Write the default variable in the role , Here we define a remote user name that is not defined in the managed machine sanheyiwuyang

┌──[[email protected]]-[~/ansible]
└─$echo -e "ansible_user: sanheyiwuyang" > ./roles/vars_demo/defaults/main.yml
┌──[[email protected]]-[~/ansible]
└─$cat ./roles/vars_demo/defaults/main.yml
ansible_user: sanheyiwuyang
┌──[[email protected]]-[~/ansible]
└─$

Write role tasks

┌──[[email protected]]-[~/ansible]
└─$vim ./roles/vars_demo/tasks/main.yml
┌──[[email protected]]-[~/ansible]
└─$cat ./roles/vars_demo/tasks/main.yml
---
# tasks file for vars_demo
- name: default_vars demo
  debug:
    var: ansible_user
┌──[[email protected]]-[~/ansible]
└─$

Write a script to perform the role

┌──[[email protected]]-[~/ansible]
└─$vim  vars_demo.yaml
┌──[[email protected]]-[~/ansible]
└─$cat vars_demo.yaml
---
- name: vars_demo roles demo
  hosts: all
  roles:
    - vars_demo
  tasks:
    - name: show vars
      debug:
        var: ansible_user
┌──[[email protected]]-[~/ansible]
└─$

Current ansible_user Variable definitions , We can see , The configuration file has the lowest priority , The second is The command line is not (-e) The way

┌──[[email protected]]-[~/ansible]
└─$ansible-playbook vars_demo.yaml  -u liruilong

PLAY [vars_demo roles demo] ****************************************************************************************

TASK [Gathering Facts] *********************************************************************************************
fatal: [vms82.liruilongs.github.io]: UNREACHABLE! => {
    "changed": false, "msg": "Failed to connect to the host via ssh: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).", "unreachable": true}

PLAY RECAP *********************************************************************************************************
vms82.liruilongs.github.io : ok=0    changed=0    unreachable=1    failed=0    skipped=0    rescued=0    ignored=0  

┌──[[email protected]]-[~/ansible]
└─$

Execute the script of the calling role , Wrong report , adopt -u The way of specifying liruilong user , But what is used in the role is not liruilong user , It is not defined by the managed machine sanhewuyang user , Because the named line is not -e The priority of variables in the role is lower than that in the role /roles/var_demo/default/main.yaml Variables defined , therefore liruilong The user is overwritten , So there's an error

modify ./roles/vars_demo/defaults/main.yml Medium ansible_user Variable , We can also find that root user , Not the command line liruilong

┌──[[email protected]]-[~/ansible]
└─$echo "ansible_user: root" >  ./roles/vars_demo/defaults/main.yml
┌──[[email protected]]-[~/ansible]
└─$ansible-playbook vars_demo.yaml  -u liruilong

PLAY [vars_demo roles demo] ****************************************************************************************

TASK [Gathering Facts] *********************************************************************************************
ok: [vms82.liruilongs.github.io]

TASK [vars_demo : default_vars demo] *******************************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "root"
}

TASK [show vars] ***************************************************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "root"
}

PLAY RECAP *********************************************************************************************************
vms82.liruilongs.github.io : ok=3    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0


┌──[[email protected]]-[~/ansible]
└─$

Host variables and group variables :

For host variables and group variables, this is the corresponding host manifest file , There are many ways to define a host list , We can go straight through inventory File defines , You can also create
inventory Files in the directory to define , You can also define... Under the specified directory in the project , There are many scenes , Let's take a look at

The following list is from Lowest to highest Lists the exact priority of these variables :

  • Set directly in the manifest file or through the dynamic manifest script al Group variable .
  • Other group variables set directly in the manifest file or through the dynamic manifest script .
  • stay inventory/group_vars/all Set in file or subdirectory all Group variables .
  • In the project group_vars/all Set in file or subdirectory all Group variables .
  • stay inventory/group_vars Other group variables set in the subdirectory .
  • In the project group_vars Other group variables set in the subdirectory .
  • Host variables set directly in the manifest file or through the dynamic manifest script .
  • stay inventory/host vars Host variables set in subdirectories .
  • In the project host vars Host variables set in subdirectories .
  • host facts And cached facts.

Let's take a look at them separately :

Set directly in the manifest file or through the dynamic manifest script all Group variable

┌──[[email protected]]-[~/ansible]
└─$vim inventory/inventory
┌──[[email protected]]-[~/ansible]
└─$cat inventory/inventory
vms82.liruilongs.github.io
[all:vars]
ansible_user=liruilong

The default value in the current role is root

┌──[[email protected]]-[~/ansible]
└─$cat ./roles/vars_demo/defaults/main.yml
ansible_user: root
┌──[r[email protected]]-[~/ansible]
└─$

Through the execution of the script, we can see all Group variables in must have priority over default Variables in the directory

┌──[[email protected]]-[~/ansible]
└─$ansible-playbook vars_demo.yaml

PLAY [vars_demo roles demo] ****************************************************************************************

TASK [Gathering Facts] *********************************************************************************************
ok: [vms82.liruilongs.github.io]

TASK [vars_demo : default_vars demo] *******************************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "liruilong"
}

TASK [show vars] ***************************************************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "liruilong"
}

PLAY RECAP *********************************************************************************************************
vms82.liruilongs.github.io : ok=3    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0  

┌──[[email protected]]-[~/ansible]
└─$

Set directly in the manifest file or through the dynamic manifest script Other group variables .

Based on the above, we create a new group variable [lb:vars]. Definition ansible_user The value of is root

┌──[[email protected]]-[~/ansible]
└─$vim inventory/inventory
┌──[[email protected]]-[~/ansible]
└─$cat inventory/inventory
[lb]
vms82.liruilongs.github.io
[lb:vars]
ansible_user=root
[all:vars]
ansible_user=liruilong

Execute the script and discover , adopt ansible_user The value of is root, The description covers all Set variables in the group

┌──[[email protected]]-[~/ansible]
└─$vim inventory/inventory
┌──[[email protected]]-[~/ansible]
└─$ansible-playbook vars_demo.yaml

PLAY [vars_demo roles demo] ****************************************************************************************

TASK [Gathering Facts] *********************************************************************************************
ok: [vms82.liruilongs.github.io]

TASK [vars_demo : default_vars demo] *******************************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "root"
}

TASK [show vars] ***************************************************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "root"
}

PLAY RECAP *********************************************************************************************************
vms82.liruilongs.github.io : ok=3    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0


┌──[[email protected]]-[~/ansible]
└─$

stay inventory/group_vars/all Set in file or subdirectory all Group variables

┌──[[email protected]]-[~/ansible]
└─$mkdir -p inventory/group_vars
┌──[[email protected]]-[~/ansible]
└─$echo "ansible_user: liruilong" > inventory/group_vars/all

Will find inventory/group_vars/all Covering the above inventory/inventory Variables defined ,ansible_user The value of is liruilong

┌──[[email protected]]-[~/ansible]
└─$ansible-playbook vars_demo.yaml

PLAY [vars_demo roles demo] ****************************************************************************************

TASK [Gathering Facts] *********************************************************************************************
ok: [vms82.liruilongs.github.io]

TASK [vars_demo : default_vars demo] *******************************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "liruilong"
}

TASK [show vars] ***************************************************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "liruilong"
}

PLAY RECAP *********************************************************************************************************
vms82.liruilongs.github.io : ok=3    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0  

┌──[[email protected]]-[~/ansible]
└─$

stay project Of group_vars/all Set in file or subdirectory all Group variables .

┌──[[email protected]]-[~/ansible]
└─$mkdir group_vars
┌──[[email protected]]-[~/ansible]
└─$echo "ansible_user: root" >  group_vars/all

We will find that the project group_vars/all The following variables will overwrite the host manifest file inventory/group_vars/all Next variable

┌──[[email protected]]-[~/ansible]
└─$ansible-playbook vars_demo.yaml

PLAY [vars_demo roles demo] ****************************************************************************************

TASK [Gathering Facts] *********************************************************************************************
ok: [vms82.liruilongs.github.io]

TASK [vars_demo : default_vars demo] *******************************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "root"
}

TASK [show vars] ***************************************************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "root"
}

PLAY RECAP *********************************************************************************************************
vms82.liruilongs.github.io : ok=3    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0  

┌──[[email protected]]-[~/ansible]
└─$

stay inventory/group_vars Other group variables set in the subdirectory

Here's the thing to note , establish lb Group variable inventory/group_vars/lb.yaml The premise of the document is , Need to be in inventory/inventory Define groups in the file

┌──[[email protected]]-[~/ansible]
└─$cat ./inventory/inventory
[lb]
vms82.liruilongs.github.io

You can see in the inventory/group_vars/lb.yaml The definition in the file overrides

┌──[[email protected]]-[~/ansible]
└─$echo "ansible_user: liruilong" >  inventory/group_vars/lb.yaml
┌──[[email protected]]-[~/ansible]
└─$ansible-playbook vars_demo.yaml

PLAY [vars_demo roles demo] ****************************************************************************************

TASK [Gathering Facts] *********************************************************************************************
ok: [vms82.liruilongs.github.io]

TASK [vars_demo : default_vars demo] *******************************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "liruilong"
}

TASK [show vars] ***************************************************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "liruilong"
}

PLAY RECAP *********************************************************************************************************
vms82.liruilongs.github.io : ok=3    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0  

┌──[[email protected]]-[~/ansible]
└─$

In the project group_vars Other group variables set in the subdirectory

You can see the of the project ./group_vars/lb.yaml The priority of variables is higher than inventory/group_vars/lb.yaml Under the

┌──[[email protected]]-[~/ansible]
└─$echo "ansible_user: root" > ./group_vars/lb.yaml
┌──[[email protected]]-[~/ansible]
└─$ansible-playbook vars_demo.yaml

PLAY [vars_demo roles demo] ****************************************************************************************

TASK [Gathering Facts] *********************************************************************************************
ok: [vms82.liruilongs.github.io]

TASK [vars_demo : default_vars demo] *******************************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "root"
}

TASK [show vars] ***************************************************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "root"
}

PLAY RECAP *********************************************************************************************************
vms82.liruilongs.github.io : ok=3    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0  

┌──[[email protected]]-[~/ansible]
└─$

What we analyzed earlier are all group variables , Now let's look at the host variables

Directly in Inventory file Or through a dynamic list script Host variables

┌──[[email protected]]-[~/ansible]
└─$sed  "s/vms82.liruilongs.github.io/& ansible_user=liruilong/" ./inventory/inventory
[lb]
vms82.liruilongs.github.io ansible_user=liruilong
[lb:vars]
ansible_user=root
[all:vars]
ansible_user=liruilong
┌──[[email protected]]-[~/ansible]
└─$sed  "s/vms82.liruilongs.github.io/& ansible_user=liruilong/" ./inventory/inventory -i

Set the host variable to ansible_user=liruilong The priority is higher than the group variable above

┌──[[email protected]]-[~/ansible]
└─$ansible-playbook vars_demo.yaml

PLAY [vars_demo roles demo] ****************************************************************************************

TASK [Gathering Facts] *********************************************************************************************
ok: [vms82.liruilongs.github.io]

TASK [vars_demo : default_vars demo] *******************************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "liruilong"
}

TASK [show vars] ***************************************************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "liruilong"
}

PLAY RECAP *********************************************************************************************************
vms82.liruilongs.github.io : ok=3    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0  

┌──[[email protected]]-[~/ansible]
└─$

stay inventory/host_vars Host variables set in subdirectories

┌──[[email protected]]-[~/ansible]
└─$mkdir inventory/host_vars
┌──[[email protected]]-[~/ansible]
└─$echo "ansible_user: root" > inventory/host_vars/vms82.liruilongs.github.io.yaml

inventory/host_vars The priority of the host variable set in the subdirectory is greater than ./inventory/inventory Host variables in

┌──[[email protected]]-[~/ansible]
└─$ansible-playbook vars_demo.yaml

PLAY [vars_demo roles demo] ****************************************************************************************

TASK [Gathering Facts] *********************************************************************************************
ok: [vms82.liruilongs.github.io]

TASK [vars_demo : default_vars demo] *******************************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "root"
}

TASK [show vars] ***************************************************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "root"
}

PLAY RECAP *********************************************************************************************************
vms82.liruilongs.github.io : ok=3    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0


┌──[[email protected]]-[~/ansible]
└─$

In the project host_vars Host variables set in subdirectories

┌──[[email protected]]-[~/ansible]
└─$mkdir  host_vars
┌──[[email protected]]-[~/ansible]
└─$echo "ansible_user: liruilong" > host_vars/vms82.liruilongs.github.io.yaml

Project host_vars The priority of host variables set in the subdirectory is higher than that in the list host_vars Variables of subdirectories

┌──[[email protected]]-[~/ansible]
└─$ansible-playbook vars_demo.yaml

PLAY [vars_demo roles demo] ****************************************************************************************

TASK [Gathering Facts] *********************************************************************************************
ok: [vms82.liruilongs.github.io]

TASK [vars_demo : default_vars demo] *******************************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "liruilong"
}

TASK [show vars] ***************************************************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "liruilong"
}

PLAY RECAP *********************************************************************************************************
vms82.liruilongs.github.io : ok=3    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0  

┌──[[email protected]]-[~/ansible]
└─$

host facts And cached facts

host facts, You can see set_fact The variables set have the highest priority

┌──[[email protected]]-[~/ansible]
└─$cat vars_demo.yaml
---
- name: vars_demo roles demo
  hosts: all
  roles:
    - vars_demo
  tasks:
    - name: show vars
      debug:
        var: ansible_user
    - name: set fact ansible_user
      set_fact:
         ansible_user: root
    - name: show vars
      debug:
        var: ansible_user
┌──[[email protected]]-[~/ansible]
└─$ansible-playbook vars_demo.yaml

PLAY [vars_demo roles demo] ****************************************************************************************

TASK [Gathering Facts] *********************************************************************************************
ok: [vms82.liruilongs.github.io]

TASK [vars_demo : default_vars demo] *******************************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "liruilong"
}

TASK [show vars] ***************************************************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "liruilong"
}

TASK [set fact ansible_user] ***************************************************************************************
ok: [vms82.liruilongs.github.io]

TASK [show vars] ***************************************************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "root"
}

PLAY RECAP *********************************************************************************************************
vms82.liruilongs.github.io : ok=5    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

For others, some pass gather_facts Collected variables , It has a high priority over the outside of the script

Relative to the list inventory Of group_vars and host_vars Subdirectories are relative to playbook The priority between the subdirectories of the project is easy to distinguish , The same type , Projects always have a higher priority than the list ,.

If in playbook In the same directory as group_vars and host_vars subdirectories , Then these group and host variables will be automatically included .

Just to summarize ansible Manifest file variable priority . stay facts The highest priority , The second is host variables , Contains the manifest variable file host_vars Contents and inventory List variable directory and inventory file , Items should be higher than the list , The list directory should be higher than the list file , Then there is a group of variables ,group_vars A file in a directory ,inventory Manifest Variable Directory ,inventory file , On the whole ,inventory The priority of the file is lower than that of the directory , The same is inventory The directory should be smaller than the project directory .

Play Variable :

preparation , We also use the previous roles and scripts

┌──[[email protected]]-[~/ansible]
└─$cat vars_demo.yaml
---
- name: vars_demo roles demo
  hosts: all
  roles:
    - vars_demo
  tasks:
    - name: show vars
      debug:
        var: ansible_user
    - name: show vars
      debug:
        var: ansible_user
┌──[[email protected]]-[~/ansible]
└─$ansible-playbook vars_demo.yaml

PLAY [vars_demo roles demo] ****************************************************************************************

TASK [Gathering Facts] *********************************************************************************************
ok: [vms82.liruilongs.github.io]

TASK [vars_demo : default_vars demo] *******************************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "liruilong"
}

TASK [show vars] ***************************************************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "liruilong"
}

TASK [show vars] ***************************************************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "liruilong"
}

PLAY RECAP *********************************************************************************************************
vms82.liruilongs.github.io : ok=4    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

Play Has a higher priority than Host or group variables 、 Role defaults , except -e Command line options other than . The following list lists the priority of these variables from the lowest to the highest :

  • from play Of vars Set in part .
  • adopt play Medium vars_prompt Part prompts the user to set .
  • adopt play Of vars_files Some settings are made from the external file list .
  • By role rolename/vars/ Set the files in the subdirectory .
  • Through this block vars Part is the current block Set it up .
  • Through this task vars Part is set for the current task .
  • adopt include_vars Module dynamic loading .
  • By using set_fact Module or by using register Record the results of task execution on the host , Set up for a specific host .
  • stay play Of role Partially loaded or by using include_role modular playbook Parameters set for roles in .
  • from vars Partly through include_tasks Set the tasks contained in the module .

Let's sort out :

from play Of vars Set in part .

---
- name: vars_demo roles demo
  hosts: all
  vars:
    ansible_user: root
  roles:
    - vars_demo
  tasks:
    - name: show vars
      debug:
        var: ansible_user
    - name: show vars
      debug:
        var: ansible_user

play Of vars Part of the variables to be set are higher than the previously set variables

┌──[[email protected]]-[~/ansible]
└─$ansible-playbook vars_demo.yaml

PLAY [vars_demo roles demo] ****************************************************************************************

TASK [Gathering Facts] *********************************************************************************************
ok: [vms82.liruilongs.github.io]

TASK [vars_demo : default_vars demo] *******************************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "root"
}

TASK [show vars] ***************************************************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "root"
}

TASK [show vars] ***************************************************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "root"
}

PLAY RECAP *********************************************************************************************************
vms82.liruilongs.github.io : ok=4    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0


adopt play Medium vars_prompt Part prompts the user to set

---
- name: vars_demo roles demo
  hosts: all
  vars:
    ansible_user: root
  vars_prompt:
    - name: ansible_user
      prompt: "input ansible_user name"
  roles:
    - vars_demo
  tasks:
    - name: show vars
      debug:
        var: ansible_user
    - name: show vars
      debug:
        var: ansible_user

By default, the input data is not displayed , You can add parameters private: no To display the value of the input variable

┌──[[email protected]]-[~/ansible]
└─$ansible-playbook vars_demo.yaml
input ansible_user name:

PLAY [vars_demo roles demo] ****************************************************************************************

TASK [Gathering Facts] *********************************************************************************************
ok: [vms82.liruilongs.github.io]

TASK [vars_demo : default_vars demo] *******************************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "liruilong"
}

TASK [show vars] ***************************************************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "liruilong"
}

TASK [show vars] ***************************************************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "liruilong"
}

PLAY RECAP *********************************************************************************************************
vms82.liruilongs.github.io : ok=4    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0  

adopt play Of vars_files Some settings are made from the external file list

---
- name: vars_demo roles demo
  hosts: all
  vars:
    ansible_user: root
  vars_files:
    - vars_files
  vars_prompt:
    - name: ansible_user
      prompt: "input ansible_user name"
      private: no
  roles:
    - vars_demo
  tasks:
    - name: show vars
      debug:
        var: ansible_user
    - name: show vars
      debug:
        var: ansible_user

Define the imported variable file

┌──[[email protected]]-[~/ansible]
└─$echo "ansible_user: liruilong" > vars_files

Execute the script , You can see that what we entered is root But what's printed is liruilong, namely vars_files Has a higher priority than vars_prompt

┌──[[email protected]]-[~/ansible]
└─$ansible-playbook vars_demo.yaml
input ansible_user name: root

PLAY [vars_demo roles demo] ****************************************************************************************

TASK [Gathering Facts] *********************************************************************************************
ok: [vms82.liruilongs.github.io]

TASK [vars_demo : default_vars demo] *******************************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "liruilong"
}

TASK [show vars] ***************************************************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "liruilong"
}

TASK [show vars] ***************************************************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "liruilong"
}

PLAY RECAP *********************************************************************************************************
vms82.liruilongs.github.io : ok=4    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

By role rolename/vars/ Set the files in the subdirectory

The variable value returned by the current script execution is liruilong, We define roles/vars_demo/vars/main.yml The directory ansible_user Variable is root. Execute the script

┌──[[email protected]]-[~/ansible]
└─$echo "ansible_user: root" > roles/vars_demo/vars/main.yml
┌──[[email protected]]-[~/ansible]
└─$ansible-playbook vars_demo.yaml

PLAY [vars_demo roles demo] ****************************************************************************************

TASK [Gathering Facts] *********************************************************************************************
ok: [vms82.liruilongs.github.io]

TASK [vars_demo : default_vars demo] *******************************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "root"
}

TASK [show vars] ***************************************************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "root"
}

TASK [show vars] ***************************************************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "root"
}

PLAY RECAP *********************************************************************************************************
vms82.liruilongs.github.io : ok=4    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

Through this task block vars Part is the current block Set it up .

---
- name: vars_demo roles demo
  hosts: all
  roles:
    - vars_demo
  tasks:
    - block:
        - name: show vars in block
          debug:
            var: ansible_user
      vars:
        ansible_user: liruilong
    - name: show vars
      debug:
        var: ansible_user

We can see , stay block Inside the block where it is located , adopt vars Variables defined have the highest priority , Printed ansible_usern The of the variable is liruilong, The variables printed in other parts of the script are root

┌──[[email protected]]-[~/ansible]
└─$ansible-playbook var_demos.yaml

PLAY [vars_demo roles demo] ****************************************************************

TASK [Gathering Facts] *********************************************************************
ok: [vms82.liruilongs.github.io]

TASK [vars_demo : default_vars demo] *******************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "root"
}

TASK [show vars in block] ******************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "liruilong"
}

TASK [show vars] ***************************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "root"
}

PLAY RECAP *********************************************************************************
vms82.liruilongs.github.io : ok=4    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

show vars The task is the task in the role , So we still use the characters vars/main.yml Definition root.

Through this task vars Part is set for the current task

It is not written in block In block vars Variable , It's written in the corresponding In the task vars Variables in

---
- name: vars_demo roles demo
  hosts: all
  roles:
    - vars_demo
  tasks:
    - block:
        - name: show vars in block
          debug:
            var: ansible_user
          vars:
            ansible_user: root
        - name: show vars  in block no vars
          debug:
            var: ansible_user
      vars:
        ansible_user: liruilong

Execution we can see in block Inside , Variables inside the task have higher priority than variables outside the task .

┌──[[email protected]]-[~/ansible]
└─$ansible-playbook vars_demo.yaml

PLAY [vars_demo roles demo] ****************************************************************

TASK [Gathering Facts] *********************************************************************
ok: [vms82.liruilongs.github.io]

TASK [vars_demo : default_vars demo] *******************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "root"
}

TASK [show vars in block] ******************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "root"
}

TASK [show vars  in block no vars] *********************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "liruilong"
}

PLAY RECAP *********************************************************************************
vms82.liruilongs.github.io : ok=4    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

adopt include_vars Module dynamic loading

stay ansible in , We can use include_vars Module to load external variables . The loading method is simple , And through the play Of vars_files Part of the setup from the external file list is very similar .

---
- name: vars_demo roles demo
  hosts: all
  roles:
    - vars_demo
  tasks:
    - block:
        - name: show vars in block
          debug:
            var: ansible_user
          vars:
            ansible_user: root
        - name: show vars  in block no vars
          debug:
            var: ansible_user
      vars:
        ansible_user: liruilong
    - name: show vars
      debug:
         var: ansible_user

    - name: include_vars vars file
      include_vars:
         file: vars_files
    - name: show vars after include vars files
      debug:
         var: ansible_user

But the priority of variables is very different , Let's put the include_vars Put the module to the end and see .

┌──[[email protected]]-[~/ansible]
└─$cat vars_files
ansible_user: liruilong
┌──[[email protected]]-[~/ansible]
└─$ansible-playbook vars_demo.yaml

PLAY [vars_demo roles demo] ****************************************************************

TASK [Gathering Facts] *********************************************************************
ok: [vms82.liruilongs.github.io]

TASK [vars_demo : default_vars demo] *******************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "root"
}

TASK [show vars in block] ******************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "root"
}

TASK [show vars  in block no vars] *********************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "liruilong"
}

TASK [show vars] ***************************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "root"
}

TASK [include_vars vars file] **************************************************************
ok: [vms82.liruilongs.github.io]

TASK [show vars after include vars files] **************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "liruilong"
}

PLAY RECAP *********************************************************************************
vms82.liruilongs.github.io : ok=7    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

It is found that there is no change before the module is executed , It will only affect the after execution .

---
- name: vars_demo roles demo
  hosts: all
  roles:
    - vars_demo
  tasks:
    - name: include_vars vars file
      include_vars:
         file: vars_files
    - block:
        - name: show vars in block
          debug:
            var: ansible_user
          vars:
            ansible_user: root
        - name: show vars  in block no vars
          debug:
            var: ansible_user
      vars:
        ansible_user: liruilong
    - name: show vars
      debug:
         var: ansible_user

    - name: show vars after include vars files
      debug:
         var: ansible_user

hold include_vars Put the module to the front , We found that all the variables in the script were replaced with liruilong 了 , Except for role variables , Because in the script , The role is executed first .

┌──[[email protected]]-[~/ansible]
└─$ansible-playbook vars_demo.yaml

PLAY [vars_demo roles demo] ****************************************************************

TASK [Gathering Facts] *********************************************************************
ok: [vms82.liruilongs.github.io]

TASK [vars_demo : default_vars demo] *******************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "root"
}

TASK [include_vars vars file] **************************************************************
ok: [vms82.liruilongs.github.io]

TASK [show vars in block] ******************************************************************
ok: [vms82.liruilongs.github.io] =>
    "ansible_user": "liruilong"
}

TASK [show vars  in block no vars] *********************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "liruilong"
}

TASK [show vars] ***************************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "liruilong"
}

TASK [show vars after include vars files] **************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "liruilong"
}

PLAY RECAP *********************************************************************************
vms82.liruilongs.github.io : ok=7    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

By using set_fact modular Or by using register Record the results of task execution on the host , Set up for a specific host .

---
- name: vars_demo roles demo
  hosts: all
  roles:
    - vars_demo
  tasks:
    - name: set facts
      set_fact:
        ansible_user: root
    - name: include_vars vars file
      include_vars:
         file: vars_files
    - block:
        - name: show vars in block
          debug:
            var: ansible_user
          vars:
            ansible_user: root
        - name: show vars  in block no vars
          debug:
            var: ansible_user
      vars:
        ansible_user: liruilong
    - name: show vars
      debug:
         var: ansible_user

    - name: show vars after include vars files
      debug:
         var: ansible_user

Um. , Not much to explain .

┌──[[email protected]]-[~/ansible]
└─$ansible-playbook vars_demo.yaml

PLAY [vars_demo roles demo] ****************************************************************

TASK [Gathering Facts] *********************************************************************
ok: [vms82.liruilongs.github.io]

TASK [vars_demo : default_vars demo] *******************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "root"
}

TASK [set facts] ***************************************************************************
ok: [vms82.liruilongs.github.io]

TASK [include_vars vars file] **************************************************************
ok: [vms82.liruilongs.github.io]

TASK [show vars in block] ******************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "root"
}

TASK [show vars  in block no vars] *********************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "root"
}

TASK [show vars] ***************************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "root"
}

TASK [show vars after include vars files] **************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "root"
}

PLAY RECAP *********************************************************************************
vms82.liruilongs.github.io : ok=8    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

stay play Of role Partially loaded or by using include_role modular playbook Parameters set for roles in .

---
- name: vars_demo roles demo
  hosts: all
  roles:
    - role: vars_demo
      ansible_user: liruilong
  tasks:
    - name: set facts
      set_fact:
        ansible_user: root
    - name: include_vars vars file
      include_vars:
         file: vars_files
    - block:
        - name: show vars in block
          debug:
            var: ansible_user
          vars:
            ansible_user: root
        - name: show vars  in block no vars
          debug:
            var: ansible_user
      vars:
        ansible_user: liruilong
    - name: show vars
      debug:
         var: ansible_user

    - name: show vars after include vars files
      debug:
         var: ansible_user

After the script sets the role variable , The built-in variable is overwritten , But only for the current role

┌──[[email protected]]-[~/ansible]
└─$ansible-playbook vars_demo.yaml

PLAY [vars_demo roles demo] ****************************************************************************

TASK [Gathering Facts] *********************************************************************************
ok: [vms82.liruilongs.github.io]

TASK [vars_demo : default_vars demo] *******************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "liruilong"
}

TASK [set facts] ***************************************************************************************
ok: [vms82.liruilongs.github.io]

TASK [include_vars vars file] **************************************************************************
ok: [vms82.liruilongs.github.io]

TASK [show vars in block] ******************************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "root"
}

TASK [show vars  in block no vars] *********************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "root"
}

TASK [show vars] ***************************************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "root"
}

TASK [show vars after include vars files] **************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "root"
}

PLAY RECAP *********************************************************************************************
vms82.liruilongs.github.io : ok=8    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

Or maybe

---
- name: vars_demo roles demo
  hosts: all
 # roles:
 # - role: vars_demo
 # ansible_user: liruilong
  tasks:
    - name: include role
      include_role:
        name: vars_demo
      vars:
         ansible_user: liruilong
    - name: set facts
      set_fact:
        ansible_user: root
    - name: include_vars vars file
      include_vars:
         file: vars_files
    - block:
        - name: show vars in block
          debug:
            var: ansible_user
          vars:
            ansible_user: root
        - name: show vars  in block no vars
          debug:
            var: ansible_user
      vars:
        ansible_user: liruilong
    - name: show vars
      debug:
         var: ansible_user

    - name: show vars after include vars files
      debug:
         var: ansible_user
┌──[[email protected]]-[~/ansible]
└─$ansible-playbook vars_demo.yaml

PLAY [vars_demo roles demo] ****************************************************************************

TASK [Gathering Facts] *********************************************************************************
ok: [vms82.liruilongs.github.io]

TASK [include role] ************************************************************************************

TASK [vars_demo : default_vars demo] *******************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "liruilong"
}

TASK [set facts] ***************************************************************************************
ok: [vms82.liruilongs.github.io]

TASK [include_vars vars file] **************************************************************************
ok: [vms82.liruilongs.github.io]

TASK [show vars in block] ******************************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "root"
}

TASK [show vars  in block no vars] *********************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "root"
}

TASK [show vars] ***************************************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "root"
}

TASK [show vars after include vars files] **************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "root"
}

PLAY RECAP *********************************************************************************************
vms82.liruilongs.github.io : ok=8    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

from vars Partly through include_tasks Set the tasks contained in the module

---
- name: vars_demo roles demo
  hosts: all
 # roles:
 # - role: vars_demo
 # ansible_user: liruilong
  tasks:
    - name: include_tasks demo
      include_tasks: task.yaml
      vars:
        ansible_user: root
    - name: include role
...
┌──[[email protected]]-[~/ansible]
└─$cat task.yaml
- name: vars demo 2
  debug:
    var: ansible_user
┌──[[email protected]]-[~/ansible]
└─$ansible-playbook vars_demo.yaml

PLAY [vars_demo roles demo] ****************************************************************************

TASK [Gathering Facts] *********************************************************************************
ok: [vms82.liruilongs.github.io]

TASK [include_tasks demo] ******************************************************************************
included: /root/ansible/task.yaml for vms82.liruilongs.github.io

TASK [vars demo 2] *************************************************************************************
ok: [vms82.liruilongs.github.io] => {
    
    "ansible_user": "root"
}

....

Extra Variable (-e Order or –extra-vars)

Use ansible-playbook Ordered -e The extra variables set by the option always have the highest priority . perhaps --extra-vars You can also use JSON Formal definition

┌──[[email protected]]-[~/ansible]
└─$ansible vms82.liruilongs.github.io -m debug -a 'var=ansible_user'
vms82.liruilongs.github.io | SUCCESS => {
    
    "ansible_user": "root"
}
┌──[[email protected]]-[~/ansible]
└─$ansible all -m debug -a "var=ansible_user" --extra-vars "{'ansible_user':'liruilong'}"
vms82.liruilongs.github.io | SUCCESS => {
    
    "ansible_user": "liruilong"
}
┌──[[email protected]]-[~/ansible]
└─$ansible all -m debug -a "var=ansible_user" --e "{'ansible_user':'liruilong'}"
vms82.liruilongs.github.io | SUCCESS => {
    
    "ansible_user": "liruilong"
}

Can be found when using --extra-vars When defining variables on the command line , Will be covered ansible.cfg Variable configuration for , Used liruilong This managed machine user

Separate variables from lists

As the environment expands in size and variety , The manifest file can become large and difficult to read .

It is better to move the variable definition from the manifest file to a separate variable file , Each host group corresponds to one , Each variable file has host group commands , And contains the variable definitions of the host group :

 Insert picture description here

For a diversified and large-scale environment , A better way is to group_vars Create subdirectories for each host group under the directory :

┌──[[email protected]]-[~/inventory-variables]
└─$ls
ansible.cfg        deploy_haproxy.yml  group_vars     roles
deploy_apache.yml  deploy_webapp.yml   inventory.yml  site.yml
┌──[[email protected]]-[~/inventory-variables]
└─$cd group_vars/
┌──[[email protected]]-[~/inventory-variables/group_vars]
└─$tree
.
├── lb_servers
│   ├── firewall.yml
│   └── haproxy.yml
└── web_servers

2 directories, 2 files

 Insert picture description here

group_vars Catalog All variables existing in the files in each directory under are merged with other variables ⼀ rise . By separating variables into files grouped by function , Can make the whole playbook Projects are easier to understand and maintain .

 Insert picture description here

Special list variables

You can use multiple variables to change Ansible How to connect to the hosts listed in the list . among ⼀ Some are most useful for host specific variables , But another ⼀ These may be related to all hosts in the group or in the list .

ansible_connection: The connection type of the host , Connection plug-ins for accessing managed hosts . By default ,ssh Used in addition to localhost All hosts outside , The latter uses local.

┌──[[email protected]]-[~/ansible]
└─$ansible all -m debug -a "msg={
    {ansible_connection}}"
vms82.liruilongs.github.io | SUCCESS => {
    
    "msg": "ssh"
}
┌──[[email protected]]-[~/ansible]
└─$ansible 127.0.0.1  -m debug -a "msg={
    {ansible_connection}}"
127.0.0.1 | SUCCESS => {
    
    "msg": "local"
}

ansible_host: Host name to connect to . actual IP Address or fully qualified domain name , Use when connecting to a managed host , Instead of using it from the manifest file (inventory_hostname) The name of the . By default , This variable has the same value as the manifest hostname .

┌──[[email protected]]-[~/ansible]
└─$ansible all -m debug -a "msg={
    {ansible_host}}"
vms82.liruilongs.github.io | SUCCESS => {
    
    "msg": "vms82.liruilongs.github.io"
}
  • ansible_port:Ansible The port used to connect the managed host . about ( Default )SSH Connect plug-ins , The default value is 22.
  • ansible_user:Ansible Connect to the managed host as this user . As Ansible Default behavior of , It will use and run on the control node Ansible Playbook Connect to the managed host with the same user name .
  • ansible_become_user:Ansible After connecting to the managed host , It will use ansible_become_method( By default sudo) Switch to this user .
  • ansible_python_interpreter:Ansible Should be used on managed hosts Python Path to executable file .

System variables : Through the script gather_facts=yes Automatic collection ( Default call setup modular ), Valid for task host , System indicators

┌──[[email protected]]-[~/ansible]
└─$ansible  all  -m  setup

Use variables to identify the current host

ansible Magic variable , refer to ansible Special variables preset for management purposes , adopt adhoc Way or playbook The way , You can call / perhaps msg see

  • inventory_hostname: Name of the managed host currently being processed , Get... From the list .
  • ansible_host: The actual server used to connect the managed host IP Address or host name .
  • ansible_facts[‘hostname’]: As a matter of fact , From the fully qualified domain name of the managed host phone .
  • ansible_play_hosts: At present Play List of all hosts that have not failed during .
┌──[[email protected]]-[~/ansible]
└─$ansible  all  -m  debug -a "var=hostvars"
vms82.liruilongs.github.io | SUCCESS => {
    
    "hostvars": {
    
        "vms82.liruilongs.github.io": {
    
            "ansible_check_mode": false,
            "ansible_diff_mode": false,
            "ansible_facts": {
    },
            "ansible_forks": 5,
            "ansible_inventory_sources": [
                "/root/ansible/inventory"
            ],
            "ansible_playbook_python": "/usr/bin/python2",
            "ansible_user": "liruilong",
            "ansible_verbosity": 0,
            "ansible_version": {
    
                "full": "2.9.25",
                "major": 2,
                "minor": 9,
                "revision": 25,
                "string": "2.9.25"
            },
            "group_names": [
                "lb"
            ],
            "groups": {
    
                "all": [
                    "vms82.liruilongs.github.io"
                ],
                "lb": [
                    "vms82.liruilongs.github.io"
                ],
                "ungrouped": []
            },
            "inventory_dir": "/root/ansible/inventory",
            "inventory_file": "/root/ansible/inventory/hosts",
            "inventory_hostname": "vms82.liruilongs.github.io",
            "inventory_hostname_short": "vms82",
            "omit": "__omit_place_holder__fbd943e37b3564fcd7926f8926da009ae4e9e4ab",
            "playbook_dir": "/root/ansible"
        }
    }
}

A complete Demo

Um. , Let's look at a specific Demo, this Demo It is used in previous blog posts , Take a look at how to start from the existing ansible Extract variables from the project to realize the reusability of the script , Maintainable

This is the original structure directory

┌──[[email protected]]-[~/ansible/inventory-variables]
└─$tree
.
├── ansible.cfg
├── deploy_apache.yml
├── deploy_haproxy.yml
├── deploy_webapp.yml
├── inventory.yml
├── roles
│   ├── apache
│   │   ├── meta
│   │   │   └── main.yml
│   │   ├── tasks
│   │   │   └── main.yml
│   │   └── tests
│   │       ├── inventory
│   │       └── test.yml
│   ├── firewall
│   │   ├── defaults
│   │   │   └── main.yml
│   │   ├── handlers
│   │   │   └── main.yml
│   │   ├── meta
│   │   │   └── main.yml
│   │   ├── tasks
│   │   │   └── main.yml
│   │   └── tests
│   │       ├── inventory
│   │       └── test.yml
│   ├── haproxy
│   │   ├── defaults
│   │   │   └── main.yml
│   │   ├── handlers
│   │   │   └── main.yml
│   │   ├── meta
│   │   │   └── main.yml
│   │   ├── tasks
│   │   │   └── main.yml
│   │   ├── templates
│   │   │   └── haproxy.cfg.j2
│   │   └── tests
│   │       ├── inventory
│   │       └── test.yml
│   └── webapp
│       ├── defaults
│       │   └── main.yml
│       ├── meta
│       │   └── main.yml
│       ├── tasks
│       │   └── main.yml
│       └── tests
│           ├── inventory
│           └── test.yml
└── site.yml

30 directories, 34 files
┌──[[email protected]]-[~/ansible/inventory-variables]
└─$

This is what we have rewritten , You'll find one more group_vars Catalog

┌──[[email protected]]-[~/ansible/inventory-variables]
└─$tree
.
├── ansible.cfg
├── deploy_apache.yml
├── deploy_haproxy.yml
├── deploy_webapp.yml
├── group_vars
│   ├── lb_servers
│   │   ├── firewall.yml
│   │   └── haproxy.yml
│   └── web_servers
├── inventory.yml
├── roles
│   ├── apache
│   │   ├── meta
│   │   │   └── main.yml
│   │   ├── tasks
│   │   │   └── main.yml
│   │   └── tests
│   │       ├── inventory
│   │       └── test.yml
│   ├── firewall
│   │   ├── defaults
│   │   │   └── main.yml
│   │   ├── handlers
│   │   │   └── main.yml
│   │   ├── meta
│   │   │   └── main.yml
│   │   ├── tasks
│   │   │   └── main.yml
│   │   └── tests
│   │       ├── inventory
│   │       └── test.yml
│   ├── haproxy
│   │   ├── defaults
│   │   │   └── main.yml
│   │   ├── handlers
│   │   │   └── main.yml
│   │   ├── meta
│   │   │   └── main.yml
│   │   ├── tasks
│   │   │   └── main.yml
│   │   ├── templates
│   │   │   └── haproxy.cfg.j2
│   │   └── tests
│   │       ├── inventory
│   │       └── test.yml
│   ├── org_common
│   │   ├── meta
│   │   │   └── main.yml
│   │   ├── tasks
│   │   │   └── main.yml
│   │   └── tests
│   │       ├── inventory
│   │       └── test.yml
│   └── webapp
│       ├── defaults
│       │   └── main.yml
│       ├── meta
│       │   └── main.yml
│       ├── tasks
│       │   └── main.yml
│       └── tests
│           ├── inventory
│           └── test.yml
└── site.yml

30 directories, 34 files

Let's take a look at this Demo, About what the script did , You can take a look at my previous ansible post

Create a new... In the project root group_vars , Create subdirectories for each host group under this directory

┌──[[email protected]]-[/home/student/git-repos/inventory-variables]
└─$mkdir group_vars

establish lb_servers ⽬ record , To store lb_servers Variables of hosts in the Group

┌──[[email protected]]-[/home/student/git-repos/inventory-variables]
└─$mkdir group_vars/lb_servers

establish web_servers ⽬ record , To store web_servers Group variables

┌──[[email protected]]-[/home/student/git-repos/inventory-variables]
└─$ mkdir group_vars/web_servers

Define variable files in each host group for the roles involved

┌──[[email protected]]-[/home/student/git-repos/inventory-variables]
└─$touch group_vars/lb_servers/firewall.yml
┌──[[email protected]]-[/home/student/git-repos/inventory-variables]
└─$touch group_vars/lb_servers/haproxy.yml
┌──[[email protected]]-[/home/student/git-repos/inventory-variables]
└─$ls

In execution deploy_haproxy When the script , call haproxy, It will involve the loading of role related variables .firewall_rules,haproxy_appservers These two role variables .firewall Roles are executed in a role dependent manner , and haproxy Execute directly through the script

┌──[[email protected]]-[/home/student/git-repos/inventory-variables]
└─$cat deploy_haproxy.yml
- name: Ensure HAProxy is deployed
  hosts: lb_servers
  force_handlers: True

  roles:
    # The "haproxy" role has a dependency on the "firewall" role.
    # The "firewall" role requires a "firewall_rules" variable be defined.
    - role: haproxy
      firewall_rules:
        # Allow 80/tcp connections
        - port: 80/tcp

      haproxy_appservers:
      - name: serverb.lab.example.com
        ip: 172.25.250.11
        backend_port: 80
      - name: serverc.lab.example.com
        ip: 172.25.250.12
        backend_port: 80

stay group_vars/lb_servers/firewall.yml Define host groups lb_servers It's about firewall Role variables

┌──[[email protected]]-[/home/student/git-repos/inventory-variables]
└─$tee group_vars/lb_servers/firewall.yml <<- EOF
> firewall_rules:
>    # Allow 80/tcp connections
>    - port: 80/tcp
> EOF
firewall_rules:
   # Allow 80/tcp connections
   - port: 80/tcp
┌──[[email protected]ation.lab.example.com]-[/home/student/git-repos/inventory-variables]
└─$

At the same time, delete the variables in the script

┌──[[email protected]]-[/home/student/git-repos/inventory-variables]
└─$cat deploy_haproxy.yml
- name: Ensure HAProxy is deployed
  hosts: lb_servers
  force_handlers: True

  roles:
    # The "haproxy" role has a dependency on the "firewall" role.
    # The "firewall" role requires a "firewall_rules" variable be defined.
    - role: haproxy
      haproxy_appservers:
      - name: serverb.lab.example.com
        ip: 172.25.250.11
        backend_port: 80
      - name: serverc.lab.example.com
        ip: 172.25.250.12
        backend_port: 80

The same in lb_servers Under the host group directory haproxy Role variables are defined in the file haproxy Variables involved in the role

┌──[[email protected]]-[/home/student/git-repos/inventory-variables]
└─$tee  group_vars/lb_servers/haproxy.yml <<- EOF
> haproxy_appservers:
>    - name: serverb.lab.example.com
>      ip: 172.25.250.11
>      backend_port: 80
>    - name: serverc.lab.example.com
>      ip: 172.25.250.12
>      backend_port: 80
> EOF
haproxy_appservers:
   - name: serverb.lab.example.com
     ip: 172.25.250.11
     backend_port: 80
   - name: serverc.lab.example.com
     ip: 172.25.250.12
     backend_port: 80
┌──[[email protected]]-[/home/student/git-repos/inventory-variables]
└─$
┌──[[email protected]]-[/home/student/git-repos/inventory-variables]
└─$cat deploy_haproxy.yml
- name: Ensure HAProxy is deployed
  hosts: lb_servers
  force_handlers: True

  roles:
    # The "haproxy" role has a dependency on the "firewall" role.
    # The "firewall" role requires a "firewall_rules" variable be defined.
    - role: haproxy

Through the above transformation , We decouple variables from the script that performs the role , This is similar to the way that static variable data is extracted from the code by loading the configuration file . If the script of the calling character is complicated , That's by pulling the variables away , Every time you need to maintain or migrate, you can directly modify the variable file .

alike deploy_apache Let's replace the script variables in the same way .

┌──[[email protected]]-[/home/student/git-repos/inventory-variables]
└─$ cat deploy_apache.yml
- name: Ensure Apache is deployed
  hosts: web_servers
  force_handlers: True

  roles:
    # The "apache" role has a dependency on the "firewall" role.
    # The "firewall" role requires a "firewall_rules" variable be defined.
    - role: apache
      firewall_rules:
        # Allow http requests from the load_balancer.
        - zone: internal
          service: http
          source: "172.25.250.10"
┌──[[email protected]]-[/home/student/git-repos/inventory-variables]
└─$tee group_vars/web_servers/firewall.yml <<- EOF
> firewall_rules:
>    # Allow http requests from the load_balancer.
>    - zone: internal
>      service: http
>      source: "172.25.250.10"
> EOF
firewall_rules:
   # Allow http requests from the load_balancer.
   - zone: internal
     service: http
     source: "172.25.250.10"
┌──[[email protected]]-[/home/student/git-repos/inventory-variables]
└─$
- name: Ensure Apache is deployed
  hosts: web_servers
  force_handlers: True

  roles:
    # The "apache" role has a dependency on the "firewall" role.
    # The "firewall" role requires a "firewall_rules" variable be defined.
    - role: apache

There are more directories after the transformation

┌──[[email protected]]-[/home/student/git-repos/inventory-variables/group_vars]
└─$tree
.
├── lb_servers
│   ├── firewall.yml
│   └── haproxy.yml
└── web_servers
    └── firewall.yml

2 directories, 3 files

At the same time, we rewrite the host manifest file

The playbook Send the list to the host load_balancer Deploy as a load balancer , And group web_servers The host in is the back end Web Server to deploy .
edit inventory.yml Static list ⽂ Pieces of , In order to playbook Middle quotation ⽤ load_balancer When the host is running Ansible Connect to servera.lab.example.com. List host serverb.lab.example.com and serverc.lab.example.com Should be in group web_servers in .

lb_servers:
  hosts:
    servera.lab.example.com:

web_servers:
  hosts:
    server[b:c].lab.example.com:
lb_servers:
  hosts:
    load_balancer:
      ansible_host: servera.lab.example.com

web_servers:
  hosts:
    server[b:c].lab.example.com:

The above is the original manifest file , The following is our rewritten manifest file , Through here ansible_host The Manifest Variable specifies the machine at execution time , And defines an alias load_balancer, in other words , In the host list is lb_servers When the group executes the script , When connecting the managed host , Use the currently defined alias . adopt DNS To map to the corresponding machine , Instead of using it from the manifest file (inventory_hostname) The name of the .

Organize reference books

《RED HAT 447 Advanced Automation:Ansible Best Practices Edition》

原网站

版权声明
本文为[The mountains and rivers are all right]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/164/202206130649055680.html