问题描述
我有一个很大的 Ansible playbook,其中在运行时构建了 Docker 镜像.我使用越来越多的数字作为标记来对它们进行版本控制.目前,我必须在每个 hosts:
部分中指定这一点.
I have a large Ansible playbook where Docker images are built when running it. I am using an increasing number as the tag to version them. Currently, I have to specify this in every hosts:
section.
我知道有全局变量,但是从我通过搜索ansible"全局变量"发现的结果来看,它们必须在剧本之外进行定义.是否可以为剧本定义全局变量?
I know there are global variables but from what I found by searching for "ansible" "global variables", they have to defined outside of the playbook. Is it possible to define global variables which are global for the playbook?
推荐答案
如果您使用的标签/版本适用于所有主机,则使用 group_vars/all 是一个可行的选择.
If the tag/version you are using is applicable to all hosts, then using group_vars/all is a viable option.
如果修订号特定于 host_vars/host_name 文件中的每个主机条目可能会更好.
If the revision numbers are specific to each host entries in a host_vars/host_name file might be better.
如果您想读取和初始化 var ,然后在每次播放后递增它,那么在剧本中跨播放(或您所说的每个 -hosts)保留该信息变得有点困难.例如,如果您想部署 N 个 docker 实例,您可能会像这样执行一些动态库存魔术:
If you want to read and initial var and then increment it after each play that becomes a bit more difficult to persist that information across plays (or each -hosts as you say) in the playbook. For example if you were looking to deploy N docker instances you might do some dynamic inventory magic like this:
- hosts: localhost
tasks:
- add_host: name=docker_{{item}} groups="dockers,other" tag={{item}}
with_sequence: start={{ext_def_start}} count={{ext_def_num}}
- hosts: docker_*
tasks:
- debug: var=tag
这篇关于是否可以在 Ansible 中定义剧本全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!