Friday, January 24, 2020

Ansible Template Tip: Split a String

Ansible is the simplest way to automate apps and IT infrastructure. Application Deployment + Configuration Management + Continuous Delivery. We use Ansible heavily for our AWS deployment stack.

When working with Ansible template, sometimes you will need to split a string and use part of its value. For example, you have a application template which setup the application base url, like follow:

<?xml version='1.1' encoding='UTF-8'?>
<app.model.AppLocationConfiguration>
    <adminAddress>admin@app.com</adminAddress>
    <appUrl>https://{{ app.split("-")[0] | lower }}-{{ env | lower }}.app.com/</appUrl>
</app.model.AppLocationConfiguration>

We have a variable "app" containing the string "asia-101.test.org" and want to extract the geolocation part of this string, we could just use "{{ app.split("-")[0] | lower }}"

The constructed url will be "https://asia-prod.app.com".

Ansible use Jinja2 for formatting, so you can apply the split filter (https://jinja.palletsprojects.com/en/2.10.x/templates/#filters).


No comments: