Ansible变量的定义与使用

Ansible变量的定义与使用

变量定义规则

  • 由字母、数字、下划线组成,必须以字母开头
  • 不能使用Ansible内置关键字作为变量名
  • 变量引用格式:{``{ 变量名 }}

变量范围与优先级(从高到低)

  1. Global范围:命令行和ansible配置设置的变量
  2. Play范围:在play和相关结构中设置的变量
  3. Host范围:inventory、facts或register的变量

优先级规则:高优先级变量会覆盖低优先级变量

变量定义与使用方式

1. vars定义变量

剧本文件:aa.yml

yaml 复制代码
---
- name: test
  hosts: node1
  vars:   #定义变量
    - aa: 11
    - bb: 22
    - cc:
        a1: c31
        a2: c32
  tasks:
    - name: 输出变量aa  
      debug:
        msg: "{{ aa }}"

    - name: 输出变量bb
      debug:
        msg: "{{ bb }}"

    - name: 输出变量cc的a1值
      debug:
        msg: "{{ cc.a1 }}"

    - name: 输出变量cc的a2值
      debug:
        msg: "{{ cc.a2 }}"

运行剧本文件:

bash 复制代码
[student@master ansible]$ ansible-playbook aa.yml 

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

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

TASK [输出变量aa] *******************************************************************
ok: [node1] => {
    "msg": 11
}

TASK [输出变量bb] *******************************************************************
ok: [node1] => {
    "msg": 22
}

TASK [输出变量cc的a1值] *************************************************************
ok: [node1] => {
    "msg": "c31"
}

TASK [输出变量cc的a2值] *************************************************************
ok: [node1] => {
    "msg": "c32"
}

PLAY RECAP **************************************************************************
node1                      : ok=5    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

2. vars_files定义变量

变量文件 /home/student/ansible/var.yml

yaml 复制代码
aa: 11
bb: 22
cc:
  a1: c31
  a2: c32

Playbook bb.yml

yaml 复制代码
---
- name: test
  hosts: node1
  vars_files: /etc/ansible/var.yml
  tasks:
    - name: 输出变量aa
      debug:
        msg: "{{ aa }}"

    - name: 输出变量bb
      debug:
        msg: "{{ bb }}"

    - name: 输出字典变量cc的a1值
      debug:
        msg: "{{ cc.a1 }}"

    - name: 输出字典变量cc的a2值
      debug:
        msg: "{{ cc.a2 }}"

运行剧本文件:

bash 复制代码
[student@master ansible]$ ansible-playbook bb.yml 

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

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

TASK [输出变量aa] *******************************************************************
ok: [node1] => {
    "msg": 11
}

TASK [输出变量bb] *******************************************************************
ok: [node1] => {
    "msg": 22
}

TASK [输出变量cc的a1值] *************************************************************
ok: [node1] => {
    "msg": "c31"
}

TASK [输出变量cc的a2值] *************************************************************
ok: [node1] => {
    "msg": "c32"
}

PLAY RECAP **************************************************************************
node1                      : ok=5    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

3. register注册变量

剧本文件:cc.yml

yaml 复制代码
---
- name: test
  hosts: node1
  tasks: 
    - name: zz 
      shell: "echo 123 > /tmp/zz"
      register: zz

    - name: 输出完整注册结果
      debug:
        var: zz

运行剧本文件

ba 复制代码
[student@master ansible]$ ansible-playbook cc.yml 

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

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

TASK [zz] ***************************************************************************
changed: [node1]

TASK [输出完整注册结果] *************************************************************
ok: [node1] => {
    "zz": {
        "changed": true,
        "cmd": "echo 123 > /tmp/zz",
        "delta": "0:00:00.005095",
        "end": "2025-09-01 19:27:55.954175",
        "failed": false,
        "msg": "",
        "rc": 0,
        "start": "2025-09-01 19:27:55.949080",
        "stderr": "",
        "stderr_lines": [],
        "stdout": "",
        "stdout_lines": []
    }
}

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

4. 事实变量(Facts)

剧本文件: dd.yml

yaml 复制代码
---
- name: test
  hosts: node1
  tasks: 
    - name: 输出主机名
      debug: 
        msg: "主机名: {{ ansible_fqdn }}"

    - name: 输出IP地址
      debug:
        msg: "主机 {{ ansible_nodename }} 的IPv4地址是 {{ ansible_enp1s0.ipv4.address }}"

