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

Source: Internet
Author: User

Ansible @ an efficient configuration management tool-Ansible configure management-translation (5), ansible-ansible
Do not reprint advanced Playbook without written permission

Extra variablesYou may have seen in our template example in the previous chapter that we used avariable called group_names . This is one of the magic variables that are provided byAnsible itself. At the time of writing there are seven such variables, described in thefollowing sections.

External variables

You have seen in the previous template example that we have a variable named group_names, which is a magic variable provided by Ansible. For example, this variable has a total of seven so far, next we will introduce them one by one!

hostvars allows you to retrieve variables about all the hosts that the current playhas dealt with. If the setup module hasn't yet been run on that host in the currentplay, only its variables will be available. You can access it like you would accessother complex variables, such as ${hostvars.hostname.fact} , so to get the Linuxdistribution running on a server named ns1 , it would be ${hostvars.ns1.ansible_distribution} . The following example sets a variable called zone master to theserver named ns1 . It then calls the template module, which would use this to set themasters for each zone.---#1- name: Setup DNS Servers#2hosts: allnameservers#3tasks:#4- name: Install BIND#5yum: name=named state=installed#6- name: Setup Slaves#7hosts: slavenamesservers#8tasks:#9- name: Get the masters IP#10set_fact: dns_master="{{hostvars.ns1.ansible_default_ipv4.address }}"- name: Configure BIND#12template: dest=/etc/named.confsrc/templates/named.conf.j2#11#13Using hostvars, you can further abstract templates from yourenvironment. If you nest your variable calls, then instead of placing anIP address in the variable section of the play, you can add the hostname.To find the address of a machine named in the variable the_machineyou would use, {{ hostvars.[the_machine].default_ipv4.address }}.

Hostvars variable

Run hostvas to retrieve all hosts processed by the current play. If the setup module is not running, only the hostvar variable is available. It can access complex variables in the form of $ {hostvars. hostname. fact}, for example, using $ {hostvars. ns1.ansible _ distribution} to access the release version of the ns1 server. The following example sets a dns master server named ns1 and calls the template module to set an mast server for each zone:

---
-Name: Setup DNS Servers
Hosts: allnameservers

Tasks:
-Name: Install BIND
Yum: name = named state = installed

-Name: Setup Slaves
Hosts: slavenamesservers

Tasks:
-Name: Get the masters IP
Set_fact: dns_master = "{{
Hostvars. ns1.ansible _ default_00004.address }}"

-Name: Configure BIND
Template: dest =/etc/named. conf
Src/templates/named. conf. j2

The groups variableThe groups variable contains a list of all hosts in the inventory grouped by theinventory group. This lets you get access to all the hosts that you have configured.This is potentially a very powerful tool. It allows you to iterate across a whole groupand for every host apply an action to the current machine.---- name: Configure the databasehosts: dbserversuser: roottasks:- name: Install mysqlyum: name={{ item }} state=installedwith_items:- mysql-server- MySQL-python- name: Start mysqlservice: name=mysqld state=started enabled=true- name: Create a user for all app serverswith_items: groups.appserversmysql_user: name=kate password=test host={{hostvars.[item].ansible_eth0.ipv4.address }}state=presentYou can even use this variable to create known_hosts files for all of your machinescontaining the host keys of all the other machines. This would allow you to then SSHfrom one machine to another without confirming the identity of the remote host. Itwould also handle removing machines when they leave service or updating them whenthey are replaced. The following is a template for a known_hosts file that does this:{% for host in groups['all'] %}{{ hostvars[host]['ansible_hostname'] }}{{hostvars[host]['ansible_ssh_host_key_rsa_public'] }}{% endfor %}The playbook that uses this template would look like this:---hosts: alltasks:- name: Setup known hostshosts: alltasks:- name: Create known_hoststemplate: src=templates/known_hosts.j2dest=/etc/ssh/ssh_known_hosts owner=root group=rootmode=0644

Groups variable

The group variable contains all the hosts in the Device List group. It allows us to access all the hosts we configured at the same time. This is a very powerful tool, this allows us to review each host in the group and apply the operation above.

---
-Name: Configure the database
Hosts: dbservers
User: root

Tasks:
-Name: Install mysql
Yum: name = {item} state = installed
With_items:
-Mysql-server
-MySQL-python


-Name: Start mysql
Service: name = mysqld state = started enabled = true


-Name: Create a user for all app servers
With_items: groups. appservers
Mysql_user: name = kate password = test host = {{
Hostvars. [item]. ansible_eth0.20.4.address }}
State = present

