Home > OS >  Ansible regexp that will change only found string instead of whole line
Ansible regexp that will change only found string instead of whole line

Time:01-30

I'm trying to setup playbook that will setup some docker services. I'm trying to pass some variables that are obtained by vars_prompt to docker-compose file.

replace:
        path: files/docker-compose.yaml
        regexp: 'SERVER_IP'
        replace: '{{ ip_address }}'

Destination file

    environment:
      (...)
      SERVER_IP: 'SERVICE_IP_ADDR' 
      (...)

Right now such task replace whole line with ip_address variable

expected result

environment:
      (...)
      SERVER_IP: ip_address 
      (...)

CodePudding user response:

After some test I've found solution for that.

replace:
        path: files/docker-compose.yaml
        regexp: (\s )\'SERVICE_IP_ADDR\'(\s .*)?$
        replace: \1'{{ ip_address }}'\2

CodePudding user response:

Instead of lineinfile, a more robust solution would be updating the dictionary. For example, given the file

shell> cat files/docker-compose.yaml
environment:
  k1: v1
  SERVER_IP: 'SERVICE_IP_ADDR'
  k3: v3

and the below variables

  dc_file: "{{ playbook_dir }}/files/docker-compose.yaml"
  ip_address: 10.1.0.10

declare the dictionary dc_update

  dc_update:
    environment:
      SERVER_IP: '{{ ip_address }}'

Include the content of the file into the dictionary dc

    - include_vars:
        file: "{{ dc_file }}"
        name: dc

and declare the below variable

  docker_compose: "{{ dc|combine(dc_update, recursive=true) }}"

This gives the updated configuration

  docker_compose:
    environment:
      SERVER_IP: 10.1.0.10
      k1: v1
      k3: v3

Writes the updated configuration into the file

    - copy:
        dest: "{{ dc_file }}"
        content: |
          {{ docker_compose|to_nice_yaml(indent=2) }}

Running the play with the --diff options gives

TASK [copy] *******************************************************************
--- before: /export/scratch/tmp7/test-176/files/docker-compose.yaml
    after: /home/admin/.ansible/tmp/ansible-local-667065tpus_pfk/tmpnkohmmiz
@@ -1,4  1,4 @@
 environment:
   SERVER_IP: 10.1.0.10
   k1: v1
-  SERVER_IP: 'SERVICE_IP_ADDR'
   k3: v3

changed: [localhost]

shell> cat files/docker-compose.yaml
environment:
  SERVER_IP: 10.1.0.10
  k1: v1
  k3: v3

Example of a complete playbook for testing

- hosts: localhost

  vars:

    dc_file: "{{ playbook_dir }}/files/docker-compose.yaml"
    ip_address: 10.1.0.10
    dc_update:
      environment:
        SERVER_IP: '{{ ip_address }}'

    docker_compose: "{{ dc|combine(dc_update, recursive=true) }}"

  tasks:

    - include_vars:
        file: "{{ dc_file }}"
        name: dc

    - debug:
        var: docker_compose

    - copy:
        dest: "{{ dc_file }}"
        content: |
          {{ docker_compose|to_nice_yaml(indent=2) }}
  • Related