How Do You Prepend or Append to a Variable in Ansible?

Problem scenario
You are using a variable in Ansible.  You want to attach a string to it to augment this variable.  You can rename it so later in the playbook you can call this modified, augmented version of the variable.

You assign the variable like this:

foo: " {{ bar }}"

You want foo to have an extra string (e.g., "/subdirectory/path/to").  What do you do?

Do the append inside the braces.  The string you append should be inside single quotes.  Here is an example of appending a string to a variable:

foo: " {{ bar + '/subdirectory/path/to' }}"

Here is an example of prepending a string to a variable:

foo: " {{ '/subdirectory/path/to' + bar }}"

With two variables in {{ }} braces with strings of regular text, the syntax is a little more tricky.  We advise against using the + operator and single quotes.  Here is an example of correct syntax with previously defined variables "foo" and "vara":

varcomp: "{{ foo }}/path/to/version-{{ vara }}.exe"

The above will expand the variables "foo" and "vara" while inserting "/path/to/version-" (without quotes) in between these two strings; it will also append ".exe" (without quotes) at the end of this string.  The above will be assigned to a variable called varcomp.

Leave a comment

Your email address will not be published. Required fields are marked *