<p>Don't nest moustaches. Once you're in a Jinja context, you should reference variables by name without any further delimiters.</p>
<p>Using standard attribute access syntax can be a lot easier to read than the <code>attr()</code> filter (and actually works for this situation, which <code>attr()</code> doesn't):</p>
<pre><code>- name: Debug jinja2
  ansible.builtin.debug:
    msg: &quot;{{ server_cert_info_result.ansible_module_results[server_ssl_certificate_name].arn }}&quot;
  tags: list_server_certificate_info
</code></pre>

CC BY-SA 4.0
2021-03-15T17:02:48.557Z
Unfortunately, the first suggestion didn't work: `FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute 'server_ssl_certificate_name'`
Life5ign
CC BY-SA 4.0
2021-03-15T17:04:15.057Z
The second didn't either, I think it contains mixed `.` and `[ ]` attribute references too: `FAILED! => {"msg": "template error while templating string: expected name or number. String: {{ server_cert_info_result.ansible_module_results.[server_ss
l_certificate_name].arn }}"}`
Life5ign
CC BY-SA 4.0
2021-03-15T17:09:55.383Z
edit for my first comment, I posted the wrong error; correct error is Unfortunately, the first suggestion didn't work: `FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute 'v6-full-deployment-SSL-Certificate'`
Life5ign
CC BY-SA 4.0
2021-03-15T18:25:54.307Z
`server_cert_info_result.ansible_module_results.[server_ssl_certificate_name].arn` is not what I suggested using. You've inserted an extra `.` before the `[`, so it's not surprising that it results in a syntax error.

Mixing . and bracket accesses in an expression is perfectly valid.
flowerysong
CC BY-SA 4.0
2021-03-19T00:17:41.070Z
you're right; I removed the extra `.` that I inadvertently inserted, and it worked.  Thanks
Life5ign
CC BY-SA 4.0
2021-03-19T00:23:30.090Z
I'm wondering why there is nothing in the ansible docs about needing to surround attributes that are variables with `[ ]` in the ansible docs; any insight?  Can you remove the top example you provided, that doesn't work, and I'll accept this as correct?  Seems you replied some fraction of a second before @Dick Visser, whose answer is also correct, but slightly less complete.
Life5ign
CC BY-SA 4.0
2021-03-19T01:30:41.613Z
Ansible doesn't try to document everything about the basic usage of Jinja, and Jinja's documentation in turn assumes some familiarity with basic Python syntax, which is where the bracket accessor syntax comes from. Jinja's special dot syntax can only be used with static keys that are valid Python identifiers, so it's more limited than using brackets by nature.
flowerysong
CC BY-SA 4.0
2021-03-14T20:15:21.303Z
2021-03-19T01:18:00.330Z
2021-03-19T01:18:00.330Z
flowerysong
<p>I think you don't need to do anything special:</p>
<pre class="lang-yaml prettyprint-override"><code>&quot;{{ server_cert_info_result.ansible_module_results[server_ssl_cert_name].arn }}&quot;
</code></pre>

