Architectural Models

Filters, Loops & Conditionals

How to use Tera filters, if/else conditionals, and for loops to create dynamic property values in models.

Filters, Loops & Conditionals

Using Filters

Tera provides a wide range of built-in filters to manipulate data. You can chain them using the | pipe character. A full list is available in the Tera documentation.

[create_resource.properties]
# Convert a property to uppercase
hostname_prefix = "{{ origin_resource.name | upper }}"
# Replace characters in a string
sanitized_name = "{{ origin_resource.name | replace(from=\".\", to=\"-\") }}"
# Map an array of related 'application' objects to just their 'volume' properties,
# then encode the resulting array as a JSON string.
volumes = "{{ origin_resource.application | map(attribute=volume) | json_encode | safe }}"

Conditional Logic and Loops

You can use {% if ... %} blocks for conditional logic and {% for ... %} for loops. This is extremely powerful for creating dynamic properties.

[create_resource.properties]
# Set a property based on another property's value
sla_level = "{% if origin_resource.environment == 'prod' %}Gold{% else %}Silver{% endif %}"

# Create a comma-separated list of formatted tags from an array property
tag_list = "{% for tag in origin_resource.tags %}{{ tag | upper }}{% if not loop.last %},{% endif %}{% endfor %}"

Simplyfing models using Tera templating:

Before two create_resource to distinguish the domain:

origin_resource = "service"

[[create_resource]]
match_on = [
  { property = "status", value = "deployed" },
  { property = "domain", exists = true }
]
resource_type = "service"
name = "{{origin_resource.service}}"
relation_type = "_GENERATED_FQDN"
[create_resource.properties]
url = "{{origin_resource.service_name}}.{{origin_resource.domain}}"
status = "dns_record_generated"

Using tera templating:

origin_resource = "service"

[[create_resource]]
match_on = [ { property = "status", value = "deployed" } ]
resource_type = "service"
name = "{{origin_resource.service}}"
relation_type = "_GENERATED_FQDN"
[create_resource.properties]
url = "{{ origin_resource.service_name }}.{{ origin_resource.domain | default(value='internal.local') }}"
status = "dns_record_generated"