Logic App bypass Null in filter query

2019-08-14 20:47发布

问题:

I am building a Logic App that uses the Azure Resource connector to obtain a list of my resources. I would then like to filter the results to Microsoft.Compute resources that have a tag name and value of stop and normal.

Here is a snippet of resource that I receive back without any filters

{
    "id": "/subscriptions/<subscription>/resourceGroups/Env1/providers/Microsoft.Compute/virtualMachines/MyVM1",
    "name": "MyVM1",
    "type": "Microsoft.Compute/virtualMachines",
    "location": "westeurope",
    "tags": {
        "stop": "normal"
    }
},
{
    "id": "/subscriptions/<subscription>/resourceGroups/LogicApp/providers/Microsoft.Logic/workflows/DWSize-Check",
    "name": "DWSize-Check",
    "type": "Microsoft.Logic/workflows",
    "location": "westeurope",
    "tags": {}
}

As you can see, the bottom resource does not contain any tags, as with many others that will appear in the list

I use the standard Compose Filter Array connector to try and filter out from the value I receive back.

Here is the code that I wish to use for the filter command:

@and(contains(item()?['id'], '/Microsoft.Compute/virtualMachines/'), contains(item()?['tags'], variables('TagName')), contains(item()?['tags'], variables('TagValue')))

variables('TagName') and variables('TagValue') will be stop and normal, as show in the example tags listed in my results snippet.

However, because there is no tag values listed in other resources, such as Microsoft.Logic/workflows, I receive the following null error:

InvalidTemplate. The execution of template action 'Filter_array' failed: The evaluation of 'query' action 'where' expression '@contains(item()?['tags'], variables('TagValue'))' failed: 'The template language function 'contains' expects its first argument 'collection' to be a dictionary (object), an array or a string. The provided value is of type 'Null'.'.

Would anyone know how to get around this?

I have tried similar queries to this @contains(item().tags?.stop, variables('TagValue')) just to see if it picks up anything, but I'm still blocked by a null response :(

I tried the above with the help of the Workflow Definition Language, but still no dice. Any help would be greatly appreciated.

EDIT

In addition to the answer posted by Thomas, I have performed the following (image below) to filter out null from the results and get to the TagName, but I am still unable to get to the TagValue, even if I use contains:

@and(contains(item()?['tags'], variables('TagName')), contains(item()?['tags'], variables('TagValue')))

or event just trying to look for TagValue

@contains(item()?['tags'], variables('TagValue'))

回答1:

You can check for null and return an empty value (an empty array in your case).

You can replace item()?['tags'] with this expression or create a variable :

if(equals(item()?['tags'], null), [], item()?['tags'])