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

查看:43
本文介绍了在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中读取.

如何在特定环境中与all/users.yml进行Ansible合并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) }}'

如果您只是尝试合并两个列表,则可以通过简单添加列表来实现:

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天全站免登陆