为模块 Ansible 设置常量参数

Set constant parameters for a module Ansible

我有一个剧本多次使用替换模块来替换文件中的多行。

所以我有类似的东西:

- name: Replace PROPERTY in NAMED file
  ansible.builtin.replace:
      path: "{{ path_to_file }}"
      after: "{{ AFTER_TEXT}}"
      before: "{{ BEFORE_TEXT }}"
      regexp: "^PROPERTY = [0-9]+$"
      replace: "PROPERTY = {{ PROPERTY }}"

这基本上用相同的前 3 个参数重复了 5 次。我查看了文档,但找不到执行此操作的方法。

有什么方法可以将这些参数存储在库存文件中,这样我就只需要写类似

的东西
- name: Replace PROPERTY in NAMED file
  ansible.builtin.replace:
      params: "{{ path, after, before }}"
      regexp: "^PROPERTY = [0-9]+$"
      replace: "PROPERTY = {{ PROPERTY }}"

反过来:只编写一次任务并循环。

- name: Replace whatever has to be
  ansible.builtin.replace:
      path: "{{ path_to_file }}"
      after: "{{ AFTER_TEXT}}"
      before: "{{ BEFORE_TEXT }}"
      regexp: "{{ item.regexp }}"
      replace: "{{ item.replace }}"
  loop:
    - regexp: "^PROPERTY = [0-9]+$"
      replace: "PROPERTY = {{ PROPERTY }}"
    - regexp: "some other regexp"
      replace: "some other replace"
    - regexp: "next regexp"
      replace: "next replace"
    # continue

如果您愿意,可以在 var 中定义该列表并在循环中引用它。


同时,作为对您问题的直接回答,您可以利用 yaml 锚点和合并密钥。下一个示例的唯一要求是所有内容都发生在同一个 yaml 文件中(没有包含、导入...)。

这是一个伪剧本的例子

- name: use anchors and merge operator
  hosts: localhost
  gahter_facts: false
  
  vars:
    # We won't really use that var but the anchor defined on it
    replace_defaults: &rep_def
      path: "{{ path_to_file }}"
      after: "{{ AFTER_TEXT}}"
      before: "{{ BEFORE_TEXT }}"

  tasks:
    - name: task1
      ansible.builtin.replace:
        # Here we load default as options
        # in current mapping
        <<: *rep_def 
        regexp: "^PROPERTY = [0-9]+$"
        replace: "PROPERTY = {{ PROPERTY }}"

    - name: task1
      ansible.builtin.replace:
        <<: *rep_def
        # Note we can still override a default if needed
        path: /some/other/path
        regexp: "^PROPERTY = [0-9]+$"
        replace: "PROPERTY = {{ PROPERTY }}"

在目前的情况下,我还是会使用最DRY的第一个场景。