Concatenating strings in Ansible YAML files

So, working with Ansible you might happen onto a situation where you might have a config string that you’d like to use in a template, that consists of a common part (shared between environments) and an environment specific part. With the template requiring a concatenated string.

While pure YAML doesn’t support this in any way, luckily Ansible runs all of it’s YAML files through Jinja prior to executing. Therefore, if you define variables such as the following in your YAML file:

test: "joe@smith,adam@brown"
test_full: "{{ test }}, sarah@henry, laura@mccoy"

and test by running two debug tasks:

- name: Debug print test
  debug: msg="Test is {{ test }}"

- name: Debug print test_full␤
  debug: msg="Test_full is {{ test_full }}"

You should end up with something like this:

____________________________________
< TASK: vpc-setup | Debug print test >
 ------------------------------------
           ^__^
           (oo)_______
            (__)       )/
                ||----w |
                ||     ||

ok: [localhost] => {
    "msg": "Test is joe@smith,adam@brown"
}
 _________________________________________
< TASK: vpc-setup | Debug print test_full >
 -----------------------------------------
           ^__^
           (oo)_______
            (__)       )/
                ||----w |
                ||     ||

ok: [localhost] => {
    "msg": "Test_full is joe@smith,adam@brown, sarah@henry, laura@mccoy"
}

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.