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).
CodePudding user response:
For the first part you can use variables like ansible_hostname
and inventory_hostname
, eg.
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
lineinfile:
path: /etc/config/{{ ansible_hostname }}_host/application.yml
regexp: 'Unix'
line: "Linux"
firstmatch: yes
state: present