是否有ansible的yaml编辑模块?

chi*_*hak 22 ansible

我需要修改一个yaml文件(schleuder配置),我想从一个ansible playbook中做到这一点 - 是否有一个模块可以这样做?很难谷歌这一点,所有出现的是如何写剧本.

kwo*_*son 26

我还需要配置管理yaml文件.我编写了一个ansible模块,在编辑yaml文件时尝试是幂等的.

我称之为yedit(yaml-edit). https://github.com/kwoodson/ansible-role-yed​​it

如果您觉得有用,请告诉我.当我们的团队满足需求,请求或拉取请求时,我将添加功能.

这是一个简单的剧本示例:

roles:
- lib_yaml_editor

tasks:
- name: edit some yaml
  yedit:
    src: /path/to/yaml/file
    key: foo
    value: bar

- name: more complex data structure
  yedit:
    src: /path/to/yaml/file
    key: a#b#c#d
    value:
      e:
        f:  This is a test
Run Code Online (Sandbox Code Playgroud)

应该产生这样的东西:

foo: bar
a:
  b:
    c:
      d:
        e:
          f: This is a test
Run Code Online (Sandbox Code Playgroud)

编辑:5/27/2018

  • 你能把它添加到 Ansible Galaxy 中吗? (3认同)
  • 非常好的模块...我现在没有你可以安装角色并直接使用它...字面上_让我大吃一惊_。 (2认同)
  • 我已将其添加到 ansible-galaxy。唯一的缺点是我必须重命名才能让星系导入工具找到它。 (2认同)

cop*_*cat 8

基于 Kevin 和 Bogd 的答案,如果您想要合并嵌套键而不是覆盖 YAML 文件的整个分支,则必须在合并函数中启用递归:

mydata: "{{ mydata | combine(newdata, recursive=True) }}"
Run Code Online (Sandbox Code Playgroud)

来自Ansible 文档

recursive 是一个布尔值,默认为 False。组合是否应该递归地合并嵌套的哈希值。注意:它不依赖于 ansible.cfg 中 hash_behaviour 设置的值。

所以完整的解决方案变成:

- name: Open yaml file
  slurp:
    path: myfile.yaml
  register: r_myfile

- name: Read yaml to dictionary
  set_fact:
    mydata: "{{ r_myfile['content'] | b64decode | from_yaml }}"

- name: Patch yaml dictionary
  set_fact:
    mydata: "{{ mydata | combine(newdata, recursive=True) }}"
  vars: 
    newdata:
      existing_key:
        existing_nested_key: new_value
        new_nested_key: new_value

- name: Write yaml file
  copy:
    content: '{{ mydata | to_nice_yaml }}'
    dest: myfile.yaml
Run Code Online (Sandbox Code Playgroud)

注意:递归仅允许添加嵌套键或替换嵌套值。删除特定的嵌套键需要更高级的解决方案。


Kev*_*ane 6

实现此目的的一种方法是将文件读入事实,根据需要更新事实,然后将事实写回 yaml 文件。

- name: Read the yaml
  slurp:
    path: myfile.yaml
  register: r_myfile

- name: extract the data
  set_fact:
    mydata: "{{ r_myfile['content'] | b64decode | from_yaml }}"
Run Code Online (Sandbox Code Playgroud)

然后根据需要更新事实,例如使用ansible.utils.update_fact 模块

- name: Write back to a file
  copy:
    content: '{{ mydata | to_nice_yaml }}'
    dest: myfile.yaml
Run Code Online (Sandbox Code Playgroud)

当然,您需要注意,这会使整个更新变得非原子性。

更新:我最初的建议使用 lookup( 'file' ) 但当然访问本地文件。slurp 是读取远程文件的正确方法。

  • 有关如何更改 yaml 文件内容的更多详细信息确实有助于使这一点大放异彩。 (3认同)

Mxx*_*Mxx 3

没有这样的模块。您可以通过查看https://docs.ansible.com/ansible/list_of_all_modules.html来检查这一点

最好的选择是使用lineinfile模板复制模块。

  • 我也推荐 blockinfile https://docs.ansible.com/ansible/latest/modules/blockinfile_module.html (2认同)