CC BY-SA 4.0
2021-03-15T17:04:41.743Z
Unfortunately, didn't work: `FAILED! => {"msg": "template error while templating string: expected name or number. String: {{ server_cert_info_result.ansible_module_results.[server_ss
l_certificate_name].arn }}"}`
Life5ign
CC BY-SA 4.0
2021-03-19T00:20:25.480Z
As above, I inadvertently inserted an extra `.` in my comment above; so your suggestion does work.  Why is there nothing about needing `[ ]` to surround variable names in attribute access in the ansible docs?
Life5ign
CC BY-SA 4.0
2021-03-14T20:15:58.273Z
2021-03-14T20:15:58.273Z
Dick Visser
<p>I am using ansible's <code>community.aws.iam_server_certificate_info</code> module to get information about a server certificate on aws ec2, and registering it as a variable <strong>&quot;server_cert_info_result&quot;</strong></p>
<p>Unfortunately, this module returns a JSON structure with a high level key that is the <em>actual value of the &quot;name&quot; of the server certificate</em>, as opposed to the more standard format of returning a list of dictionaries, one of which would be {name: &lt;actual_name_of_cert&gt;}. I have the actual name of the cert as a variable <strong>&quot;server_ssl_cert_name&quot;</strong> in my playbook.  This is what the module's return value looks like, with the offending key highlighted:</p>
<pre><code>TASK [aws_full_deployment : Debug server cert return info] ************************************************************************************************
ok: [localhost] =&gt; {                                                                                                                                                         
    &quot;server_cert_info_result&quot;: {                                                                                                                                             
        &quot;ansible_module_results&quot;: {                                                                                                                                          
            **&quot;v6-full-deployment-SSL-Certificate&quot;**: {                                                                                                                          
                &quot;arn&quot;: &quot;arn:aws-us-gov:iam::xxxxxxxxxxxxxxxxxxxxxxOBFUSCATED&quot;,                                         [truncated.....]
</code></pre>
<p>I want the <strong>arn</strong> value, in order to create an application elastic load balancer with and https listener.  How do I retrieve the value of the <strong>arn</strong>, using jinja2 filters?</p>
<p>Things I've tried (which failed):</p>
<ol>
<li>use the jinja builtin <code>attr</code> filter, which cannot accept the variable name of the cert inside it's parameter space, and throws an error.  It only accepts strings as parameters, such that trying expand a playbook variable with the normal {{ }} will not work.</li>
</ol>
<pre><code>- name: Debug jinja2 attr filter
  ansible.builtin.debug:
    msg: &quot;{{ server_cert_info_result.ansible_module_results | attr({{ server_ssl_certificate_name }} | attr('arn') }}&quot;
  tags: list_server_certificate_info
</code></pre>
<p>which returns:</p>
<pre><code>TASK [aws_full_deployment : Debug jinja2 attr filter] ***********************************************************************************************************************
fatal: [localhost]: FAILED! =&gt; {&quot;msg&quot;: &quot;template error while templating string: expected token ':', got '}'. String: {{ server_cert_info_result.ansible_module_results | attr({{ server_ssl_certificate_name }} | attr('arn') }}&quot;}
</code></pre>
<ol start="2">
<li><code>community.builtin.json_query</code>:</li>
</ol>
<pre><code>- name: Create and debug a query for json_query
  vars:
    cert_arn_query: &quot;'{{ server_ssl_certificate_name }}.arn'&quot;
  ansible.builtin.debug:
    var: cert_arn_query
  tags: list_server_certificate_info
</code></pre>
<p>Returns:</p>
<pre><code>TASK [aws_full_deployment : Create and debug a query for json_query] ********************************************************************************************************
ok: [localhost] =&gt; {
    &quot;cert_arn_query&quot;: &quot;'v6-full-deployment-SSL-Certificate.arn'&quot;
}
</code></pre>
<p>and</p>
<pre><code>- name: Debug the json_query result of the above query
  vars:
    cert_arn_query: &quot;'{{ server_ssl_certificate_name }}.arn'&quot;
  ansible.builtin.debug:
    msg: &quot;{{ server_cert_info_result.ansible_module_results | community.general.json_query(cert_arn_query) }}&quot;
  tags: list_server_certificate_info
</code></pre>
<p>Which returns:</p>
<pre><code>TASK [aws_full_deployment : Debug the json_query result of the above query] *************************************************************************************************
ok: [localhost] =&gt; {
    &quot;msg&quot;: &quot;v6-full-deployment-SSL-Certificate.arn&quot;
}
</code></pre>
<p>which obviously fails when I try to create the load balancer, since the json_query didn't actually retrieve the arn. Any ideas?  I may have to resort to using <code>ansible.builtin.command</code> and using the raw <code>awscli</code> call, which I believe returns the data in a format that jinja could handle.</p>

<ansible><amazon-ec2><aws-iam><jinja><ansible-galaxy>
ansible & jinja2: How to reference JSON structure items whose keys are variables?
Life5ign
# ansible & jinja2: How to reference JSON structure items whose keys are variables?

(Asked by: username_0 on 2021-03-14)

I am using ansible's community.aws.iam_server_certificate_info module to get information about a server certificate on aws ec2, and registering it as a variable "server_cert_info_result"
Unfortunately, this module returns a JSON structure with a high level key that is the actual value of the "name" of the server certificate, as opposed to the more standard format of returning a list of dictionaries, one of which would be {name: }. I have the actual name of the cert as a variable "server_ssl_cert_name" in my playbook.  This is what the module's return value looks like, with the offending key highlighted:
TASK [aws_full_deployment : Debug server cert return info] ************************************************************************************************
ok: [localhost] => {                                                                                                                                                         
    "server_cert_info_result": {                                                                                                                                             
        "ansible_module_results": {                                                                                                                                          
            **"v6-full-deployment-SSL-Certificate"**: {                                                                                                                          
                "arn": "arn:aws-us-gov:iam::xxxxxxxxxxxxxxxxxxxxxxOBFUSCATED",                                         [truncated.....]

I want the arn value, in order to create an application elastic load balancer with and https listener.  How do I retrieve the value of the arn, using jinja2 filters?
Things I've tried (which failed):

use the jinja builtin attr filter, which cannot accept the variable name of the cert inside it's parameter space, and throws an error.  It only accepts strings as parameters, such that trying expand a playbook variable with the normal {{ }} will not work.

- name: Debug jinja2 attr filter
  ansible.builtin.debug:
    msg: "{{ server_cert_info_result.ansible_module_results | attr({{ server_ssl_certificate_name }} | attr('arn') }}"
  tags: list_server_certificate_info

which returns:
TASK [aws_full_deployment : Debug jinja2 attr filter] ***********************************************************************************************************************
fatal: [localhost]: FAILED! => {"msg": "template error while templating string: expected token ':', got '}'. String: {{ server_cert_info_result.ansible_module_results | attr({{ server_ssl_certificate_name }} | attr('arn') }}"}


community.builtin.json_query:

- name: Create and debug a query for json_query
  vars:
    cert_arn_query: "'{{ server_ssl_certificate_name }}.arn'"
  ansible.builtin.debug:
    var: cert_arn_query
  tags: list_server_certificate_info

Returns:
TASK [aws_full_deployment : Create and debug a query for json_query] ********************************************************************************************************
ok: [localhost] => {
    "cert_arn_query": "'v6-full-deployment-SSL-Certificate.arn'"
}

and
- name: Debug the json_query result of the above query
  vars:
    cert_arn_query: "'{{ server_ssl_certificate_name }}.arn'"
  ansible.builtin.debug:
    msg: "{{ server_cert_info_result.ansible_module_results | community.general.json_query(cert_arn_query) }}"
  tags: list_server_certificate_info

Which returns:
TASK [aws_full_deployment : Debug the json_query result of the above query] *************************************************************************************************
ok: [localhost] => {
    "msg": "v6-full-deployment-SSL-Certificate.arn"
}

which obviously fails when I try to create the load balancer, since the json_query didn't actually retrieve the arn. Any ideas?  I may have to resort to using ansible.builtin.command and using the raw awscli call, which I believe returns the data in a format that jinja could handle.

**Tags:** ansible, amazon-ec2, aws-iam, jinja, ansible-galaxy


---

## 2 answers

### Answer by username_1 on 2021-03-14. Score: 2 | Accepted answer

Don't nest moustaches. Once you're in a Jinja context, you should reference variables by name without any further delimiters.
Using standard attribute access syntax can be a lot easier to read than the attr() filter (and actually works for this situation, which attr() doesn't):
- name: Debug jinja2
  ansible.builtin.debug:
    msg: "{{ server_cert_info_result.ansible_module_results[server_ssl_certificate_name].arn }}"
  tags: list_server_certificate_info

> **Comments:**
> **username_0**: Unfortunately, the first suggestion didn't work: `FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute 'server_ssl_certificate_name'`  
> **username_0**: The second didn't either, I think it contains mixed `.` and `[ ]` attribute references too: `FAILED! => {"msg": "template error while templating string: expected name or number. String: {{ server_cert_info_result.ansible_module_results.[server_ss l_certificate_name].arn }}"}`  
> **username_0**: edit for my first comment, I posted the wrong error; correct error is Unfortunately, the first suggestion didn't work: `FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute 'v6-full-deployment-SSL-Certificate'`  
> **username_1**: `server_cert_info_result.ansible_module_results.[server_ssl_certificate_name].arn` is not what I suggested using. You've inserted an extra `.` before the `[`, so it's not surprising that it results in a syntax error.  Mixing . and bracket accesses in an expression is perfectly valid.  
> **username_0**: you're right; I removed the extra `.` that I inadvertently inserted, and it worked.  Thanks  
> **username_0**: I'm wondering why there is nothing in the ansible docs about needing to surround attributes that are variables with `[ ]` in the ansible docs; any insight?  Can you remove the top example you provided, that doesn't work, and I'll accept this as correct?  Seems you replied some fraction of a second before @username_2, whose answer is also correct, but slightly less complete.  
> **username_1**: Ansible doesn't try to document everything about the basic usage of Jinja, and Jinja's documentation in turn assumes some familiarity with basic Python syntax, which is where the bracket accessor syntax comes from. Jinja's special dot syntax can only be used with static keys that are valid Python identifiers, so it's more limited than using brackets by nature.  

---

### Answer by username_2 on 2021-03-14. Score: 0

I think you don't need to do anything special:
"{{ server_cert_info_result.ansible_module_results[server_ssl_cert_name].arn }}"

> **Comments:**
> **username_0**: Unfortunately, didn't work: `FAILED! => {"msg": "template error while templating string: expected name or number. String: {{ server_cert_info_result.ansible_module_results.[server_ss l_certificate_name].arn }}"}`  
> **username_0**: As above, I inadvertently inserted an extra `.` in my comment above; so your suggestion does work.  Why is there nothing about needing `[ ]` to surround variable names in attribute access in the ansible docs?  

---