运行剧本文件:

bash 复制代码
[student@master ansible]$ ansible-playbook dd.vim 

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

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

TASK [输出主机名] *******************************************************************
ok: [node1] => {
    "msg": "主机名: node1.example.com"
}

TASK [输出IP地址] *******************************************************************
ok: [node1] => {
    "msg": "主机 node1.example.com 的IPv4地址是 192.168.122.10"
}

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

常见的事实变量:

类别 常用变量 含义说明 示例值
主机基本信息 ansible_hostname 目标主机的短主机名 node1
ansible_fqdn 目标主机的完全限定域名(FQDN) node1.example.com
ansible_system 目标主机的操作系统类型 Linux/Windows
操作系统信息 ansible_os_family 操作系统家族(简化分类) RedHat/Debian/Suse
ansible_distribution 具体操作系统名称 CentOS/Ubuntu/RedHat
ansible_distribution_version 操作系统版本号 9.2(RHEL 9.2)/22.04(Ubuntu)
硬件资源 ansible_memtotal_mb 总内存大小(MB) 7824(约 8GB)
ansible_memfree_mb 空闲内存大小(MB) 5120
ansible_processor_cores CPU 核心数(单颗 CPU) 4
ansible_processor_count CPU 物理颗数 1
网络信息 ansible_default_ipv4.address 默认 IPv4 地址(路由优先的 IP) 192.168.1.101
ansible_default_ipv4.gateway 默认 IPv4 网关 192.168.1.1
ansible_eth0.ipv4.address 特定网卡(如 eth0)的 IPv4 地址(需根据实际网卡名调整) 192.168.1.101
文件系统 ansible_mounts 所有挂载点信息(列表类型,含路径、文件系统类型、容量等) [{"mount": "/", "fstype": "xfs", ...}]
用户信息 ansible_user_id 执行 Ansible 任务的用户 ID root/student

5. 命令行传递变量

Playbook (d.yml)

yaml 复制代码
---
- name: test
  hosts: node1
  tasks:
    - name: 输出第一个变量
      debug:
        msg: "我的名字是 {{ name1 }}"
    - name: 输出第二个变量
      debug:
        msg: "我的名字是 {{ name2 }}"

执行命令:

bash 复制代码
ansible-playbook d.yml -e 'name1=tom name2=marry'

执行结果示例:

bash 复制代码
[student@master ansible]$ ansible-playbook d.yml -e 'name1=tom name2=marry'

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

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

TASK [输出第一个变量] ***************************************************************
ok: [node1] => {
    "msg": "我的名字是 tom"
}

TASK [输出第二个变量] ***************************************************************
ok: [node1] => {
    "msg": "我的名字是 marry"
}

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

6. 主机清单中的变量

Inventory文件 (/home/student/ansible/hosts)

ini 复制代码
node1
node2
node3
node4
node5

[test01]
node1
[test02]
node2
[web]
node3
node4
[test05]
node5
[webtest:children]
web
[test01:vars]
vars1='hello'
vars2='world'

Playbook (e.yml)

bash 复制代码
[student@master ansible]$ ansible-playbook e.yml 

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

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

TASK [输出变量vars1] ****************************************************************
ok: [node1] => {
    "msg": " hello"
}

TASK [输出变量vars2] ****************************************************************
ok: [node1] => {
    "msg": " world"
}

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

运行剧本文件:

7. host_vars和group_vars目录定义变量

创建主机变量文件

bash 复制代码
[student@master ansible]$ mkdir host_vars
[student@master ansible]$ vim host_vars/node1

文件内容:

yaml 复制代码
vars1: groupvars1
vars2: groupvars2

Playbook (f.yml)

yaml 复制代码
---
- name: test
  hosts: node1
  tasks:
    - name: 输出变量vars1
      debug:
        msg: " {{ vars1 }}"

    - name: 输出变量vars2
      debug:
        msg: " {{ vars2 }}"

运行剧本文件:

bash 复制代码
[student@master ansible]$ ansible-playbook f.yml 

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

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

TASK [输出变量vars1] ****************************************************************
ok: [node1] => {
    "msg": " groupvars1"
}

