3.4 Management variables and facts
Use some variables in playbook instead of variables to simplify playbook writing
3.4.1 Management variables
Introduction to ansible variables
Variables may contain the following values:
users to be created,
software packages to be installed,
services to be restarted,
files to be deleted, documents to
be retrieved from the Internet
Named variable
Variable names must start with a letter, and can only contain letters, numbers, and underscores.
Incorrect
web server web_server
westos.file remote_file
1file file1
Define variables
Three scope levels
Global scope: Variables set from the command line or ansible configuration
Play scope: Variables set in play and related structures
Host scope: Tasks collected or registered by inventory, facts, set on host groups and individual hosts Variables
'If variables with the same name are defined on multiple levels, the variable with the highest level is preferred, and narrow scope takes precedence over wide scope'
3.4.2 Variables
in playbook Define variables in playbook
1. Common way: in the vars block at the beginning of playbook:
2. Define playbook variables in external files
cat user.yml
3.4.2 Using variables in playbooks
Put the variable name in curly brackets.
'Note: When the variable is used as the first element to start a value, you must use quotation marks.'
3.4.3 Host variables and group variables
The list variables directly applied to the host are divided into two categories:
1. Host variables: apply to specific hosts
2. Group variables: apply to all hosts in a host group or a group of host groups
Host variables take precedence over group variables, but playbook The variables defined in are higher than both.
Define host variables and group variables:
Method one (older, not recommended):
Define server1.example.com single-user ansible_user host variable:
define the dbservers host group user group variable:
define the nested group user variable:
'This approach makes the manifest file difficult to handle, mixing host and variable in the same file Information, grammar is also outdated '
Method 2: Use the directory to populate the host and group variables
The preferred method for defining host and host group variables is to create two directories, group_vars
and host_vars , in the same working directory as the manifest file or directory. These two directories contain files for defining group variables and host variables.
Create a YAML file for group_vars / servers and set the variable to the value:
user: student
also needs to create a file with a name matching the host in the host_vars directory to store the host variables.
So a project directory contains:
ansible.cfg, group_vars, host_vars, inventory, playbook.yml
#Overwrite variables from the command line List variables can be overwritten by variables set in the playbook, and both can be overwritten by command line parameters
#Use array as a variable
Access method:
users.lilei.first_name
users.hanmeimei.home_dir
Variables are defined as Python dictionaries, and alternative syntax can be used:
users['lilei']['first_name']
users['hanmeimei']['home_dir']
#Use registered variables to capture command output
Administrators can use register statements to capture command output
---
- name: install
hosts: web
tasks:
- name: install http
yum:
name: httpd
state: installed
register: install_result
- debug: var=install_result
...
effect:
The process of operation can be seen with debug, which ensures our affirmation of the process.
### Exercises for managing variables
Create a playbook, install apache and start it so that it can be accessed, the playbook queries the web server and confirms that it is set up and running.
Variable name:
web_pkg #web server package
to be installed firewall_pkg #firewall package to be installed
web_service #web
service to be managed firewall_service
#firewall service to be managed python_pkg #uri module required package
rule #service to be opened
- name: config Apache
hosts: web
vars:
web_pkg: httpd
firewall_pkg: firewalld
web_service: httpd
firewall_service: firewalld
python_pkg: python3-PyMySQL
rule: http
tasks:
- name: Install Package
yum:
name:
- "{{ web_pkg }}"
- "{{ firewall_pkg }}"
- "{{ python_pkg }}"
state: latest
- name: the {{ firewall_service }} started and enabled #确保 firewalld 和 apache 开机启动
service:
name: "{{ firewall_service }}"
enabled: true
state: started
- name: the {{ web_service }} started and enabled
service:
name: "{{ web_service }}"
enabled: true
state: started
- name: config index.html #配置默认发布页面
copy:
content: "hello westos!"
dest: /var/www/html/index.html
- name: Firewall permit http #使防火墙允许 http
firewalld:
service: "{{ rule }}"
permanent: true
state: enabled
- name: Verify the Apache #验证 apache 服务
hosts: localhost
become: false #在本机测试,不必更改身份
tasks:
- name: Curl webserver
uri:
url: http://rhe82.com
status_code: 200
#run:
3.4.4 Management Confidentiality
Objective: Use ansible-vault to encrypt sensitive variables, and run the playbook of vault encrypted variable files.
Ansible-vault
ansible may require access to sensitive data such as passwords or api keys in order to configure the host.
Encryption and decryption tool: the ansible-vault command
'ansible vault does not implement its own encryption function, but uses an external python tool set'
## Create an encrypted file
Method: ansible-vault create filename
requires a password
and cannot be viewed at this time.
## Create an encrypted file and save the password at the same time, the password must be written in the westos file
## View the encrypted file
方法:ansible-vault view filename
## Edit an existing encrypted file
Principle: decrypt the file into a temporary file and edit it; when saving, copy the content and delete the temporary file
The 'edit command always rewrites the file, so it is only used when changing the file, use view as much as possible'
## Encrypt existing files
方法:ansible-vault encrypt filename #filename 参数可以是多个
You can use –output = filename to save the encrypted file with a new name. When using this parameter, the input file can only be one
## Decrypt existing files
方法:ansible-vault decrypt filename
## Rename while decrypting
–Output = filename
## Change the encrypted file password
方法:ansible-vault rekey filename
'Can update multiple file passwords at once' #When
using vault password files, it is best to use –net-vault-password-file
[root @ workstation wsp] # ansible-vault rekey --new-vault-password-file = wsp
westos .yml
Vault password:
Rekey successful
##-Vault PlayBook and ansible
# running encrypted playbook, no password is given
# interactive password
'before 2.4 ansible, using -ask-vault-pass for providing an interactive code'
# may be Keep the secret in the file (note the file system permissions to protect the file)
ansible-playbook --vault-password-file=password user.yml
3.4.5 Management facts ######
Facts include: host name, kernel version, network excuses, IP address, etc.
## Describe ansible facts
# View host information
var: ansible_facts #System variable name, no need to define.
ansible-playbook fact.yml
## Replace the facts with dynamic values
---
- name: fact
hosts : all
tasks:
- name: Print Facts
debug:
var: ansible_facts
- hosts: all
tasks:
- name: Print IP and dn
debug:
msg:
the IPv4 address of {{ ansible_facts.fqdn }} #使用字典的方式查询值
is {{ ansible_facts.all_ipv4_addresses }}
## ansible fact as variable injection
# Use the setup module to display all fact information
# Turn off fact collection and improve execution speed
cat user.yml
# Operation
when performed no gather_facts this one up.
## Create custom facts
# Can use INI format or JSON format
##INI
[packages]
web_packages=httpd
da_packages=mariadb_server
[users]
user1=westos
user2=redhat
##JSON
{
"packages": {
"web_packages": "httpd",
"db_packages": "mariadb-server"
},
"users": {
"user1": "westos",
"user2": "redhat"
}
}
'Custom format cannot use ymal format, it is best to use json closest to ymal format'
mkdir /etc/ansible/facts.d
vim /etc/ansible/facts.dcustom.fact #必须以.fact 结尾
"packages": {
"web_packages": "httpd",
"db_packages": "mariadb-server"
},
"users": {
"user1": "westos",
"user2": "redhat"
}
}
ansible localhost -m setup 查看我们定义的事实
'Custom facts are used in the same way as default facts'
## Using magic variables
There are four commonly used:
hostvars | #Contains the variables of the managed host, which can be used to obtain the value of the variable of another managed host |
group_names | #List all groups to which the currently managed host belongs |
groups | #List all groups and hosts in the list |
inventory_hostname | #Contains the host name of the currently managed host configured in the list |
#One of the purposes: use the debug module to report the value of hostvars for a specific host
ansible localhost -m debug -a 'var=hostvars["servera.lab.example.com"]'
## Manage Facts: Exercise 1
[root @ workstation data-facts] # ansible rhel82.com -m setup #Display information
Can be displayed.
Create custom variable
vim westos.fact
Create playbook
vim facts.yml
---
- name: Install fact
hosts: web
vars:
remote_dir: /etc/ansible/facts.d
facts_file: westos.fact
tasks:
- name: Create directory
file:
state: directory
recurse: yes
path: "{{ remote_dir }}"
- name: copy file facts
copy:
src: "{{ facts_file }}"
dest: "{{ remote_dir }}"
...
Run: The
directory has been created and the file has passed.
Write the main playbook
---
- name: INstall Apache
hosts: web
tasks:
- name: Install package
yum:
name: "{{ ansible_facts['ansible_local']['westos']['westos']['package'] }}"
state: latest
- name: statr apache
service:
name: "{{ ansible_facts['ansible_local']['westos']['westos']['service'] }}"
state: "{{ ansible_facts['ansible_local']['custom']['westos']['state'] }}"
enabled: "{{ ansible_facts['ansible_local']['custom']['westos']['enabled'] }}"
#Verify that the httpd service is not running on servera
ansible servera.lab.example.com -m command -a 'systemctl status httpd'
It can be seen that the httpd service is not installed on the 82 host.
#Law check
# Run