Let's start with an example : Suppose I want to get the host IP by 172.25.250.9 Fully qualified domain name (FQDN), But I can't log in to this host , Then you can use the hostvars Magic variable ( I will share my understanding of the word magic later ) In this dictionary ansible_fact This sub dictionary ( It will be explained later ) To get .

First of all, let's take a look at hostvars What's in it , We can use the following command to view hostvars This dictionary :

ansible locahost -m debug -a “var=hostvars"
localhost | SUCCESS => {
"hostvars": {
"172.25.250.10": {
"ansible_check_mode": false,
"ansible_diff_mode": false,
"ansible_facts": {},
"ansible_forks": 5,
"ansible_inventory_sources": [
"/home/greg/ansible/inventory"
],
"ansible_password": "redhat",
"ansible_playbook_python": "/usr/libexec/platform-python",
"ansible_user": "root",
"ansible_verbosity": 0,
"ansible_version": {
"full": "2.8.0",
"major": 2,
"minor": 8,
"revision": 0,
"string": "2.8.0"
},
"group_names": [
"test"
],
"groups": {
"all": [
"172.25.250.9",
"172.25.250.10",
"172.25.250.13",
"172.25.250.11",
"172.25.250.12"
],
"balancers": [
"172.25.250.13"
],
"dev": [
"172.25.250.9"
],
"prod": [
"172.25.250.11",
"172.25.250.12"
],
"test": [
"172.25.250.10"
],
"ungrouped": [],
"webservers": [
"172.25.250.11",
"172.25.250.12"
]
},
"inventory_dir": "/home/greg/ansible",
"inventory_file": "/home/greg/ansible/inventory",
"inventory_hostname": "172.25.250.10",
"inventory_hostname_short": "172",
"omit": "__omit_place_holder__24431a21232ab0a628ff5c537f472e6b49d1e14a",
"playbook_dir": "/home/greg/ansible"
}, "172.25.250.11": {
"ansible_check_mode": false,
"ansible_diff_mode": false,
"ansible_facts": {},
....................
"172.25.250.12": {
"ansible_check_mode": false,
"ansible_diff_mode": false,
"ansible_facts": {},
"ansible_forks": 5,
"ansible_inventory_sources": [
"/home/greg/ansible/inventory"
],
..........................
"172.25.250.13": {
"ansible_check_mode": false,
"ansible_diff_mode": false,
"ansible_facts": {},
"ansible_forks": 5,
"ansible_inventory_sources": [
"/home/greg/ansible/inventory"
],
............................
"172.25.250.9": {
"ansible_check_mode": false,
"ansible_diff_mode": false,
"ansible_facts": {},
"ansible_forks": 5,
"ansible_inventory_sources": [
"/home/greg/ansible/inventory"
],
     ......................
"inventory_dir": "/home/greg/ansible",
"inventory_file": "/home/greg/ansible/inventory",
"inventory_hostname": "172.25.250.9",
"inventory_hostname_short": "172",
"omit": "__omit_place_holder__24431a21232ab0a628ff5c537f472e6b49d1e14a",
"playbook_dir": "/home/greg/ansible"
}
}
}

As you can see from the output , stay hostvars There are 5 Key value pairs (‘172.25.250.9’: value 1,‘172.25.250.13: value 2 Form like this . Because there are... In my environment 5 Controlled nodes , So there are five key value pairs ), There is one in the value of each key value pair ”ansible_facts“ Key , The value corresponding to this key is generated f Of acts( Information about remote host nodes ).

Tip: hostvars There are also groups This magic variable ( You can see from the top output ), It contains 5 Of nodes IP, That is to say all This group ,( All nodes are automatically divided into all In the group , Corresponding , If a group is not added to the division all Groups other than groups , Then the host will be automatically divided into ungrouped In the group , in other words ,ungrouped The hosts in the group are not joined to other groups ( except all Group ))

Okay , Now we can say :fqdn Can pass ansible_facts From a certain element in it , Since we know hostvars There are ansible_facts, Now let's take a look at ansible_facts There's something in it .

ansible localhost -m setup -a "filter=*fqdn*"
# localhost: The execution node is native
# -m: module
# setup: Generate ansible_facts
# -a: append
# filter: The command composed of the preceding parameters will output all the output of one brain ,filter Parameter is used to filter these outputs
# *fqdn*: Regular expressions , contain fqdn The item

Tip: Can be executed directly “ansible localhost -m setup” To see all of ansible_facts, Because it is too redundant, it will not be shown here .

As can be seen from the picture above ,ansible_facts Inside ansible_fqdn It stores localhost( The upper left corner shows localhost) Of fqdn.

So we can pass hostvars---->ansible_facts------->ansible_fqdn To get fqdn, however hostvars There are many different hosts ansible_facts, So we need to specify which host it belongs to ansible_facts, Only in this way can we get the correct fqdn, So we can get the following results :

hostvars["172.25.250.9"]["ansible_facts"]["ansible_fqdn"]

Yes “ magic ” The understanding of the :

If you want to configure your database server using the value of a ‘fact’ from another node, or the value of an inventory variable assigned to another node, you can use hostvars in a template or on an action line

If we want to use information from other nodes , Then you can jinja Or on the command line hostvars This magic variable , My personal understanding is : Its “ magic ” This is reflected in the fact that it is this machine , But you can get information from other hosts , So it's amazing .

With hostvars, you can access variables defined for any host in the play, at any point in a playbook. You can access Ansible facts using the hostvars variable too, but only after you have gathered (or cached) facts.

We can also go through hostvars Variable acquisition ansible_facts.

Document links :

Discovering variables: facts and magic variables — Ansible Documentation

Search the document for :“Information about Ansible” You can navigate to .

Here is a question for the netizens , I have just come into contact with ansible, incomprehension jinja Why can we not define these magic variables first when calling them in the template , That means I want to know ansible How to call jinja Of documents , Or is it jinja How to get those without implementation definitions in jinja Magic variables in the file ( for example groups) Of ? Please preach and teach , I am obliged .

ansible Medium hostvars More articles about

  1. ansible Medium playbook Detailed explanation

    First of all, let's briefly explain playbook,playbook What is it? ? essence playbook and shell There's no difference in scripts ,playbook It's like shell equally , It's also a combination of commands , Then add the corresponding condition judgment and so on ...

  2. ansible Medium map

    ansible Medium filter:   map  , It's actually jinja2 Medium filter python in map(func, iter) return func Iterator after calculation with each element ,iter It's an iterative object an ...

  3. ansible Detailed explanation of common modules in

    ansible Detailed explanation of modules commonly used in : file modular ansible The built-in commands to view module usage are as follows : [[email protected] ~]# ansible-doc -s file - name: Sets ...

  4. ansible in playbook Use

    palybook Use ####yaml grammar ansible Used in yaml Basic elements : Variable Inventory Conditional test iterations playbook Structure of InventoryModulesAd Hoc Comma ...

  5. ansible in yaml Grammar application

    4.yaml Grammar application ansible Of playbook Written by yaml Language writing , master yaml The grammar is playbook Necessary conditions , Format requirements and Python be similar , The specific tutorial reference is as follows yaml Language course Attach a ...

  6. ansible Common loop modules in with_items

    ansible There are many loop modules in , however with_items Most commonly used , And it's simpler , The most important function of the loop module is to simplify repetitive tasks , As shown in the following example : - hosts: all remote_user: root ...

  7. ansible Medium docker_container modular

    docker_container modular 1.docker_container The module is mainly used for ansible-playbook operation docker A module of the container , Using this module, batch creation can be realized docker Containers An ...

  8. Two 、Ansible in playbook The variable of

    Have a look first debug Use of modules : msg: Output debugging information var: Pass the output of a task to as a variable debug modular ,debug The module prints it out verbosity:debug Task level   1: stay playbo ...

  9. Ansible in playbook The variable of

    from :http://www.cnblogs.com/lemon-le/p/6862788.html Have a look first debug Use of modules : msg: Output debugging information var: Pass the output of a task to as a variable debu ...

  10. ansible in tag Usage of

    Tags According to the official documents : ansible Allow to give... By using custom keywords playbook Tag resources in , Then run only the one marked by the tag task Mission . for example , There may be a complete OS To configure , Then the specific step is marked as “nt ...

Random recommendation

  1. Sharepoint 2010 Processing error when workflow started

    stay Sharepoint 2010 Use in Sharepoint 2010 designer I did a workflow : When running a workflow , Being the lead engineer is “ Zhang San ” When , An error is reported as soon as the workflow is started . -------------- ...

  2. JAVA: abstract class VS Interface

    JAVA Compare the differences between abstract classes and interfaces in , And their respective uses . 1.JAVA abstract class : Abstract classes can't be instantiated , It's no different from the normal class . stay <JAVA Programming idea > In a Book , Define an abstract class as “ Class containing abstract methods ...

  3. The illustration SQL 2008 Database replication

    In order to achieve timely data backup , Generally, full backup is used + Differential backup is enough , Or add log backup , This article introduces how to use database replication technology to synchronize data : PS: The article is mainly based on pictures , The picture shows the operation steps and configuration methods more intuitively ! 1. First create a test data ...

  4. The second one of summer training competition UVA 10982 Troublemakers

    The question : Put the points in two sets , The edges of the same set are preserved , The edges of different sets are deleted , Make the edges at least halve .  Output any scheme . If not , Output Impossible  Ideas : If two people are a pair of troublemakers , be two[i][j]=t ...

  5. hdu-2586-How far away ?( offline LCA)

    The question : Given a tree , Each edge has a certain weight ,q Time to ask , Ask the distance between two points each time . analysis : In this way, you can use LCA To solve , First find u, v Two o'clock lca, Then calculate the distance value . The calculation method here is , Note the root node ...

  6. Cortex-M3 Dynamic loading three ( Modules call system functions )

    In my arm In the dynamic loading experiment, we need to solve the problem that a module calls the system function , You can use one of the following methods . Fix the system function in a certain address space , Then export the symbol table of this block to the symbol file , Modules to be recorded link Use this symbol table file when you use it , ...

  7. myeclipse To configure resin-pro-4.0.34

    Thermal deployment : stay resin.xml Under the document increase <host id="" root-directory="."> <!-- webapps ca ...

  8. Vuex The simplest example of quantity increase and decrease

    Vuex Is a special for Vue.js State management mode of application development . It USES centralized storage to manage the state of all components of the application , And the corresponding rules ensure that the state changes in a predictable way .Vuex Also integrated into the Vue The official debugging tool ...

  9. Python note - Advanced features

    1. iteration If given a list or tuple, We can go through for Loop through this list or tuple, This kind of traversal is called iteration (Iteration). If you want to iterate value, It can be used for value in d ...

  10. Hdoj 1517.A Multiplication Game Answer key

    Problem Description Stan and Ollie play the game of multiplication by multiplying an integer p by on ...