3

I have the below playbook:

   - name: Add hosts
     include_tasks: "{{ playbook_dir }}/gethosts1.yml"
     vars:
       PROFILE_NUM: "{{ my_result }}"
     loop: "{{ query('sequence', 'start=1 end='+(PROFILES)) }}"
     loop_control:
       loop_var: my_result

I run the playbook as:

ansible-playbook test.yml -e  PROFILES=12

This gets me PROFILE_NUM as 1,2,3,4,5...12

However, i want PROFILE_NUM to be two digits i.e 01,02,03,04,05....12

I tried the following but it errors out PROFILE_NUM: "%02d{{ my_result }}"

Can you please suggest?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Ashar
  • 2,942
  • 10
  • 58
  • 122

2 Answers2

3

You were close, you're looking for:

PROFILE_NUM: '{{ "%02d" | format(my_result) }}'

which will use jinja2 to format the string "%02d" using the parameters my_result, giving you:

01

if you pass a 1.

gaige
  • 17,263
  • 6
  • 57
  • 68
1

You may check this related post: Display number with leading zeros

(if using python3) consider to take the second approach:

print("{:02d}".format(1))

Or the one below using f-strings.

  • Could you please suggest @Alexander Brockmeier an ansible code where I'm assigning it to a variable `PROFILE_NUM: "{{ my_result }}"` – Ashar Apr 22 '20 at 07:23
  • @Ashar I apologize for only using ansible a few times, yet: https://stackoverflow.com/questions/18050911/how-to-format-a-variable-in-ansible-value may help you. – Alexander Brockmeier Apr 22 '20 at 07:45