Ansible-变量及加密

1.变量命名
只能包含数字,下划线,字母
只能用下划线或字母开头

2.变量级别
全局:    从命令行或配置文件中设定的
paly:    在play和相关结构中设定的
主机:    由清单,事实收集或注册的任务

变量优先级设定: 狭窄范围有限与广域范围

书写playbook文件
[admin@ansible .ansible]$ vim test.yml
[admin@ansible .ansible]$ cat test.yml 
  - name: test
    hosts: westos
    vars:
      NAME: westos
    tasks:
      - name: debug
        debug:
        msg: "{{ NAME }}"

      - name: create file
        file:
          path: "/mnt/{{ NAME }}"
          state: touch

      - name: create file
        file:
          path: "/mnt/{{ item }}"
          state: touch
          loop:
            - file1
            - file2
            - file3

      - name: copy
        copy:
          dest: /mnt/testfile
          content: "{{ansible_facts['fqdn']}}"
测试书写的playbook文件
[admin@ansible .ansible]$ ansible-playbook test.yml 

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

TASK [Gathering Facts] ************************************************************************************************************
ok: [172.25.32.12]
ok: [172.25.32.11]

TASK [debug] **********************************************************************************************************************
ok: [172.25.32.11] => {
    "msg": "westos"
}
ok: [172.25.32.12] => {
    "msg": "westos"
}

TASK [create file] ****************************************************************************************************************
changed: [172.25.32.12]
changed: [172.25.32.11]

TASK [create file] ****************************************************************************************************************
changed: [172.25.32.11] => (item=file1)
changed: [172.25.32.12] => (item=file1)
changed: [172.25.32.11] => (item=file2)
changed: [172.25.32.12] => (item=file2)
changed: [172.25.32.11] => (item=file3)
changed: [172.25.32.12] => (item=file3)

TASK [copy] ***********************************************************************************************************************
changed: [172.25.32.11]
changed: [172.25.32.12]

PLAY RECAP ************************************************************************************************************************
172.25.32.11               : ok=5    changed=3    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
172.25.32.12               : ok=5    changed=3    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

3.变量设定和使用方式

3.1 在playbook中直接定义变量

[admin@ansible .ansible]$ vim user.yml
[admin@ansible .ansible]$ cat user.yml 
  - name: create user
    hosts: westos
    vars:
      USER1:
        NAME: user1
        UID: 6666
    tasks:
      - name: create user1
        user:
          name: "{{USER1['NAME']}}"
          uid: "{{USER1.UID}}"
测试书写的playbook文件
[admin@ansible .ansible]$ ansible-playbook user.yml 

PLAY [create user] ****************************************************************************************************************

TASK [Gathering Facts] ************************************************************************************************************
ok: [172.25.32.12]
ok: [172.25.32.11]

TASK [create user1] ***************************************************************************************************************
changed: [172.25.32.12]
changed: [172.25.32.11]

PLAY RECAP ************************************************************************************************************************
172.25.32.11               : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
172.25.32.12               : ok=2    changed=1    unreachable=0    failed=0

3.2 在文件中定义变量

书写palybook文件
[admin@ansible .ansible]$ cat user1.yml 
---
  USER1:
    NAME: user1
    UID: 6666
[admin@ansible .ansible]$ cat user.yml 
  - name: create user
    hosts: westos
    vars_files:
      - ./user1.yml
    tasks:
      - name: create user1
        user:
          name: "{{USER1['NAME']}}"
          uid: "{{USER1.UID}}"
测试书写的文件
[admin@ansible .ansible]$ ansible-playbook user.yml 

PLAY [create user] ****************************************************************************************************************

TASK [Gathering Facts] ************************************************************************************************************
ok: [172.25.32.12]
ok: [172.25.32.11]

TASK [create user1] ***************************************************************************************************************
ok: [172.25.32.12]
ok: [172.25.32.11]

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

3.3 使用变量

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

3.4 设定主机变量和清单变量

在定义主机变量和清单变量时使用

[admin@ansible .ansible]$ cat inventory 
[westos1]
172.25.32.11

[westos2]
172.25.32.12

[westos1:vars]
USER=linux
[admin@ansible .ansible]$ ansible-playbook user.yml 

PLAY [create user] ****************************************************************************************************************

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

TASK [debug] **********************************************************************************************************************
ok: [172.25.32.11] => {
    "msg": "linux"
}

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

3.5 目录设置变量

group_vars           ##清单变量,目录中的文件名称与主机清单名称一致
host_vars             ##主机变量,目录中的文件名称与主机名称一致

建立一个自定义目录,在目录中定义变量
[admin@ansible .ansible]$ mkdir group_vars
[admin@ansible .ansible]$ vim group_vars/westos.yml
[admin@ansible .ansible]$ cat  group_vars/westos.yml 
WESTOS: hello westos
[admin@ansible .ansible]$ cat user.yml 
  - name: create user
    hosts: westos
    tasks:
      - debug:
          msg: "{{WESTOS}}"
