Local and dynamic blocks:

jaffar shaik
1 min readJan 5, 2021

--

Local and dynamic blocks:

Local blocks:

If we need to use common values in repeated blocks then we go for local blocks.all the values can be declared in a block called locals{}.

To use these values in source code we can call them with local.tagname

In our example we declared common tags as shown below

locals {
common_tags = {
users = "devteam"
}
}

Example usage:

provider "aws" {
region = "us-east-1"
access_key = ""
}
locals {
common_tags = {
users = "devteam"
}
}
resource aws_instance "myec2" {
ami = "ami-96fda3c22c1c990a"
instance_type = "t2.small"
tags = local.common_tags
}
resource aws_instance "myec3" {
ami = "ami-96fda3c22c1c990a"
instance_type = "t2.small"
tags = local.common_tags
}

Dyanmic blocks:

Dynamic blocks helps to reduce repetitive codes. In below example we have shown the inbound rule for various security groups.here we have used for_each loop to pick the values from list .

provider "aws" {
region = "us-east-1"
access_key = ""
}
variable "ports" {
type = list
default = [22, 2049, 80]
}
resource aws_security_group "mysec" {
name = "prodsecgroups"
dynamic "ingress" {
for_each = var.ports
content {
from_port = ingress.value
to_port = ingress.value
protocol = "tcp"
cidr_blocks = ["10.0.0.0/16"]
}
}
}

--

--

jaffar shaik
jaffar shaik

Written by jaffar shaik

Am DevOps Engineer and SRE based in india.

No responses yet