I am stumped trying to validate that a data source returns exactly one result. Say for example if querying an AWS resource filtering by the Name tag. If the result is just a single object, attempts to use something list tolist() fail if it is a single object. So length() is only successful if multiple results are returned. I’ve tried try() and can() and they throw run-time errors if attempting to index a list that isn’t a list.
There must be a way to get the cardinality of a data source result set?
Speaking generally, a single data block only ever produces one result per instance. “Instance” here means that if you use count or for_each then you are instantiating the same data resource multiple times with slightly different arguments.
However, some data sources do represent collections of remote objects matching a query. In that case there is still only one result from the data source as a whole, but that result can include an attribute which is itself a list, set, or map of values, and so you could say in that case that there are “multiple results” from the perspective of that attribute even though Terraform Core still sees it as just a single object that happens to have a collection inside it.
The schema for each different data source type defines the shape of its results, so you should be able to see from the documentation which attributes the data source returns and what types they have. For any data source that represents a query for multiple objects in the remote system the documentation should describe at least one attributes that is of a collection type, and you can apply the length function to that collection to get the number of results.
Many data sources represent only exactly one object in the remote system, and so those ones don’t include any collection-typed attributes. For those ones you can expect them to return either exactly one object or raise an error explaining that it isn’t possible to do so – either because no objects match or because more than one object matches
Thanks @apparentlymart , that clears it up . I see what I was missing now. The AWS data sources say they must have exactly one match or they will fail. I misunderstood that they only failed if there were zero matches and assumed they must be returning a list of objects if there were multiple matches. Should have just tried a config with multiple matches to see it return that error.