测试在目录中定义的变量
[admin@ansible .ansible]$ ansible-playbook user.yml

PLAY [create user] ****************************************************************************************************************

TASK [Gathering Facts] ************************************************************************************************************
ok: [172.25.32.11]
ok: [172.25.32.12]

TASK [debug] **********************************************************************************************************************
ok: [172.25.32.11] => {
    "msg": "hello westos"
}
ok: [172.25.32.12] => {
    "msg": "hello westos"
}

PLAY RECAP ************************************************************************************************************************
172.25.32.11               : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
172.25.32.12               : ok=2    changed=0    unreachable=0    failed=0    sk

3.6 用命令覆盖变量

ansible-playbook user.yml -e "WESTOS=nihao"

[admin@ansible .ansible]$ ansible-playbook user.yml -e "WESTOS=linux"
PLAY [create user] ****************************************************************************************************************

TASK [Gathering Facts] ************************************************************************************************************
ok: [172.25.32.11]
ok: [172.25.32.12]

TASK [debug] **********************************************************************************************************************
ok: [172.25.32.11] => {
    "msg": "linux"
}
ok: [172.25.32.12] => {
    "msg": "linux"
}

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

3.7 使用数组设定变量

在文件中设置数组变量
[admin@ansible .ansible]$ cat user_var.yml 
USER:
  lee:
    age: 18
    obj: linux

  westos:
    age: 20
    obj: java
[admin@ansible .ansible]$ cat user.yml 
  - name: Create User
    hosts: westos
    gather_facts: no
    vars_files:
      ./user_var.yml

    tasks:
      - name: create user
        shell:
          echo "{{USER['lee']['age']}}"
          echo "{{USER.westos.obj}}"
测试书写的变量
[admin@ansible .ansible]$ ansible-playbook user.yml -v
Using /home/admin/.ansible/ansible.cfg as config file

PLAY [Create User] ****************************************************************************************************************

TASK [create user] ****************************************************************************************************************
changed: [172.25.32.11] => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"}, "changed": true, "cmd": "echo \"18\" echo \"java\"", "delta": "0:00:00.001604", "end": "2022-07-30 03:31:54.621472", "rc": 0, "start": "2022-07-30 03:31:54.619868", "stderr": "", "stderr_lines": [], "stdout": "18 echo java", "stdout_lines": ["18 echo java"]}
changed: [172.25.32.12] => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"}, "changed": true, "cmd": "echo \"18\" echo \"java\"", "delta": "0:00:00.002361", "end": "2022-07-30 03:31:55.165762", "rc": 0, "start": "2022-07-30 03:31:55.163401", "stderr": "", "stderr_lines": [], "stdout": "18 echo java", "stdout_lines": ["18 echo java"]}

PLAY RECAP ************************************************************************************************************************
172.25.32.11               : ok=1    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
172.25.32.12               : ok=1    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

3.8 注册变量

register 把模块输出注册到指定字符串中

[admin@ansible .ansible]$ cat westos.yml 
- name: test register
  hosts: 172.25.32.11
  tasks:
    - name: hostname command
      shell:
        hostname
      register: info
    - name: show messages
      shell:
        echo "{{info['stdout']}}"
[admin@ansible .ansible]$ ansible-playbook westos.yml -v
Using /home/admin/.ansible/ansible.cfg as config file

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

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

TASK [hostname command] ****************************************************************************************************************************
changed: [172.25.32.11] => {"changed": true, "cmd": "hostname", "delta": "0:00:00.001995", "end": "2022-07-31 05:14:24.857372", "rc": 0, "start": "2022-07-31 05:14:24.855377", "stderr": "", "stderr_lines": [], "stdout": "www.westos.org", "stdout_lines": ["www.westos.org"]}

TASK [show messages] *******************************************************************************************************************************
changed: [172.25.32.11] => {"changed": true, "cmd": "echo \"www.westos.org\"", "delta": "0:00:00.001784", "end": "2022-07-31 05:14:25.111958", "rc": 0, "start": "2022-07-31 05:14:25.110174", "stderr": "", "stderr_lines": [], "stdout": "www.westos.org", "stdout_lines": ["www.westos.org"]}

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

3.9 事实变量

事实变量是ansible在受控主机中自动检测出的变量
事实变量中还有与主机相关的信息

当需要使用主机相关信息时不需要采集赋值,直接调用即可
因为变量信息为系统信息所以不能随意设定仅为采集信息,故被成为事实变量

ather_facts: no     ##在playbook中关闭事实变量收集

ansible westos -m  setup | less  #查看清单中受控机的全部信息

