Search code examples
ansiblejinja2

How to check if attribute is not defined?


I have a playbook where I grab the metadata of an object in AWS S3 and register it to the item_info variable. If the createddate metadata key doesn't match a certain value, or if there is no createddate key, I want to download that file from a location via the uri module. Currently I'm having trouble with the "if there is no key" part.

Here's what the object looks like:

{
  "changed": false,
  "failed": false,
  "object_info": [
    {
      "object_data": {
        "accept_ranges": "bytes",
        "content_length": 2760249,
        "content_type": "binary/octet-stream",
        "e_tag": "\\"0b82b2320d1d8ac226cd2720ccad554c\\"",
        "last_modified": "2023-05-15T16:32:27+00:00",
        "metadata": {
          "createddate": "2022-11-30T21:29:25.066Z"
        },
        "server_side_encryption": "AES256",
        "version_id": "SRehoPRyDbp.Rn2GKYXRE_40FzyLg4ek"
      }
    }
  ]
}

Here's the conditional I'm using:

item_info.object_info | map(attribute='object_data.metadata.createddate') | first != item.history.createdDate

This works fine if there is a createddate key, but it fails if there isn't. I've tried this filter:

item_info.object_info | map(attribute='object_data.metadata.createddate') is not defined or
item_info.object_info | map(attribute='object_data.metadata.createddate') | first != item.history.createdDate

But it throws the error:

'dict object' has no attribute 'createddate'

So what's the best way to accomplish this?


Solution

  • In case the value is not present, you can use default filter to provide that value:

    (item_info.object_info | map(attribute='object_data.metadata.createddate') | first | default('') != item.history.createdDate) or
    (item_info.object_info | map(attribute='object_data.metadata.createddate') | first is none)