Automated operation and maintenance tools-Ansible introduction (3)

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:
Insert picture description here
2. Define playbook variables in external files

Insert picture description here

cat user.yml

Insert picture description here

3.4.2 Using variables in playbooks

Put the variable name in curly brackets.
Insert picture description here
'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:
Insert picture description here
define the dbservers host group user group variable:
Insert picture description here
define the nested group user variable:
Insert picture description here
'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
Insert picture description here
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:

Insert picture description here
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.
Insert picture description here
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:
Insert picture description here

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
Insert picture description here
requires a password
Insert picture description here
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
Insert picture description here
## View the encrypted file

方法:ansible-vault view filename

Insert picture description here
## 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
Insert picture description here
Insert picture description here

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 参数可以是多个

Insert picture description here
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

Insert picture description here
## Rename while decrypting

–Output = filename
Insert picture description here
## Change the encrypted file password

方法:ansible-vault rekey filename

'Can update multiple file passwords at once' #When
Insert picture description here
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
Insert picture description here
# interactive password
Insert picture description here
'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
Insert picture description here
var: ansible_facts #System variable name, no need to define.

ansible-playbook fact.yml

Insert picture description here
## 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 }}

Insert picture description here
## ansible fact as variable injection
# Use the setup module to display all fact information
Insert picture description here
# Turn off fact collection and improve execution speed

cat user.yml

Insert picture description here
# Operation
Insert picture description here
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       查看我们定义的事实

Insert picture description here
'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"]'

Insert picture description here
## Manage Facts: Exercise 1

[root @ workstation data-facts] # ​​ansible rhel82.com -m setup #Display information
Insert picture description here
Can be displayed.

Create custom variable
vim westos.fact
Insert picture description here

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
Insert picture description here
Insert picture description here
directory has been created and the file has passed.

Write the main playbook
Insert picture description here

---
- 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'

Insert picture description here
It can be seen that the httpd service is not installed on the 82 host.
#Law check
Insert picture description here
# Run

Insert picture description here
Insert picture description here
Insert picture description here

Published 50 original articles · Liked 18 · Visits 3780

Guess you like

Origin blog.csdn.net/thermal_life/article/details/105346098