Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if variable is in a list within a dictionary in Ansible

Tags:

ansible

jinja2

I have the following tasks:

- name: Retrieve records from Route53
  route53:
    command: get
    zone: "{{ stag_zone }}"
    record: "{{ stag_record }}"
    type: A
    aws_access_key: "{{ aws_access_key }}"
    aws_secret_key: "{{ aws_secret_key }}"
  register: rec

- name: Print records
  debug: var=rec

- name: Record contains IP
  debug: msg="{{rec}} contains {{stag_ip}}"
  when: "'{{stag_ip}}' in {{rec.set.values}}"

The Print records task outputs something like this:

ok: [XXX.XXX.XXX.XXX] => {
    "var": {
        "rec": {
            "changed": false, 
            "invocation": {
                "module_args": "", 
                "module_name": "route53"
            }, 
            "set": {
                "alias": false, 
                "record": "YYY.XXX.ZZZ.", 
                "ttl": "300", 
                "type": "A", 
                "value": "AAA.AAA.AAA.AAA,BBB.BBB.BBB.BBB", 
                "values": [
                    "AAA.AAA.AAA.AAA",
                    "BBB.BBB.BBB.BBB"
                ], 
                "zone": "XXX.ZZZ."
            }
        }
    }
}

And I want to execute "Record contains IP" task only when {{stag_ip}} is in {{rec.set.values}}. But my when clause is definitely broken. It outputs this:

fatal: [XXX.XXX.XXX.XXX] => Failed to template {% if 'QQQ.QQQ.QQQ.QQQ' in <built-in method values of dict object at 0x7fb66f54e6e0> %} True {% else %} False {% endif %}: template error while templating string: unexpected '<'

How can I "cast" rec.set.values to a list?

like image 326
borges Avatar asked Jul 30 '15 21:07

borges


1 Answers

The problem here is because values is a dict method. So it has "precedence" over accessing keys. To fix this, one has to explicitly call get:

when: stag_ip in rec.set.get('values')
like image 84
borges Avatar answered Oct 14 '22 03:10

borges