ansible

Quote and white spaces erroneously added to symlink?


With my Ansible task which creates symlink for specific branches I see that it adds white spaces and quotes to the created symlink.

- name: "Symlink to git branch"
  file:
    src: "{{ repository }}/{{ application }}"
    dest: "/path/to/my/{{ symlink_name }}"
    state: link
  vars:
    symlink_name: >-
      {% if git_branch == 'development' %}
      my-development
      {% elif git_branch == 'master' %}
      newest
      {% elif git_branch == 'hotfix' %}
      my-hotfix
      {% endif %}

It results with:

root# ls -lha
' my-development ' -> /path/to/my/symlink

It is based on the development branch. I tried to add before and after the symlink_name different signs, unfortunately without success.


Solution

  • The quotes are just a way for you OS to indicates you that the symlink contains spaces, they are not part of the link.

    The spaces though, are coming from your Jinja expression, due to the spacing introduced by the Jinja statement blocks all being on new lines.
    Mind that your use of the folded YAML syntax (>-) causes this: it replaces new lines by spaces!

    One easy way to resolve this is to use the whitespace control of Jinja:

    vars:
      symlink_name: >-
        {%- if git_branch == 'development' -%}
        my-development
        {%- elif git_branch == 'master' -%}
        newest
        {%- elif git_branch == 'hotfix' -%}
        my-hotfix
        {%- endif -%}
    

    Another, arguably more compact, way to resolve this is to make a dictionary of the branches and their equivalent symlink:

    - name: "Symlink to git branch"
      file:
        src: "{{ repository }}/{{ application }}"
        dest: "/path/to/my/{{ symlink_name[git_branch] }}"
        state: link
      vars:
        symlink_name:
          development: my-development
          master: newest
          hotfix: my-hotfix