英文:
Naming variables in Ansible roles
问题
在Ansible角色中,你可以以不同的方式定义变量:
- 在
vars/main.yml
中 - 在
defaults/main.yml
中 - 通过任务中的
register
- 通过
set_fact
任务 - 在任务的
vars
中 - 可能还有其他方式...
通过这个答案我了解到推荐使用角色变量名称的命名约定,例如 role_name__variable_name
。但我不确定这是否只是一个建议,还是我需要担心由角色引起的作用域/命名空间问题。
我可以想象在使用 set_fact
定义变量时应该采取这种预防措施,因为这可能会覆盖现有的主机变量。但这是否属实呢?在角色的哪些变量定义中我需要担心可能的“命名空间损坏”?
英文:
In Ansible roles you can define variables in different ways:
- in
vars/main.yml
- in
defaults/main.yml
- via
register
in a task - via a
set_fact
task - in task
vars
- probably more...
Through this answer I came across the recommendation to use a naming convention for role variable names, e. g. role_name__variable_name
. But I am not sure if this is just a recommendation or if I have to worry about scope/namespace problems caused by a role.
I can imagine that I should take such precaution when defining variables with set_fact
as this may overwrite existing host variables. But is this even true? At which variable definitions in a role do I have to worry about possible "namespace corruption"?
答案1
得分: 1
所以,将变量命名为角色名称的一部分,然后指明变量表示的内容,是一个最佳实践。
一个明显的例子是Elasticsearch角色来自Elastic。
他们简单地使用es_whatever
作为命名惯例。当主机具有这些变量时,很容易识别它们的用途。
在角色中的哪些变量定义会让我担心可能的“命名空间损坏”?
嗯,Ansible有‘魔术变量’和预定义变量。当您不在命名中使用它们时,您基本上是清晰的。
一旦您熟悉它们,您就会理解它们为什么被称为魔术和/或特殊,很可能不会再次使用它们。
我可以想象在使用
set_fact
定义变量时应该采取这样的预防措施,因为这可能会覆盖现有的主机变量。但这是真的吗?
是的,但当您编写一个set_fact
任务时,定义变量通常会涉及到它必须做的事情。只是稍微小心一些在命名它们时,并确保它们是唯一的。
英文:
So, it's a best practice to name variables indeed w (part) of the role name, and then what the variable stand for.
A clear example is the Elasticsearch role from Elastic.
They simply use es_whatever
as naming convention. When a host has those variables, it's easy to recognize what they're for.
> At which variable definitions in a role do I have to worry about possible "namespace corruption"?
Well, Ansible has 'magic variables' and predefined variables.
You're most in the clear when you do not use them in naming.
Ensure to watch out for the magic variables, and the special named variables.
Once you've gone through them, you understand why they're either magic and/or special, and most likely will not use them again.
> I can imagine that I should take such precaution when defining variables with set_fact as this may overwrite existing host variables. But is this even true?
Yes, but when you write a set_fact
task, defining the variable usually ends up with something it has to do.
Just watch out a bit with naming them, and ensure they're unique.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论