Variable and encryption in Ansible

Posted by buceta on Wed, 08 Dec 2021 19:57:41 +0100

##1. Variable naming##

It can only contain numbers, underscores and letters
Can only start with an underscore or a letter

##2. Variable level##

overall situation:          Set from the command line or configuration file
paly:          Set in play and related structures
host:          Tasks collected or registered by lists, facts

Variable priority setting:
Narrow and wide area

##3. Variable setting and usage##

#1. Directly define variables in playbook

---
- name: test var
  hosts: all
  vars:
     USER: westosuser

#2. Define variables in the file#

vim user_list.yml
---
user: westosuser
vim westos.yml
---
- name: Create User
  hosts: all
  vars_files:
      - ./user_list.yml

[devops@nodea111 .ansible]$ vim user_list.yml
---
USER1:
  NAME: user1
  UID: 666

[devops@nodea111 .ansible]$ vim user.yml
- name: create user
  hosts: westos
  vars_files:
    - ./user_list.yml
  tasks:
    - name: create user1
      user:
        name: "{{USER1['NAME']}}"
        uid: "{{USER1.UID}}"

[devops@nodea111 .ansible]$ ansible-playbook user.yml 

#3. Use variables#

tasks:
- name: create user
user:
name: "{{ USER }}"

#4. Set host variables and list variables#

#Used when defining host variables and manifest variables

vim inventory
[westos_list1]
172.25.0.254
172.25.0.1

[westos_list2]
172.25.0.2

[westos_list3]
172.25.0.3

[westos_group:children]
westos_list2
westos_list3

[westos_list1:vars]
USER=westos1

[westos_group:vars]
USER=westos2

[devops@nodea111 .ansible]$ cat inventory 
[westos]
172.25.254.211

[westos:vars]
WESTOS=hello

[devops@nodea111 .ansible]$ vim var.yml
- name: test
  hosts: westos
  tasks:
    - debug:
        msg: "{{WESTOS}}"

[devops@nodea111 .ansible]$ ansible-playbook var.yml 

PLAY [test] *****************************************************************************

TASK [Gathering Facts] ******************************************************************
ok: [172.25.254.211]

TASK [debug] ****************************************************************************
ok: [172.25.254.211] => {
    "msg": "hello"
}

PLAY RECAP ******************************************************************************
172.25.254.211             : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   



#5. Directory setting variables#

group_vars         ## List variable. The file name in the directory is consistent with the host list name
host_vars           ## Host variable. The file name in the directory is consistent with the host name

#6. Override variables with commands#

ansible-playbook user.yml -e "USER=hello"

#7. Use an array to set variables#

#vim user_var.yml
---
USER:
  lee:
    age: 18
    obj: linux
  westos:
    age: 20
    obj: java
#vim user.yml
- name: Create User
  hosts: all
  gather_facts: no
  vars_files:
    ./user_var.yml
  tasks:
- name: create user
  shell:
    echo "{{USER['lee']['age']}}"
    echo "{{USER.westos.obj}}"

practice:

create web vhost
www.westos.com 80------ > /var/www/html------> www.westos.com
linux.westos.com 80 ------> /var/www/virtual/westos.com/linux -----> linux.westos.com

[devops@nodea111 .ansible]$ cat vhost_var.yml 
web_default:
  doc: /var/www/html
  index: www.westos.com
web_linux:
  name: linux.westos.com
  doc: /var/www/virtual/westos.com/linux
  index: linux.westos.com

