Carina

For / If Expressions

Learn how to use for loops and if/else expressions in Carina to create multiple resources, iterate over lists and maps, and conditionally include resources.

Carina supports for and if expressions to dynamically generate resources. This guide shows you how to iterate over collections and conditionally create resources.

For expressions

A for expression creates multiple resources by iterating over a list or map.

A let-bound simple list loop uses each element’s String value as its child address. Its length alone is insufficient: each key must be known and public. Indexed loops need the list’s length, and map loops need its keys; their element values may still await apply. For example, use for (i, x) in [producer_a.identifier, producer_b.identifier] to plan two children before those identifiers are available.

When the whole collection is unknown, a managed-resource loop remains a deferred block with an unknown count. It may expand after its producer applies and must then pass the same key checks. A shape-known simple list with unresolved members is deferred until planning; an element that will only become known during apply is rejected. Module-call and read bodies cannot remain deferred: for a partial list, use (i, x) when its length is already known. A provider output’s length or keys are not inferred from unrelated inputs.

Iterating over a list

The simplest form iterates over a list of values:

provider awscc {
  source  = 'carina-rs/awscc'
  version = '0.7.1'
  region  = awscc.Region.ap_northeast_1
}

let vpcs = for env in ['dev', 'stg'] {
  awscc.ec2.Vpc {
    cidr_block = '10.0.0.0/16'

    tags = {
      Name        = "vpc-${env}"
      Environment = env
    }
  }
}

This creates vpcs.dev and vpcs.stg. Reordering the list preserves both addresses; inserting or removing a String affects only that child. List traversal still follows the authored order.

The elements must be distinct Strings. Numbers, booleans, durations, enum values, lists, maps, structs, and resource handles cannot be keys. A proven non-String element type is rejected even for an empty typed list. Protected collections, protected members, and diagnostic-sensitive Strings are also rejected; their contents never become addresses or diagnostic text. Rewrite the elements as public Strings or use for (i, x) in ....

String keys that do not round-trip through state address canonicalization and decomposition are also rejected. Use (i, x) for those elements. This restriction is lifted automatically when carina#4552 fixes key escaping; map-loop keys keep their existing behavior.

These rules apply to let-bound loops with resource, read, or module bodies. Anonymous loops keep their schema-derived identities and existing struct-list support.

Indexed iteration

Use the (index, value) form to opt into positional addresses, including when iterating over structs or repeated values:

let vpcs = for (i, env) in ['dev', 'stg'] {
  awscc.ec2.Vpc {
    cidr_block = cidr_subnet('10.0.0.0/8', 8, i)

    tags = {
      Name        = "vpc-${env}"
      Environment = env
    }
  }
}

The index i starts at 0, producing vpcs[0] and vpcs[1]. Here it is also used with cidr_subnet to assign different CIDR blocks. Changing list order can change which element occupies each address.

Iterating over a map

Use key, value binding to iterate over map entries:

let cidrs = {
  dev = '10.0.0.0/16'
  stg = '10.1.0.0/16'
}

let vpcs = for name, cidr in cidrs {
  awscc.ec2.Vpc {
    cidr_block = cidr

    tags = {
      Name        = "vpc-${name}"
      Environment = name
    }
  }
}

Accessing for expression results

A bound loop is a structural group. Select an instance attribute with a String subscript for simple list and map loops (vpcs['dev'].vpc_id), or an integer subscript for indexed loops (vpcs[0].vpc_id). vpcs[0] on a simple list loop is an error that points to the indexed form. Bare length(vpcs) and bare-value exports of the group remain errors; author an ordinary collection of selected attributes when you need a value.

For keyed loops, vpcs.dev.vpc_id is equivalent to vpcs['dev'].vpc_id outside function bodies and parameter defaults. Dot keys must start with a letter and contain only letters, digits, or underscores. A key named vpc_id is selected first in vpcs.vpc_id.vpc_id; the second .vpc_id reads its attribute. Use String subscripts for keys such as '3rd', 'my-key', or 'a.b'. Indexed loops reject dot selection, including .0.

