我使用以下:
目录文件:dir.yml
x86_64:
alpine:
update:
version: 3.14.0
aarch64:
alpine:
update:
version: 3.14.0
Ansible 剧本:
---
- name: Playbook
hosts: localhost
vars:
new_version: 3.15.0
update:
tasks:
- name: "Include: dir.yml"
ansible.builtin.include_vars:
file: dir.yml
- debug:
msg:
- "{{x86_64.alpine.version}}"
- "{{new_version}}"
- "{{update}}"
- set_fact:
update: "{{'true' if x86_64.alpine.version < new_version else 'false'}}"
问题:
如何更新 dir.yml 中的以下字段
x86_64:
alpine:
update: true <------
我试图使用 ansible.builtin.replace 或 ansible.builtin.lineinfile 但仍然无法弄清楚
有谁有任何解决方案吗
答案1
将文件读入字典
- ansible.builtin.include_vars:
file: dir.yml
name: arch
给出
arch:
aarch64:
alpine:
update: null
version: 3.14.0
x86_64:
alpine:
update: null
version: 3.14.0
更新字典
- ansible.builtin.set_fact:
arch: "{{ arch|combine({'x86_64': _x86_64}) }}"
vars:
_update: "{{ arch.x86_64.alpine.version is version(new_version, '<') }}"
_x86_64_alpine: "{{ arch.x86_64.alpine|combine({'update': _update}) }}"
_x86_64: "{{ arch.x86_64|combine({'alpine': _x86_64_alpine}) }}"
给出
arch:
aarch64:
alpine:
update: null
version: 3.14.0
x86_64:
alpine:
update: true
version: 3.14.0
并重写文件
- ansible.builtin.copy:
dest: dir.yml
content: |-
{% for k,v in arch.items() %}
{{ k }}:
{{ v|to_nice_yaml }}
{% endfor %}
给出
shell> cat dir.yml
x86_64:
alpine:
update: true
version: 3.14.0
aarch64:
alpine:
update: null
version: 3.14.0
笔记
属性的空值更新将被替换为“空”。这应该不是问题,因为在 YAML 中“null”会转换为布尔值“false”。
更新属性的值更新将被替换为“true”或“false”。
由于前两个注释,这些任务是幂等的。
您可能想要更新更多项目。例如,给定变量
new_version:
x86_64: 3.15.0
aarch64: 3.14.0
下面的任务更新字典
- ansible.builtin.set_fact:
arch: "{{ arch|combine({item: _arch}) }}"
loop: "{{ new_version.keys()|list }}"
vars:
_update: "{{ arch[item].alpine.version is version(new_version[item], '<') }}"
_arch_alpine: "{{ arch[item].alpine|combine({'update': _update}) }}"
_arch: "{{ arch[item]|combine({'alpine': _arch_alpine}) }}"
给出
arch:
aarch64:
alpine:
update: false
version: 3.14.0
x86_64:
alpine:
update: true
version: 3.14.0