<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Youness Zarhali on Medium]]></title>
        <description><![CDATA[Stories by Youness Zarhali on Medium]]></description>
        <link>https://medium.com/@youness.zarhali?source=rss-9e7316d43131------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ZAOHS25ZpzT4fj7x3Zm_FQ.png</url>
            <title>Stories by Youness Zarhali on Medium</title>
            <link>https://medium.com/@youness.zarhali?source=rss-9e7316d43131------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 06:15:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@youness.zarhali/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[AWS VPC Security Explained: Security Groups vs Network ACLs]]></title>
            <link>https://aws.plainenglish.io/aws-vpc-security-explained-security-groups-vs-network-acls-3b5cfd326c7d?source=rss-9e7316d43131------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b5cfd326c7d</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Youness Zarhali]]></dc:creator>
            <pubDate>Sat, 28 Feb 2026 22:55:00 GMT</pubDate>
            <atom:updated>2026-03-30T22:14:43.882Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ek7WhRKqKeWXpj0wdbo2mg.png" /><figcaption>Credits: AI Generated Image for Visual Representation.</figcaption></figure><p>In the previous article of <a href="https://medium.com/@youness.zarhali/list/aws-networking-mastery-with-terraform-concepts-handson-680a089ba476"><strong>AWS Networking Mastery from the ground up</strong></a><strong> </strong>series, we explained how to provide Internet access for both public and private subnets of our VPC. We also included a hands-on section where we deployed a VPC, private and public subnets, IGW and NGW alongside the necessary routing configuration, all using the Community VPC Terraform Module.</p><p>That gave us a functional Network but not a secure one ! In this article, we will try to answer one simple question:</p><p><strong>How do we control what traffic is allowed in or out of our VPC ?</strong></p><p>Short Answer: <strong>Security Groups</strong> and <strong>NACLs !</strong></p><p>It is essential to understand these two concepts and know when to use each one of them to create secure VPC architectures. So keep reading to gain a detailed understanding of these two concepts and see how we can implement them using Terraform.</p><h4>Security Groups: Instance-Level Traffic Control</h4><p>Security groups are virtual firewalls that are attached to Elastic Network Interfaces (ENIs). They are commonly used in the case of EC2 instances, but can also be attached to RDS Databases, Lambda functions or Load balancers. They determine which <strong>inbound </strong>and <strong>outbound </strong>traffic in authorized based on numerous parameters: port range, protocols and sources.</p><p><strong>Key Characteristics:</strong></p><ul><li><strong>Stateful</strong>: If an inbound rule allows traffic in, the response is automatically allowed out (and vice-versa), even if no explicit outbound rule exists.</li><li><strong>Instance-level firewall</strong>: SGs apply directly to <strong>EC2 instances</strong> (and other AWS resources that support them), <strong>not to subnets</strong>.</li><li><strong>Default deny</strong>: All inbound traffic is denied unless explicitly allowed.<br> Outbound is allowed by default unless you change the rules.</li><li><strong>Only allow rules</strong>: They <strong>cannot</strong> contain deny rules — only “Allow” rules.<br> This keeps them simpler and reduces complexity.</li><li><strong>Support for multiple resource attachments</strong>: A resource can be attached to multiple security groups; all rules are aggregated.</li><li><strong>Limited number of rules</strong>: Each SG has soft limits on inbound/outbound rules, which can be increased by requesting a quota increase.</li></ul><p>Below is an illustration to better grasp how Security Groups fit into an AWS network architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/1*ksGe5b7C85LLTGmvM661rA.png" /><figcaption>Security Group diagram made using Draw.io</figcaption></figure><h4>Network ACLs: Subnet-Level Access Protection</h4><p>While SGs provide instance level protection, <strong>Network Access Control Lists (NACLs)</strong> protect your environment at the subnet level. They act as a stateless firewall around an entire subnet, providing filtering of traffic before it reaches any instance or service.</p><p>NACLs can be used in different scenarios such as:</p><ul><li>Blocking known malicious CIDRs</li><li>Limiting inbound/outbound traffic by subnet</li><li>Adding and extra layer of security at the subnet level.</li></ul><p>Note that NACLs do not replace Security Groups, they complement them.</p><p><strong>Key Characteristics:</strong></p><ul><li><strong>Stateless</strong>: Inbound and outbound traffic are evaluated <strong>independently</strong>.<br> Return traffic must be explicitly allowed in both directions.</li><li><strong>Subnet-level firewall</strong>: NACLs apply to <strong>entire subnets</strong>, affecting all resources inside them.</li><li><strong>Allow and deny rules</strong>: Unlike Security Groups, NACLs support <strong>explicit deny rules</strong>.</li><li><strong>Rule order matters</strong>: Rules are evaluated in <strong>ascending numerical order</strong> (lowest number first). The first matching rule is applied.</li><li><strong>Default NACL</strong>: Allows all inbound and outbound traffic</li><li><strong>One NACL per subnet</strong>: Each subnet can be associated with <strong>only one</strong> NACL at a time.</li></ul><p>Below is an illustration to understand how Network ACLs fit into the AWS network architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*KdRRMPKxUB1irm8nmKPJVA.png" /><figcaption>NACL diagram made using Draw.io</figcaption></figure><h4>🆚 Security Groups vs NACLs: Which One to Use and When</h4><p>Although their concepts overlap, SGs and NACLs solve different problems. It is therefore very important and crucial for cloud infrastructure architects and platform engineers to understand the difference between them. Below is a summary table describing their main differences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*eZvrlEO2LbgUh0gLJouk5g.png" /><figcaption>Comparison matrix between Security Groups and NACLs</figcaption></figure><h4><strong>👨‍💻 </strong>Hands-on section — Terraform</h4><p>As in the previous articles in our <a href="https://medium.com/@youness.zarhali/list/aws-networking-mastery-with-terraform-concepts-handson-680a089ba476">series</a>, we will put the concepts covered in this article into practice with a Terraform workshop, where we will create a Security Group and a NACL, as well as all associated resources.</p><p>Below you will find the structure of our project. For this implementation section, we will make use of Terraform Modules.</p><pre>└── terraform-vpc-security<br>    ├── modules<br>    │   ├── vpc<br>    │   │   ├── main.tf<br>    │   │   ├── outputs.tf<br>    │   │   ├── variables.tf<br>    │   │   └── versions.tf<br>    │   └── vpc-security<br>    │       ├── main.tf<br>    │       ├── outputs.tf<br>    │       ├── variables.tf<br>    │       └── versions.tf<br>    └── vpc-security-workshop.tf</pre><p>Regarding the <strong>vpc</strong>module, it will be exactly the same module that we presented in the first article <a href="https://medium.com/aws-in-plain-english/aws-networking-fundamentals-understanding-vpcs-subnets-and-ip-addressing-b667fe0a94ae"><strong>AWS Networking Fundamentals: Understanding VPCs, Subnets, and IP Addressing</strong></a><strong>. </strong>Now, let’s break down the content of the <strong>vpc-security </strong>module.</p><pre>#########################################<br># versions.tf<br>#########################################<br><br>terraform {<br>  required_version = &quot;&gt;= 1.3.10&quot;<br>  required_providers {<br>    aws = {<br>      source  = &quot;hashicorp/aws&quot;<br>      version = &quot;&gt;= 5.75.0&quot;<br>    }<br>  }<br>}</pre><pre>#########################################<br># variables.tf<br>#########################################<br><br>####### VPC variable #######<br><br>variable &quot;vpc_id&quot; {<br>  description = &quot;VPC ID where security resources will be deployed&quot;<br>  type        = string<br>}<br><br>####### SGs variable #######<br><br>variable &quot;security_groups&quot; {<br>  description = &quot;List of security groups and their rules&quot;<br>  type = list(object({<br>    name        = string<br>    description = string<br><br>    ingress_rules = list(object({<br>      description = string<br>      protocol    = string<br>      from_port   = number<br>      to_port     = number<br>      cidr_blocks = list(string)<br>    }))<br><br>    egress_rules = list(object({<br>      description = string<br>      protocol    = string<br>      from_port   = number<br>      to_port     = number<br>      cidr_blocks = list(string)<br>    }))<br>  }))<br>}<br><br>####### NACLs variable #######<br><br>variable &quot;network_acls&quot; {<br>  description = &quot;List of network ACLs and their rules&quot;<br>  type = list(object({<br>    name       = string<br>    subnet_ids = list(string)<br><br>    ingress_rules = list(object({<br>      rule_number = number<br>      protocol    = string<br>      action      = string<br>      cidr_block  = string<br>      from_port   = number<br>      to_port     = number<br>    }))<br><br>    egress_rules = list(object({<br>      rule_number = number<br>      protocol    = string<br>      action      = string<br>      cidr_block  = string<br>      from_port   = number<br>      to_port     = number<br>    }))<br>  }))<br>}</pre><pre>#########################################<br># main.tf<br>#########################################<br><br>####### SGs Resource #######<br><br>resource &quot;aws_security_group&quot; &quot;sg&quot; {<br><br>  for_each = {<br>    for sg in var.security_groups :<br>    sg.name =&gt; sg<br>  }<br><br>  name        = each.value.name<br>  description = each.value.description<br>  vpc_id      = var.vpc_id<br><br>  tags = {<br>    Name = each.value.name<br>  }<br>}<br><br>####### SG Ingress Rules Resource #######<br><br>resource &quot;aws_security_group_rule&quot; &quot;ingress&quot; {<br><br>  for_each = {<br>    for rule in flatten([<br>      for sg in var.security_groups : [<br>        for r in sg.ingress_rules : {<br>          key     = &quot;${sg.name}-ingress-${r.from_port}-${r.to_port}&quot;<br>          sg_name = sg.name<br>          rule    = r<br>        }<br>      ]<br>    ]) : rule.key =&gt; rule<br>  }<br><br>  type              = &quot;ingress&quot;<br>  security_group_id = aws_security_group.sg[each.value.sg_name].id<br><br>  description = each.value.rule.description<br>  protocol    = each.value.rule.protocol<br>  from_port   = each.value.rule.from_port<br>  to_port     = each.value.rule.to_port<br>  cidr_blocks = each.value.rule.cidr_blocks<br>}<br><br><br>####### SG Egress Rules Resource #######<br><br>resource &quot;aws_security_group_rule&quot; &quot;egress&quot; {<br><br>  for_each = {<br>    for rule in flatten([<br>      for sg in var.security_groups : [<br>        for r in sg.egress_rules : {<br>          key     = &quot;${sg.name}-egress-${r.from_port}-${r.to_port}&quot;<br>          sg_name = sg.name<br>          rule    = r<br>        }<br>      ]<br>    ]) : rule.key =&gt; rule<br>  }<br><br>  type              = &quot;egress&quot;<br>  security_group_id = aws_security_group.sg[each.value.sg_name].id<br><br>  description = each.value.rule.description<br>  protocol    = each.value.rule.protocol<br>  from_port   = each.value.rule.from_port<br>  to_port     = each.value.rule.to_port<br>  cidr_blocks = each.value.rule.cidr_blocks<br>}<br><br>####### NACL Resource #######<br><br>resource &quot;aws_network_acl&quot; &quot;nacl&quot; {<br><br>  for_each = {<br>    for nacl in var.network_acls :<br>    nacl.name =&gt; nacl<br>  }<br><br>  vpc_id     = var.vpc_id<br>  subnet_ids = each.value.subnet_ids<br><br>  tags = {<br>    Name = each.value.name<br>  }<br>}<br><br>####### NACL Ingress Rules Resource #######<br><br>resource &quot;aws_network_acl_rule&quot; &quot;ingress&quot; {<br><br>  for_each = {<br>    for rule in flatten([<br>      for nacl in var.network_acls : [<br>        for r in nacl.ingress_rules : {<br>          key       = &quot;${nacl.name}-ingress-${r.rule_number}&quot;<br>          nacl_name = nacl.name<br>          rule      = r<br>        }<br>      ]<br>    ]) : rule.key =&gt; rule<br>  }<br><br>  network_acl_id = aws_network_acl.nacl[each.value.nacl_name].id<br>  egress         = false<br><br>  rule_number = each.value.rule.rule_number<br>  protocol    = each.value.rule.protocol<br>  rule_action = each.value.rule.action<br>  cidr_block  = each.value.rule.cidr_block<br><br>  from_port = each.value.rule.from_port<br>  to_port   = each.value.rule.to_port<br>}<br><br>####### NACL Egress Rules Resource #######<br><br>resource &quot;aws_network_acl_rule&quot; &quot;egress&quot; {<br><br>  for_each = {<br>    for rule in flatten([<br>      for nacl in var.network_acls : [<br>        for r in nacl.egress_rules : {<br>          key       = &quot;${nacl.name}-egress-${r.rule_number}&quot;<br>          nacl_name = nacl.name<br>          rule      = r<br>        }<br>      ]<br>    ]) : rule.key =&gt; rule<br>  }<br><br>  network_acl_id = aws_network_acl.nacl[each.value.nacl_name].id<br>  egress         = true<br><br>  rule_number = each.value.rule.rule_number<br>  protocol    = each.value.rule.protocol<br>  rule_action = each.value.rule.action<br>  cidr_block  = each.value.rule.cidr_block<br><br>  from_port = each.value.rule.from_port<br>  to_port   = each.value.rule.to_port<br>}</pre><pre>#########################################<br># outputs.tf<br>#########################################<br><br><br>output &quot;security_groups&quot; {<br>  description = &quot;SG rules overview&quot;<br><br>  value = {<br>    for sg_key, sg in aws_security_group.sg : sg_key =&gt; {<br>      id = sg.id<br><br>      ingress = [<br>        for r in aws_security_group_rule.ingress :<br>        &quot;${r.protocol}:${r.from_port}-${r.to_port}:${join(&quot;,&quot;, r.cidr_blocks)}&quot;<br>        if r.security_group_id == sg.id<br>      ]<br><br>      egress = [<br>        for r in aws_security_group_rule.egress :<br>        &quot;${r.protocol}:${r.from_port}-${r.to_port}:${join(&quot;,&quot;, r.cidr_blocks)}&quot;<br>        if r.security_group_id == sg.id<br>      ]<br>    }<br>  }<br>}<br><br>output &quot;network_acls&quot; {<br>  description = &quot;NACL rules overview&quot;<br><br>  value = {<br>    for nacl_key, nacl in aws_network_acl.nacl : nacl_key =&gt; {<br>      id = nacl.id<br><br>      ingress = [<br>        for r in aws_network_acl_rule.ingress :<br>        &quot;${r.rule_number}:${r.rule_action}:${r.protocol}:${r.from_port}-${r.to_port}:${r.cidr_block}&quot;<br>        if r.network_acl_id == nacl.id<br>      ]<br><br>      egress = [<br>        for r in aws_network_acl_rule.egress :<br>        &quot;${r.rule_number}:${r.rule_action}:${r.protocol}:${r.from_port}-${r.to_port}:${r.cidr_block}&quot;<br>        if r.network_acl_id == nacl.id<br>      ]<br>    }<br>  }<br>}</pre><p>Now let’s display the content of thevpc-security-workshop.tf file.</p><p>The only thing left is to run the terraform workflow commands: terraform init , terraform planand terraform apply at the root of the project.</p><pre>#########################################<br># VPC Module<br>#########################################<br><br>module &quot;vpc&quot; {<br>  source = &quot;./modules/vpc&quot;<br><br>  vpc_configuration = {<br>    name = &quot;main-vpc&quot;<br>    cidr_block = &quot;10.0.0.0/16&quot;<br>  }<br><br>  subnets = [<br>    {<br>      type = &quot;private&quot;<br>      az   = &quot;eu-west-3a&quot;<br>      cidr_block = &quot;10.0.1.0/24&quot;<br>    }<br>  ]<br>}<br><br>#########################################<br># VPC Security Module<br>#########################################<br><br>module &quot;vpc_security&quot; {<br>  source = &quot;./modules/vpc-security&quot;<br><br>  vpc_id = values(module.vpc.vpc)[0].id<br>  security_groups = [<br>    {<br>      name        = &quot;web-sg&quot;<br>      description = &quot;Web tier security group&quot;<br><br>      ingress_rules = [<br>        {<br>          description = &quot;HTTPS&quot;<br>          protocol    = &quot;tcp&quot;<br>          from_port   = 443<br>          to_port     = 443<br>          cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>        }<br>      ]<br><br>      egress_rules = [<br>        {<br>          description = &quot;Allow all&quot;<br>          protocol    = &quot;-1&quot;<br>          from_port   = 0<br>          to_port     = 0<br>          cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>        }<br>      ]<br>    }<br>  ]<br><br>  network_acls = [<br>    {<br>      name = &quot;private-nacl&quot;<br><br>      subnet_ids = [<br>        for name, subnet in module.vpc.subnets :<br>        subnet.id<br>        if startswith(name, &quot;private&quot;)<br>      ]<br><br>      ingress_rules = [<br>        {<br>          rule_number = 100<br>          protocol    = &quot;tcp&quot;<br>          action      = &quot;allow&quot;<br>          cidr_block  = &quot;10.0.0.0/16&quot;<br>          from_port   = 1024<br>          to_port     = 65535<br>        }<br>      ]<br><br>      egress_rules = [<br>        {<br>          rule_number = 100<br>          protocol    = &quot;-1&quot;<br>          action      = &quot;allow&quot;<br>          cidr_block  = &quot;0.0.0.0/0&quot;<br>          from_port   = 0<br>          to_port     = 0<br>        }<br>      ]<br>    }<br>  ]<br>}<br><br>#########################################<br># Outputs <br>#########################################<br><br>output &quot;security_groups&quot; {<br>    value = module.vpc_security.security_groups<br>}<br><br>output &quot;network_acls&quot; {<br>    value = module.vpc_security.network_acls<br>  <br>}</pre><h4>Interesting Points</h4><p>Here are some key takeaways from the previous coding section:</p><ul><li><strong>Modular Architecture: </strong>Networking (VPC module) and security (VPC Security module) are fully decoupled, making the infrastructure easier to maintain and reuse.</li><li><strong>Dynamic Resource Creation with </strong><strong>for_each</strong>: Resources like Security Groups and NACLs are created dynamically, allowing the module to scale effortlessly without duplicating code.</li><li><strong>Advanced Data Transformation with </strong><strong>flatten()</strong>: Nested rule definitions (SG/NACL rules) are flattened into a structure compatible with for_each, enabling clean and flexible configurations.</li><li><strong>Structured Inputs with </strong><strong>list(object)</strong>: Using typed object variables enforces consistency and makes the module more predictable and self-documented.</li><li><strong>Structured outputs:</strong> Which makes it easy to reference them programmatically in other modules or Terraform configurations. Let’s see how the outputs are presented :</li></ul><pre>network_acls = {<br>  &quot;private-nacl&quot; = {<br>    &quot;egress&quot; = [<br>      &quot;100:allow:-1:0-0:0.0.0.0/0&quot;,<br>    ]<br>    &quot;id&quot; = &quot;acl-0b87449dcc4b0ca58&quot;<br>    &quot;ingress&quot; = [<br>      &quot;100:allow:6:1024-65535:10.0.0.0/16&quot;,<br>    ]<br>  }<br>}<br>security_groups = {<br>  &quot;web-sg&quot; = {<br>    &quot;egress&quot; = [<br>      &quot;-1:0-0:0.0.0.0/0&quot;,<br>    ]<br>    &quot;id&quot; = &quot;sg-029989ad6f9aaec5e&quot;<br>    &quot;ingress&quot; = [<br>      &quot;tcp:443-443:0.0.0.0/0&quot;,<br>    ]<br>  }<br>}</pre><h4>🎯 Conclusion</h4><p>As a platform engineer or cloud engineer, mastering network infrastructure security is a must. Securing the AWS Network isn’t about choosing between Security Groups or Network ACL — it’s about using them both effectively. Security Groups provide fine-grained, stateful protection at the instance level, while NACLs add subnet-level, stateless control with explicit deny capabilities.</p><h4>🔜 <strong>What’s Next in our series ?</strong></h4><p>So far, we have explored the basic concepts of AWS Networking, how we can provide Internet Connectivity for public and private subnets and finally, how we can secure the AWS Network both on the subnet and the instance level.</p><p>But what happens when multiple VPCs need to communicate?</p><p>In the next article, we’ll explore <strong>VPC Peering</strong> — how separate VPCs can securely connect, exchange traffic privately, and extend architectures across environments or accounts without exposing anything to the public internet.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b5cfd326c7d" width="1" height="1" alt=""><hr><p><a href="https://aws.plainenglish.io/aws-vpc-security-explained-security-groups-vs-network-acls-3b5cfd326c7d">AWS VPC Security Explained: Security Groups vs Network ACLs</a> was originally published in <a href="https://aws.plainenglish.io/">AWS in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Internet Connectivity in AWS: Internet Gateways and NAT Gateways]]></title>
            <link>https://aws.plainenglish.io/internet-connectivity-in-aws-internet-gateways-and-nat-gateways-9b86982a7c70?source=rss-9e7316d43131------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b86982a7c70</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Youness Zarhali]]></dc:creator>
            <pubDate>Sun, 30 Nov 2025 22:59:22 GMT</pubDate>
            <atom:updated>2025-12-01T21:15:20.994Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dl0ARrQHUiR_fe_kXKproQ.png" /><figcaption>Credits: AI Generated Image for Visual Representation.</figcaption></figure><p>In the previous <a href="https://medium.com/aws-in-plain-english/aws-networking-fundamentals-understanding-vpcs-subnets-and-ip-addressing-b667fe0a94ae">article</a>, we laid the foundation of AWS Networking, explaining concepts such as: VPC, IP adressing, private and public subnets. We have also illustrated everything with a complete implementation of a VPC and subnet creation using Terraform. Now that these basic concepts have been explained, we will move on to the next step and explain how to connect our VPC to the outside world — the Internet.</p><p>Many workloads in AWS need some sort of Internet Access. To achieve this, AWS provides two key components:</p><ul><li><strong>Internet Gateway (IGW):</strong> Enables <strong>inbound and outbound</strong> internet connectivity for public resources.</li><li><strong>NAT Gateway (NGW):</strong> Enables <strong>outbound-only</strong> internet access for private resources.</li></ul><p>Througout this article, we will explore these concepts in detail and implement them using Terraform to gain a comprehensive understanding with IaC best practices used in production environments.</p><h4>Internet Gateway (IGW): Enabling Inbound and Outbound Traffic for Public Subnets.</h4><p>The Internet Gateway is the component that allows resources in your VPC to communicate with the public Internet. It acts as a bridge between your VPC’s public subnets and the outside world.</p><p>An IGW provides two capabilities, assuming that the VPC routing configuration is correctly set up:</p><ul><li><strong>Outbound access: </strong>The IGW automatically performs <strong>1:1 NAT</strong> between an instance’s private IP and its public IP, allowing the instance to make requests to the internet and receive responses.</li><li><strong>Inbound access: </strong>Traffic targeted to the instance’s public IP is routed back through the IGW.</li></ul><p><strong>Key consideration when using the Internet Gateway:</strong></p><ul><li>The IGW is used when running public-facing workloads such as web servers and load balancers.</li><li>Deploying an IGW does not mean that all your VPC is public and can be reached from the public internet.</li><li>An instance in a public subnet whithin a VPC is only reachable from the internet if the following conditions are met : <br>- The subnet routes 0.0.0.0/0 to the IGW <br>- The instance has a <strong>public</strong> or <strong>Elastic</strong> IP<br>- Security groups/NACLs allow the traffic</li></ul><p>Below is a diagram illustrating where the IGW fits into an AWS network architecture and how traffic is routed to and from public subnets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*mAW1xt0IxiVza5xyHYCgvw.png" /><figcaption>IGW Architecture diagram created using drawio</figcaption></figure><p>With the Internet Gateway handling the inbound and outbound connectivity for public resources. The challenge is now to enable outbound connectivity for private resources. That’s where the <strong>NAT Gateway</strong> comes in, providing outbound-only internet access to private subnets while keeping them isolated from incoming traffic.</p><h4>NAT Gateway (NGW): Enabling Secure Outbound Access for Private Subnets</h4><p>Private subnets are isolated subnets with no direct Internet Access. Therefore, EC2 instances in these subnets cannot communicate with the public Internet using the <strong>IGW </strong>in order to download packages or reach public APIs for example<strong>. </strong>By deploying a <strong>NAT Gateway (NGW)</strong> and correctly setting up the routing for private subnets, you can easily solve this issue and grant outbound Internet Access to instances in private subnets without actually exposing them the the internet.</p><p><strong>Key Takeaways for NAT Gateways:</strong></p><ul><li>They must reside in a <strong>public subnet</strong> and use an <strong>Elastic IP</strong>.</li><li>Private instances <strong>do not</strong> need public IPs; their traffic is translated by the NAT Gateway.</li><li>The NAT Gateway forwards responses back to the originating private instance, but <strong>does not allow inbound</strong> connections from the internet.</li><li>The routing must be configured correctly: Private subnets should route 0.0.0.0/0 to the <strong>NGW</strong> of the same AZ (in case of deploying one NAT Gateway per AZ — for high availability).</li><li>AWS charges for NAT Gateways on an hourly basis and on each gigabyte of data that it processes; heavy S3/DynamoDB traffic should use <strong>VPC Endpoints</strong> instead of <strong>NAT</strong>.</li></ul><p><strong>Internet Access Workflow for Private instances:</strong></p><p>As we mentioned above, NGW are a must in order to grant private instance access to the Internet. Below is a detailed workflow with all the steps involved in a request from a private instance to the public internet and back to the instance.</p><ol><li><strong>Private EC2 initiates a request: </strong>The instance sends outbound traffic using its private IP.</li><li><strong>The Private Subnet route table forwards the traffic: </strong>Since the destination is outside the VPC, the private subnet’s route table sends 0.0.0.0/0 to the <strong>NAT Gateway</strong>.</li><li><strong>Traffic reaches the NAT Gateway in the public subnet.</strong></li><li><strong>The NAT Gateway translates the source IP: </strong>The private IP is replaced with the <strong>NAT Gateway’s Elastic IP</strong> (public IP), This mecanism is called SNAT (Source Network Address Translation).</li><li><strong>NAT Gateway sends traffic to the IGW: </strong>Because the NAT Gateway is in a public subnet, its route table forwards the packet to the <strong>Internet Gateway</strong>.</li><li><strong>Internet Gateway sends the traffic to the internet: </strong>The IGW processes the outbound request and routes it to the external destination.</li><li><strong>Response returns from the internet: </strong>The response packet is addressed to the NAT Gateway’s Elastic IP.</li><li><strong>NAT Gateway performs reverse translation: </strong>The NGW maps the returning packet back to the original private Ip and the original ephemeral port. This ensures the correct EC2 instance receives it.</li><li><strong>Packet is sent back into the private subnet: </strong>The NAT Gateway forwards the packet over the VPC’s internal network.</li><li><strong>Private EC2 receives the response: </strong>The instance gets the data as if it communicated directly with the internet — even though it stays private the entire time.</li></ol><p>Below is an architecture diagram to better understand where the <strong>NGW</strong> fits into the VPC architecture, as well as how the traffic flows from Private Subnets to the Internet</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*LAHm5cbnr9qxcYAi_CQsUw.png" /><figcaption>NGW and IGW Architecture diagram created using drawio</figcaption></figure><h4>👨‍💻 Terraform Implementation</h4><p>In this hands-on section, we will see how to create the architecture described in the previous section, since it encompasses all the concepts discussed in both the previous <a href="https://medium.com/aws-in-plain-english/aws-networking-fundamentals-understanding-vpcs-subnets-and-ip-addressing-b667fe0a94ae">article</a> and this one, i.e The VPC, Subnets, IGW and NGW.</p><p>This time, we won’t be writing all the Terraform code from scratch, just like we did in the previous article, but we will make use of the Terraform official community VPC module (check this <a href="https://github.com/terraform-aws-modules/terraform-aws-vpc/tree/master">link</a> to see the entire VPC module). By doing so, we can quickly set up our infrastructure without having to write hundreds of lines of code.</p><p>Below is the code required to deploy our AWS Network Architecture. All the necessary resources will be created automatically, everything is handled within the Terraform module.</p><pre>module &quot;vpc&quot; {<br>  source = &quot;terraform-aws-modules/vpc/aws&quot;<br>  version = &quot;~&gt; 5.0&quot;<br><br>  name = &quot;test-vpc&quot;<br>  cidr = &quot;10.0.0.0/16&quot;<br><br>  azs             = [&quot;eu-west-3a&quot;, &quot;eu-west-3b&quot;]<br>  private_subnets = [&quot;10.0.1.0/24&quot;, &quot;10.0.2.0/24&quot;]<br>  public_subnets  = [&quot;10.0.101.0/24&quot;, &quot;10.0.102.0/24&quot;]<br><br>  enable_nat_gateway = true<br>  single_nat_gateway = false<br>  one_nat_gateway_per_az = true<br><br>  tags = {<br>    Owner = &quot;platform-team&quot; <br>  }<br>}</pre><p>The only thing left is to run the terraform workflow commands: terraform init , terraform planand terraform apply after making sure that the aws provider is correctly configured. Using the terraform state list command, you can display all the deployed resources as shown below.</p><pre>module.vpc.aws_default_network_acl.this[0]<br>module.vpc.aws_default_route_table.default[0]<br>module.vpc.aws_default_security_group.this[0]<br>module.vpc.aws_eip.nat[0]<br>module.vpc.aws_eip.nat[1]<br>module.vpc.aws_internet_gateway.this[0]<br>module.vpc.aws_nat_gateway.this[0]<br>module.vpc.aws_nat_gateway.this[1]<br>module.vpc.aws_route.private_nat_gateway[0]<br>module.vpc.aws_route.private_nat_gateway[1]<br>module.vpc.aws_route.public_internet_gateway[0]<br>module.vpc.aws_route_table.private[0]<br>module.vpc.aws_route_table.private[1]<br>module.vpc.aws_route_table.public[0]<br>module.vpc.aws_route_table_association.private[0]<br>module.vpc.aws_route_table_association.private[1]<br>module.vpc.aws_route_table_association.public[0]<br>module.vpc.aws_route_table_association.public[1]<br>module.vpc.aws_subnet.private[0]<br>module.vpc.aws_subnet.private[1]<br>module.vpc.aws_subnet.public[0]<br>module.vpc.aws_subnet.public[1]<br>module.vpc.aws_vpc.this[0]</pre><h4>🎯 Wrapping Up</h4><p>In this article, we explored how to give Internet connectivity to your VPC using <strong>Internet Gateways</strong> for public subnets and <strong>NAT Gateways</strong> for private subnets. Along with a Terraform implementation of all these concepts.</p><p><strong>Next in the series → Security in the VPC:</strong><br>We’ll dive into <strong>Security Groups</strong> and <strong>Network ACLs (NACLs)</strong> — AWS’s primary tools for controlling inbound and outbound traffic.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b86982a7c70" width="1" height="1" alt=""><hr><p><a href="https://aws.plainenglish.io/internet-connectivity-in-aws-internet-gateways-and-nat-gateways-9b86982a7c70">Internet Connectivity in AWS: Internet Gateways and NAT Gateways</a> was originally published in <a href="https://aws.plainenglish.io/">AWS in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Networking Fundamentals: Understanding VPCs, Subnets, and IP Addressing]]></title>
            <link>https://aws.plainenglish.io/aws-networking-fundamentals-understanding-vpcs-subnets-and-ip-addressing-b667fe0a94ae?source=rss-9e7316d43131------2</link>
            <guid isPermaLink="false">https://medium.com/p/b667fe0a94ae</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Youness Zarhali]]></dc:creator>
            <pubDate>Tue, 30 Sep 2025 21:53:14 GMT</pubDate>
            <atom:updated>2025-10-14T05:50:42.125Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4IEcWqoZLdiHnYoK1YEf1Q.png" /><figcaption>Credits: AI Generated Image for Visual Representation.</figcaption></figure><p>Let’s be straightforward, Networking is the backbone of every Cloud infrastructure. Before deploying any application, your network must be well-designed and properly deployed while keeping in mind several challenges such as ip segmentation, high availability and security— in short, your network design must be flawless. In order to be able to address these challenges, you need to first have a solid understanding of how AWS organizes its global infrastructure, how Virtual Private Clouds (VPCs) work, and how IP addressing and subnets fit into the picture. This article lays the foundation for mastering AWS Networking and will be the first in our AWS Networking Series. We will not only explain all the concepts mentioned earlier, but we will also include a Terraform coding section to demonstrate how we can implement these concepts in a more tangible manner.</p><h3>🌍 <strong>AWS Global Infrastructure</strong></h3><p>First, let’s start with a few definitions. AWS organizes its infrastructure into regions and availability zones. A region is a geographical location somewhere in the world where data centers are grouped. In order to enable the highest possible fault tolerance and maximum stability, AWS regions are completely isolated from one another. Also, each region includes at least three isolated and physically separated group of data centers called Availability Zones (AZs). For exemple, the Paris region eu-west-3 has three availability zones eu-west-3a , eu-west-3b and eu-west-3c .</p><p>It is extremely important to understand how the AWS global infrastructure is structured in order to get a good grasp of AWS Networking. Here, two key points should be kept in mind:</p><ul><li><strong>VPCs</strong> are <strong>regional:</strong> When you create a VPC, it automatically spans all availability zones (AZs) in that region.</li><li><strong>Subnets </strong>are <strong>zonal</strong>. Each subnet is deployed in one AZ, this is where your workloads will be deployed.</li></ul><h3>🌐 AWS Networking Fundamentals</h3><p>To fully understand the AWS network, you must first get familiar with three key elements: <strong>VPCs</strong>, <strong>CIDR blocks</strong>, and <strong>Subnets</strong>. These are the basic elements that define the structure of your network and how resources connect to it.</p><h4>Virtual Private Cloud</h4><p>A Virtual Private Cloud (VPC) is your isolated network inside the AWS cloud. Consider it as your private data center in the cloud, where you have full control over IP addressing, routing, and connectivity. Here are a few things to be aware of when it comes to VPCs:</p><ul><li><strong>Resource isolation:</strong> VPCs provide logical separation between workloads, so workloads in one VPC are separated from those of another.</li><li><strong>Default vs Custom</strong>: Each AWS account comes with a pre-configured, ready-to-use default VPC. This VPC is fine for testing but custom VPCs are a must for production workloads.</li><li><strong>IP addressing: </strong>VPCs let you define your own private IP address range using CIDR blocks.</li><li><strong>Service limits:</strong> Be aware of AWS limits (number of VPCs, subnets per VPC, etc.).</li></ul><p>In short, the VPC is the backbone of your cloud infrastructure, and everything else is built on top of it. Understanding it, in great detail, will help you master how traffic flows through the AWS network, allowing you to architect and implement effective cloud solutions.</p><h4>CIDR and IP Addressing</h4><p>When creating a VPC, you need to define its IP address range, which tells how many IP addresses are available inside your VPC. AWS uses <strong>CIDR </strong>notation to describe network ranges. Here are some key elements regarding CIDR and IP addressing in AWS:</p><ul><li><strong>CIDR notation:</strong> Written as &lt;network&gt;/&lt;prefix&gt;, for example 10.0.0.0/16.</li><li><strong>Private ranges: </strong>Use addresses from the RFC 1918 ranges (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16).</li><li><strong>VPC CIDR size: </strong>Must be between/28 (16 addresses) and /16 (65,536 addresses).</li><li><strong>Multiple CIDR blocks:</strong> You can associate more than one CIDR block with a VPC if you need to expand.</li><li><strong>Reserved IP addresses:</strong> AWS reserves 5 IP addresses (the first <strong>four</strong> and the last <strong>one</strong>) in every subnet for networking purposes (e.g., network address, VPC router, DNS, future use, and broadcast).</li><li><strong>Subnetting:</strong> You divide your VPC CIDR into smaller blocks (subnets) to organize resources across Availability Zones.</li></ul><h4>Subnets: Public and Private</h4><p>Subnets are subsets of your VPC and are linked to a specific availability zone. By default, subnets are just ranges of IP addresses, but they take on different roles — private or public, depending on how you configure their routing. Let’s dive a little in the difference between public and private subnets:</p><ul><li><strong>Public Subnets</strong>: These subnets are directly connected to the internet via an Internet Gateway. You typically deploy your load balancers or web servers in these subnets.</li><li><strong>Private subnets</strong>: These subnets do not have direct access to the internet. To grant them internet access, you must use a NAT Gateway and configure the routing accordingly.</li></ul><p>Some of the key information and best practices around Subnets are the following:</p><ul><li><strong>Zonal scope:</strong> Each subnet exists in exactly one Availability Zone.</li><li><strong>Workload separation:</strong> Separate workloads by function (e.g., public applications vs. internal systems).</li><li><strong>High availability:</strong> Best practice is to spread subnets across multiple AZs for redundancy.</li></ul><h3>👨‍💻 Terraform Implementation</h3><p>In a previous <a href="https://medium.com/@youness.zarhali/list/terraform-unlocked-mastering-infrastructure-as-code-105fe7243fc6">series</a>, we introduced Terraform and explained several concepts related to this tool, so we will capitalize on this and use Terraform to deploy the resources in this series dedicated to AWS Networking.</p><h4>Project description and Coding section</h4><p>The following diagram explains the VPC architecture we are deploying and the related IP addressing plan. We are going to put into practice the different concepts we tackled in this article: Regions, AZs, VPC and Subnets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*yLdjR16Voe1Ntgqc66x45w.png" /><figcaption>Architecture diagram created with drawio</figcaption></figure><p>Below you will find the structure of our project. For this implementation section, we will make use of Terraform Modules.</p><pre>├── aws-vpc-infrastructure<br>   ├── module<br>   │   └── vpc<br>   │       ├── main.tf<br>   │       ├── outputs.tf<br>   │       ├── variables.tf<br>   │       └── versions.tf<br>   └── vpc.tf</pre><p>Let’s break down the content of each file of our VPC module:</p><pre># versions.tf<br>terraform {<br>  required_version = &quot;&gt;= 1.3.10&quot;<br>  required_providers {<br>    aws = {<br>      source  = &quot;hashicorp/aws&quot;<br>      version = &quot;&gt;= 5.75.0&quot;<br>    }<br>  }<br>}</pre><pre># variarbles.tf<br><br>variable &quot;enabled&quot; {<br>  type        = bool<br>  default     = true<br>  description = &quot;Wether or not to create the VPC&quot;<br>}<br><br>variable &quot;vpc_configuration&quot; {<br>  description = &quot;VPC configuration object variable&quot;<br>  type = object({<br>    name                 = string<br>    cidr_block           = string<br>    enable_dns_support   = optional(bool, true)<br>    enable_dns_hostnames = optional(bool, true)<br>  })<br>}<br><br><br>variable &quot;subnets&quot; {<br>  description = &quot;List of subnets to create in the VPC&quot;<br>  type = list(object({<br>    type       = string<br>    az         = string<br>    cidr_block = string<br>  }))<br>  validation {<br>    condition = alltrue([<br>      for s in var.subnets : contains([&quot;public&quot;, &quot;private&quot;], s.type)<br>    ])<br>    error_message = &quot;Each subnet type must be either &#39;public&#39; or &#39;private&#39;.&quot;<br>  }<br>}<br><br>variable &quot;default_tags&quot; {<br>  description = &quot;Default tags to be applied to resources&quot;<br>  type        = map(string)<br>  default     = {}<br><br>}</pre><pre># main.tf<br><br>resource &quot;aws_vpc&quot; &quot;this&quot; {<br>  count                = var.enabled ? 1 : 0<br>  cidr_block           = var.vpc_configuration.cidr_block<br>  enable_dns_support   = var.vpc_configuration.enable_dns_support<br>  enable_dns_hostnames = var.vpc_configuration.enable_dns_hostnames<br><br>  tags = merge(var.default_tags,<br>    { Name = var.vpc_configuration.name }<br>  )<br>}<br><br><br>resource &quot;aws_subnet&quot; &quot;this&quot; {<br>  for_each = { for s in var.subnets : format(&quot;%s-%s&quot;, s.type, s.az) =&gt; s }<br><br>  vpc_id                  = aws_vpc.this[0].id<br>  cidr_block              = each.value.cidr_block<br>  availability_zone       = each.value.az<br>  map_public_ip_on_launch = each.value.type == &quot;public&quot; ? true : false<br><br>  tags = merge(var.default_tags, {<br>    Name = &quot;${each.value.type}-${each.value.az}&quot;<br>  })<br>}</pre><pre># outputs.tf<br><br>output &quot;vpc&quot; {<br>  description = &quot;VPC details&quot;<br>  value = {<br>    &quot;${var.vpc_configuration.name}&quot; = {<br>      id   = aws_vpc.this[0].id<br>      cidr = aws_vpc.this[0].cidr_block<br>    }<br>  }<br>}<br><br>output &quot;subnets&quot; {<br>  description = &quot;Subnets details&quot;<br>  value = {<br>    for s in var.subnets :<br>    format(&quot;%s-%s&quot;, s.type, s.az) =&gt; {<br>      id         = aws_subnet.this[format(&quot;%s-%s&quot;, s.type, s.az)].id<br>      cidr_block = aws_subnet.this[format(&quot;%s-%s&quot;, s.type, s.az)].cidr_block<br>    }<br>  }<br>}</pre><p>Now let’s display the content of the vpc.tf file :</p><pre>module &quot;vpc&quot; {<br>  source = &quot;./module/vpc&quot;<br><br>  enabled = true<br><br>  vpc_configuration = {<br>    name       = &quot;test-vpc&quot;<br>    cidr_block = &quot;10.0.0.0/16&quot;<br>  }<br><br>  subnets = [<br>    { type = &quot;public&quot;, az = &quot;eu-west-3a&quot;, cidr_block = &quot;10.0.0.0/21&quot; },<br>    { type = &quot;public&quot;, az = &quot;eu-west-3b&quot;, cidr_block = &quot;10.0.8.0/21&quot; },<br>    { type = &quot;public&quot;, az = &quot;eu-west-3c&quot;, cidr_block = &quot;10.0.16.0/21&quot; },<br>    { type = &quot;private&quot;, az = &quot;eu-west-3a&quot;, cidr_block = &quot;10.0.24.0/21&quot; },<br>    { type = &quot;private&quot;, az = &quot;eu-west-3b&quot;, cidr_block = &quot;10.0.32.0/21&quot; },<br>    { type = &quot;private&quot;, az = &quot;eu-west-3c&quot;, cidr_block = &quot;10.0.40.0/21&quot; },<br>  ]<br><br>  default_tags = {<br>    Owner = &quot;platform-team&quot;<br>  }<br>}<br><br># output section <br>output &quot;vpc&quot; {<br>    value = module.vpc.vpc <br>}<br><br>output &quot;subnets&quot; {<br>    value = module.vpc.subnets<br>  <br>}</pre><p>The only thing left is to run the terraform workflow commands: terraform init , terraform planand terraform apply at the root of the project.</p><h4>Interesting Points</h4><p>Here are some key takeaways from the previous coding section:</p><ul><li>We used object variable for both the VPC and Subnets configurations, which makes the configuration scalable and clean.</li><li>Validation block to make sure the subnet type is either privateor public which prevents invalid input before resources are created.</li><li>Dynamically compute the name of the subnets as type-az (e.g.public-eu-west-3a).</li><li>Using<strong> </strong>for_each meta-argument to avoid repeating the resource block for each subnet, which makes scaling to more subnets much easier.</li><li>Structured outputs which makes it easy to reference them programmatically in other modules or Terraform configurations. Let’s see how the outputs are presented :</li></ul><pre>subnets = {<br>  &quot;private-eu-west-3a&quot; = {<br>    &quot;cidr_block&quot; = &quot;10.0.24.0/21&quot;<br>    &quot;id&quot; = &quot;subnet-0e7e24196441f00a1&quot;<br>  }<br>  &quot;private-eu-west-3b&quot; = {<br>    &quot;cidr_block&quot; = &quot;10.0.32.0/21&quot;<br>    &quot;id&quot; = &quot;subnet-0c9f23a23db57531e&quot;<br>  }<br>  &quot;private-eu-west-3c&quot; = {<br>    &quot;cidr_block&quot; = &quot;10.0.40.0/21&quot;<br>    &quot;id&quot; = &quot;subnet-03bb847fe4fd84e18&quot;<br>  }<br>  &quot;public-eu-west-3a&quot; = {<br>    &quot;cidr_block&quot; = &quot;10.0.0.0/21&quot;<br>    &quot;id&quot; = &quot;subnet-03caeb350649bbb4c&quot;<br>  }<br>  &quot;public-eu-west-3b&quot; = {<br>    &quot;cidr_block&quot; = &quot;10.0.8.0/21&quot;<br>    &quot;id&quot; = &quot;subnet-048645771ba20a6b0&quot;<br>  }<br>  &quot;public-eu-west-3c&quot; = {<br>    &quot;cidr_block&quot; = &quot;10.0.16.0/21&quot;<br>    &quot;id&quot; = &quot;subnet-020f3887d0177556b&quot;<br>  }<br>}<br>vpc = {<br>  &quot;test-vpc&quot; = {<br>    &quot;cidr&quot; = &quot;10.0.0.0/16&quot;<br>    &quot;id&quot; = &quot;vpc-0f05c514ee78547a8&quot;<br>  }<br>}</pre><h3>🎯 Wrapping Up</h3><p>The purpose of this article was to present the basic elements that enable an understanding of the AWS Networking. We covered the following topics: AWS global infrastructure, the basics of AWS VPC, IP addressing and Subnets. We also included a terraform coding section that implements all the covered topics. The goal of this series is not only to explain concepts but also to put these ideas into action.</p><p>This is just the beginning. In the next article, we’ll extend this setup by introducing <strong>Internet Gateways and NAT Gateways</strong>, so your resources can have internet access.</p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b667fe0a94ae" width="1" height="1" alt=""><hr><p><a href="https://aws.plainenglish.io/aws-networking-fundamentals-understanding-vpcs-subnets-and-ip-addressing-b667fe0a94ae">AWS Networking Fundamentals: Understanding VPCs, Subnets, and IP Addressing</a> was originally published in <a href="https://aws.plainenglish.io/">AWS in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Terraform Workspaces: Managing Deployments Across Multiple Environments]]></title>
            <link>https://faun.pub/terraform-workspaces-managing-deployments-across-multiple-environments-1517c5f96fd5?source=rss-9e7316d43131------2</link>
            <guid isPermaLink="false">https://medium.com/p/1517c5f96fd5</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[iac]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Youness Zarhali]]></dc:creator>
            <pubDate>Sun, 31 Aug 2025 21:56:30 GMT</pubDate>
            <atom:updated>2025-09-07T12:07:25.365Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wMuvx1F1t981LOEf" /><figcaption>Credits: AI Generated Image for Visual Representation.</figcaption></figure><p>Over the past articles in our <a href="https://medium.com/@youness.zarhali/list/terraform-unlocked-mastering-infrastructure-as-code-105fe7243fc6">series</a>, we have gradually deepened our understanding of Terraform and are now getting closer to mastering it. We started with basics, learning how to define and provision cloud infrastructure. From there, we explored loops, variables, functions and modules which gave us the ability to write clean, reusable and dynamic code. And most recently, we tackled state management, and learned why setting up remote state is critical when managing cloud infrastructures as a team. Now that we’ve laid this foundation, it’s time to move one step further and see how to manage multiple environments in a clean and scalable way using <strong>Terraform Workspaces.</strong></p><h3>🙋🏻 Why Workspaces ?</h3><p>In real-world scenarios, terraform configuration differs from one environment to another. The most commonly used breakdown of environments is as follows:</p><ul><li><strong>Development</strong>: For frequent changes and experimental deployments</li><li><strong>Staging</strong> : Production-like set up used for testing purposes</li><li><strong>Production</strong>: Stable configuration.</li></ul><p>Worskpaces allow you to manage the configuration of the previously mentioned environments without changing the terraform code. Which means that without changing your code or switching between different directories, you can still deploy infrastructure in multiple environments. Leveraging Terraform Workspaces helps you keep your code DRY (Don’t Repeat Yourself) and allows you to handle multiple configurations based on the different environment in an intelligent and clean approach.</p><p>Below are some of the <strong>Best Practices</strong> regarding the use of <strong>Workspaces</strong> :</p><ul><li><strong>Name Terraform Workspaces clearly and consistently</strong> : Stick to clear, predictable names (dev, staging, prod) so your team immediately knows which environment is being targeted and most importantly avoid using vague names like sandbox-poject or test1.</li><li><strong>Use Remote Backend Storage for State Management</strong>: Always use a remote backend so that workspace states are stored centrally and securely. This prevents conflicts and ensures that all team members are working with a single source of truth.</li><li><strong>Keep Environment-Specific Config in Variables: </strong>Store environment-specific values in <strong>separate variable files</strong> and not in the main configuration.</li></ul><h3>🧑🏻‍💻 Hands-on section</h3><p>Let’s get our hands dirty ! In this section, we will see how to work with Terraform Workspaces from the command line. We will also look at a complete example of a Terraform Project that uses different workspaces and take a closer look at the code benefits that workspaces offer.</p><p>Note that the terraform CLI provides straightforward commands to handle workspaces so no additional software needs to be installed. Below is a code snippet with the most used commands when working with Workspaces:</p><pre># Displays the current workspace. The default value is: &quot;default&quot;<br>terraform workspace show <br><br># Shows all available workspaces<br>terraform workspace list <br><br># Creates a new workspace with the given name<br>terraform workspace new &lt;workspace_name&gt;<br><br># Selects an existing workspace<br>terraform workspace select &lt;workspace_name&gt;<br><br># Removes a workspace (you cannot delete the “default” workspace or the workspace you are currently in).<br>terraform workspace delete &lt;workspace_name&gt;<br></pre><p>As explained in the first section, one of the biggest advantages of Terraform workspaces is the ability to reuse the same configuration for multiple environments. This ensures consistency, reduces code duplication, and makes deployments safer. Let’s walk through a practical example ( deploying an ec2 instance) to see how this works in action.</p><p><strong>📁 Project Directory structure:</strong></p><pre>terraform-ec2-instance/<br>├── main.tf<br>├── variables.tf<br>├── outputs.tf<br>└── env/<br>    ├── dev.tfvars           <br>    ├── staging.tfvars       <br>    └── prod.tfvars          </pre><h4>☕︎<strong> Terraform HCL Code :</strong></h4><pre># main.tf file <br><br>terraform {<br>  required_version = &quot;&gt;= 1.5.0&quot;<br><br>  required_providers {<br>    aws = {<br>      source  = &quot;hashicorp/aws&quot;<br>      version = &quot;~&gt; 5.0&quot;<br>    }<br>  }<br>  backend &quot;s3&quot; {<br>    bucket               = &quot;terraform-infrastructure-remote-state-s3-bucket&quot;<br>    key                  = &quot;terraform.tfstate&quot;<br>    region               = &quot;eu-west-3&quot;<br>    workspace_key_prefix = &quot;infrastructure&quot;<br>    encrypt              = true<br>    use_lockfile         = true<br>  }<br>}<br><br># EC2 instance<br>resource &quot;aws_instance&quot; &quot;this&quot; {<br>  ami           = var.ami_id<br>  instance_type = var.instance_type<br><br>  tags = {<br>    Name = &quot;${terraform.workspace}-app-server&quot;<br>    Env  = &quot;${terraform.workspace}&quot;<br>  }<br>}</pre><pre># variables.tf file<br><br>variable &quot;aws_region&quot; {<br>  description = &quot;AWS region to deploy resources&quot;<br>  type        = string<br>  default     = &quot;eu-west-3&quot;<br>}<br><br>variable &quot;ami_id&quot; {<br>  description = &quot;AMI to use for the instance&quot;<br>  type        = string<br>}<br><br>variable &quot;instance_type&quot; {<br>  description = &quot;EC2 instance type&quot;<br>  type        = string<br>}</pre><pre># outputs.tf file <br><br>output &quot;instance_id&quot; {<br>  value = aws_instance.this.id<br>}<br><br>output &quot;public_ip&quot; {<br>  value = aws_instance.this.public_ip<br>}</pre><p><strong>🔹 Environment variable files (</strong><strong>env/)</strong></p><pre># dev.tfvars file <br><br>ami_id        = &quot;ami-0a4d45bf44591e8bc&quot;<br>instance_type = &quot;t2.micro&quot;</pre><pre># staging.tfvars file <br><br>ami_id        = &quot;ami-0a4d45bf44591e8bc&quot;<br>instance_type = &quot;t3.small&quot;</pre><pre># prod.tfvars file <br><br>ami_id        = &quot;ami-0a4d45bf44591e8bc&quot;<br>instance_type = &quot;t3.medium&quot;</pre><p>🚀 <strong>Key explanations and deployment method</strong></p><ul><li>Each workspace gets its own EC2 instance.</li><li>The <strong>${terraform.workspace}</strong> variable makes it easy to name resources differently depending on the environment. This makes our configuration code more dynamic. We also added different <strong>*.tfvars </strong>files that hold environment-specific configurations.</li><li>Note that when using the default workspace, the state is stored in the location specified in the <strong>key</strong>input variable inside the backend configuration block. However when configuring other workspaces, just like in our case, the state of each workspace is stored using the path <strong>&lt;workspace_key_prefix&gt;/&lt;workspace_name&gt;/&lt;key&gt; . </strong>This way each workspace has its own separated state. The structure of the state S3 bucket according to our configuration will be as follows:</li></ul><pre>terraform-infrastructure-remote-state-s3-bucket/<br>└── infrastructure/<br>    ├── dev/<br>    │   └── terraform.tfstate<br>    ├── prod/<br>    │   └── terraform.tfstate<br>    └── staging/<br>        └── terraform.tfstate</pre><ul><li>The following steps should be followed in order to deploy the infrastructure depending on the workspace we are targeting:</li></ul><pre># First, Create the different workspaces<br>terraform workspace new dev<br>terraform workspace new staging<br>terraform workspace new prod<br><br># Then select a workspace (staging for example) <br>terraform workspace select staging<br><br># Finally deploy the infrastructure<br>terraform apply -var-file=&quot;env/staging.tfvars&quot;</pre><h3>🎯 Final Thoughts</h3><p>As we have seen throughout this article, Terraform Workspaces bring more clarity to our code and more structure to our deployments. Combined with modules, and remote state management, they enable infrastructure teams to work safely, collaboratively and at scale.</p><p>With this final step, we concluded our series dedicated to Mastering Terraform. We explored some of the most important building blocks for managing cloud infrastructure at scale: starting from the very basics, to mastering variables, using modules, functions, loops and configuring remote state and finally arriving at workspaces to control multiple environments with ease. Keep in mind that your journey with Terraform has just started and there are many other things to tackle but we chose these concepts because they will forever be part of your journey and by combining them all together your infrastructure code will be <strong>more reliable, maintainable, and adaptable</strong> to future growth.</p><p>👉 If you’re new here, and want to get the full picture, here is the link to my Terraform series: <a href="https://medium.com/@youness.zarhali/list/terraform-unlocked-mastering-infrastructure-as-code-105fe7243fc6">https://medium.com/@youness.zarhali/list/terraform-unlocked-mastering-infrastructure-as-code-105fe7243fc6</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*B-LH_wC_fnfuxfHb.png" /></figure><h4>👋 If you find this helpful, please click the clap 👏 button below a few times to show your support for the author 👇</h4><h4>🚀<a href="http://from.faun.to/r/8zxxd">Join FAUN Developer Community &amp; Get Similar Stories in your Inbox Each Week</a></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1517c5f96fd5" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/terraform-workspaces-managing-deployments-across-multiple-environments-1517c5f96fd5">Terraform Workspaces: Managing Deployments Across Multiple Environments</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Terraform State Management Demystified: From Local to Remote]]></title>
            <link>https://faun.pub/terraform-state-management-demystified-from-local-to-remote-b18f547102d1?source=rss-9e7316d43131------2</link>
            <guid isPermaLink="false">https://medium.com/p/b18f547102d1</guid>
            <category><![CDATA[iac]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Youness Zarhali]]></dc:creator>
            <pubDate>Mon, 25 Aug 2025 09:05:54 GMT</pubDate>
            <atom:updated>2025-09-07T12:10:23.799Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UHocxj__YsMOvjM98S4CpA.png" /><figcaption>Credits: AI Generated Image for Visual Representation.</figcaption></figure><p>Through our <a href="https://medium.com/@youness.zarhali/list/terraform-unlocked-mastering-infrastructure-as-code-105fe7243fc6">series</a> dedicated to mastering Terraform, we had the opportunity to discuss various topics such as the deployment workflow, variables, loops, functions and modules. At this stage, we have acquired a solid foundation and mastery of various concepts, enabling us to deliver high-quality, modular, scalable code that is easy to maintain by a team of cloud and platform engineers. Building on that foundation, this article will be dedicated to State Management and Remote State. Having a clear understanding of this matter is an essential element in order to level up and start managing cloud infrastructure at scale.</p><h3>🙋🏻 Terraform State: What is it and Why it’s Important ?</h3><p>When applying your infrastructure code, Terraform not only creates or updates cloud resources, it also stores metadata about them in a state file named terraform.tfstate. Without this file, Terraform would have no way of knowing which resources are already created and which are not. In fact, the state file allows Terraform to :</p><ul><li><strong>Track resources</strong>: Know which resources are already created and their current specifications.</li><li><strong>Plan changes efficiently</strong>: Compare desired vs. actual infrastructure.</li><li><strong>Handle dependencies</strong>: Ensure resources are created or destroyed in the correct order.</li></ul><p>⚠️ <strong>Problem</strong>: By default, Terraform stores the state locally. This works fine for experiments and testing purposes, however when managing the infrastructure as a team, this could cause various problems such as <strong>drift </strong>since team members could have different versions of the state file, or state file <strong>security </strong>issues as sensitive data will be exposed in plain text and shared across team members. Let’s see how to solve these issues in the next section.</p><h3>☁️ Remote State Management</h3><p>This section will contain everything you need to know in order to deeply understand Remote State Management, this includes concepts and hands-on configurations.</p><h4>🧑🏻‍💻 Remote State Configuration</h4><p>The Remote State approach consists of storing the state file in a c<strong>entralized and shared backend </strong>accessible to all team members. By doing so, we are solving all the problems described in the previous section. Among the most frequently used remote backends, we can list: <strong>AWS</strong> <strong>S3, Google Cloud Storage (GCS), Azure Blob Storage.</strong></p><p>Here are the benefits of using remote backend for State Management:</p><ul><li><strong>Collaboration:</strong> Everyone works with a single source of truth.</li><li><strong>Security:</strong> State can be encrypted and access-controlled.</li><li><strong>Locking:</strong> Prevents two people from updating state at the same time.</li><li><strong>Automation-ready:</strong> Integrates with CI/CD pipelines.</li></ul><p>Now that we are familiar with the idea, let’s see how to set it up using an <strong>S3 bucket</strong> as our remote state.</p><pre>terraform {<br>  backend &quot;s3&quot; {<br>    bucket         = &quot;terraform-infrastructure-remote-state-s3-bucket&quot;<br>    key            = &quot;infrastructure/terraform.tfstate&quot;<br>    region         = &quot;eu-west-3&quot;<br>    encrypt        = true<br>    use_lockfile   = true<br>  }<br>}</pre><p>Here is what each input represents:</p><ul><li><strong>bucket</strong> : S3 bucket where the state file will be stored.</li><li><strong>key</strong> : Path inside the S3 bucket where the state file will be stored ( useful to separate environments state files).</li><li><strong>region</strong>: AWS region where the S3 bucket is located.</li><li><strong>encrypt:</strong> Ensures sensitive data is protected.</li><li><strong>use_lockfile</strong>: Whether to use a lockfile for locking the state (This is a new feature, check the explanations below).</li></ul><p>💡 <strong>Important Notes:</strong></p><ul><li>Make sure that the user or role you are using has the necessary permissions in order to properly interact with the S3 bucket during State Operations. You can check the official Terraform documentation regarding permissions here: <a href="https://developer.hashicorp.com/terraform/language/backend/s3#permissions-required">https://developer.hashicorp.com/terraform/language/backend/s3#permissions-required</a></li><li>When different team members (or CI/CD pipelines) run Terraform at the same time, there is a risk of <strong>modifying the state file simultaneously</strong>. This can corrupt the state or cause conflicts. <strong>State locking</strong> prevents this problem by ensuring that only one Terraform operation can modify the state at a time.</li><li>In older setups (e.g., using <strong>S3 backend</strong>), a <strong>DynamoDB table</strong> was required for locking. Terraform would create a lock entry in DynamoDB while an operation was running. Now that S3 buckets support <strong>object locking</strong>, Terraform (starting from version 1.10.0), has fully supported the <strong>use_lockfile</strong>attribute to enable<strong> built-in locking </strong>for S3 backend — no need for a separate DynamoDB table. This simplifies configuration and reduces the operational burden. A<strong>backend</strong> configuration section in older setups would look like this:</li></ul><pre>terraform {  <br>  backend &quot;s3&quot; {  <br>    bucket         = &quot;terraform-infrastructure-remote-state-s3-bucket&quot;  <br>    key            = &quot;infrastructure/terraform.tfstate&quot;  <br>    region         = &quot;eu-west-3&quot; <br>    dynamodb_table = &quot;infrastructure-dynamodb-lock-table&quot;  <br>    encrypt        = true  <br>  }  <br>}</pre><h4>🛠 ️How to interact with the State using CLI</h4><p>Terraform gives you several built-in CLI commands to inspect and manipulate the <strong>state file</strong> directly. While you should avoid to manually edit the state file, using the CLI commands can be very useful for troubleshooting, debugging, or advanced workflows.</p><p>Here are some scenarios you might encounter when managing Terraform State, along with the appropriate command for each use case.</p><pre># Display the resources stored in the state file with their current attributes.<br>terraform show <br><br># Show all resources currently managed in the state file.<br>terraform state list <br><br># Inspect details of a specific resource<br>terraform state show &lt;resource_name&gt;<br><br># Rename a resource in your configuration but keeping the existing state reference.<br>terraform state mv &lt;source&gt; &lt;destination&gt;<br><br># Remove a resource from Terraform&#39;s tracking<br>terraform state rm &lt;resource_name&gt;<br><br># Import exiting resource into the state <br>terraform import &lt;resource_name&gt; &lt;resource_id&gt;<br><br># Force State Unlock<br>terraform force-unlock &lt;LOCK_ID&gt;</pre><h3>✅ Remote State Best Practices</h3><p>I think we can now safely say that using remote state is essential when you are managing cloud infrastructures. Configuring and interacting with the state are not everything. I would like to share some best practices regarding the Remote State I highly advise you to follow when managing cloud infrastructures at scale.</p><ul><li><strong>Enable state locking</strong> : Prevents simultaneous operations from corrupting the state.</li><li><strong>Encrypt your state file</strong> : State often contains sensitive data (like secrets, ARNs, IDs).</li><li><strong>Limit access with IAM policies</strong> : Apply least-privilege access to state storage (e.g., only admins can modify).</li><li><strong>Enable versioning in the backend</strong> : Allows rollback in case of accidental changes or corruption.</li><li><strong>Back up your State File</strong> : Even with remote backends, enable backups (e.g., Cross-region S3 Replication to provide Disaster Recovery in case a region goes down).</li><li><strong>Document state location and backend configuration</strong> : Makes onboarding and troubleshooting easier.</li></ul><h3>🎯 Final Thoughts</h3><p>As we have been able to see throughout this article, Terraform State is the backbone of your Infrastructure As Code. Adopting Remote State backend makes state management scalable, collaborative and safe. Also, bear in mind that mismanaging the state file can lead to serious issues, but with a few best practices, you can ensure your teams work smoothly and securely when deploying and managing cloud resources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*B-LH_wC_fnfuxfHb.png" /></figure><h4>👋 If you find this helpful, please click the clap 👏 button below a few times to show your support for the author 👇</h4><h4>🚀<a href="http://from.faun.to/r/8zxxd">Join FAUN Developer Community &amp; Get Similar Stories in your Inbox Each Week</a></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b18f547102d1" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/terraform-state-management-demystified-from-local-to-remote-b18f547102d1">Terraform State Management Demystified: From Local to Remote</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Terraform Modules: Reuse, Scale, and Organize Your Infrastructure]]></title>
            <link>https://faun.pub/mastering-terraform-modules-reuse-scale-and-organize-your-infrastructure-15ec385c5f8b?source=rss-9e7316d43131------2</link>
            <guid isPermaLink="false">https://medium.com/p/15ec385c5f8b</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[iac]]></category>
            <dc:creator><![CDATA[Youness Zarhali]]></dc:creator>
            <pubDate>Thu, 31 Jul 2025 13:02:29 GMT</pubDate>
            <atom:updated>2025-09-03T15:04:41.899Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xsgD2FN4EQsl3IwI3DnbZQ.png" /><figcaption>Credits: AI Generated Image for Visual Representation.</figcaption></figure><p>Following up on our <a href="https://medium.com/@youness.zarhali/list/terraform-unlocked-mastering-infrastructure-as-code-105fe7243fc6">series</a> on mastering Terraform, we will dedicate this new article to uderstanding the ins and outs of terraform modules. As your infrastructure grows, maintaining readability and manageability becomes more and more difficult. Copy-Pasting terraform code across environments leads to duplication and inconsistency. Terraform modules offer a clean way to write your code once, reuse it anywhere.</p><p>If you are interested in including terraform modules in your infrastructure code, continue reading this article to understand in detail what Terraform modules are, why they are useful, and how you can start using them effectively.</p><h4>📦 What is a Terraform Module ?</h4><p>A module is simply a collection of Terraform configuration files in a directory. Any folder with .tf files can be considered as a module. By default, each terraform configuration is part of the root module, and you can create child modules to include reusable infrastructure components. From my perspective and experience, each module must have the following folder structure, which contains .tf files, each of which holds part of the configuration. By doing so, you make sure that your module is readable, comprehensive and structured.</p><pre>└── terraform-module<br>    ├── data.tf<br>    ├── locals.tf<br>    ├── main.tf<br>    ├── outputs.tf<br>    ├── variables.tf<br>    └── versions.tf</pre><p>Below is a brief description of what each file is for:</p><ul><li>data.tf — Define data sources used to fetch external information.</li><li>locals.tf —Define local variables for reuse and cleaner logic.</li><li>main.tf — Define the core terraform resources of the module.</li><li>outputs.tf — Expose values from the module to parent configurations.</li><li>variables.tf —Declare input variables for the module.</li><li>versions.tf — Define provider and Terraform version constraints.</li></ul><h4>🤷 Why Use Modules ?</h4><p>When working in a production environment, setting IaC standards, and making sure that you write clean and easy to follow terraform code are both very important to better manage your cloud infrastructure. Modules offer an number of advantages that become essential when managing large scale infrastructures :</p><ul><li><strong>Reusability </strong>:<strong> </strong>You can define your Network, Compute or Monitoring stack once, and then use it in different environments such as development, staging and production.</li><li><strong>Abstraction</strong> : Using terraform modules enables you to only expose the necessary variables to the user. You can hide all the implementation details such as : logic, computations, naming conventions and more.</li><li><strong>Maintainability </strong>: Updating a module or fixing a bug in it affects all its uses, there is no need to update the same code multiple times.</li><li><strong>Consistency </strong>: Modules help you enforce IaC standards such as consistent use of tags, naming patterns or policies across all environments.</li></ul><h4>🛠 Terraform Modules In Action</h4><p>Now that we have covered the basics, let’s dive deeper and see how terraform modules actually work. In this section, we will expose a terraform module that provisions an AWS KMS key, an alias for the KMS key and a KMS policy. The key objective behind this section is to showcase each file’s configuration according to the structure we introduced in the first section. Let’s first show our project’s structure.</p><pre>└── aws-infrastructure<br>    ├── kms-key.tf<br>    └── modules<br>        └── kms<br>            ├── data.tf<br>            ├── locals.tf<br>            ├── main.tf<br>            ├── outputs.tf<br>            ├── variables.tf<br>            └── versions.tf</pre><p>Below is the KMS module terraform code.</p><pre># main.tf file <br><br>resource &quot;aws_kms_key&quot; &quot;this&quot; {<br>  count                   = var.enabled ? 1 : 0<br>  deletion_window_in_days = var.kms_key_configuration[&quot;deletion_window_in_days&quot;]<br>  enable_key_rotation     = var.kms_key_configuration[&quot;enable_key_rotation&quot;]<br>  description             = var.kms_key_configuration[&quot;description&quot;]<br>  key_usage               = var.kms_key_configuration[&quot;key_usage&quot;]<br>  multi_region            = var.kms_key_configuration[&quot;multi_region&quot;]<br>  tags                    = var.tags<br>}<br><br>resource &quot;aws_kms_key_policy&quot; &quot;this&quot; {<br>  key_id = aws_kms_key.this[*].id<br>  policy = lookup(var.kms_key_configuration, &quot;policy&quot;, data.aws_iam_policy_document.kms_policy.json)<br>}<br>resource &quot;aws_kms_alias&quot; &quot;this&quot; {<br>  count         = var.enabled ? 1 : 0<br>  name          = local.alias_name<br>  target_key_id = join(&quot;&quot;, aws_kms_key.this[*].id)<br>}</pre><pre># variables.tf file <br><br>variable &quot;enabled&quot; {<br>  type        = bool<br>  default     = true<br>  description = &quot;Wether or not to run this module&quot;<br>}<br><br>variable &quot;aws-region&quot; {<br>  type        = string<br>  description = &quot;AWS Region&quot;<br>  default     = &quot;eu-west-3&quot;<br><br>}<br>variable &quot;kms_key_configuration&quot; {<br>  description = &quot;KMS Key configuration object variable&quot;<br>  type = object({<br>    name                    = string<br>    description             = string<br>    deletion_window_in_days = optional(number, 10)<br>    enable_key_rotation     = optional(bool, true)<br>    policy                  = optional(string, &quot;&quot;)<br>    key_usage               = optional(string, &quot;ENCRYPT_DECRYPT&quot;)<br>    multi_region            = optional(bool, false)<br><br>  })<br>  validation {<br>    condition     = contains([&quot;ENCRYPT_DECRYPT&quot;, &quot;SIGN_VERIFY&quot;, &quot;GENERATE_VERIFY_MAC&quot;], var.kms_key_configuration.key_usage)<br>    error_message = &quot;The key_usage must be either &#39;ENCRYPT_DECRYPT&#39;, &#39;SIGN_VERIFY&#39; or &#39;GENERATE_VERIFY_MAC&#39; &quot;<br>  }<br><br>}<br><br>variable &quot;tags&quot; {<br>  type        = map(any)<br>  description = &quot;Tags for the kms key &quot;<br>  default     = null<br>}</pre><pre># data.tf file<br><br>data &quot;aws_caller_identity&quot; &quot;current&quot; {}<br><br>data &quot;aws_iam_policy_document&quot; &quot;kms_policy&quot; {<br>  statement {<br>    sid    = &quot;&quot;<br>    effect = &quot;Allow&quot;<br><br>    principals {<br>      type        = &quot;AWS&quot;<br>      identifiers = [&quot;arn:aws:iam::${data.aws_caller_identity.current.account_id}:root&quot;]<br>    }<br><br>    actions   = [&quot;kms:*&quot;]<br>    resources = [&quot;*&quot;]<br>  }<br>}</pre><pre># locals.tf file<br><br>locals {<br>  alias_name = format(&quot;alias/%s-%s&quot;, var.kms_key_configuration.name, var.aws-region)<br>}</pre><pre># versions.tf file<br><br>terraform {<br>  required_version = &quot;&gt;= 1.3.10&quot;<br>  required_providers {<br>    aws = {<br>      source  = &quot;hashicorp/aws&quot;<br>      version = &quot;&gt;= 5.75.0&quot;<br>    }<br>  }<br>}</pre><pre># outputs.tf file<br><br>output &quot;key_arn&quot; {<br>  value       = join(&quot;&quot;, aws_kms_key.this[*].arn)<br>  description = &quot;Key ARN&quot;<br>}<br><br>output &quot;key_id&quot; {<br>  value       = join(&quot;&quot;, aws_kms_key.this[*].key_id)<br>  description = &quot;Key ID&quot;<br>}<br><br>output &quot;alias_arn&quot; {<br>  value       = join(&quot;&quot;, aws_kms_alias.this[*].arn)<br>  description = &quot;Alias ARN&quot;<br>}<br><br>output &quot;alias_name&quot; {<br>  value       = join(&quot;&quot;, aws_kms_alias.this[*].name)<br>  description = &quot;Alias name&quot;<br>}</pre><p>Now that we have displayed the entire KMS module configuration, let’s see how we can use this module to deploy the configured resources. The below code is the terraform configuration for the kms-key.tf file that calls the module and sets up the expected inputs.</p><pre>module &quot;kms_key&quot; {<br>  source = &quot;./modules/kms&quot;<br><br>  enabled = true<br><br>  kms_key_configuration = {<br>    name                    = &quot;infrastructure_kms_key&quot;<br>    description             = &quot;KMS key for secure encryption&quot;<br>    deletion_window_in_days = 10<br>    enable_key_rotation     = true<br>    key_usage               = &quot;ENCRYPT_DECRYPT&quot;<br>    multi_region            = false<br>  }<br><br>  tags = {<br>    Owner = &quot;platform-team&quot;<br>  }<br>}</pre><p>You may notice that we didn’t fill all the fields in the kms_key_configuration variable. We, indeed, used some advanced concepts in order to simplify the input section. We used optional fields in the variable section, and the lookup function to set a default value for the key’s policy.</p><h4>✅ Best Practices for Writing Terraform Modules</h4><p>To help you get the most out of Terraform modules, I will devote this section to presenting some best practices that I strongly recommend you follow when working with Terraform modules:</p><ul><li><strong>Keep modules focused</strong>: A module should do one thing — Create network stack, or storage nor both at once.</li><li><strong>Validate Inputs</strong>: Use the validation block to catch configuration mistakes early. (check our <a href="https://medium.com/faun/mastering-terraform-variables-complex-structures-input-validation-c2c46b21d4e6">article</a> about terraform variables and input validation)</li><li><strong>Use Clear Inputs and Outputs: </strong>Define only the inputs you need, and output only what will be used. Use terraform functions and some computational logic to make your module’s inputs as small as possible.</li><li><strong>Document Everything</strong>: Include descriptions for all variables and outputs. Also consider adding a README.md file to give further information about the module and how it should be used.</li><li><strong>Pin Module Versions</strong>: When using modules from a VCS ( Github, Gitlab, …etc) or the Terraform registry, always pin the version to avoid any changes that could cause dysfunctions. I strongly recommend that you also use Git tags to pin your own modules, which will allow you to track improvements made to the module.</li></ul><h4>🎯Wrapping Up</h4><p>Terraform modules help you transform your infrastructure code into a reusable, scalable and easy-to-maintain architecture. Whether you’re managing a few cloud resources or developing complex cloud architectures, mastering terraform modules is a game changer. It is a must when working in production environments.</p><p>More Terraform-related content is coming. <strong>Stay Tuned ! 👀</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*-ioQjhTSEGKvao8e.png" /></figure><h4>👋 If you find this helpful, please click the clap 👏 button below a few times to show your support for the author 👇</h4><h4>🚀<a href="http://from.faun.to/r/8zxxd">Join FAUN Developer Community &amp; Get Similar Stories in your Inbox Each Week</a></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15ec385c5f8b" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/mastering-terraform-modules-reuse-scale-and-organize-your-infrastructure-15ec385c5f8b">Mastering Terraform Modules: Reuse, Scale, and Organize Your Infrastructure</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Terraform Functions Explained: From Basics to Advanced Patterns]]></title>
            <link>https://faun.pub/terraform-functions-explained-from-basics-to-advanced-patterns-ac8bb5e60a85?source=rss-9e7316d43131------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac8bb5e60a85</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[iac]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Youness Zarhali]]></dc:creator>
            <pubDate>Mon, 14 Jul 2025 12:04:32 GMT</pubDate>
            <atom:updated>2025-09-03T15:04:24.538Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gYP4Ajdd6mf4QXflH1nUYg.png" /><figcaption>Credits: AI Generated Image for Visual Representation.</figcaption></figure><p>Across the past articles of our <a href="https://medium.com/@youness.zarhali/list/terraform-unlocked-mastering-infrastructure-as-code-105fe7243fc6">series</a> dedicated to mastering Terraform, we’ve covered a range of topics, from explaining the basic terraform concepts to more advanced subjects such as looping patters and complex variables. Now that we are pretty comfortable with all that, we’re going one step further and unlock some new features that will definitely make our code more clean, dynamic and flexible.</p><p>In this article, we will take a deep look at Terraform functions, which will allow you to manipulate data structures and reduce duplication across your configurations. Whether you’re formatting string variables, flattening nested lists or merging complex maps, this article will guide you through how to get the most out of terraform functions and take your code to the next level.</p><h3>📊 Terraform Function Categories</h3><p>Writing terraform code isn’t just about defining infrastructure, it’s about defining it clearly, and ensure that your configuration is scalable and dynamic. Terraform functions enables you to do all this, so let’s start explaining this engaging topic by introducing a few types of functions and when each is used.</p><h4><strong>1. String Functions</strong></h4><p>String functions are used to manipulate and transform string data, which is very useful for usecases like: forcing naming conventions, generating identifiers and dynamic configurations. Among the most frequently used string functions we can find:</p><ul><li>format(format_string, values…) : Injects values into a string template</li><li>join(seperator, list) : Concatenates a list into a string</li><li>split(seperator, list) : Breaks a list into a list</li><li>replace(string, substring, replacement) : Substitutes parts of a string</li></ul><h4>2. Numeric Functions</h4><p>Numeric functions can be used to perform basic mathematical operations or apply constraints on numerical values. Below are few examples of some of terraform’s numeric functions:</p><ul><li>max(a,b,...) | mix(a,b,...) : Returns the largest | smallest number.</li><li>ceil(number) | floor(number) : Rounds up | down</li><li>abs(number) : Absolute value</li></ul><h4>3. Collection Functions</h4><p>Used to handling lists, maps and sets, collection functions are essential for processing repeated resource definitions or transforming grouped data. Here are some of the widely used collection functions:</p><ul><li>length(list/map): Counts elements.</li><li>lookup(map, key, default) : Retrieves a value with fallback.</li><li>merge(map1,map2) : Combines maps.</li><li>zipmap(key_list, value_list) : Constructs a map from a list of keys and corresponding list of values.</li></ul><h4>4. Conditional and Logical Functions</h4><p>Conditional and logical functions help build logic and conditional expressions within Terraform resources or variables. These functions are making your code more resilient and robust.</p><ul><li>contains(list, value): Checks existence of a value within a list</li><li>anytrue(list) | alltrue(list) : Aggregate logical checks</li><li>flatten([list1, list2,…]) : Takes a nested list and returns a single, flat list containing all the elements.</li><li>try(expression1, expression2,…) : Returns the result of the first one without errors.</li></ul><h3>✅ Terraform Functions: <strong>Best Practices And Real-World S</strong>cenarios</h3><p>Terraform functions are more than just a syntactic enhancement, they are essential tools for writing flexible, DRY and production-ready terraform code. Functions can be utilized in various usecases such as: validating inputs, dynamically forcing naming conventions and transforming data structures. In this section, we will explore some of the most useful functions using practical scenarios drawn from real-life AWS infrastructure models.</p><h4>1. Input validation</h4><p>In the following coding section, we will explore how input validation can be done in terraform variables using two functions such: alltrue(list) and contains(list, value) .</p><pre>variable &quot;codecommit_repositories&quot; {<br>  description = &quot;A list of repositories, each containing name, description and tags &quot;<br>  type = list(object({<br>    repository_name = string<br>    description     = string<br>    repository_type = string<br>    tags            = map(string)<br>  }))<br>  validation {<br>    condition = alltrue([<br>      for repo in var.codecommit_repositories :<br>      repo.repository_type == &quot;configuration-project&quot; || repo.repository_type == &quot;terraform-project&quot;<br>    ])<br>    error_message = &quot;repository_type must be either &#39;configuration-project&#39; or &#39;terraform-project&#39;.&quot;<br>  }<br>}</pre><pre>variable &quot;authentication_parameters&quot; {<br>  description = &quot;Authentication Parameters for the EKS cluster&quot;<br>  type = object({<br>    create_admin_permisssions = bool<br>    authentication_mode       = string<br>  })<br>  default = {<br>    create_admin_permisssions = true<br>    authentication_mode       = &quot;API_AND_CONFIG_MAP&quot;<br>  }<br>  validation {<br>    condition     = contains([&quot;API&quot;, &quot;CONFIG_MAP&quot;, &quot;API_AND_CONFIG_MAP&quot;], var.authentication_parameters.authentication_mode)<br>    error_message = &quot;Invalid value detected in authentication_mode. Accepted values are: &#39;API&#39;, &#39;CONFIG_MAP&#39;, &#39;API_AND_CONFIG_MAP&#39; &quot;<br>  }<br>}</pre><h4>2. Dynamic Naming Conventions</h4><p>The below coding section shows how we can force a dynamic naming convention using the format function. By doing so, we have standardized EKS cluster names according the environment , a unique naming_prefixand the aws_region where the cluster will be deployed.</p><pre>variable &quot;naming_prefix&quot; {<br>  description = &quot;Naming Prefix&quot;<br>  type        = string<br>}<br>variable &quot;environment&quot; {<br>  description = &quot;Environment&quot;<br>  type        = string<br>  default     = &quot;dev&quot;<br>}<br>variable &quot;aws_region&quot; {<br>  description = &quot;AWS region&quot;<br>  type        = string<br>  default     = &quot;eu-west-3&quot;<br>}<br><br>locals {<br>  eks_cluster_name = format(&quot;%s-%s-%s&quot;, var.naming_prefix, var.environment, var.aws_region)<br>}</pre><h4>3. Changing Data Structures</h4><p>In this section, we will look into a real-world scenario, where changing data structure is key to better structure your code and make it more powerful and flexible. Managing subnet definitions for a VPC, might involve mapping lists of CIDR blocks to various AZs, we will showcase how the flatten function makes it easy for us.</p><pre>variable &quot;az_subnet_cidrs&quot; {<br>  description = &quot;A map of AZs and list of subnet CIDRs per AZ&quot;<br>  type = map(list(string))<br>  default = {<br>    &quot;eu-west-3a&quot; = [&quot;10.0.1.0/24&quot;, &quot;10.0.2.0/24&quot;]<br>    &quot;eu-west-3b&quot; = [&quot;10.0.3.0/24&quot;]<br>    &quot;eu-west-3c&quot; = [&quot;10.0.4.0/24&quot;, &quot;10.0.5.0/24&quot;]<br>  }<br>}<br><br>locals {<br>  subnets = flatten([<br>    for az, cidrs in var.az_subnet_cidrs : [<br>      for cidr in cidrs : {<br>        az   = az<br>        cidr = cidr<br>      }<br>    ]<br>  ])<br>  <br>  default_tags = {<br>    Business_Unit  = &quot;Infrastructure&quot;<br>    Component      = &quot;Network&quot; <br>  }<br>}</pre><p>The flattened list subnet local variable will look like this:</p><pre>[<br>  {<br>    &quot;az&quot; = &quot;eu-west-3a&quot;<br>    &quot;cidr&quot; = &quot;10.0.1.0/24&quot;<br>  },<br>  {<br>    &quot;az&quot; = &quot;eu-west-3a&quot;<br>    &quot;cidr&quot; = &quot;10.0.2.0/24&quot;<br>  },<br>  {<br>    &quot;az&quot; = &quot;eu-west-3b&quot;<br>    &quot;cidr&quot; = &quot;10.0.3.0/24&quot;<br>  },<br>  {<br>    &quot;az&quot; = &quot;eu-west-3c&quot;<br>    &quot;cidr&quot; = &quot;10.0.4.0/24&quot;<br>  },<br>  {<br>    &quot;az&quot; = &quot;eu-west-3c&quot;<br>    &quot;cidr&quot; = &quot;10.0.5.0/24&quot;<br>  },<br>]</pre><p>We can now streamline subnet resource creation using a for_each loop, we also made use of the merge function to combine the default_tagsand some other subnet specific tag:</p><pre>resource &quot;aws_subnet&quot; &quot;this&quot; {<br>  for_each = { for i, s in local.subnets : &quot;${s.az}-${s.cidr}&quot; =&gt; s }<br><br>  vpc_id     = aws_vpc.main.id<br>  cidr_block = each.value.cidr<br>  availability_zone = each.value.az<br>  tags = merge(local.default_tags, {<br>    Name = &quot;subnet-${each.value.az}&quot;<br>  })<br>}</pre><h3>🎯 Final Thoughts</h3><p>As we have seen through this article, Terraform Functions are not just there for aesthetic purposes. They are essential to write production-ready terraform code. By using them, you can handle everything from input validation to more advanced tasks like data transformation and building conditional logic. Here is a link i highly advice you to check if you want to go further and see the full set of functions that you can use with Terraform:</p><ul><li>Terraform Functions Documentation : <a href="https://developer.hashicorp.com/terraform/language/functions"><em>https://developer.hashicorp.com/terraform/language/functions</em></a></li></ul><p>In the next article of our <a href="https://medium.com/@youness.zarhali/list/terraform-unlocked-mastering-infrastructure-as-code-105fe7243fc6">series</a>, we’ll take an in-depth look at Terraform modules and how they help us structure our code to build scalable cloud infrastructure. <strong>Stay Tuned ! 👀</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*hRlrCr6i5iLQjbG-.png" /></figure><h4>👋 If you find this helpful, please click the clap 👏 button below a few times to show your support for the author 👇</h4><h4>🚀<a href="http://from.faun.to/r/8zxxd">Join FAUN Developer Community &amp; Get Similar Stories in your Inbox Each Week</a></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac8bb5e60a85" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/terraform-functions-explained-from-basics-to-advanced-patterns-ac8bb5e60a85">Terraform Functions Explained: From Basics to Advanced Patterns</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Terraform Variables: Complex Structures & Input Validation]]></title>
            <link>https://faun.pub/mastering-terraform-variables-complex-structures-input-validation-c2c46b21d4e6?source=rss-9e7316d43131------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2c46b21d4e6</guid>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[iac]]></category>
            <dc:creator><![CDATA[Youness Zarhali]]></dc:creator>
            <pubDate>Sat, 31 May 2025 21:59:32 GMT</pubDate>
            <atom:updated>2025-09-03T15:04:10.161Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sf_lxbzmRPag_TcwJS_4Dg.png" /><figcaption>Credits: AI Generated Image for Visual Representation.</figcaption></figure><p>In our previous <a href="https://medium.com/faun/terraform-loops-explained-using-count-for-each-and-advanced-patterns-d178a8bba5e8">article</a>, we explored how to use the count and for_each meta-arguments to manage multiple resources dynamically. As your Terraform configurations grow in scale and complexity, simple variables no longer cut it. You will need to take that one step further, by using <strong>complex variables — </strong>like <strong>lists of objects, nested maps, </strong>and learn how to <strong>validate </strong>your terraform input variable to prevent misconfigurations.</p><p>In this article, we will see how to implement all this, along with multiple advanced patters in order to enhance the quality of your code and make it “production-ready”.</p><h4>🧠1. Terraform Complex Variables: What you need to know</h4><p>A <strong>complex variable</strong> is any input type that isn’t a primitive (string, number, or bool). In this article, we will focus on the following three types:</p><ul><li><strong>Lists</strong>: A list is an ordered collection of values of the same type. You should keep in mind that the position of each value in the list matters and can be acccessed by index. Lists are ideal for defining sequences like AWS regions, Availability Zones, List of VPC subnet CIDR blocks. We can use lists to define AWS Availability Zones as follows:</li></ul><pre>variable &quot;availability_zones&quot; {<br>  description = &quot;List of availability zones&quot;<br>  type    = list(string)<br>  default = [&quot;eu-west-3a&quot;, &quot;eu-west-3b&quot;, &quot;eu-west-3c&quot;]<br>}</pre><ul><li><strong>Maps: </strong>A<strong> </strong>map is a collection of string keys and values of some type. Note that, unlike lists, maps values are not ordered and can be accessed by their keys. You can use map when trying to define tags or any input variables you want to reference its item by name. Below is a code snippet that describes a map variable containing the default tags for production environment resources.</li></ul><pre>variable &quot;default_tags&quot; {<br>  description = &quot; Default tags to be applied in production environment&quot;<br>  type = map(string)<br>  default = {<br>    Environment = &quot;Prod&quot;<br>    Owner       = &quot;Ops_Team&quot;<br>  }<br>}</pre><ul><li><strong>Objects</strong>: An object is a structured group of named attribute, each attribute has its own defined type. Objects can be used to define EC2 instance configuration, EKS nodegroups or VPC routing configuration. Let’s see how we can define an EC2 instance configuration using an object variable:</li></ul><pre>variable &quot;ec2_configuration&quot; {<br>  description = &quot;EC2 Instance Configuration&quot;<br>  type = object({<br>      name             = string<br>      instance_type    = string<br>      ami_id           = string<br>      instance_profile = string<br>      tags             = map(string)<br>      })<br>}</pre><blockquote>💡In fact, you will often find yourself combining these three variable types and deal with <strong>map(list(string))</strong>, <strong>list(object({})) or map(object({})) variables.</strong></blockquote><h4>🔁 2. Structured Configuration With Object Variables and Nesting</h4><p>When working with production grade cloud infrastructure, maintaining clarity, scalability and consistency in your Terraform code is a must. That’s why we will focus a little bit more on <strong>object variables. </strong>They allow you to group related attributes into structured units, which makes your terraform configuration more modular and easier to manage and maintain over time.</p><p>Let’s take a closer look at this very important structure using real-world examples from the aws terraform provider. We’ve already seen, in the previous section, how object variables can be used in case of EC2 instance configurations, now we’ll look at the EKS Nodegroup use case and provide some additional explanations.</p><pre>variable &quot;eks_node_group_configuration&quot; {<br>  description = &quot;EKS Nodegroup configuration structure&quot;<br>  type = object({<br>    name           = string<br>    description    = optional(string, &quot;EKS managed nodegroup&quot;)<br>    ami_type       = string<br>    instance_types = list(string)<br>    labels         = optional(map(string), {})<br>    disk_size      = optional(number, 20)<br>    disk_type      = optional(string, &quot;gp3&quot;)<br>    sizing = object({<br>      max_size     = number<br>      min_size     = number<br>      desired_size = number<br>    })<br>    schedules = map(any)<br>  })<br>}</pre><p>This variable is an ideal example of a rich <strong>object </strong>variable that encompasses complex infrastructure parameters in a structured, readable format. This object includes both required and optional attributes, which makes your configuration more flexible. Note that you need to specify default values for the optional attributes.</p><p>This example also illustrates the possibility of nesting other complex types within an object, such as the sizing block, which is another required object attribute and schedules, a map(any) input, allowing unrestricted key-value pairs.</p><p>This approach is particularly powerful in high quality, production-level Terraform code, where modularity, type safety and maintainability are essential. I highly encourage you to organize your Terraform input variables in this way, so that you can inforce structure while maintaining the flexibility and scalability of your infrastructure code.</p><h4>✅ 3. Input Validation: How to Prevent Misconfigurations</h4><p>When working with terraform variables, it is essential to ensure that their values are accurate. Terraform provides a way to ensure that your values are correct according to some conditions and rules you configure, which is the <strong>validation block </strong>inside the variable declaration. This allows you to detect errors early, avoid misconfigurations and build more robust and production-ready infrastructure code. Whether you’re expecting a specific format, limiting values to a range or validating complex structures such as maps or objects, input validation gives you a clean, easy-to-maintain method. Let’s take a look at some practical, real-world examples:</p><pre># Check whether the defined aws_region is either eu-west-3 or eu-west-1<br># Display error_message otherwise<br><br>variable &quot;aws_region&quot; {<br>  description = &quot;AWS region&quot;<br>  type        = string<br>  default     = &quot;eu-west-3&quot;<br>  validation {<br>    condition     = contains([&quot;eu-west-1&quot;, &quot;eu-west-3&quot;], var.aws_region)<br>    error_message = &quot;The region must be either &#39;eu-west-1&#39; or &#39;eu-west-3&quot;<br>  }<br>}</pre><p>In a more sophisticated example, we will see how to validate a specific attribute in an object typed variable:</p><pre># Check whether the defined subnet is private<br># Display error_message otherwise<br><br>variable &quot;subnet_configuration&quot; {<br>  type = list(object({<br>    name       = string<br>    cidr_block = string<br>    is_public  = bool<br>  }))<br><br>  validation {<br>    condition     = alltrue([for subnet in var.subnet_configuration : subnet.is_public == false])<br>    error_message = &quot;All subnets must be private (is_public = false)&quot;<br>  }<br>}</pre><h4>🎯 Conclusion</h4><p>Terraform’s variable system is very powerful and far more complex than just strings and numbers. By using <strong>complex types</strong>, <strong>proper validation</strong>, and <strong>clean patterns</strong>, you’ll create infrastructure code that is reusable across teams, easy to maintain and safe to evolve over time.</p><p>In the next article of this <a href="https://medium.com/@youness.zarhali/list/terraform-unlocked-mastering-infrastructure-as-code-105fe7243fc6">series</a>, we will look at some advanced patterns around Terraform variables. Stay tuned !</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*u63GXODYN2-k9NZw.png" /></figure><h4>👋 If you find this helpful, please click the clap 👏 button below a few times to show your support for the author 👇</h4><h4>🚀<a href="http://from.faun.to/r/8zxxd">Join FAUN Developer Community &amp; Get Similar Stories in your Inbox Each Week</a></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2c46b21d4e6" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/mastering-terraform-variables-complex-structures-input-validation-c2c46b21d4e6">Mastering Terraform Variables: Complex Structures &amp; Input Validation</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Terraform Loops Explained: Using count, for_each, and Advanced Patterns]]></title>
            <link>https://faun.pub/terraform-loops-explained-using-count-for-each-and-advanced-patterns-d178a8bba5e8?source=rss-9e7316d43131------2</link>
            <guid isPermaLink="false">https://medium.com/p/d178a8bba5e8</guid>
            <category><![CDATA[iac]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Youness Zarhali]]></dc:creator>
            <pubDate>Sat, 17 May 2025 18:56:13 GMT</pubDate>
            <atom:updated>2025-09-03T15:24:56.627Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F9Z4-9EL6YnipD7aZ6jTFg.png" /><figcaption>Credits: AI Generated Image for Visual Representation.</figcaption></figure><p>In the first two articles in our <a href="https://medium.com/@youness.zarhali/list/terraform-unlocked-mastering-infrastructure-as-code-105fe7243fc6">series</a> dedicated to mastering IaC through Terraform, we covered the foundational concepts of writing infrastructure as code using Terraform as well as the Terraform workflow that shows how declarative code turns into cloud resources. Now, let’s level up.</p><p>When you’re provisioning multiple cloud resources — like several EC2 instances — Terraform provides powerful constructs to help you loop over infrastructure definitions with elegance and control. In this article, we’ll learn the difference between the count and for_each meta-arguments and how to use each of them in order to make the terraform configuration DRY (Don’t Repeat Yourself) . We will also tackle advanced looping patters with for expression and nested objects.</p><h4>🧮 Count: Repetition Made Simple</h4><p>The count meta-argument is the most basic way to loop. It lets you define a resource multiple times by specifying how many copies you want. Below is an example on how to use the count meta-argument in your configuration to create multiple aws codecommit repositories.</p><pre># CodeCommit variable<br>variable &quot;codecommit-repositories&quot; {<br>  description = &quot;A list of repositories&quot;<br>  type = list(string)<br>  default = [&quot;project-a&quot;, &quot;project-b&quot;]<br>}<br><br>#Local variables <br>locals {<br>  common_tags = {<br>    Environment = &quot;Sandbox&quot;<br>  }<br>}<br><br># Terraform resource block<br>resource &quot;aws_codecommit_repository&quot; &quot;this&quot; {<br>  count           = length(var.codecommit-repositories)<br>  repository_name = var.codecommit-repositories[count.index]<br>  description     = &quot;Repository for ${var.codecommit-repositories[count.index]}&quot;<br>  tags            = merge(local.common_tags, {Repository = var.codecommit-repositories[count.index]})<br>}</pre><p>In the code snipped above, the count meta-argument is used to create multiple codecommit repositories. We used the length()function to calculate how many items are in the codecommit-repositories variable since the count meta-argument is expecting and integer value. count.index is used to access each item in the list and can be used in the resource attributes using var.codecommit-repositories[count.index].</p><p>The count meta-argument has some drawbacks:</p><ul><li>It uses a <strong>list</strong>, so resources can be referenced by index, e.g., aws_codecommit_repository.this[0].</li><li>If you reorder items in the list, <strong>Terraform will destroy and recreate</strong> them.</li><li><strong>Keys aren’t preserved</strong>, which can lead to instability in large deployments.</li></ul><h4>🔁 For_each: Loop With Control</h4><p>The for_each meta-argument is ideal when dealing with <strong>maps</strong> or <strong>sets</strong> where each item has a unique key. Now let’s take a look at the same previous example, but this time using the for_each meta-argument.</p><pre># CodeCommit variable<br>variable &quot;codecommit-repositories&quot; {<br>  type = map(string)<br>  description = &quot; Codecommit repositories map variable&quot;<br>  default = {<br>    &quot;project-a&quot; = &quot;Repository for Project A&quot;<br>    &quot;project-b&quot; = &quot;Repository for Project B&quot;<br>  }<br>}<br><br>#Local variables <br>locals {<br>  common_tags = {<br>    Environment = &quot;Sandbox&quot;<br>  }<br>}<br><br># Terraform resource block<br>resource &quot;aws_codecommit_repository&quot; &quot;this&quot; {<br>  for_each        = var.codecommit-repositories<br>  repository_name = each.key<br>  description     = each.value<br>  tags            = merge(local.common_tags, {Repository = each.key})<br> <br>}</pre><p>In the code snipped above, the for_each meta-argument is used to create two codecommit repositories. We use each.key to access the map keys in the codecommit_repositories variable (e.g., &quot;project-a&quot;). each.value is used to access the map values (e.g., &quot;Repository for Project A&quot;). Both each.key and each.value can be used in the resource attributes.</p><h4>🧠 Advanced Looping with Object Variables and for Expressions</h4><p>Now that we are more familiar with the for_each<strong> </strong>meta-argument, let’s build more complex loops using <strong>object variables</strong> and <strong>inline </strong><strong>for expressions </strong>always using the same example as before.</p><pre><br># CodeCommit variable<br>variable &quot;codecommit-repositories&quot; {<br>  description = &quot;A list of repositories, each containing name, description and tags &quot;<br>  type = list(object({<br>    repository_name = string<br>    description     = string<br>    tags            = map(string)<br>  }))<br>  default = [<br>    {<br>    repository_name = &quot;project-a&quot;<br>    description     = &quot;Repository for Project-a&quot;<br>    tags            = { &quot;Repository&quot; : &quot;poject-a&quot; }<br>    },<br>    {<br>    repository_name = &quot;project-b&quot;<br>    description     = &quot;Repository for Project-b&quot;<br>    tags            = { &quot;Repository&quot; : &quot;poject-b&quot; }<br>    }<br>    ]<br>}<br><br><br>#Local variables <br>locals {<br>  common_tags = {<br>    Environment = &quot;Sandbox&quot;<br>  }<br>}<br><br><br># Terraform resource block<br>resource &quot;aws_codecommit_repository&quot; &quot;this&quot; {<br>  for_each = {<br>    for repo in var.codecommit-repositories : repo.repository_name =&gt; repo<br>  }<br>  repository_name = each.key<br>  description = each.value.description<br>  tags = merge(local.common_tags, each.value.tags )<br>}</pre><p>Let’s break down this code snippet to better understand it.</p><ul><li>The<strong> </strong>codecommit-repositories<strong> </strong>variable<strong> </strong>is a list of objects, each representing a repository.</li><li>Each object includes a repository_name, description, and a tags map.</li><li>Two repositories (project-a and project-b) are defined as examples (default value of the codecommit-repositoriesvariable).</li><li><strong>for_each</strong>: Converts the list of repositories into a <strong>map</strong> where each key is the repository_name. This allows Terraform to uniquely track each repository by name.</li><li>repository_name: Uses each.key (which is the repository name).</li><li>description<strong> and </strong>tags: Pulled from each.value, i.e., the corresponding repository object.</li></ul><h4>🆚 Comparing count and for_each</h4><p>While both count and for_each let you create multiple resources from a single resource terraform block, they serve slightly different purposes and behave differently under the hood as terraform stores the looped resources as a <strong>list</strong> when using the count meta-argument and as a <strong>map</strong> when using for_each</p><p>Choosing the right one can impact the readability, maintainability, and reliability of your Terraform configuration. Here’s a side-by-side comparison to help you decide which is best for your use case:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*eXzvVYTqLWMO8z7TbTl8uA.png" /></figure><h4>🎯 Final thoughts</h4><p>Loops in Terraform are essential for managing real-world, scalable infrastructure. Whether you use count, for_each, or advanced object transformations, these tools help you write DRY, elegant, and maintainable code.</p><p>These are some useful links to go even further and master terraform loops:</p><ul><li><a href="https://developer.hashicorp.com/terraform/language/meta-arguments/count">https://developer.hashicorp.com/terraform/language/meta-arguments/count</a></li><li><a href="https://developer.hashicorp.com/terraform/language/meta-arguments/for_each">https://developer.hashicorp.com/terraform/language/meta-arguments/for_each</a></li><li><a href="https://developer.hashicorp.com/terraform/language/expressions/for">https://developer.hashicorp.com/terraform/language/expressions/for</a></li></ul><p>Stay tuned for more !</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*rBrrQUK7_REGLs60.png" /></figure><h4>👋 If you find this helpful, please click the clap 👏 button below a few times to show your support for the author 👇</h4><h4>🚀<a href="http://from.faun.to/r/8zxxd">Join FAUN Developer Community &amp; Get Similar Stories in your Inbox Each Week</a></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d178a8bba5e8" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/terraform-loops-explained-using-count-for-each-and-advanced-patterns-d178a8bba5e8">Terraform Loops Explained: Using count, for_each, and Advanced Patterns</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying the Terraform Workflow: From Code to Cloud]]></title>
            <link>https://faun.pub/demystifying-the-terraform-workflow-from-code-to-cloud-e7c9bfb8da6d?source=rss-9e7316d43131------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7c9bfb8da6d</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Youness Zarhali]]></dc:creator>
            <pubDate>Sun, 13 Apr 2025 20:52:43 GMT</pubDate>
            <atom:updated>2025-09-03T15:24:34.980Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jivRH9id_dIpMk4FQS6a4A.png" /><figcaption>Credits: AI Generated Image for Visual Representation.</figcaption></figure><p>In our previous <a href="https://faun.pub/introduction-to-cloud-infrastructure-automation-with-terraform-4a3a1258e34b">article</a> introducing Terraform, we explored some key concept of this very powerful IaC tool like providers, resources, data sources, variables and output variables. All using AWS as our working example. Now that we are familiar with the basics, it’s time to get a grasp of the Terraform workflow, and how the declarative code turns into cloud resources.</p><p>Terraform follows a clear and simple workflow each time you want to create cloud resources. This process is structured around three main steps: <strong>init</strong>, <strong>plan</strong> and <strong>apply</strong>. Each of these three steps plays a crucial role in turning the terraform configuration into actual cloud infrastructure. Let’s go into the details of each step.</p><h4>▶️ Init: Initialize Your Working Directory</h4><p>The first step in any Terraform project is to initialize the working directory by running the command: “<em>terraform init”</em>. This commands downloads the different providers plugins that are required to properly execute the terraform code (AWS, Azure, GCP, …). During this step, the backend configuration is also initialized, which tells terraform where to store the infrastructure’s state files. The state can be stored locally, or remotely in an S3 bucket for example.</p><p>What happens behind the scene during the <em>terraform init</em> command is that terraform creates a <em>.terraform/ </em>directory in our project’s root directory that contains the following components:</p><ul><li><em>providers/</em> : Directory that contains downloaded provider binaries, such as AWS.</li><li><em>modules/</em> : Directory that contains source code for any referenced modules in the configuration.</li><li><em>terraform.tfstate</em> : A snapshot of the infrastructure’s current state if local backend is used.</li><li>Backend-specific metadata like <em>terraform.lock.hcl</em> which ensures consistent provider versions across environments.</li></ul><p>The following illustration is an example of what you can expect when running the terraform init command:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*_zb7D4UguiR3dsiUtdyUCg.png" /></figure><h4>🔎 Plan: Preview What Terraform Will Do</h4><p>The next step in our terraform workflow is running the <em>terraform plan </em>command to get a detailed overview about what terraform is intending to do without making any actual changes. Think of it as your dry-run. The plan must be carefully reviewed before moving forward with the apply.</p><p>During this stage, Terraform performs the following actions :</p><ul><li>Loads the current state file from local or remote backend.</li><li>Parses and validates all .tf configuration files.</li><li>Evaluates locals, variables, data sources and computes operations that might be present in the configuration files.</li><li>Compares the existing infrastructure state (from the local or remote backend state file) with your configuration code.</li><li>Determines the necessary changes to align the infrastructure with the desired configuration.</li><li>Produces a list of proposed actions — what will be created, updated or destroyed.</li></ul><p>The figure below is an example of how you can expect the <em>terraform plan</em> command to work:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QJa7YdIZXDWEbUI3nEvHSQ.png" /></figure><h4>🚀 Apply: Make It Real</h4><p>Once you have checked the plan, and made sure that the proposed changes meet your expectations, you run the <em>terraform apply</em> command to apply the changes and create, delete or modify the resources in your cloud provider.</p><p>Terraform conducts the following operations during this phase:</p><ul><li>If no plans is passed, terraform re-executes the <em>terraform plan</em> command.</li><li>Requests user approval (unless -auto-approve is used)</li><li>Sends API requests to your cloud provider using provider plugins</li><li>Executes changes in a dependency-aware order (i.e. dependent resources wait for their necessary preconditions).</li><li>Produces a real-time log for each resource action.</li><li>Updates the state file to match the updated state of the infrastructure.</li><li>Evaluates and prints output values on the console.</li></ul><p>The following picture is an example of the terraform apply command (I applied the plan produced in the previous section).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lu8XPgnAtgSsCGmCPLQcNA.png" /></figure><h4>🗑️ Bonus: Destroy when needed</h4><p>The <em>terraform destroy </em>command<em> </em>plans the destruction of all the infrastructure managed by the current configuration. This command is very useful for cleanup or remove all resources in sandbox environments that are only for testing purposes, or simply if you want to start fresh.</p><p>Here is an example of what the terraform destroy command displays:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sBwAMrKb49ZzB5Tos-Rdzg.png" /></figure><h4>🎯 Final thoughts</h4><p>Mastering the Terraform workflow is crucial when trying to create or update cloud infrastructures. It’s the bridge between your code and the cloud provider. In this article we’ve looked at the three stages of a terraform workflow in detail, with all the operations terraform does behind the scenes during each of these stages. These are some useful links to go even further and master the options of each command:</p><ul><li><a href="https://developer.hashicorp.com/terraform/cli/commands/init">https://developer.hashicorp.com/terraform/cli/commands/init</a></li><li><a href="https://developer.hashicorp.com/terraform/cli/commands/plan">https://developer.hashicorp.com/terraform/cli/commands/plan</a></li><li><a href="https://developer.hashicorp.com/terraform/cli/commands/apply">https://developer.hashicorp.com/terraform/cli/commands/apply</a></li></ul><p>Stay tuned for more !</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*z5zNzQlCsreuCPtR.png" /></figure><h4>👋 If you find this helpful, please click the clap 👏 button below a few times to show your support for the author 👇</h4><h4>🚀<a href="http://from.faun.to/r/8zxxd">Join FAUN Developer Community &amp; Get Similar Stories in your Inbox Each Week</a></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7c9bfb8da6d" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/demystifying-the-terraform-workflow-from-code-to-cloud-e7c9bfb8da6d">Demystifying the Terraform Workflow: From Code to Cloud</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>