TASK [输出变量vars2] ****************************************************************
ok: [node1] => {
    "msg": " groupvars2"
}

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

8. 内置变量

ansible_version变量(a.yml)
yaml 复制代码
---
- name: test
  hosts: node1
  tasks:
    - name: 输出Ansible版本
      debug:
        msg: "{{ ansible_version }}"

运行剧本文件:

bash 复制代码
[student@master ansible]$ ansible-playbook a.yml 

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

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

TASK [输出Ansible版本] **************************************************************
ok: [node1] => {
    "msg": {
        "full": "2.13.3",
        "major": 2,
        "minor": 13,
        "revision": 3,
        "string": "2.13.3"
    }
}

PLAY RECAP **************************************************************************
node1                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
inventory_hostname变量
yaml 复制代码
---
- name: test
  hosts: node1
  tasks:
    - name: 输出主机名
      debug:
        msg: "{{ inventory_hostname }}"

运行剧本文件:

bash 复制代码
[student@master ansible]$ ansible-playbook a.yml 

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

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

TASK [输出主机名] *******************************************************************
ok: [node1] => {
    "msg": "node1"
}

PLAY RECAP **************************************************************************
node1                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
play_hosts变量
yaml 复制代码
---
- name: test
  hosts: net
  tasks:
    - name: 输出目标主机列表
      debug:
        msg: "{{ play_hosts }}"

运行剧本文件:

bash 复制代码
[student@master ansible]$ ansible-playbook a.yml 

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

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

TASK [输出目标主机列表] *************************************************************
ok: [node1] => {
    "msg": [
        "node1"
    ]
}

PLAY RECAP **************************************************************************
node1                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
groups变量
yaml 复制代码
---
- name: test
  hosts: node1
  tasks:
    - name: 输出主机组信息
      debug:
        msg: "{{ groups }}"

运行剧本文件:

bash 复制代码
[student@master ansible]$ ansible-playbook a.yml 

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

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

TASK [输出主机组信息] ***************************************************************
ok: [node1] => {
    "msg": {
        "all": [
            "node1",
            "node2",
            "node5",
            "node3",
            "node4"
        ],
        "test01": [
            "node1"
        ],
        "test02": [
            "node2"
        ],
        "test05": [
            "node5"
        ],
        "ungrouped": [],
        "web": [
            "node3",
            "node4"
        ],
        "webtest": [
            "node3",
            "node4"
        ]
    }
}

PLAY RECAP **************************************************************************
node1                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
group_names变量
yaml 复制代码
---
- name: test
  hosts: node1
  tasks:
    - name: 输出所属主机组
      debug:
        msg: "{{ group_names }}"

运行剧本文件:

bash 复制代码
[student@master ansible]$ ansible-playbook a.yml 

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

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

TASK [输出所属主机组] ***************************************************************
ok: [node1] => {
    "msg": [
        "test01"
    ]
}

PLAY RECAP **************************************************************************
node1                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
inventory_dir变量
yaml 复制代码
---
- name: test
  hosts: node1
  tasks:
    - name: 输出inventory目录
      debug:
        msg: "{{ inventory_dir }}"

运行剧本文件:

bash 复制代码
[student@master ansible]$ ansible-playbook a.yml 

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

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

TASK [输出inventory路径] ************************************************************
ok: [node1] => {
    "msg": "/home/student/ansible"
}

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

9. with_items迭代变量

yaml 复制代码
---
- name: test
  hosts: node1
  tasks:
    - name: 循环输出字符串
      shell:
        cmd: echo "{{ item }}"
      with_items:
        - haha
        - heihei
        - hehe
      register: hi_var

    - name: 输出第一个结果
      debug:
        var: hi_var.results[0].stdout

    - name: 输出第二个结果
      debug:
        var: hi_var.results[1].stdout

    - name: 输出第三个结果
      debug:
        var: hi_var.results[2].stdout

运行剧本文件:

bash 复制代码
[student@master ansible]$ ansible-playbook w.yml 

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

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

TASK [循环输出字符串] ***************************************************************
changed: [node1] => (item=haha)
changed: [node1] => (item=heihei)
changed: [node1] => (item=hehe)

TASK [输出第一个结果] ***************************************************************
ok: [node1] => {
    "hi_var.results[0].stdout": "haha"
}