You can even use this variable to create a known_hosts file that contains all other hosts known to this host and then apply it to all your hosts. In this way, you do not need to authenticate when using ssh to log on from one machine to another. It can also be used to remove the host when the service is disconnected or when it is replaced by an update. The code for the known_hosts file template is as follows:

{% For host in groups ['all'] %}
{Hostvars [host] ['ansible _ hostname']}
{Hostvars [host] ['ansible _ ssh_host_key_rsa_public ']}
{% Endfor %}


You can use this template in playbook as follows:
---
Hosts: all
Tasks:
-Name: Setup known hosts
Hosts: all
Tasks:
-Name: Create known_hosts
Template: src = templates/known_hosts.j2
Dest =/etc/ssh/ssh_known_hosts owner = root group = root mode = 0644

The group_names variableThe group_names variable contains a list of strings with the names of all thegroups the current host is in. This is not only useful for debugging, but also forconditionals detecting group membership. This was used in the last chapter toset up a nameserver.This variable is mostly useful for skipping a task or in a template as a condition. Forinstance, if you had two configurations for the SSH daemon, one secure and one lesssecure, but you only wanted the secure configuration on the machines in the securegroup, you would do it like this:- name: Setup SSHhosts: sshserverstasks:- name: For secure machinesset_fact: sshconfig=files/ssh/sshd_config_securewhen: "'secure' in group_names"- name: For non-secure machinesset_fact: sshconfig=files/ssh/sshd_config_defaultwhen: "'secure' not in group_names"- name: Copy over the configcopy: src={{ sshconfig }} dest=/tmp/sshd_configIn the previous example, we used the set_fact module to set the factfor each case, and then used the copy module. We could have usedthe copy module in place of the set_facts modules and used onefewer task. The reason this was done is that the set_fact moduleruns locally and the copy module runs remotely. When you use theset_facts module first and only call the copy module once, the copiesare made on all the machines in parallel. If you used two copy moduleswith conditions, then each would execute on the relevant machinesseparately. Since copy is the longer task of the two, it benefits the mostfrom running in parallel.

Group_names variable

Group_names is a variable about the groups of the current host and the string list obtained by adding these group names. It is not only used for debugging, but also used as a condition for determining group members. We used the dns configuration in the previous chapter. This variable is useful when it is used to skip execution of some tasks or is used as a condition of the template. For example, you have two ssh configurations, one with a higher security level and the other with a lower security level. The following example shows how to use a high-security configuration for devices in a high-security group:

-Name: Setup SSH
Hosts: sshservers


Tasks:
-Name: For secure machines
Set_fact: sshconfig = files/ssh/sshd_config_secure
When: "'Secure 'in group_names"
-Name: For non-secure machines
Set_fact: sshconfig = files/ssh/sshd_config_default
When: "'Secure 'not in group_names"


-Name: Copy over the config
Copy: src = {sshconfig} dest =/tmp/sshd_config


In the preceding example, we set fact in the two conditions and then deploy a copy. The reason is that set_fact is executed locally, while copy is executed remotely, when running, the copy module runs in parallel. Otherwise, when we use copy in two conditions, it runs separately. If the copy module runs for a long time, the parallel running performance will be better!

The inventory_hostname variableThe inventory_hostname variable stores the hostname of the server as recorded inthe inventory. You should use this if you have chosen not to run the setup moduleon the current host, or if for various reasons the value detected by the setup moduleis not correct. This is useful when you are doing the initial setup of the machine andchanging the hostname.The inventory_hostname_short variableThe inventory_hostname_short variable is the same as the previous variable;however, it only includes the characters up to the first dot. So for host.example.com , it would return host .

Inventory_hostname variable

The inventory_hostname variable saves the server host name in the device configuration list. This is useful when you choose not to use the setup module or the setup module cannot run for other reasons. In addition, it is useful when you initialize a host and modify its hostname.

Inventory_hostname_short variable

The inventory_hostname_short variable is the same as that of inventory_hostname, but the domain name is removed. For example, if inventory_hostname is host. example, inventory_hostname_short is host.

The inventory_dir variableThe inventory_dir variable is the path name of the directory containing theinventory file.The inventory_file variableThe inventory_file variable is the same as the previous one, except it also includesthe filename.

Inventory_dir

Inventory_dir is the path of the device list file.

Inventory_file

Inventory_file is the file name of the device list file.









Contact Us

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

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

A Free Trial That Lets You Build Big!

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

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

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

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