Jinja:从词典列表中检索IP地址-过滤器

时间:2018-12-04 00:16:43

标签: ansible jinja2

我已经很接近了,但是在找出正确的jinja过滤器以轻松获取该IP地址时遇到了麻烦:

这是我从Amazon Web Services AWS上的API调用到route53的JSON数据

{    "record_sets": {
        "IsTruncated": true,
        "ResourceRecordSets": [
            {
                "Name": "student1.junostesting.rhdemo.io.",
                "ResourceRecords": [
                    {
                        "Value": "35.183.128.49"
                    }
                ],
                "TTL": 3600,
                "Type": "A"
            }
        ],
        "changed": false,
        "failed": false
    }
}

我当前使用的过滤器是:

{{ record_sets.ResourceRecordSets | selectattr("Name", "match", "student1.junostesting.rhdemo.io") | map(attribute="ResourceRecords") | join(',') }}

这将返回以下词典列表。...

[{u'Value': u'35.183.128.49'}]

2 个答案:

答案 0 :(得分:1)

您在这里:(此示例使用json_query过滤器)

---
- name: JSON query extraction
  hosts: 127.0.0.1
  connection: local
  gather_facts: no
  tasks:
    - name: Set facts for search
      set_fact:
        name_to_find: 'student1.junostesting.rhdemo.io.'
        route53_json_string: '{"record_sets":{"IsTruncated":true,"ResourceRecordSets":[{"Name":"student1.junostesting.rhdemo.io.","ResourceRecords":[{"Value":"35.183.128.49"}],"TTL":3600,"Type":"A"}],"changed":false,"failed":false}}'

    - name: Convert json string to facts
      set_fact:
        route53_data: "{{ route53_json_string | from_json }}"

    - name: get IP
      set_fact:
        ip: "{{ route53_data | json_query(\"record_sets.ResourceRecordSets[?Name=='\" + name_to_find + \"'].ResourceRecords[0].Value\") }}"
...

答案 1 :(得分:0)

我发现我可以使用->

{{ (record_sets.ResourceRecordSets | selectattr("Name", "match", "student1.junostesting.rhdemo.io") | map(attribute="ResourceRecords") | flatten | first) | first }}

或this->

{{ (record_sets.ResourceRecordSets | selectattr("Name", "match", "student1.junostesting.rhdemo.io") | map(attribute="ResourceRecords") | first | first)['Value'] }}