2

For the ansible variable param I'd like the behaviour that is similar to the following bash code:

echo ${param:+--arg=}$param

It outputs nothing when the variable is undefined or empty. When the variable has a non-empty value it prints --arg=value.

Is this the best that can be done?

- debug:
  msg: "{{ (param | default('') | length > 0) | ternary('--arg=', '') + (param | default('')) }}"

1 Answer 1

3

Jinja seems to be simpler

  options: |
    {% if param|d('')|length > 0 %}
    --arg={{ param }}
    {% else %}
    {{ '' }}
    {% endif %}
Sign up to request clarification or add additional context in comments.

3 Comments

TIL you can use jinja2 directly with playbooks
See Flow Scalar Styles. It's very useful to understand the differences among the styles: double-quoted, single-quoted and plain (unquoted).
Thanks for the d() filter. The if/else doesn't make it shorter, but it's clearer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.