1

I just started using Ansible for my home project and I am having problems with the Ansible shell module.

From my host_vars I define a list of bash commands to be executed:

commands:
  - sed -i -E 's/\/var\/www\/html/\/var\/www\/public/' /etc/apache2/sites-available/000-default.conf
  - chmod -R 755 /var/www/public/.htaccess
  - service apache2 restart

Then within my task:

- name: Executing post steps for service
  shell:
    cmd: |
      /bin/bash -ilc 'docker-compose exec "{{ service }}" bash -c "{{ item }}"'
    chdir: "{{ docker_compose_target_location }}/{{ dir }}"
  register: result
  with_list: "{{ commands }}"

Adding a debug statement shows that my item is passed correctly:

TASK [docker : DEBUG post] ******************************************************************************************************************************************************************************************************************
ok: [nas.loc] => (item=sed -i -E 's/\/var\/www\/html/\/var\/www\/public/' /etc/apache2/sites-available/000-default.conf) => {
    "msg": "sed -i -E 's/\\/var\\/www\\/html/\\/var\\/www\\/public/' /etc/apache2/sites-available/000-default.conf\n"
}

It seems Ansible is auto-escaping the backslashes in my sed command. The chmod and service restart both work fine. I tried using the | quote filter already and also tried doing something as | replace('\\\\', '\\') (replace 2 backslashes with 1). Both didn't work.

Is Ansible doing something 'magically' with backslashes?

Roy Lenferink
  • 311
  • 3
  • 10
  • 2
    The first character after the s is treated as the delimiter, change it to # or something else to avoid the need to escape. – mkst Jun 03 '20 at 19:22
  • @streetster thank you very much. This indeed solved my problem. Why didn't I think of this :p. However, I am still curious why Ansible auto-magically escapes backslashes if you happen to no this as well. – Roy Lenferink Jun 03 '20 at 20:02
  • I *think* it's just writing `\\` in the output to show you that it's not escaping `/` (it's just Python under the hood). Not sure if the shell or bash -c might have been adding additional escaping... – mkst Jun 03 '20 at 20:05

0 Answers0