Ansible变量:括号表示法与点表示法的选择,及RHCE备考中facts引用方式的疑问
Great questions—let’s break these down clearly since they’re common points of confusion, especially when prepping for RHCE!
1. 括号表示法 vs 点表示法:该选哪种?
Both syntaxes are valid in Ansible, but the choice depends on your variable names and use case:
点表示法 (
vars.my_var):- 更简洁易读,适合常规变量名(无特殊字符、空格、数字开头的情况)
- 示例:
{{ web_server.port }} - 注意:如果变量名和Ansible内置关键字(比如
default、when)冲突,点表示法可能会被误解析,这时候换括号表示法更安全。
括号表示法 (`vars['my_var']):
- 必须使用的场景:变量名包含特殊字符(连字符、空格、数字开头,比如
my-var、1st_var) - 适合动态变量引用:比如在循环中使用
{{ vars[item.key] }}来调用动态生成的变量名 - 示例:
{{ vars['my-custom-var'] }}
- 必须使用的场景:变量名包含特殊字符(连字符、空格、数字开头,比如
2. Ansible Facts:ansible_facts['hostname'] vs ansible_hostname?
First off, both are completely valid and functionally equivalent—here’s why:
When Ansible gathers facts, it automatically maps every key in the ansible_facts dictionary to a top-level variable prefixed with ansible_. So ansible_hostname is just an alias for ansible_facts['hostname'].
About the "speed" concern:
Your feeling that ansible_hostname is faster is actually a misconception. Internally, Ansible stores both references to the same data in memory—there’s no meaningful performance difference between the two. Both will retrieve the fact instantly.
Best practices for RHCE:
- Either syntax will be accepted in the exam, so pick whichever you find more readable and stick with it for consistency.
- If you disable fact gathering (
gather_facts: no) and collect specific facts manually, just ensure the fact you’re referencing has been collected (both syntaxes will work as long as the fact exists). - Newer Ansible versions (2.10+) still support both styles, so you don’t have to worry about deprecation.
内容的提问来源于stack exchange,提问作者Zer0o

