Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format a variable in Ansible value

Tags:

ansible

jinja2

Given that Ansible processes all variables through Jinja2, and doing something like this is possible:

- name: Debug sequence item value
  debug: msg={{ 'Item\:\ %s'|format(item) }}
  with_sequence: count=5 format="%02d"

Which correctly interpolates the string as:

ok: [server.name] => (item=01) => {"item": "01", "msg": "Item: 01"}
ok: [server.name] => (item=02) => {"item": "02", "msg": "Item: 02"}
ok: [server.name] => (item=03) => {"item": "03", "msg": "Item: 03"}
ok: [server.name] => (item=04) => {"item": "04", "msg": "Item: 04"}
ok: [server.name] => (item=05) => {"item": "05", "msg": "Item: 05"}

Why then doesn't this work:

- name: Debug sequence item value
  debug: msg={{ 'Item\:\ %02d'|format(int(item)) }}
  with_sequence: count=5

This apparently causes some sort of parsing issue which results in our desired string being rendered verbose:

ok: [server.name] => (item=01) => {"item": "01", "msg": "{{Item\\:\\ %02d|format(int(item))}}"}

Noting that in the above example item is a string because the default format of with_sequence is %d, and format() doesn't cast the value of item to the format required by the string interpolation %02d, hence the need to cast with int().

Is this a bug or am I missing something?

like image 367
Ivan Avatar asked Aug 05 '13 05:08

Ivan


People also ask

How do you assign a value to a variable in Ansible?

Assigning a value to a variable in a playbook is quite easy and straightforward. Begin by calling the vars keyword then call the variable name followed by the value as shown. In the playbook above, the variable name is salutations and the value is Hello world!

What is the format of strings in Ansible?

It can be a Python, Yaml or Jinja syntax thing. There are a couple of situations where the standard string syntax in Ansible is not enough to pass the configuration data to the IBM Security Ansible Collection.

How do we define variables in Ansible?

To define a variable in a playbook, simply use the keyword vars before writing your variables with indentation. To access the value of the variable, place it between the double curly braces enclosed with quotation marks. In the above playbook, the greeting variable is substituted by the value Hello world!

What is Foo Ansible?

foo: field1: one field2: two. You can then reference a specific field in the dictionary using either bracket notation or dot notation: foo['field1'] foo.field1. These will both reference the same value (“one”).


1 Answers

It took me a couple of tries to get this right, but try this, instead:

debug: msg={{ 'Item\:\ %02d'|format(item|int) }}

Jinja2 is a bit funny.

like image 72
Tybstar Avatar answered Oct 25 '22 22:10

Tybstar