Search code examples
ansibleansible-inventoryansible-template

My Host vars and Group vars are not loading


This is my ansible.cfg at the root of the project.

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

This is my content of staging inventory

[all_hosts]
rails ansible_ssh_host=170.64.208.17

[app_hosts]
rails

this is my playbook:

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

and in my roles/ruby/main.yml. I have following code

- 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 }}"

But it throws this:

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"}

I expect it to load variables from ansible/host_vars/rails

ruby_version: "3.2.2"
rails_env: staging

I also tried to load variables by defining group vars using ansible/group_vars/app_hosts

ruby_version: "3.2.2"
rails_env: staging

But it didn't work. Please suggest what i did wrong. I want to load them on jinga templates as well. Thanks in advance


Solution

  • Take a look at Variable precedence: Where should I put a variable?. There are two options for host_vars:

    • 9.inventory host_vars/*
    • 10.playbook host_vars/*

    You configured the path to the inventory ./ansible/inventory/staging. In this case, you have to put the host_vars also into this directory

    ./ansible/inventory/staging/host_vars/rails
    

    The next option is putting the host_vars into the playbook's directory. This one (10.) will override the previous option (9.).