[admin@ansible .ansible]$ cat register.yml 
- name: test register
  hosts: 172.25.32.11
  tasks:
  - name: show messages
    debug:
      msg: "{{ansible_facts['architecture']}}"
[admin@ansible .ansible]$ ansible-playbook register.yml 

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

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

TASK [show messages] *******************************************************************************************************************************
ok: [172.25.32.11] => {
    "msg": "x86_64"
}

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

[admin@ansible .ansible]$ ansible westos -m  setup | less
172.25.32.12 | SUCCESS => {
    "ansible_facts": {
        "ansible_all_ipv4_addresses": [
            "172.25.32.12"
        ], 
        "ansible_all_ipv6_addresses": [
            "fe80::5054:ff:fefd:53c7"
        ], 
        "ansible_apparmor": {
            "status": "disabled"
        }, 
        "ansible_architecture": "x86_64", 
        "ansible_bios_date": "04/01/2014", 
..........

3.10 魔法便变量

hostvars:    ##ansible软件的内部信息

[admin@ansible .ansible]$ ansible localhost -m debug -a "var=hostvars"
localhost | SUCCESS => {
    "hostvars": {
        "172.25.32.11": {
            "WESTOS": "hello westos", 
            "ansible_check_mode": false, 
            "ansible_diff_mode": false, 
            "ansible_facts": {}, 
            "ansible_forks": 5, 
            "ansible_inventory_sources": [
                "/home/admin/.ansible/inventory"
            ], 
            "ansible_playbook_python": "/usr/bin/python2", 
            "ansible_verbosity": 0, 
            "ansible_version": {
                "full": "2.9.27", 
                "major": 2, 
                "minor": 9, 
                "revision": 27, 
                "string": "2.9.27"
..............
group_names:      ##当前受管主机所在组

[admin@ansible .ansible]$ ansible localhost -m debug -a "var=group_names"
localhost | SUCCESS => {
    "group_names": []
}


groups:       ##列出清单中所有的组和主机

[admin@ansible .ansible]$ ansible localhost -m debug -a "var=groups"
localhost | SUCCESS => {
    "groups": {
        "all": [
            "172.25.32.11", 
            "172.25.32.12"
        ], 
        "ungrouped": [], 
        "westos": [
            "172.25.32.11", 
            "172.25.32.12"
        ]
    }
}


inventory_hostname:          ##包含清单中配置的当前授管主机的名称

[admin@ansible .ansible]$ ansible localhost -m debug -a "var=inventory_hostname"
localhost | SUCCESS => {
    "inventory_hostname": "localhost"
}

4. JINJA2模板

介绍:
Jinja2是Python下一个被广泛应用的模版引擎
他的设计思想来源于Django的模板引擎,
并扩展了其语法和一系列强大的功能。
其中最显著的一个是增加了沙箱执行功能和可选的自动转义功能

4.1 j2模板书写规则

{# /etc/hosts line #}       ##注释说明文件用途
127.0.0.1   localhost     ##文件内容
{{ ansible_facts['all_ipv4_addresses'] }}    {{ansible_facts['fqdn']}}      ##使用事实变量

4.2 for循环

vim users.yml
users:
  - westos
  - linux
  - ansible

vim test.j2
{% for NAME in users %}
{{ NAME }}
{%endfor%}

4.3 if 判定

#if 判定#

{% for NAME in users if not NAME == "ansible" %}
User number {{loop.index}} - {{ NAME }}
{%endfor%}

loop.index   ##循环迭代记数从1开始 
loop.index0  ##循环迭代计数从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%}

4.4 j2模板在playbook中的应用

应用一:
[admin@ansible .ansible]$ cat westos.yml 
  - name: users
    hosts: westos
    tasks:
      - name: test.j2
        template:
          src: ./test.j2
          dest: /mnt/westos
[admin@ansible .ansible]$ cat test.j2 
  {% for user in users %}
  {{ user }}
  {% endfor %}
[admin@ansible .ansible]$ cat host_vars/172.25.32.11.yml 
 users:
   - westos
   - lee
   - linux
[admin@ansible .ansible]$ ansible-playbook westos.yml 

PLAY [users] ***************************************************************************************************************************************

TASK [Gathering Facts] *****************************************************************************************************************************
ok: [172.25.32.12]
ok: [172.25.32.11]

TASK [test.j2] *************************************************************************************************************************************
fatal: [172.25.32.12]: FAILED! => {"changed": false, "msg": "AnsibleUndefinedVariable: 'users' is undefined"}
ok: [172.25.32.11]

PLAY RECAP *****************************************************************************************************************************************
172.25.32.11               : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
172.25.32.12               : ok=1    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0   

受控主机172.25.32.11中:
[root@www mnt]# cat westos
    westos
    lee
    linux
  
应用二:
[admin@ansible .ansible]$ cat test.j2 
  {% for user in users %}
  {% if user.obj is defined %}
  {{ user.name }} - {{ user.age }} - {{ user.obj }}
  {% endif %}
  {% if user.obj is not defined %}
  {{ user.name }} - {{ user.age }} - NONE
  {% endif %}
  {% endfor %}
[admin@ansible .ansible]$ cat westos.yml 
  - name: users
    hosts: westos
    tasks:
      - name: test.j2
        template:
          src: ./test.j2
          dest: /mnt/westos
[admin@ansible .ansible]$ cat host_vars/172.25.32.12.yml 
users:
  - name: lee
    age: 18
    obj: linux
  - name: westos
    age: 20
[admin@ansible .ansible]$ ansible-playbook westos.yml 

PLAY [users] ***************************************************************************************************************************************

TASK [Gathering Facts] *****************************************************************************************************************************
ok: [172.25.32.12]
ok: [172.25.32.11]

TASK [test.j2] *************************************************************************************************************************************
fatal: [172.25.32.11]: FAILED! => {"changed": false, "msg": "AnsibleUndefinedVariable: 'ansible.parsing.yaml.objects.AnsibleUnicode object' has no attribute 'name'"}
changed: [172.25.32.12]

PLAY RECAP *****************************************************************************************************************************************
172.25.32.11               : ok=1    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0   
172.25.32.12               : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

受控主机172.25.32.12中:
[root@admin mnt]# cat westos
lee - 18 - linux
westos - 20 - NONE
  

 5. Ansible的加密控制 

5.1 创建加密文件

5.1.1 ansible-vault create westos

[admin@ansible .ansible]$ ansible-vault create westos
New Vault password: 
Confirm New Vault password:

5.1.2 创建加密文件的密码文件

[admin@ansible .ansible]$ vim westos-vault
westos

5.1.3 查看加密的文件

直接查看会是一串数字
[admin@ansible .ansible]$ cat westos
$ANSIBLE_VAULT;1.1;AES256
64663934353161646234373766383133356430653630353564363039663163623538373730366266
3037303534626562366135393933356666623531386264660a366536616565363330656562343930
35376132643763656139633362653035386133333565333766613865656233313662663438623638
3935653530633161360a366537336138373163393835363939366331626137303731613664346165
3035

利用刚才创建的密码文件查看
[admin@ansible .ansible]$ ansible-vault view --vault-password-file=westos-valut westos
hello westos

5.2 加密现有文件

[admin@ansible .ansible]$ ansible-vault encrypt test.j2 
New Vault password: 
Confirm New Vault password: 
Encryption successful

5.2.1 查看加密的现有文件

[admin@ansible .ansible]$ ansible-vault view --vault-password-file=westos-valut test.j2 
  {% for user in users %}
  {% if user.obj is defined %}
  {{ user.name }} - {{ user.age }} - {{ user.obj }}
  {% endif %}
  {% if user.obj is not defined %}
  {{ user.name }} - {{ user.age }} - NONE
  {% endif %}
  {% endfor %}

5.3 编辑加密文件

[admin@ansible .ansible]$ ansible-vault edit --vault-password-file=westos-valut westos

查看编辑的加密文件
[admin@ansible .ansible]$ ansible-vault view --vault-password-file=westos-valut westos  
hello westos
hello linux

5.4 解密文件

文件永久解密
[admin@ansible .ansible]$ ansible-vault decrypt test.j2 
Vault password: 
Decryption successful
[admin@ansible .ansible]$ cat test.j2 
  {% for user in users %}
  {% if user.obj is defined %}
  {{ user.name }} - {{ user.age }} - {{ user.obj }}
  {% endif %}
  {% if user.obj is not defined %}
  {{ user.name }} - {{ user.age }} - NONE
  {% endif %}
  {% endfor %}

文件解密保存为linux
[admin@ansible .ansible]$ ansible-vault decrypt westos --output=linux
Vault password: 
Decryption successful
[admin@ansible .ansible]$ cat linux 
hello westos
hello linux

5.5 更改密码

第一种方法:
[admin@ansible .ansible]$ ansible-vault rekey linux  
Vault password: 
New Vault password: 
Confirm New Vault password: 
Rekey successful

第二种方法:
[admin@ansible .ansible]$ vim linux-vault
[admin@ansible .ansible]$ cat linux-vault 
linux
[admin@ansible .ansible]$ ansible-vault rekey linux --new-vault-password-file=linux-vault
Vault password: 
Rekey successful
[admin@ansible .ansible]$ ansible-vault view --vault-password-file=linux-vault linux      
hello westos
hello linux
posted @ 2023-03-16 19:48  yunyeblog  阅读(43)  评论(0编辑  收藏  举报  来源