Changing list value in Ansible

时间:2018-09-19 08:16:54

标签: ansible jinja2 ansible-2.x

I have inventory with a very complicated structure. For my specific installation I want to override only some values. For example, I have structure:

---    
System:
  atr1: 47
  config:
    - nodes:
        - logger:
            id: 'all'
            svr: 'IEW'
        - Database:
            constr: 'login/pass@db'
  atr2: 'some value'

I want to override severity of the logger, i.e. add statistic information svr: 'IEWS'. I want to provide an override within --extra-vars parameter.

In ansible.cfg -> hash_behaviour = merge

I don't want to use something like - svr: "{{ svr_custom | default('IEW') }}", because there are too many parameters, and thus it will be difficult to write the entire inventory in such way. I read about combine filter, but I can't use it, when I had to override only one item in hash.

How can I achieve my goal?

2 个答案:

答案 0 :(得分:0)

  1. 您找到的方法是最简单的方法。编写起来很冗长,但是很容易调试和修复。
  2. 如果您 REALLY 想要缩小此工作,则可以编写自己的查找插件。 (https://docs.ansible.com/ansible/2.5/plugins/lookup.html)。

根据我的经验,我真的想说直接和愚蠢的方法(写冗长)对于整体可维护性要好得多。下一个人将看到一个易于修复的傻瓜转储,而不是一些晦涩的python代码片段。

为使生活更轻松,您可能需要将此配置存储为单独的文件(包含所有jinja片段)并使用lookup(文档右侧):

# Since 2.4, you can pass in variables during evaluation
 - debug: msg="{{ lookup('template', './some_template.j2', template_vars=dict(x=42)) }} is evaluated with x=42"

此外,您可以使用Jinja的|from_yaml(或from_json)将已加载和处理的模板转换为数据结构。

答案 1 :(得分:0)

  

我阅读了有关合并过滤器的信息,但是当我只需要覆盖哈希中的一项时,我将无法使用它。

那是为什么? -extra-vars 中定义的 new_svr 是否无法实现您想要的?

- set_fact:                                                                                                   
    System: "{{ System | combine({'config':[{'nodes':[{'logger':{'svr':new_svr }}]}]}, recursive=True) }}"