[devops@nodea111 .ansible]$ cat creat_web.yml
- name: create web vhost
  hosts: westos
  vars_files:
    ./vhost_var.yml
  tasks:
    - name: install http
      dnf:
        name: httpd
        state: present
    - name: firewalld
      firewalld:
        service: http
        permanent: yes
        state: enabled
        immediate: yes
    - name: copy
      copy:
        dest: /var/www/html/index.html
        content: " www.westos.com"
    - name: create directory
      file:
        path: /var/www/virtual/westos.com/linux/
        state: directory
    - name: copy2
      copy:
        dest: /var/www/virtual/westos.com/linux/index.html
        content: " linux.westos.com "

    - name: check_file
      file:
        path: /etc/httpd/conf.d/vhosts.conf
        state: absent
    - name: create web
      lineinfile:
        path: /etc/httpd/conf.d/vhosts.conf
        state: present
        create: yes
        line: |+
          <VirtualHost _default_:80>
            DocumentRoot {{web_default.doc}}
          </VirtualHost>
          <VirtualHost *:80>
            ServerName {{web_linux.name}}
            DocumentRoot {{web_linux.doc}} 
          </VirtualHost>
    - name: start httpd
      service:
        name: httpd
        state: restarted
        enabled: yes
      
Address resolution in browser host
[root@westos_student11 ~]# vim /etc/hosts
172.25.254.211 www.westos.com  linux.westos.com

#8. Register variables#

#register registers the module output to the specified string

You can't see the output directly. You need to use registered variables to display the output

[devops@nodea111 .ansible]$ cat westos.yml
- name: test playbook
  hosts: westos
  tasks:
    - name: check file
      shell: test -e /mnt/file1
      register: out
    - name: debug
      debug:
        msg: "{{out.rc}}"
[devops@nodea111 .ansible]$ ansible-playbook westos.yml

PLAY [test playbook] ***********************************************************

TASK [Gathering Facts] *********************************************************
ok: [172.25.254.211]

TASK [check file] **************************************************************
changed: [172.25.254.211]

TASK [debug] *******************************************************************
ok: [172.25.254.211] => {
    "msg": "0"  ##0 represents successful operation
}

PLAY RECAP *********************************************************************
172.25.254.211             : ok=3    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   


[devops@nodea111 .ansible]$ cat westos.yml
- name: test playbook
  hosts: westos
  tasks:
    - name: check file
      shell: test -e /mnt/file1
      register: out
    - name: debug
      debug:
        msg: "{{out.end}}"

[devops@nodea111 .ansible]$ ansible-playbook westos.yml

PLAY [test playbook] ***********************************************************

TASK [Gathering Facts] *********************************************************
ok: [172.25.254.211]

TASK [check file] **************************************************************
changed: [172.25.254.211]

TASK [debug] *******************************************************************
ok: [172.25.254.211] => {
    "msg": "2021-12-03 09:30:17.763556" ##end display time
}

PLAY RECAP *********************************************************************
172.25.254.211             : ok=3    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

#9. Factual variables#

Fact variables are variables automatically detected by ansible in the controlled host
There is also host related information in the fact variable
When the host related information needs to be used, there is no need to collect and assign values, and it can be called directly
Because the variable information is system information, it cannot be arbitrarily set to collect information only, so it is called a fact variable

[devops@nodea111 .ansible]$ ansible westos -m setup ##Collected information


[devops@nodea111 .ansible]$ cat westos.yml
- name: test playbook
  hosts: westos
  tasks:
    - name: debug
      debug:
        msg: "{{ansible_facts['fqdn']}}" ##Corresponding to "ansible_fqdn" in setup: "NodeB. Westos. Org",

[devops@nodea111 .ansible]$ ansible-playbook westos.yml

PLAY [test playbook] ***********************************************************

TASK [Gathering Facts] *********************************************************
ok: [172.25.254.211]

TASK [debug] *******************************************************************
ok: [172.25.254.211] => {
    "msg": "nodeb.westos.org"
}

PLAY RECAP *********************************************************************
172.25.254.211             : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

--------------------------------------

#10. Magic variables#

hostvars:         ## Internal information of ansible software
#eg:
ansible localhost -m debug -m "var=hostvars"

group_names:         ## Current managed host group
#eg:
ansible localhost -m debug -m "var=group_names"

groups:         ## Lists all groups and hosts in the list
#eg:
ansible localhost -m debug -m "var=groups"

inventory_hostname:         ## Contains the name of the currently managed host configured in the manifest
#eg:
ansible localhost -m debug -m "var=inventory_hostname

