You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ansible主机/组变量未加载,ruby_version变量未定义求助

Ansible主机/组变量无法加载问题排查

项目配置

项目根目录下的ansible.cfg

[defaults]
inventory = ./ansible/inventory/staging

staging清单文件

[all_hosts]
rails ansible_ssh_host=170.64.208.17

[app_hosts]
rails

Playbook内容

- hosts: rails
  remote_user: deploy
  become: yes
  roles:
    - ruby
    - rails

Ruby角色tasks/main.yml

- name: Install dependencies for rbenv
  package:
    name: "{{ item }}"
    state: present
  with_items:
    - git
    - curl
    - libssl-dev
    - libreadline-dev
    - zlib1g-dev
    - build-essential
    - libffi-dev
    - libyaml-dev
- name: Clone rbenv repository
  git:
    repo: https://github.com/rbenv/rbenv.git
    dest: /home/deploy/.rbenv 
    version: master
- name: Set rbenv path
  lineinfile:
    dest: "{{ ansible_env.HOME }}.bashrc"
    line: 'export PATH="/home/deploy/.rbenv/bin:$PATH"'
    insertafter: EOF
    state: present
- name: Initialize rbenv in shell
  shell: |
    export PATH="/home/deploy/.rbenv/bin:$PATH"
    eval "$(rbenv init -)"
- name: Clone ruby-build repository
  git:
    repo: https://github.com/rbenv/ruby-build
    dest: ~/.rbenv/plugins/ruby-build
    version: master
- name: Install Ruby version
  shell: |
    export PATH="/home/deploy/.rbenv/bin:$PATH"
    eval "$(rbenv init -)"
    rbenv install {{ ruby_version }}
    rbenv global {{ ruby_version }}
- name: Debug ruby version
  debug:
    msg: "{{ ruby_version }}"

运行错误信息

fatal: [rails]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'ruby_version' is undefined. 'ruby_version' is undefined

The error appears to be in '/Users/rabin/code/web/ansible/playbooks/roles/ruby/tasks/main.yml': line 34, column 3, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:

    version: master
- name: Install Ruby version
  ^ here
"}

已尝试的变量配置

主机变量文件(当前路径:ansible/host_vars/rails)

ruby_version: "3.2.2"
rails_env: staging

组变量文件(当前路径:ansible/group_vars/app_hosts)

ruby_version: "3.2.2"
rails_env: staging

问题原因与解决方法

  1. 核心问题:变量路径错误
    Ansible默认从inventory文件所在目录的同级目录加载host_vars和group_vars,而非项目根目录。你的inventory路径是./ansible/inventory/staging,因此正确的变量存放路径应为:

    • 主机变量:./ansible/inventory/host_vars/rails
    • 组变量:./ansible/inventory/group_vars/app_hosts
      把变量文件移动到上述路径即可自动加载。
  2. 验证变量加载状态
    执行以下命令确认变量是否被正确读取:

    ansible rails -m debug -a "var=ruby_version"
    

    若输出变量值则说明加载正常,否则检查路径、文件名是否完全匹配(主机名大小写敏感),或YAML文件是否存在语法错误。

Jinja模板中加载变量

只需在.j2模板文件中直接引用变量名即可,示例:

# config/database.yml
environment: {{ rails_env }}
ruby_version: {{ ruby_version }}

内容的提问来源于stack exchange,提问作者Rabin Poudyal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 04:17:33