Vadimski
Vadimski

Reputation: 43

How to set concatenated string variable in Ansible template based on a condition

I need to create a string in a template that can change between hosts, and it needs to be in the form of: "cores": "0,1,2,3"

And the reason the string is "0,1,2,3" in this example is because the host has 4 processor cores.

So I got stuck with something which seems too convoluted to me and I'm not even sure how to use this core_count variable in my template file.

{% set core_count = '' %}
{% for i in range(ansible_processor_cores) %}
  {% set core_count = core_count ~ i %}
    {% if not loop.last %}
     {% set core_count = core_count ~ ',' %}
    {% endif %}
{% endfor %}

Upvotes: 2

Views: 849

Answers (1)

Konstantin Suvorov
Konstantin Suvorov

Reputation: 68269

There are many handy lookup plugins in Ansible. Take sequence:

- hosts: localhost
  gather_facts: yes
  tasks:
    - debug:
        msg: '"cores": "{{ lookup("sequence","start=0 count="+(ansible_processor_cores|string)) }}"'

Upvotes: 3

Related Questions