Terraform - loop
È possibile creare un ciclo che crei queste risorse? C'è molta ripetizione delle stesse risorse. Ho provato a utilizzare le mappe per creare un ciclo ma la mappa non accetta altro blocco predefinito.
O è normale creare manualmente tutte e 4 le risorse? Solo alcuni suggerimenti come risposta sono sufficienti, sto cercando di impararlo da solo.
resource "aws_subnet" "public-test-a" {
vpc_id = aws_vpc.vpc-test-02.id
cidr_block = "10.0.0.16/28"
map_public_ip_on_launch = true
availability_zone = var.AZ[1]
tags = {
Name = var.subnets_names[index]
}
}
resource "aws_subnet" "public-test-b" {
vpc_id = aws_vpc.vpc-test-02.id
cidr_block = "10.0.0.16/28"
map_public_ip_on_launch = true
availability_zone = var.AZ[1]
tags = {
Name = "public-test-b"
}
}
resource "aws_subnet" "private-test-a" {
vpc_id = aws_vpc.vpc-test-02.id
cidr_block = "10.0.0.32/28"
availability_zone = var.AZ[0]
tags = {
Name = "private-test-a"
}
}
resource "aws_subnet" "private-test-b" {
vpc_id = aws_vpc.vpc-test-02.id
cidr_block = "10.0.0.48/28"
availability_zone = var.AZ[1]
tags = {
Name = "private-test-b"
}
}
Stavo provando qualcosa di simile ma non mi sembra valido.
Inoltre non possiamo usare aws_vpc.vpc-test-02.idall'interno della variabile poiché fa parte di un altro tf.
variable "subnets" {
type = map
default = {
vpc_id = aws_vpc.vpc-test-02.id
}
public-test-a = {
map_public_ip_on_launch = true
availability_zone = var.AZ[0]
}
public-test-b = {
map_public_ip_on_launch = true
availability_zone = var.AZ[1]
}
private-test-a = {
availability_zone = var.AZ[0]
}
private-test-b = {
availability_zone = var.AZ[1]
}
}
variable "AZ" {
type = list
default = ["ap-south-1a", "ap-south-1b", "ap-south-1c"]
}
variable "subnets_cird" {
type = list
default = ["10.0.0.0/28", "10.0.0.16/26", "10.0.0.32/28", "10.0.0.48/28"]
}
variable "subnets_names" {
type = list
default = ["public-test-a", "public-test-b", "private-test-a", "private-test-b"]
}
Risposte
Per questa ricerca count e for_each nella documentazione terraform. Ecco un esempio di come sostituire public-test-a e public-test-b con un public-test:
variable "number_of_subnets" {
default = 2
}
resource "aws_subnet" "public-test" {
count = var.number_of_subnets
vpc_id = aws_vpc.vpc-test-02.id
cidr_block = "10.0.0.16/28"
map_public_ip_on_launch = true
availability_zone = var.AZ[1]
tags = {
# here you pick the right name according to the subnet index, where e.g subnets_names = ["public-test-a","public-test-b"]
Name = var.subnets_names[count.index]
}
}
Lo stesso può essere fatto per private_test.
Riguardo alle cose che hai provato. Non è possibile assegnare alle variabili altre variabili. Per ottenere questa funzionalità usa i locali:
locals {
x = aws_vpc.vpc-test-02.id
}
e quindi accedi al valore come
local.x