Problem when dynamically constructing dict variables with string list as values

17 views
Skip to first unread message

Lu Liu

unread,
Oct 28, 2018, 10:56:48 AM10/28/18
to Ansible Project
##### SUMMARY
When dynamically creating a dict var with a list as its value, it's working when the list elements are int but will fallback to a string when the list elements are strings.

##### ISSUE TYPE
- Not sure if this is a bug in Ansible, YAML or Jinja2, or is a feature by design

##### COMPONENT NAME
n/a

##### ANSIBLE VERSION

```paste below
2.7.0
```

##### OS / ENVIRONMENT
```
Linux awx 3.10.0-862.14.4.el7.x86_64 #1 SMP Wed Sep 26 15:12:11 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux
```
(Ansible AWX 2.0.1 official docker image)

##### STEPS TO REPRODUCE
The points are:
1. the dict's key has to be dynamic with vars passed at runtime
2. the dict's value has to be a string list

A sample play:
```yaml
- name: Dynamically construct dict with string list and pass to some role
  hosts: test
  remote_user: tester
  become: no
  roles:
    - role: some_role
      variables: "{
        '{{ dynamic_key }}_KEY': '{{ [\"value1\"] + [\"value2\"] }}'
      }"
```

With the above play, `variables` we got in `some_role` is as follows when give it `var1` for `dynamic_key`:
```
ok: [test] => {
    "variables": "{ 'var1_KEY': '['value1', 'value2']' }"
}
```
where both the templating of `dynamic_key` and list concatenating worked as expected, but the dict became a string as a whole. However, if we change the two lists into integer lists, it will work fine:

input:
```yaml
- name: Dynamically construct dict with int list and pass to some role
  hosts: test
  remote_user: tester
  become: no
  roles:
    - role: some_role
      variables: "{
        '{{ dynamic_key }}_KEY': '{{ [1,2,3] + [4,5,6] }}'
      }"
```

output:
```
ok: [test] => {
  "variables": {
        "var1_KEY": "[1, 2, 3, 4, 5, 6]"
    }
}
```
in this case, the whole dict are constructed correctly. I would like to know if this is a feature by design or a bug.

Maybe some of you may ask why I don't construct and pass the `variables` like this:
```yaml
- name: Dynamically construct dict with int list and pass to some role
  hosts: test
  remote_user: tester
  become: no
  roles:
    - role: some_role
      variables:
         "{{ dynamic_key }}_KEY": "{{ [1,2,3] + [4,5,6] }}"
```
The reason is the "{{ dynamic_key }}_KEY" won't get templated and will be kept as `{{ dynamic_key }}_KEY` in the result. I don't know either this is a feature or a bug.

I hope I have described everything clearly. Thanks!

##### EXPECTED RESULTS
as above mentioned


##### ACTUAL RESULTS
as above mentionedEnter code here...

Reply all
Reply to author
Forward
0 new messages