[devops@nodea111 .ansible]$ ansible localhost -m debug -a 'var=hostvars'
[devops@nodea111 .ansible]$ ansible westos -m debug -a 'var=group_names'
172.25.254.211 | SUCCESS => {
    "group_names": [
        "westos"
    ]
}
[devops@nodea111 .ansible]$ ansible westos -m debug -a 'var=groups'
172.25.254.211 | SUCCESS => {
    "groups": {
        "all": [
            "172.25.254.211"
        ],
        "ungrouped": [],
        "westos": [
            "172.25.254.211"
        ]
    }
}
[devops@nodea111 .ansible]$ ansible westos -m debug -a 'var=inventory_hostname'
172.25.254.211 | SUCCESS => {
    "inventory_hostname": "172.25.254.211"
}

##JINJA2 template##

#Introduction
Jinja2 is the next widely used template engine in Python
His design idea comes from Django's template engine,
And extends its syntax and a series of powerful functions.
One of the most significant is the addition of sandbox execution function and optional automatic escape function

#j2 template writing rules#
{# /etc/hosts line #}         ## Notes describe the purpose of the document
127.0.0.1          localhost         ## File content
{{ ansible_facts['all_ipv4_addresses'] }}          {{ansible_facts['fqdn']}}         ## Using fact variables

for loop

vim users.yml
users:
  - westos
  - linux
  - ansible
vim test.j2
{% for NAME in users %}
{{ NAME }}
{%endfor%}

if decision

{% for NAME in users if not NAME == "ansible" %}
User number {{loop.index}} - {{ NAME }}
{%endfor%}
loop.index    ##Loop iteration counting starts with 1
loop.index0    ##Loop iteration count starts at 0


{% for user in students %}
name:    {{user['name']}}
{%if user['age'] is defined%}
age:    {{user['age']}}
{%endif%}
{% if user['age'] is not defined %}
age:    null
{% endif%}
obj:{{user['obj']}}
{%endfor%}

#Application of j2 template in playbook#

[devops@nodea111 .ansible]$ mkdir host_vars
[devops@nodea111 .ansible]$ cat host_vars/172.25.254.211.yml
users:
  - westos
  - lee
  - linux

[devops@nodea111 .ansible]$ cat test.j2
{# /mnt/westos #}
{% for user in users%}
{{ user }}
{% endfor %}

[devops@nodea111 .ansible]$ cat westos.yml 
- name: test playbook
  hosts: westos
  tasks:
    - name: test j2
      template:
        src: ./test.j2
        dest: /mnt/westos
[devops@nodea111 .ansible]$ ansible-playbook westos.yml
[root@nodeb mnt]# cat westos
westos
lee
linux
[devops@nodea111 .ansible]$ cat westos1.yml 
- name: host playbook
  hosts: westos
  tasks:
    - name: hosts j2
      template:
        src: ./hosts.j2
        dest: /mnt/westos1
[devops@nodea111 .ansible]$ cat hosts.j2 
{%for HOST in groups['westos']%}
{{ hostvars[HOST]['ansible_facts']['fqdn']}}
{%endfor%}

##Ansible encryption control##

#Create build file

1.
ansible-vault create westos
2.
vim westos-vault
lee

ansible-vault create --vault-password-file=westos-valut westos

#Encrypt existing files
ansible-vault encrypt test

#View encrypted files
ansible-vault view westos
ansible-vault view --vault-password-file=westos-valut westos

#Edit encrypted file
ansible-vault edit westos1
ansible-vault edit --vault-password-file=westos-valut westos

##Decrypt file
ansible-vault decrypt westos         ## File permanent decryption
ansible-vault decrypt westos --output=linux         ## Decrypt the file and save it as Linux

##Change password
ansible-vault rekey westos1
ansible-vault rekey westos1 --new-vault-password-file=key1

#playbook#
ansible-playbook apache_install.yml        --ask-vault-pass

Topics: Operation & Maintenance