-1

I have a template of a system.d service script that I get filled using Ansible playbook.

The template includes experssion

[Service]
Environment="JAVA_OPTS=-Djava.net.preferIPv4Stack=true -Denvironmentname={{environment_name | default('NOT_SET') }}"

where environment_name above is a variable present in Ansible while running the playbook. Playbook has this instruction:

- name: Copy systemd service script
  template: src=systemd.service dest="{{systemd_dir}}/{{systemd_service_name}}.service"

I want to add memory-related parameters to the JAVA_OPTS such as:

if environment_name=DEV, then add to JAVA_OPTS '-Xmx=2000Mb -Xms=1000Mb', if environment_name=PROD, then add '-Xmx=20000Mb -Xms=10000Mb'*, etc (I have several environments).

How I can encode such substitutions in template or in calling script?

onkami
  • 8,791
  • 17
  • 90
  • 176

1 Answers1

2

You can use the if Jinja template directive. Maybe something like:

{% if environment_name == 'DEV' %}
{% set extra_java_opts = "-Xmx=2000Mb -Xms=1000Mb" %}
{% elif environment_name == 'PROD' %}
{% set extra_java_opts = "-Xmx=20000Mb -Xms=10000Mb" %}
{% endif %}
Environment="JAVA_OPTS=-Djava.net.preferIPv4Stack=true -Denvironmentname={{environment_name | default('NOT_SET') }} {{ extra_java_opts }}"

This isn't the only way of tackling this problem (for example, you could put an if block inline in the Environment= statement, but I think that gets messy).

Read through the control structures section of the Jinja documentation for more information about if/then, and read about assignments for information about the set directive.

Having said that, I would probably put this logic in my ansible playbook, rather than embedding it in the template:

- set_fact:
    extra_java_opts: "-Xmx=2000Mb -Xms=1000Mb"
  when: environment == 'DEV'

- set_fact:
    extra_java_opts: "-Xmx=20000Mb -Xms=10000Mb"
  when: environment == 'PROD'

This makes the templates much simpler, and keeps all your logic in one place rather than splitting it between the playbooks and the templates.

larsks
  • 277,717
  • 41
  • 399
  • 399