Ralph
Ralph

Reputation: 458

Replace Specific String in YAML File using Ansible

I have a web application that uses a YAML file for configuration. This is an except from the file:

---
settings:
  domain: 127.0.0.1

I have an Ansible playbook that uses the lineinfile module to replace the IP address in the YAML file above with the server's public IP address.

- name: Discovering Public Internet Protocol Address
  ipify_facts:
  register: public_ip

- name: Configuring Application with discovered Public IP
  lineinfile:
    dest: /application/path/settings.yml
    regexp: '^(.*)domain: (.*)$'
    line: 'domain: {{ ipify_public_ip }}'

This finds and replaces the 127.0.0.1 IP with the public server's IP but it breaks the YAML indentation as follows:

---
settings:
domain: 54.12.33.3

Problem: "domain" is moved to the same line with "settings" and my ruby app fails to run migrations because it identifies a YAML syntax error.

I do not mind replacing lineinfile with another module, but I'd like to keep it if possible. I've been struggling with this for hours and will appreciate any assistance.

Upvotes: 1

Views: 7119

Answers (2)

Hayden
Hayden

Reputation: 2112

You could just create a yaml template verision.

- template:
    src: /path/to/settings.tpl.yml
    dest: /path/to/settings.yml

settings.tpl.yml

---
settings:
domain: {{ public_ip }}

Upvotes: 3

azbarcea
azbarcea

Reputation: 3657

As a quick solution, try to use the 2 spaces () for a better match and substitution:

    regexp: '^.*domain: (.*)$'
    line: '  domain: {{ ipify_public_ip }}'

I'm sure other improvements can be made to the regex, to use \s or [:space:].

UPDATE: .* from the beginning of regexp shouldn't be needed. Updated per comment requested.

Upvotes: 4

Related Questions