本文介绍了是否可以在Ansible中定义剧本全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大型Ansible剧本,运行时会在其中构建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,然后在每次播放后递增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中定义剧本全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 13:35