Ansible 变量指南:声明、优先级、作用域与最佳实践(一)

发布于:2025-07-24 ⋅ 阅读:(17) ⋅ 点赞:(0)

Ansible 变量的声明

前言

全面理解 Ansible 变量是编写高效、可维护 Playbook 的关键。由于最近使用 Ansible 比较多,在变量问题上踩了不少坑,也因此对变量的声明,优先级和作用域有了更深的理解。姑且总结一下,分享给大家,作为一个学习、避坑小指南。


在哪儿声明 Ansible 变量?

简单来说,变量可以放在下面这些地方,我们平时用得最多的也就这几种。加上代码示例后会更清晰。

  1. 命令行里直接加

    • -e--extra-vars 参数,在跑 playbook 的时候临时指定。

    ansible-playbook my_playbook.yml -e “user=admin http_port=8080”

    
    
  2. Playbook 文件里

    • vars::直接在 Playbook 里写。
    - name: My Playbook
      hosts: webservers
      vars:
        app_name: "AwesomeApp"
        app_version: "1.2.3"
      tasks:
        - name: Display app info
          debug:
            msg: "Deploying {{ app_name }} version {{ app_version }}"
    
    • vars_files: 把变量单独存到一个文件里,然后在 Playbook 里引用。
    # vars/db.yml
    db_user: "mysql_user"
    db_pass: "secret"
    
    # playbook.yml
    - name: My Playbook
      hosts: db_servers
      vars_files:
        - vars/db.yml
      tasks:
        - name: Configure database
          debug:
            msg: "Configuring DB with user {{ db_user }}"
    
    • vars_prompt: 运行时会提示你手动输入,适合密码这类敏感信息。
    - name: Deploy with user confirmation
      hosts: all
      vars_prompt:
        - name: "deploy_user"
          prompt: "Enter your username for deployment"
          private: no # 输入时可见
        - name: "deploy_password"
          prompt: "Enter your password"
          private: yes # 输入时不可见
      tasks:
        - name: Run deployment
          debug:
            msg: "Running as {{ deploy_user }}"
    
  3. Inventory 清单里

    • group_vars/: 这是最常用的。给某个主机组(比如 webservers)创建一个 group_vars/webservers.yml 文件,里面的变量就对这个组所有机器生效。group_vars/all.yml 里的变量对所有机器都生效。
    # 目录结构
    inventory
    group_vars/
      webservers.yml
      all.yml
    
    # group_vars/webservers.yml
    http_port: 80
    ntp_server: "ntp.web.example.com"
    
    • host_vars/: 如果只想给某一台机器(比如 server1.example.com)指定变量,就创建一个 host_vars/server1.example.com.yml 文件。
    # 目录结构
    inventory
    host_vars/
      server1.example.com.yml
    
    # host_vars/server1.example.com.yml
    # 这个配置会覆盖 group_vars/webservers.yml 里的 http_port
    http_port: 8080
    
  4. Role (角色) 里

    • roles/your_role/defaults/main.yml: 角色的默认变量。注意是“默认”,意思是它的优先级最低,很容易被其他地方的同名变量覆盖。
    # roles/my_apache_role/defaults/main.yml
    apache_port: 80
    
    • roles/your_role/vars/main.yml: 角色的“标准”变量,比 defaults 里的优先级高。
    # roles/my_apache_role/vars/main.yml
    apache_package_name: "httpd"
    
  5. 运行时动态生成

    • Facts (事实变量): Ansible 会自动收集远程机器的信息,比如 IP 地址 (ansible_default_ipv4.address)、系统版本等。这些是它自己发现的变量。
    - name: Show OS
      debug:
        msg: "The OS is {{ ansible_facts['distribution'] }} {{ ansible_facts['distribution_version'] }}"
    
    • register: 把一个任务的执行结果存成一个变量,给后面的任务用。
    - name: Check file existence
      command: ls /path/to/some/file
      register: file_check_result
      ignore_errors: yes
    
    - name: Report if file exists
      debug:
        msg: "File exists!"
      when: file_check_result.rc == 0
    
    • set_fact: 在 playbook 运行过程中,手动创建一个新变量。
    - name: Set a custom fact
      set_fact:
        my_custom_variable: "Hello World"
        
    - name: Use the custom fact
      debug:
        msg: "{{ my_custom_variable }}"
    

后续会再写一篇介绍 Ansible 变量的优先级和作用域。

参考资料


网站公告

今日签到

点亮在社区的每一天
去签到