我的主机变量和组变量未加载

问题描述 投票:0回答:1

这是我位于项目根目录的 ansible.cfg。

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

这是我分期盘点的内容

[all_hosts]
rails ansible_ssh_host=170.64.208.17

[app_hosts]
rails

这是我的剧本:

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

在我的roles/ruby/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\n\nThe error appears to be in '/Users/rabin/code/web/ansible/playbooks/roles/ruby/tasks/main.yml': line 34, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n    version: master\n- name: Install Ruby version\n  ^ here\n"}

我希望它从

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

但是没有成功。请建议我做错了什么。我也想将它们加载到 jinga 模板上。预先感谢

ansible ansible-inventory ansible-template
1个回答
1
投票

看看变量优先级:我应该在哪里放置变量?host_vars有两个选项:

  • 9.库存host_vars/*
  • 10.playbook host_vars/*

您配置了清单的路径./ansible/inventory/staging。在这种情况下,您必须将 host_vars 也放入此目录中

./ansible/inventory/staging/host_vars/rails

下一个选项是将 host_vars 放入 playbook 的目录中。此选项 (10.) 将覆盖上一个选项 (9.)。

© www.soinside.com 2019 - 2024. All rights reserved.