Get a list of distinct values from map

user2650277

I would like to create a NAT gateway for each distinct availability zone in terraform.For that to happen i would need to get a list of distinct availability zones.

variable "public_subnets" {
 type = map(object({
   cidr = string
   az   = string
 }))
 description = "Public subnets for My VPC"
}

Subnet

public_subnets = {
 "a" = {
   cidr = "10.0.0.0/24"
   az   = "us-east-2a"
 },
 "b" = {
   cidr = "10.0.1.0/24"
   az   = "us-east-2b"
 }
}

The resources would be defined as follows:

   resource "aws_subnet" "public-subnets" {
     for_each          = var.public_subnets
     vpc_id            = aws_vpc.main_vpc.id
     cidr_block        = each.value.cidr
     availability_zone = each.value.az
     map_public_ip_on_launch = true
     
     tags = {
       Name = "public-subnet-${each.value.cidr}-${each.value.az}"
     }
    }


resource "aws_eip" "ip-nats" {
  for_each = aws_subnet.public-subnets
  # EIP may require IGW to exist prior to association. 
  depends_on = [aws_internet_gateway.igw]
}

When creating each aws_nat_gateway i would need to state the allocation_id and subnet_id. In a typical programming language i would do the following:

  1. Create elastic ips for each public subnet and create a map / dictionary with public subnet as key with the elastic ip as value
  2. Loop for that dictionary and create the NAT gateway.

How do i achieve this with terraform

Martin Atkins

An aws_nat_gateway effectively behaves as a pairing of a particular Elastic IP "allocation ID" and a particular subnet ID, and so I assume your goal here is to create one such pairing for each corresponding pair of instances of your aws_subnet.public-subnets and aws_eip.ip-nats resources.

Since these NAT gateways will be one-to-one with each entry in var.public_subnets, you can just use for_each with that map one more time and then tell Terraform how to gather the data from the relevant instances of the other resources:

resource "aws_nat_gateway" "example" {
  for_each = var.public_subnets

  allocation_id = aws_eip.ip-nats[each.key]
  subnet_id     = aws_subnet.public-subnets[each.key]
  # ...
}

It could also be valid to use for_each chaining from one of the other resources as you did to chain aws_eip.ip-nats from aws_subnet.public-subnets, but I chose to just use the original collection here because we can only chain from one other resource at a time and neither resource here seems obviously "more connected" to the NAT gateway than the other: each NAT gateway descends from one instance of each of them equally.

Este artigo é coletado da Internet.

Se houver alguma infração, entre em [email protected] Delete.

editar em
0

deixe-me dizer algumas palavras

0comentários
loginDepois de participar da revisão

Artigos relacionados

Return a List of distinct values from DataGridView

Java - Retrive Indivudual Values from a List in a Map

Groovy groupby List generated from Map values

Get the count of distinct elements from a list of lists using LINQ

How do I get distinct items from a list?

Get a list of values from a list of dictionaries?

Replacing values from list of custom objects with map values

java : get count of all distinct keys and values in Map<String,Set<String>>

Using C# code Get Distinct values from MongoDB array where it is matching some values specifically

Python Selenium: get values from dropdown list

how to get values from a dictionary for a list of words?

How to get values from list in variables in dart

Get specific values from list python

Transform an object (map) into a distinct list with terraform

Get distinct strings from a list then create a new object and add it to the same list

Haskell find and replace values from list using map

Maxima: define a function that returns a random integer in a range, such that the value is distinct from another value or a list of other values

Filter list of distinct values from one column of grouped data in the same order as it shows

Optimal way to transfer values from a Map<K, V<List>> to a Map<otherKey, otherValue<List>>

How do I list distinct values as columns?

Count number of distinct values in the same position in a list

Python XML distinct list of child tags values

SQL list only unique / distinct values

Get list of keys from a dictionary matches to list of values

How do you get distinct values from dataTables and sum the total specific field using JS

How to get distinct values from an array of arrays in JavaScript using the filter() method?

How to get specific map values from inside Freemarker template

How to get 3d metric values from disparity map?

How do I get specific values from a collection map

TOP lista

  1. 1

    R Shiny: use HTML em funções (como textInput, checkboxGroupInput)

  2. 2

    O Chromium e o Firefox exibem as cores de maneira diferente e não sei qual deles está fazendo certo

  3. 3

    Como assinar digitalmente um documento PDF com assinatura e texto visíveis usando Java

  4. 4

    R Folheto. Dados de pontos de grupo em células para resumir muitos pontos de dados

  5. 5

    Gerenciar recurso shake de Windows Aero com barra de título personalizado

  6. 6

    Como obter dados API adequados para o aplicativo angular?

  7. 7

    UITextView não está exibindo texto longo

  8. 8

    Por que meus intervalos de confiança de 95% da minha regressão multivariada estão sendo plotados como uma linha de loess?

  9. 9

    Acessando relatório de campanhas na AdMob usando a API do Adsense

  10. 10

    Usando o plug-in Platform.js do Google

  11. 11

    Como posso modificar esse algoritmo de linha de visada para aceitar raios que passam pelos cantos?

  12. 12

    Dependência circular de diálogo personalizado

  13. 13

    Coloque uma caixa de texto HTML em uma imagem em uma posição fixa para site para desktop e celular

  14. 14

    iOS: como adicionar sombra projetada e sombra de traço no UIView?

  15. 15

    Como usar a caixa de diálogo de seleção de nomes com VBA para enviar e-mail para mais de um destinatário?

  16. 16

    Tabela CSS: barra de rolagem para a primeira coluna e largura automática para a coluna restante

  17. 17

    How to create dynamic navigation menu select from database using Codeigniter?

  18. 18

    Converter valores de linha SQL em colunas

  19. 19

    ChartJS, várias linhas no rótulo do gráfico de barras

  20. 20

    用@StyleableRes注释的getStyledAttributes。禁止警告

  21. 21

    não é possível adicionar dependência para com.google.android.gms.tasks.OnSuccessListener

quentelabel

Arquivo