How to assign to an object with arbitrary characters in key

4 views
Skip to first unread message

Oleg Semyonov

unread,
Mar 3, 2019, 5:12:08 AM3/3/19
to Ansible Project
I have a list of objects with names like this: 'obj-0001', 'obj-0002' and need to set_stats with some data about these objects in the following structure:

"data": {
  "obj-0001": { "a": 1, "b": 2 },
  "obj-0002": { "a": 3, "b": 4 }
}

They then can be referenced as data['obj-0001'].a

set_stats:
  data:
    'obj_0001': 5        # this works
    'obj-0002': 6         # this does NOT work: the variable name 'obj-0002' is not valid

As far as I understand, there is no limitation on character set in keys while they are accessed using quotes in brackets: data['obj-0002'].

Is there any way to make such assignment in ansible? I really do not want to restrict character sets in hash keys to alphanumeric only if possible.

Kai Stian Olstad

unread,
Mar 3, 2019, 8:48:58 AM3/3/19
to ansible...@googlegroups.com
On 03.03.2019 11:12, Oleg Semyonov wrote:
> I have a list of objects with names like this: 'obj-0001', 'obj-0002'
> and
> need to set_stats with some data about these objects in the following
> structure:
>
> "data": {
> "obj-0001": { "a": 1, "b": 2 },
> "obj-0002": { "a": 3, "b": 4 }
> }
>
> They then can be referenced as data['obj-0001'].a
>
> set_stats:
> data:
> 'obj_0001': 5 # this works
> 'obj-0002': 6 # this does NOT work: the variable name
> 'obj-0002' is not valid
>
> As far as I understand, there is no limitation on character set in keys
> while they are accessed using quotes in brackets: data['obj-0002'].

There are limits as they are variables in Ansible.
From
https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html#creating-valid-variable-names

"Variable names should be letters, numbers, and underscores. Variables
should always start with a letter.

foo_port is a great variable. foo5 is fine too.

foo-port, foo port, foo.port and 12 are not valid variable names."


--
Kai Stian Olstad
Reply all
Reply to author
Forward
0 new messages