Keyed child lookup on a deferred loop remains unsupported. Managed resource loops whose pending members are only module arguments expand after argument substitution, so their String-keyed children can be referenced inside the module and appear within its plan group. Changing a previously eager partial simple list to deferred syntax also removes its parse-time child lookup; use indexed iteration when that lookup is required.

let vpcs = for env in ['dev', 'stg'] {
  awscc.ec2.Vpc {
    cidr_block = '10.0.0.0/16'

    tags = {
      Name = "vpc-${env}"
    }
  }
}

# Reference the VPC keyed by 'dev'
awscc.ec2.Subnet {
  vpc_id            = vpcs['dev'].vpc_id
  cidr_block        = '10.0.1.0/24'
  availability_zone = 'ap-northeast-1a'

  tags = {
    Name = 'dev-subnet'
  }
}

Existing index-addressed state needs explicit moves when switching to simple list syntax. See Migrating index-addressed list loops, including loops that remain deferred. Regenerate saved plans after upgrading.

Local variables in for body

You can define local let bindings inside a for body:

let vpc = awscc.ec2.Vpc {
  cidr_block = '10.0.0.0/16'
}

let subnets = for (i, az) in ['ap-northeast-1a', 'ap-northeast-1c'] {
  let name = "subnet-${az}"

  awscc.ec2.Subnet {
    vpc_id            = vpc.vpc_id
    cidr_block        = cidr_subnet('10.0.0.0/16', 8, i)
    availability_zone = az

    tags = {
      Name = name
    }
  }
}

For with modules

You can call modules inside for expressions to create multiple instances of a module. See the Using Modules guide for a full example.

If expressions

An if expression conditionally creates a resource or selects a value.

Conditional resources

Create a resource only when a condition is true:

let enabled = true

let vpc = if enabled {
  awscc.ec2.Vpc {
    cidr_block = '10.0.0.0/16'

    tags = {
      Name = 'conditional-vpc'
    }
  }
}

When enabled is false, no VPC is created and the let binding is empty.

Conditional values with if/else

Use if/else as a value expression to choose between two values:

let is_production = true

awscc.ec2.Vpc {
  cidr_block = if is_production { '10.0.0.0/16' } else { '172.16.0.0/16' }

  tags = {
    Name = if is_production { 'prod-vpc' } else { 'dev-vpc' }
  }
}

This creates a single VPC but uses different CIDR blocks and names depending on the condition.

Value-producing if expressions always require an else branch. A resource-producing if may omit else; when its condition is false, it creates no resource.

This is also enforced for literal conditions in root files. For example, let x = if true { 'a' } is now an error because there would be no value when the condition is false; fix it by adding an else branch, such as let x = if true { 'a' } else { 'b' }. This aligns statement-position values with value-position if expressions and prevents a binding from having no value.

Module argument conditions

A reusable module may use a Bool argument, or a pure function of that argument, as an if condition. Carina keeps both branches in the module template and selects one for each module instance:

arguments {
  production: Bool
}

fn identity(value: Bool): Bool { value }

attributes {
  environment: String = if identity(production) { 'prod' } else { 'dev' }
}

A shape-only computation can be static even when collection elements are pending: length([resource.identifier]) is 1 without reading the identifier. A pure function can use that count to produce a static Bool condition.

The caller can instantiate the module with either value. Resource attributes are runtime values, so they cannot be used as if conditions; the condition must be known from literals, module arguments, and pure computations when the module is expanded.

Combining for and if

You can use if value expressions inside for bodies. To conditionally create every resource from a for, put the if in the iterable, such as for item in (if enabled { items } else { [] }) { ... }. A resource-producing for cannot be used directly as an if branch.

An if condition must be a Bool value; comparison operators such as == are not part of the expression language (they are only available in validation, require, and wait conditions), so carry the flag in the data you iterate over:

let environments = {
  dev = { cidr = '10.0.0.0/16', production = false }
  stg = { cidr = '10.1.0.0/16', production = false }
  prd = { cidr = '10.2.0.0/16', production = true }
}

let vpcs = for name, env in environments {
  awscc.ec2.Vpc {
    cidr_block       = env.cidr
    instance_tenancy = if env.production { dedicated } else { default }

    tags = {
      Name        = "vpc-${name}"
      Environment = name
    }
  }
}