简体   繁体   中英

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.

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.

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 }}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM