github.com/rstandt/terraform@v0.12.32-0.20230710220336-b1063613405c/website/docs/configuration/functions/matchkeys.html.md (about) 1 --- 2 layout: "functions" 3 page_title: "matchkeys - Functions - Configuration Language" 4 sidebar_current: "docs-funcs-collection-matchkeys" 5 description: |- 6 The matchkeys function takes a subset of elements from one list by matching 7 corresponding indexes in another list. 8 --- 9 10 # `matchkeys` Function 11 12 -> **Note:** This page is about Terraform 0.12 and later. For Terraform 0.11 and 13 earlier, see 14 [0.11 Configuration Language: Interpolation Syntax](../../configuration-0-11/interpolation.html). 15 16 `matchkeys` constructs a new list by taking a subset of elements from one 17 list whose indexes match the corresponding indexes of values in another 18 list. 19 20 ```hcl 21 matchkeys(valueslist, keyslist, searchset) 22 ``` 23 24 `matchkeys` identifies the indexes in `keyslist` that are equal to elements of 25 `searchset`, and then constructs a new list by taking those same indexes from 26 `valueslist`. Both `valueslist` and `keyslist` must be the same length. 27 28 The ordering of the values in `valueslist` is preserved in the result. 29 30 ## Examples 31 32 ``` 33 > matchkeys(["i-123", "i-abc", "i-def"], ["us-west", "us-east", "us-east"], ["us-east"]) 34 [ 35 "i-abc", 36 "i-def", 37 ] 38 ``` 39 40 If the result ordering is not significant, you can achieve a similar result 41 using a `for` expression with a map: 42 43 ``` 44 > [for i, z in {"i-123"="us-west","i-abc"="us-east","i-def"="us-east"}: i if z == "us-east"] 45 [ 46 "i-def", 47 "i-abc", 48 ] 49 ``` 50 51 If the keys and values of interest are attributes of objects in a list of 52 objects then you can also achieve a similar result using a `for` expression 53 with that list: 54 55 ``` 56 > [for x in [{id="i-123",zone="us-west"},{id="i-abc",zone="us-east"}]: x.id if x.zone == "us-east"] 57 [ 58 "i-abc", 59 ] 60 ``` 61 62 For example, the previous form can be used with the list of resource instances 63 produced by a `resource` block with the `count` meta-attribute set, to filter 64 the instances by matching one of the resource attributes: 65 66 ``` 67 > [for x in aws_instance.example: x.id if x.availability_zone == "us-east-1a"] 68 [ 69 "i-abc123", 70 "i-def456", 71 ] 72 ``` 73 74 Since the signature of `matchkeys` is complicated and not immediately clear to 75 the reader when used in configuration, prefer to use `for` expressions where 76 possible to maximize readability.