Home > Mobile >  Easiest way to replace multiple config lines in a Bash script with Ansible
Easiest way to replace multiple config lines in a Bash script with Ansible

Time:11-02

I'm trying to replace some variables in a bash script with Ansible. Here is some part of the original function (from a much bigger script):

set_variable_defaults() {
    : "${MK_LIBDIR:="/usr/lib/check_mk_agent"}"
    : "${MK_CONFDIR:="/etc/check_mk"}"
    : "${MK_VARDIR:="/var/lib/check_mk_agent"}"
    : "${MK_LOGDIR:="/var/log/check_mk_agent"}"
    : "${MK_BIN:="/usr/bin"}"
}

And what I want instead:

set_variable_defaults() {
    : "${MK_LIBDIR:="/share/usr/lib/check_mk_agent"}"
    : "${MK_CONFDIR:="/share/etc/check_mk"}"
    : "${MK_VARDIR:="/share/var/lib/check_mk_agent"}"
    : "${MK_LOGDIR:="/var/log/check_mk_agent"}"
    : "${MK_BIN:="/share"}"
}

I tried lineinfile and replace but I'm getting issues with the fact that my regexes and lines have double-quotes, colons, slashes and {}. What would be the best approach to do this with Ansible?

CodePudding user response:

I was able to make it work, the idea is to put the regexes in variables to then use regex_escape() as suggested by @Zeitounator in the comments.

- name: adjust agent to work in HaOS
  ansible.builtin.lineinfile:
    path: /path/to/my/file
    regexp: '{{ item.regexp }}'
    line: '{{ item.line }}'
  with_items:
    - { regexp: '{{ MK_LIBDIR | regex_escape() }}', line: '    : "${MK_LIBDIR:="/share/usr/lib/check_mk_agent"}"' }
    - { regexp: '{{ MK_CONFDIR | regex_escape() }}', line: '    : "${MK_CONFDIR:="/share/etc/check_mk"}"' }
    - { regexp: '{{ MK_VARDIR | regex_escape() }}', line: '    : "${MK_VARDIR:="/share/var/lib/check_mk_agent"}"' }
    - { regexp: '{{ MK_BIN | regex_escape() }}', line: '    : "${MK_BIN:="/share"}"' }
  vars:
    - MK_LIBDIR: '    : "${MK_LIBDIR:="/usr/lib/check_mk_agent"}"'
    - MK_CONFDIR: '    : "${MK_CONFDIR:="/etc/check_mk"}"'
    - MK_VARDIR: '    : "${MK_VARDIR:="/var/lib/check_mk_agent"}"'
    - MK_BIN: '    : "${MK_BIN:="/usr/bin"}"'
  • Related