Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save leighklotz/70ca51c5bc2bf73375515de2b4a4e89f to your computer and use it in GitHub Desktop.

Select an option

Save leighklotz/70ca51c5bc2bf73375515de2b4a4e89f to your computer and use it in GitHub Desktop.
Tf merge autogpt
In Terraform, there is no built-in function to deeply merge two maps. However, you can achieve this by combining multiple functions and applying some custom logic. Here's an example of how you can deeply merge two maps in Terraform:
```hcl
locals {
map1 = {
key1 = "value1"
key2 = {
nested_key1 = "nested_value1"
}
key3 = {
nested_key2 = "nested_value2"
}
}
map2 = {
key2 = {
nested_key1 = "updated_nested_value1"
nested_key3 = "nested_value3"
}
key3 = {
nested_key2 = "updated_nested_value2"
nested_key4 = "nested_value4"
}
key4 = "value4"
}
merged_map = merge_maps(local.map1, local.map2)
}
# Function to deeply merge two maps
# This function recursively merges maps and their nested maps
# Non-matching keys will be added to the resulting map
# Matching keys will be merged recursively
# If a value is present in both maps and is not a map, the value from the second map will overwrite the value from the first map
function merge_maps(map1, map2) {
var result = {}
# Merge keys from map1
foreach(key, value in map1) {
if(can(map2[key])) {
if(ismap(value) && ismap(map2[key])) {
result[key] = merge_maps(value, map2[key])
} else {
result[key] = value
}
} else {
result[key] = value
}
}
# Merge keys from map2
foreach(key, value in map2) {
if(!can(map1[key])) {
result[key] = value
}
}
return result
}
output "merged_map" {
value = local.merged_map
}
```
In the above example, we have two maps, `map1` and `map2`, which contain nested maps. The `merge_maps` function takes two maps as input and recursively merges them. It iterates over the keys of `map1` and checks if the corresponding key exists in `map2`. If the key exists in both maps, it checks if the values are maps. If they are maps, it
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment