Ansible Playbook读取组变量值错误问题求助
Let me walk you through the most common fixes for this exact issue—I’ve run into it a handful of times myself:
1. Double-Check Your group_vars Directory Location
This is the #1 culprit. Ansible looks for group variables relative to your inventory file, not your playbook. So if your inventory is at inventories/hosts.inv, your group_vars folder must live inside the inventories/ directory, not alongside your playbooks.
Your project structure should look like this:
your_project/ ├── inventories/ │ ├── hosts.inv │ └── group_vars/ │ ├── group_A │ └── group_B └── playbooks/ └── playbook.yml
If you had group_vars in the playbooks/ folder, Ansible was pulling variables from there (or defaulting to nothing) instead of the ones you defined for your inventory groups.
2. Verify Group Name & Filename Exact Match
Ansible is case-sensitive when matching group names to group_vars filenames. Double-check that:
- Your inventory has
[group_B](exact capitalization) - Your
group_varsfile is namedgroup_B(no typos, no different case likeGroup_Borgroup-b)
Even a tiny mismatch here will cause Ansible to ignore the correct variable file.
3. Check for Variable Overrides
Group variables can be overridden by higher-priority variables. Run this debug command to see where var_port is coming from:
ansible server3 -i inventories/hosts.inv -m debug -a "var=var_port"
If the output shows 9001, check for these possible overrides:
- Host variables: A
host_vars/server3file definingvar_port - Command-line variables: Did you pass
-e var_port=9001in a previous run? - Playbook-level variables: Does your playbook have a
varssection definingvar_port? - Nested groups: Is
group_Ba child ofgroup_Ain your inventory (e.g.,[group_A:children]withgroup_Blisted)? That would inheritgroup_A’s variables.
4. Validate YAML Syntax in Variable Files
A tiny YAML syntax error in group_vars/group_B can cause Ansible to ignore the file entirely. Make sure the line looks exactly like:
var_port: 9002
No extra spaces, no tabs (use spaces for indentation), no trailing characters. You can use a tool like yamllint to check for syntax issues if you have it installed.
5. Test with a Minimal Playbook
To rule out issues in your existing playbook, create a minimal test playbook (test.yml) in your playbooks/ folder:
- name: Test group variables hosts: all tasks: - name: Print var_port debug: var: var_port
Run it with the same limit:
ansible-playbook playbooks/test.yml -i inventories/hosts.inv -l group_B
If this shows the correct 9002 value, the problem is in your original playbook (not the group variables themselves).
内容的提问来源于stack exchange,提问作者oleg.borovykh

