Ansible变量详解

目录

一、变量定义方法

[1. 在Play中定义变量](#1. 在Play中定义变量)

方式一:列表方式(一个名称对应一个值)

方式二:一个名称包含多个值

[2. 在文件中定义变量](#2. 在文件中定义变量)

单个文件定义

多个文件定义

[3. 在主机清单中定义变量](#3. 在主机清单中定义变量)

[4. 官方推荐方式:host_vars 和 group_vars](#4. 官方推荐方式:host_vars 和 group_vars)

主机变量定义

组变量定义

所有组通用变量

[二、Ansible 内置变量(Facts)](#二、Ansible 内置变量(Facts))

[查看所有 Facts](#查看所有 Facts)

使用内置变量示例

常用内置变量

三、变量注册(Register)

为什么需要变量注册?

基础用法

查看具体参数

实际应用:列出文件信息

注册变量的常用属性

条件判断结合注册变量

四、变量优先级(从低到高)

五、综合应用示例

案例:部署Nginx并配置

六、变量使用技巧总结

变量默认值示例


一、变量定义方法

1. 在Play中定义变量

方式一:列表方式(一个名称对应一个值)
复制代码
- hosts: web01
  vars:
    - p1: wget
    - p2: lrzsz
  tasks:
    - name: yum test
      yum:
        name:
          - "{{ p1 }}"
          - "{{ p2 }}"
        state: present
方式二:一个名称包含多个值
复制代码
- hosts: web01
  vars:
    pack:
      - wget
      - lrzsz
  tasks:
    - name: yum test
      yum:
        name: "{{ pack }}"
        state: present

注意:

  • 如果变量单独存在需要加双引号,如 "{``{ p1 }}"

  • 如果带路径的变量则不需要加双引号

复制代码
- hosts: web01
  vars:
    - ip: 10.0.0.7
    - ho: web01
  tasks:
    - name: create directory
      file:
        path: /root/{{ ho }}_{{ ip }}  # 路径中的变量无需引号
        state: directory

2. 在文件中定义变量

单个文件定义
复制代码
# v1.yml
p1: lrzsz
p2: wget
p3: tree
复制代码
# test.yml
- hosts: web01
  vars_files: ./v1.yml
  tasks:
    - name: yum test
      yum:
        name:
          - "{{ p1 }}"
          - "{{ p2 }}"
          - "{{ p3 }}"
        state: present
多个文件定义
复制代码
# v1.yml
p1: tree
复制代码
# v2.yml
pack:
  - lrzsz
复制代码
# test.yml
- hosts: web01
  vars_files:
    - v1.yml
    - v2.yml
  tasks:
    - name: yum test
      yum:
        name: "{{ pack }}"
        state: absent

3. 在主机清单中定义变量

复制代码
# /etc/ansible/hosts
nfs ansible_ssh_host=10.0.0.31

[webs]
web01 ansible_ssh_host=10.0.0.7
web02 ansible_ssh_host=10.0.0.8

[webs:vars]
p1=wget
p2=lrzsz
复制代码
# test.yml
- hosts: web01
  tasks:
    - name: yum test
      yum:
        name:
          - "{{ p1 }}"
          - "{{ p2 }}"
        state: present

4. 官方推荐方式:host_vars 和 group_vars

创建目录结构:

复制代码
mkdir host_vars group_vars
主机变量定义
复制代码
# host_vars/web01
p1: wget
p2: lrzsz
复制代码
# test.yml
- hosts: web01
  tasks:
    - name: yum test
      yum:
        name:
          - "{{ p1 }}"
          - "{{ p2 }}"
        state: absent
组变量定义
复制代码
# group_vars/webs
p1: tree
p2: lrzsz
复制代码
# test.yml
- hosts: webs
  tasks:
    - name: yum test
      yum:
        name:
          - "{{ p1 }}"
          - "{{ p2 }}"
        state: present
所有组通用变量
复制代码
# group_vars/all
p1: wget
p2: lrzsz

二、Ansible 内置变量(Facts)

查看所有 Facts

复制代码
ansible web01 -m setup
ansible web01 -m setup -a 'filter=ansible_hostname'
ansible web01 -m setup | grep ansible_hostname -A 5

使用内置变量示例

传统方式(不推荐):

复制代码
- hosts: web01
  tasks:
    - name: create directory
      file:
        path: /root/web01_10.0.0.7
        state: directory

- hosts: web02
  tasks:
    - name: create directory
      file:
        path: /root/web02_10.0.0.8
        state: directory

使用内置变量(推荐):

复制代码
- hosts: webs
  tasks:
    - name: create directory with facts
      file:
        path: /root/{{ ansible_hostname }}_{{ ansible_default_ipv4.address }}
        state: directory

常用内置变量

变量名 说明
ansible_hostname 主机名
ansible_default_ipv4.address 默认IPv4地址
ansible_os_family 操作系统家族
ansible_distribution 发行版名称
ansible_distribution_version 发行版版本
ansible_processor_cores CPU核心数
ansible_memtotal_mb 内存大小(MB)
ansible_devices 磁盘设备信息

三、变量注册(Register)

为什么需要变量注册?

在执行某些命令时,Ansible不会直接返回执行结果,需要通过变量注册来捕获输出。

基础用法

复制代码
- hosts: web01
  tasks:
    - name: check nginx config
      command: 'nginx -t'
      register: result_nginx

    - name: print result
      debug:
        msg: "{{ result_nginx }}"

查看具体参数

复制代码
- hosts: web01
  tasks:
    - name: check nginx config
      command: 'nginx -t'
      register: result_nginx

    - name: print stderr lines
      debug:
        msg: "{{ result_nginx.stderr_lines }}"

    - name: print return code
      debug:
        msg: "{{ result_nginx.rc }}"

实际应用:列出文件信息

复制代码
- hosts: web01
  tasks:
    - name: list root directory
      command: 'ls -l /root/'
      register: list_dir

    - name: print directory listing
      debug:
        msg: "{{ list_dir.stdout_lines }}"

注册变量的常用属性

属性 说明
rc 返回码(0表示成功)
stdout 标准输出(字符串)
stdout_lines 标准输出(列表形式)
stderr 错误输出(字符串)
stderr_lines 错误输出(列表形式)
changed 是否发生变更

条件判断结合注册变量

复制代码
- hosts: web01
  tasks:
    - name: check nginx config
      command: 'nginx -t'
      register: result
      ignore_errors: yes

    - name: restart nginx if config is valid
      systemd:
        name: nginx
        state: restarted
      when: result.rc == 0

四、变量优先级(从低到高)

  1. group_vars/all

  2. group_vars/组名

  3. host_vars/主机名

  4. 主机清单中定义的变量

  5. Playbook中定义的 vars

  6. vars_files 引入的变量

  7. 命令行传递的变量 -e

复制代码
# 命令行传递变量(最高优先级)
ansible-playbook test.yml -e "p1=git p2=python3"

五、综合应用示例

案例:部署Nginx并配置

复制代码
- hosts: webs
  vars:
    nginx_port: 80
    nginx_user: www
  tasks:
    - name: install nginx
      yum:
        name: nginx
        state: present

    - name: create nginx user
      user:
        name: "{{ nginx_user }}"
        uid: 666
        group: "{{ nginx_user }}"
        shell: /sbin/nologin
        create_home: no

    - name: copy nginx config
      template:
        src: nginx.conf.j2
        dest: /etc/nginx/nginx.conf
      register: config_result

    - name: test nginx config
      command: nginx -t
      register: test_result
      changed_when: false

    - name: restart nginx
      systemd:
        name: nginx
        state: restarted
        enabled: yes
      when: config_result.changed and test_result.rc == 0

    - name: display nginx info
      debug:
        msg: 
          - "Server: {{ ansible_hostname }} ({{ ansible_default_ipv4.address }})"
          - "Nginx port: {{ nginx_port }}"
          - "Config status: {{ 'Valid' if test_result.rc == 0 else 'Invalid' }}"

六、变量使用技巧总结

  1. 命名规范 :使用小写字母和下划线,如 nginx_port

  2. 默认值 :可以使用 {``{ variable | default('default_value') }}

  3. 变量合并{``{ variable1 ~ '_' ~ variable2 }}

  4. 类型转换{``{ string_var | int }}{``{ int_var | string }}

  5. 条件判断when: variable is defined

变量默认值示例

复制代码
- hosts: webs
  tasks:
    - name: use default if variable not defined
      debug:
        msg: "{{ custom_port | default(80) }}"

通过合理使用Ansible变量,可以大大提高Playbook的灵活性和可复用性。建议在实际项目中优先使用 group_varshost_vars 的目录结构来管理变量。

相关推荐
大树883 天前
金刚石散热越强,管路越先见顶
大数据·运维·服务器·人工智能·ai
摇滚侠3 天前
Linux CentOS7 rpm 安装 MySQL 5.7
linux·运维·mysql
霸道流氓气质3 天前
领域驱动设计(DDD)在 Spring Boot 微服务中的实践指南
运维·spring boot·微服务
Inhand陈工3 天前
基于台达PLC与映翰通IG502的智慧水产养殖精准投喂与远程运维解决方案
运维·人工智能·物联网·阿里云·信息与通信
酣大智3 天前
ARP代理--工作原理
运维·网络·arp·arp代理
shushangyun_3 天前
2026年快消品B2B系统推荐:支持终端门店订货、促销政策自动化的工具?
java·运维·网络·数据库·人工智能·spring·自动化
施努卡机器视觉3 天前
SNK施努卡侧滑门锁上滑轮总成自动化装配线,从零件到组件,全流程精密制造方案
运维·自动化·制造
dayuOK63073 天前
写作卡壳怎么办?我的“5分钟启动法”
人工智能·职场和发展·自动化·新媒体运营·媒体
AC赳赳老秦3 天前
用 OpenClaw 搭建服务器故障应急响应系统,自动处理 80% 常见运维故障
android·运维·服务器·python·rxjava·deepseek·openclaw
java_cj3 天前
深入kube-apiserver认证机制:从Bearer Token到mTLS的完整认证链解析
linux·运维·服务器·云原生·容器·kubernetes