在 Ansible 中将共享参数与环境特定参数合并 [英] Merging shared parameters with environment specific parameter in Ansible

查看:13
本文介绍了在 Ansible 中将共享参数与环境特定参数合并的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在命令行上指定目标服务器环境运行我的剧本,例如:

I run my playbooks specifying the target server environment on the command line, e.g.:

ansible-playbook -e env=staging playbook.yml

现在我希望能够提供参数,例如在服务器上创建的用户字典,其中有通用所有环境的用户,以及特定那个环境的用户> 我运行剧本的环境.

Now I want to be able to provide parameters, e.g. dictionary of users to create on the server in such a way that there are users common to all environments, and also users that are specific to that one environment for which I run the playbook.

目录结构可能如下所示:

The directory structure could look like this:

├── group_vars
│   ├── all
│   │   ├── users.yml
│   │  
│   ├── development
│   │   ├── users.yml
│   │  
│   ├── production
│   │   ├── users.yml
│   │  
│   └── staging
│       ├── users.yml

我最初认为这样的设置可以完成这项工作.但是,每个环境的 users.yml 字典永远不会合并all/users.yml

I initially thought that a setup like this would do the job. However, the users.yml dictionaries for each environment are never merged with all/users.yml

ansible-playbook -e env=production playbook.yml 只会从 production/users.yml 读取.

如何让 Ansible 将来自特定环境的 users.ymlall/users.yml 合并 - 以便我始终创建公共和特定于环境的用户?

How can I have Ansible merge users.yml from specific environments with all/users.yml - so that I always have the common and env-specific users created?

推荐答案

Ansible 默认情况下将使用具有更高优先级的等效项覆盖哈希/字典值.

Ansible by default will override hash/dictionary values by their equivalents that have a higher precedence.

您可以通过更改hash_behaviour ansible.cfg 中的选项,如果你真的想要,但我建议在这样的全球范围内反对它.

You can override this by change the hash_behaviour option in ansible.cfg if you really want but I would suggest against it at such a global level.

相反,您可以这样定义您的用户:

Instead you could define your users like this:

users:
  name: dev-foo
  ...

然后在您的所有 group_vars 中定义一个 all_users 变量,如下所示:

and then also have an all_users variable defined in your all group_vars like this:

all_users:
  name: common-foo
  ...

然后您可以组合变量使用一个 set_fact 任务来创建这样的合并变量:

And then you could combine the variables either by using a set_fact task to create the merged variable like this:

name: combine users
set_fact:
  combined_users: '{{ users | combine(all_users) }}'

或者您可以将它直接组合到您打算使用它的任务中:

Or you could combine it directly in the task where you intend to use it:

name: create users
user:
  name: {{ item.name }}
  ...
with_items: '{{ users | combine(all_users) }}'

如果您只是想合并 2 个列表,您可以通过简单的添加列表来实现:

If you're simply trying to combine 2 lists you can do this with simple addition of the lists:

name: combine users
set_fact:
  combined_users: '{{ users + all_users }}'

或者直接:

name: create users
user:
  name: {{ item.name }}
  ...
with_items: users + all_users

这篇关于在 Ansible 中将共享参数与环境特定参数合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