Ansible - 替换文件中某个表达式的第一次出现 - 路径包括主机名

Ansible - replace first occurrence of certain expression in file - path includes hostname

我需要替换特定文件中某个字符串的第一次出现。

我考虑用Ansible的replace模块来解决这个问题

- hosts: abc
  tasks:
  - name: Replace first occurence of specific string
    replace:
      path: /etc/config/abc_host/application.yml
      regexp: 'Unix'
      replace: "Linux"

这会将此特定 .yml 文件中所有出现的 Unix 替换为 Linux。但我还有一些其他主机(def_host、ghi_host 等),我想只用 Linux.[=16 替换第一次出现的 Unix =]

所以,有两个问题需要解决:

首先,使用主机名作为路径中的变量。而不是硬编码 abc_host.yml 我想要 path: /etc/config/($host)_host/application.yml.

其次,我只想替换特定字符串的第一次出现(而不是任何其他随后出现的字符串)。

对于第一部分,您可以使用 ansible_hostnameinventory_hostname 等变量,例如 path: /etc/config/{{ ansible_hostname }}_host/application.yml(请参阅此 以了解差异)。

要解决第二部分,您可以像这样使用 lineinfile 模块:

  - name: Ansible replace string example
    lineinfile:
      path: /etc/config/{{ ansible_hostname }}_host/application.yml
      regexp: 'Unix'
      line: "Linux"
      firstmatch: yes
      state: present

你只能在提到的关键字之后使用 ansible after for replace

- name: Replace project info 
  ansible.builtin.replace:
    path: /home/ec2-user/Info.yml
    after: 'versions:'
    regexp: '(^  test_tree_1:)(.*)$'
    replace: ' {{ version.split(".")[1:] | join(".") }}'
  delegate_to: localhost

我的档案

build_version: 1.1.1.1
tests:
  hello_1: smith
  hello_2: john
  hello_3: justin
  test_tree_1: card
versions:
  version_1: 6.2.1
  version_2: 6.0.0
  version_3: 6.0.2
  test_tree_1: 0.1.0.i1

这里test_tree_1只会替换后版本:

注意版本是一个ansible变量