TASK [输出第二个结果] ***************************************************************
ok: [node1] => {
    "hi_var.results[1].stdout": "heihei"
}

TASK [输出第三个结果] ***************************************************************
ok: [node1] => {
    "hi_var.results[2].stdout": "hehe"
}

PLAY RECAP **************************************************************************
node1                      : ok=5    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

Ansible Vault管理机密

创建加密文件

bash 复制代码
[student@master ansible]$ ansible-vault create vault.yml
New Vault password:    #建立密码
Confirm New Vault password: # 确认密码

直接查看加密文件无法获得正确内容:

bash 复制代码
[student@master ansible]$ cat vault.yml 
$ANSIBLE_VAULT;1.1;AES256
33636230323933313962393537376136376330613161663339363933373135636331326330366236
6463393531366136356337303832383062643530616564340a303532393966646339623337326366
30373162306362336139643565333461386636323164623037393066646466626337363938303963
6561386531366339630a623361323662323038623838383166363235373562333133353036636563
31623839373032636233663635356339656664666163666235653532396237336431353036666434
30353339316534663161653465316166386334623135326434356239363634363263646263396638
37383663623162653734363665303031363931333232646361323163363664306334336433373535
38376262633631326533656531313263313133613666623131663639333633623633613266326131
63333864326537343966663437333137333861396638396339353030386631623831373830353834
3033373932333636393334366361653365393234343139666238

查看加密文件

bash 复制代码
[student@master ansible]$ ansible-vault view vault.yml
Vault password:   #  输入密码
---
- name: test
  hosts: node1
  tasks:
    - name: 输出所属主机组
      debug:
        msg: "{{ group_names }}"

编辑加密文件

bash 复制代码
[student@master ansible]$ ansible-vault edit vault.yml
Vault password:   # 输入密码

加密现有文件

bash 复制代码
[student@master ansible]$ ansible-vault encrypt a.yml
New Vault password:    #建立密码
Confirm New Vault password:  # 确认密码
Encryption successful

解密文件

bash 复制代码
# 直接解密
ansible-vault[student@master ansible]$ ansible-vault decrypt a.yml
Vault password: 
Decryption successful
[student@master ansible]$ cat a.yml 
---
- name: test
  hosts: node1
  tasks: 
    - name: 输出inventory路径
      debug:
        msg: "{{inventory_dir}}"
 decrypt test.yml

# 解密为其他文件
ansible-vault decrypt a.yml --output=a-secret.yml

更改加密文件密码

bash 复制代码
[student@master ansible]$ ansible-vault rekey vault.yml
Vault password:  #输入原密码
New Vault password: #输入新密码
Confirm New Vault password: #确认新密码
Rekey successful

执行加密的Playbook

bash 复制代码
[student@master ansible]$ ansible-playbook --ask-vault-pass vault.yml
Vault password: 

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

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

TASK [输出所属主机组] ***************************************************************
ok: [node1] => {
    "msg": [
        "test01"
    ]
}

PLAY RECAP **************************************************************************
node1                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
相关推荐
特种加菲猫7 小时前
深入Linux内核:IPC资源管理揭秘
linux·笔记
北冥电磁电子智能7 小时前
江协科技STM32学习笔记补充之001。为什么C语言在对STM32编程过程中的二进制要用十六进制来进行读写。而不能直接用二进制来进行读写。
linux·stm32
工藤新一¹7 小时前
Linux 孤儿进程 (Orphan Process)
linux·孤儿进程·c/c++·orphan process
礼拜天没时间.8 小时前
Tomcat 企业级运维实战系列(四):Tomcat 企业级监控
运维·centos·tomcat·firefox
礼拜天没时间.8 小时前
Tomcat 企业级运维实战系列(一):核心概念与基础部署
java·运维·centos·tomcat
大白菜201501058 小时前
ubuntu 创建系统服务 开机自启
linux·运维·ubuntu
willhuo8 小时前
学生请假就餐系统
运维·服务器·.netcore
lhxsir8 小时前
linux连接服务器sftp无法输入中文
linux·运维·服务器
小沈熬夜秃头中୧⍤⃝9 小时前
无需服务器也能建网站:Docsify+cpolar让技术文档分享像写笔记一样简单
运维·服务器·笔记