Tobitor
Tobitor

Reputation: 1508

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

I need to replace the first occurrence of a certain string in a specific file.

I think about to use the replace module of Ansible for this.

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

This would replace all occurences of Unix with Linux in this specific .yml-file. But I also have some other hosts (def_host, ghi_host etc.) for which I would I like to replace only the first occurrence of Unix with Linux.

So, there are two issues to solve:

First, using the hostnames as variable in path. Instead of hard-coding abc_host.yml I want something like path: /etc/config/($host)_host/application.yml.

Second, I just want to replace the first occurrence of the specific string (and not any other following occurrences of it).

Upvotes: 1

Views: 5078

Answers (2)

Fuwan
Fuwan

Reputation: 84

For the first part you can use variables like ansible_hostname and inventory_hostname, e.g. path: /etc/config/{{ ansible_hostname }}_host/application.yml (see this post for the differences).

To solve the second part you could use the lineinfile module like this:

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

edit: changed module to fqcn.

Upvotes: 3

Rifwan Jaleel
Rifwan Jaleel

Reputation: 19

you can use ansible after for replace only after the mentioned keyword

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

my file

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

in here test_tree_1 will only replace after version:

note version is a ansible variable

Upvotes: 1

Related Questions