Breaking News: Grepper is joining You.com. Read the official announcement!
Check it out

Loops with for_each expressions

Sumit Rawal answered on May 14, 2023 Popularity 1/10 Helpfulness 1/10

Contents


More Related Answers

  • for in or for each loop in dart
  • for each loop python 3
  • how to do a foreach loop in python
  • for_each in rust
  • java for each loop
  • for each loop java
  • for each R
  • For Each Loop
  • for each loop in java
  • java for each loop
  • using condition for each loop
  • for_each c++
  • for each in python
  • Java for-each Loop
  • for_loops
  • for-each Loop Sytnax JAVA
  • for-each loop
  • For Each Loop

  • Loops with for_each expressions

    0

    The for_each expression allows you to loop over lists, sets, and maps to create (a) multiple copies of an entire resource, (b) multiple copies of an inline block within a resource, or (c) multiple copies of a module. Let’s first walk through how to use for_each to create multiple copies of a resource.

    The syntax looks like this:

    resource "_" "" {

    for_each =

    [CONFIG ...]

    }

    where COLLECTION is a set or map to loop over (lists are not supported when using for_each on a resource) and CONFIG consists of one or more arguments that are specific to that resource. Within CONFIG, you can use each.key and each.value to access the key and value of the current item in COLLECTION.

    For example, here’s how you can create the same three IAM users using for_each on a resource:

    resource "aws_iam_user" "example" {

    for_each = toset(var.user_names)

    name = each.value

    }

    Note the use of toset to convert the var.user_names list into a set. This is because for_each supports sets and maps only when used on a resource. When for_each loops over this set, it makes each username available in each.value. The username will also be available in each.key, though you typically use each.key only with maps of key-value pairs.

    Once you’ve used for_each on a resource, it becomes a map of resources, rather than just one resource (or an array of resources as with count). To see what that means, remove the original all_arns and first_arn output variables, and add a new all_users output variable:

    output "all_users" {

    value = aws_iam_user.example

    }  

    Popularity 1/10 Helpfulness 1/10 Language javascript
    Source: Grepper
    Link to this answer
    Share Copy Link
    Contributed on May 14 2023
    Sumit Rawal
    0 Answers  Avg Quality 2/10


    X

    Continue with Google

    By continuing, I agree that I have read and agree to Greppers's Terms of Service and Privacy Policy.
    X
    Grepper Account Login Required

    Oops, You will need to install Grepper and log-in to perform this action.