<?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 Stéphane Noutsa on Medium]]></title>
        <description><![CDATA[Stories by Stéphane Noutsa on Medium]]></description>
        <link>https://medium.com/@stephanenoutsa?source=rss-8f915bc52368------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*6ZgW8N_FDMMYTu1cccMJTA.jpeg</url>
            <title>Stories by Stéphane Noutsa on Medium</title>
            <link>https://medium.com/@stephanenoutsa?source=rss-8f915bc52368------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 16:44:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@stephanenoutsa/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[Terraform & Terragrunt to Deploy a Web Server with Amazon EC2]]></title>
            <link>https://stephanenoutsa.medium.com/terraform-terragrunt-to-deploy-a-web-server-with-amazon-ec2-fba9d51fc21e?source=rss-8f915bc52368------2</link>
            <guid isPermaLink="false">https://medium.com/p/fba9d51fc21e</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[terragrunt]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Stéphane Noutsa]]></dc:creator>
            <pubDate>Thu, 13 Jul 2023 17:42:27 GMT</pubDate>
            <atom:updated>2023-11-03T15:36:41.187Z</atom:updated>
            <content:encoded><![CDATA[<p>Terraform &amp; Terragrunt to Deploy a Web Server with Amazon EC2</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*xLY34MxTGqyLqJozNxlaGQ.jpeg" /><figcaption>Terraform &amp; Terragrunt to Deploy a Web Server with Amazon EC2</figcaption></figure><p><strong>Disclaimer<br></strong>a) Some basic understanding of the AWS cloud, Terraform, and Terragrunt is needed to be able to follow along with this tutorial.<br>b) This article builds on my previous two articles, so to follow along you’ll need to go through them first:<br> * <a href="https://medium.com/@stephanenoutsa/terraform-terragrunt-to-create-a-vpc-and-its-components-part-i-4de01b78e46f">Terraform &amp; Terragrunt to Create a VPC and its Components (Part I)</a><br> * <a href="https://medium.com/@stephanenoutsa/terraform-terragrunt-to-create-a-vpc-and-its-components-part-ii-8f34a1d8d365">Terraform &amp; Terragrunt to Create a VPC and its Components (Part II)</a></p><p>In this article, we’ll use Terraform &amp; Terragrunt to deploy an Apache web server to an EC2 instance that will be in the public subnet of a VPC. As stated in the disclaimer above, this article builds on my last articles, whose links are provided in the disclaimer.</p><p>An EC2 instance, which stands for Elastic Compute Cloud, is a virtual server in AWS. It allows you to run applications and services on the AWS cloud infrastructure and provides computing resources, such as CPU, memory, storage, and networking capabilities, which can be easily configured and scaled as per your requirements. You can think of an EC2 instance as a virtual machine in the cloud.</p><p>By the end of this article, we’ll be able to access the Apache web server deployed to our EC2 instance by using its public IP address or its public DNS name.<br>Below are the different components we’ll create to reach our objective:</p><ol><li>Security group building block</li><li>SSH key pair building block</li><li>EC2 instance profile building block</li><li>EC2 instance building block</li><li>Security group module in VPC orchestration Terragrunt code</li><li>Web server orchestration Terragrunt code</li></ol><p>Our building blocks will have the same common files as described in <a href="https://medium.com/@stephanenoutsa/terraform-terragrunt-to-create-a-vpc-and-its-components-part-i-4de01b78e46f">this article</a>, although the <strong>variables.tf</strong> files will have additional variables in them.</p><ol><li><strong>Security group building block</strong></li></ol><p>This building block will be used to set a firewall (security rules) on our EC2 instance. It will allow us to define multiple ingress and egress rules at once for any security group that we create.</p><p><strong>main.tf</strong></p><pre>resource &quot;aws_security_group&quot; &quot;security_group&quot; {<br>  name        = var.name<br>  description = var.description<br>  vpc_id      = var.vpc_id<br><br>  # Ingress rules<br>  dynamic &quot;ingress&quot; {<br>    for_each = var.ingress_rules<br>    content {<br>      from_port   = ingress.value.from_port<br>      to_port     = ingress.value.to_port<br>      protocol    = ingress.value.protocol<br>      cidr_blocks = ingress.value.cidr_blocks<br>    }<br>  }<br><br>  # Egress rules<br>  dynamic &quot;egress&quot; {<br>    for_each = var.egress_rules<br>    content {<br>      from_port   = egress.value.from_port<br>      to_port     = egress.value.to_port<br>      protocol    = egress.value.protocol<br>      cidr_blocks = egress.value.cidr_blocks<br>    }<br>  }<br><br>  tags = merge(var.tags, {<br>    Name = var.name<br>  })<br>}<br><br>output &quot;security_group_id&quot; {<br>  value = aws_security_group.security_group.id<br>}</pre><p><strong>variables.tf </strong>(additional variables)</p><pre>variable &quot;vpc_id&quot; {<br>  type = string<br>}<br><br>variable &quot;name&quot; {<br>  type = string<br>}<br><br>variable &quot;description&quot; {<br>  type = string<br>}<br><br>variable &quot;ingress_rules&quot; {<br>  type = list(object({<br>    protocol    = string<br>    from_port   = string<br>    to_port     = string<br>    cidr_blocks = list(string)<br>  }))<br>  default = []<br>}<br><br>variable &quot;egress_rules&quot; {<br>  type = list(object({<br>    protocol    = string<br>    from_port   = string<br>    to_port     = string<br>    cidr_blocks = list(string)<br>  }))<br>  default = []<br>}<br><br>variable &quot;tags&quot; {<br>  type = map(string)<br>}</pre><p>2. <strong>SSH key pair building block</strong></p><p>This building block will allow us to create key pairs that we’ll use to SSH into our EC2 instance. We’ll first need to use OpenSSH to manually create a key pair, then provide the public key as an input to this building block (in the corresponding Terragrunt module).</p><p>This article shows you how to create a key pair on macOS and Linux:<br><a href="https://docs.digitalocean.com/products/droplets/how-to/add-ssh-keys/create-with-openssh/">https://docs.digitalocean.com/products/droplets/how-to/add-ssh-keys/create-with-openssh/</a></p><p><strong>variables.tf </strong>(additional variables)</p><pre>variable &quot;key_name&quot; {<br>  type = string<br>}<br><br>variable &quot;public_key&quot; {<br>  type = string<br>}<br><br>variable &quot;tags&quot; {<br>  type = map(string)<br>}</pre><p><strong>main.tf</strong></p><pre>resource &quot;aws_key_pair&quot; &quot;ssh&quot; {<br>  key_name   = var.key_name<br>  public_key = var.public_key<br><br>  tags = merge(var.tags, {<br>    Name = var.key_name<br>  })<br>}<br><br>output &quot;key_name&quot; {<br>  value = aws_key_pair.ssh.key_name<br>}<br><br>output &quot;key_pair_id&quot; {<br>  value = aws_key_pair.ssh.key_pair_id<br>}<br><br>output &quot;key_pair_arn&quot; {<br>  value = aws_key_pair.ssh.arn<br>}</pre><p>NB: We actually don’t need this because our EC2 instance profile’s role will allow our EC2 instance to be managed by Systems Manager (an AWS service), which will allow us to log into our instance using Session Manager (a Systems Manager feature) without needing an SSH key pair.<br>(<strong>This key pair will be used in the next article where Ansible gets involved, so stay alert for that one 😉</strong>)</p><p>3. <strong>EC2 instance profile building block</strong></p><p>An EC2 instance profile in AWS is a container for an IAM (Identity and Access Management) role that you can assign to an EC2 instance. It provides the necessary permissions for the instance to access other AWS services and resources securely.</p><p>For the purpose of this article, our instance profile will be assigned a role with permissions to be managed by Systems Manager.</p><p><strong>variables.tf</strong> (additional variables)</p><pre>variable &quot;iam_policy_statements&quot; {<br>  type = list(object({<br>    sid    = string<br>    effect = string<br>    principals = object({<br>      type        = optional(string)<br>      identifiers = list(string)<br>    })<br>    actions   = list(string)<br>    resources = list(string)<br>  }))<br>}<br><br>variable &quot;iam_role_name&quot; {<br>  type = string<br>}<br><br>variable &quot;iam_role_description&quot; {<br>  type = string<br>}<br><br>variable &quot;iam_role_path&quot; {<br>  type = string<br>}<br><br>variable &quot;other_policy_arns&quot; {<br>  type = list(string)<br>}<br><br>variable &quot;instance_profile_name&quot; {<br>  type = string<br>}<br><br>variable &quot;tags&quot; {<br>  type = map(string)<br>}</pre><p><strong>main.tf</strong></p><pre># IAM Policy<br>data &quot;aws_iam_policy_document&quot; &quot;iam_policy&quot; {<br>  dynamic &quot;statement&quot; {<br>    for_each = { for statement in var.iam_policy_statements : statement.sid =&gt; statement }<br><br>    content {<br>      sid    = statement.value.sid<br>      effect = statement.value.effect<br><br>      principals {<br>        type        = statement.value.principals.type<br>        identifiers = statement.value.principals.identifiers<br>      }<br><br>      actions   = statement.value.actions<br>      resources = statement.value.resources<br>    }<br>  }<br>}<br><br># IAM Role<br>resource &quot;aws_iam_role&quot; &quot;iam_role&quot; {<br>  name               = var.iam_role_name<br>  description        = var.iam_role_description<br>  path               = var.iam_role_path<br>  assume_role_policy = data.aws_iam_policy_document.iam_policy.json<br><br>  tags = {<br>    Name = var.iam_role_name<br>  }<br>}<br><br># Attach more policies to role<br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;other_policies&quot; {<br>  for_each = toset([for policy_arn in var.other_policy_arns : policy_arn])<br><br>  role       = aws_iam_role.iam_role.name<br>  policy_arn = each.value<br>}<br><br># EC2 Instance Profile<br>resource &quot;aws_iam_instance_profile&quot; &quot;instance_profile&quot; {<br>  name = var.instance_profile_name<br>  role = aws_iam_role.iam_role.name<br><br>  tags = merge(var.tags, {<br>    Name = var.instance_profile_name<br>  })<br>}<br><br>output &quot;instance_profile_name&quot; {<br>  value = aws_iam_instance_profile.instance_profile.name<br>}</pre><p>4. <strong>EC2 instance building block</strong></p><p>This building block will create the virtual machine where the Apache web server will be deployed.</p><p><strong>variables.tf</strong> (additional variables)</p><pre>variable &quot;most_recent_ami&quot; {<br>  type = bool<br>}<br><br>variable &quot;owners&quot; {<br>  type = list(string)<br>}<br><br>variable &quot;ami_name_filter&quot; {<br>  type = string<br>}<br><br>variable &quot;ami_values_filter&quot; {<br>  type = list(string)<br>}<br><br>variable &quot;instance_profile_name&quot; {<br>  type = string<br>}<br><br>variable &quot;instance_type&quot; {<br>  type = string<br>}<br><br>variable &quot;subnet_id&quot; {<br>  type = string<br>}<br><br>variable &quot;associate_public_ip_address&quot; {<br>  type = bool<br>}<br><br>variable &quot;vpc_security_group_ids&quot; {<br>  type = list(string)<br>}<br><br>variable &quot;has_user_data&quot; {<br>  type = bool<br>}<br><br>variable &quot;user_data_path&quot; {<br>  type = string<br>}<br><br>variable &quot;user_data_replace_on_change&quot; {<br>  type = bool<br>}<br><br>variable &quot;instance_name&quot; {<br>  type = string<br>}<br><br>variable &quot;uses_ssh&quot; {<br>  type = bool<br>}<br><br>variable &quot;key_name&quot; {<br>  type = string<br>}<br><br>variable &quot;tags&quot; {<br>  type = map(string)<br>}</pre><p><strong>main.tf</strong></p><pre># AMI<br>data &quot;aws_ami&quot; &quot;ami&quot; {<br>  most_recent = var.most_recent_ami<br>  owners      = var.owners<br><br>  filter {<br>    name   = var.ami_name_filter<br>    values = var.ami_values_filter<br>  }<br>}<br><br># EC2 Instance<br>resource &quot;aws_instance&quot; &quot;instance&quot; {<br>  ami                         = data.aws_ami.ami.id<br>  associate_public_ip_address = var.associate_public_ip_address<br>  iam_instance_profile        = var.instance_profile_name<br>  instance_type               = var.instance_type<br>  key_name                    = var.uses_ssh ? var.key_name : null<br>  subnet_id                   = var.subnet_id<br>  user_data                   = var.has_user_data ? file(var.user_data_path) : null<br>  user_data_replace_on_change = var.has_user_data ? var.user_data_replace_on_change : null<br>  vpc_security_group_ids      = var.vpc_security_group_ids<br><br>  tags = merge(var.tags, {<br>    Name = var.instance_name<br>  })<br>}<br><br>output &quot;instance_id&quot; {<br>  value = aws_instance.instance.id<br>}<br><br>output &quot;instance_arn&quot; {<br>  value = aws_instance.instance.arn<br>}<br><br>output &quot;instance_private_ip&quot; {<br>  value = aws_instance.instance.private_ip<br>}<br><br>output &quot;instance_public_ip&quot; {<br>  value = aws_instance.instance.public_ip<br>}<br><br>output &quot;instance_public_dns&quot; {<br>  value = aws_instance.instance.public_dns<br>}</pre><p>5. <strong>Security group module in VPC orchestration Terragrunt code</strong></p><p>In the <strong>vpc-live/dev/</strong> directory that we created in the previous article, we’ll create a new directory called <strong>security-group</strong> that will contain a <strong>terragrunt.hcl</strong> file.</p><p><strong>Directory structure</strong></p><pre>vpc-live/<br>  dev/<br>    ... (previous modules)<br>    security-group/<br>      terragrunt.hcl<br>  terragrunt.hcl</pre><p><strong>vpc-live/dev/security-group/terragrunt.hcl</strong></p><pre>include &quot;root&quot; {<br>  path = find_in_parent_folders()<br>}<br><br>terraform {<br>  source = &quot;&lt;path_to_local_security_group_building_block_or_git_repo_url&gt;&quot;<br>}<br><br>dependency &quot;vpc&quot; {<br>  config_path = &quot;../vpc&quot;<br>}<br><br>inputs = {<br>  AWS_ACCESS_KEY_ID = &quot;&lt;your_aws_access_key_id&gt;&quot;<br>  AWS_SECRET_ACCESS_KEY = &quot;&lt;your_aws_secret_access_key&gt;&quot;<br>  AWS_REGION = &quot;&lt;your_aws_region&gt;&quot;<br>  vpc_id = dependency.vpc.outputs.vpc_id<br>  name = &quot;dev-sg&quot;<br>  description = &quot;Allow HTTP (80), HTTPS (443) and SSH (22)&quot;<br>  ingress_rules = [<br>    {<br>      protocol    = &quot;tcp&quot;<br>      from_port   = 80<br>      to_port     = 80<br>      cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>    },<br>    {<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>      protocol    = &quot;tcp&quot;<br>      from_port   = 22<br>      to_port     = 22<br>      cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>    }<br>  ]<br>  egress_rules = [<br>    {<br>      protocol    = &quot;tcp&quot;<br>      from_port   = 80<br>      to_port     = 80<br>      cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>    },<br>    {<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>      protocol    = &quot;tcp&quot;<br>      from_port   = 22<br>      to_port     = 22<br>      cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>    }<br>  ]<br>  tags = {}<br>}</pre><p>This module will create a security group that allows internet traffic on ports 80 (HTTP), 443 (HTTPS), and 22 (SSH).</p><p>After adding this, I can run the command below from the <strong>vpc-live/dev/</strong> directory to create the security group (enter <strong>y</strong> when prompted to confirm the creation of the resource).<br>Be sure to set the appropriate values for <strong>AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY</strong>, and <strong>AWS_REGION, </strong>and DO NOT commit these values to a Git repository.</p><pre>terragrunt apply-all</pre><p>Below is part of the output of the above command which shows that the security group has been created:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H8H4M-4gs6tiHmXyBRzH0A.png" /><figcaption>Security group created with Terragrunt</figcaption></figure><p>6. <strong>Web server orchestration Terragrunt code</strong></p><p>To proceed, we’ll first need to copy the ID of one public subnet and the ID of our newly created security group from our VPC. Don’t use the ID in the image as that won’t work for you.</p><p>Our Terragrunt code will have the following directory structure:</p><pre>ec2-live/<br>  dev/<br>    apache-server/<br>      ec2-key-pair/<br>        terragrunt.hcl<br>      ec2-web-server/<br>        terragrunt.hcl<br>        user-data.sh<br>      ssm-instance-profile/<br>        terragrunt.hcl<br>      terragrunt.hcl</pre><p>The content of the <strong>terragrunt.hcl</strong> files will be shared below.<br>Notice that the <strong>ec2-web-server</strong> subdirectory contains a script (<strong>user-data.sh</strong>). This script will deploy the Apache web server to our EC2 instance as will be illustrated in a step further down.</p><p><strong>ec2-live/dev/apache-server/terragrunt.hcl</strong></p><pre>generate &quot;backend&quot; {<br>  path      = &quot;backend.tf&quot;<br>  if_exists = &quot;overwrite_terragrunt&quot;<br>  contents = &lt;&lt;EOF<br>terraform {<br>  backend &quot;s3&quot; {<br>    bucket         = &quot;&lt;s3_bucket_name&gt;&quot;<br>    key            = &quot;${path_relative_to_include()}/terraform.tfstate&quot;<br>    region         = &quot;us-east-1&quot;<br>    encrypt        = true<br>  }<br>}<br>EOF<br>}</pre><p>The above file, which is the root Terragrunt file, defines the backend configuration and will save the Terraform state file in an S3 bucket that you would have already created manually (and whose name will replace the placeholder <strong>&lt;s3_bucket_name&gt;</strong> in the above configuration).</p><p><strong>ec2-live/dev/apache-server/ec2-key-pair/terragrunt.hcl</strong></p><pre>include &quot;root&quot; {<br>  path = find_in_parent_folders()<br>}<br><br>terraform {<br>  source = &quot;&lt;path_to_local_key_pair_building_block_or_git_repo_url&gt;&quot;<br>}<br><br>inputs = {<br>  AWS_ACCESS_KEY_ID = &quot;&lt;your_aws_access_key_id&gt;&quot;<br>  AWS_SECRET_ACCESS_KEY = &quot;&lt;your_aws_secret_access_key&gt;&quot;<br>  AWS_REGION = &quot;&lt;your_aws_region&gt;&quot;<br>  key_name = &quot;Apache server SSH key pair&quot;<br>  public_key = &quot;&lt;your_ssh_public_key&gt;&quot;<br>  tags = {}<br>}</pre><p>This module will create the key pair that will be used to SSH into the EC2 instance.<br>Be sure to replace the <strong>source</strong> value in the <strong>terraform</strong> block with the path to your local building block or the URL of the Git repo hosting the building block’s code.<br>Also, replace the <strong>public_key </strong>value in the <strong>inputs</strong> section with the content of your SSH public key.</p><p><strong>ec2-live/dev/apache-server/ssm-instance-profile/terragrunt.hcl</strong></p><pre>include &quot;root&quot; {<br>  path = find_in_parent_folders()<br>}<br><br>terraform {<br>  source = &quot;&lt;path_to_local_ec2_instance_profile_building_block_or_git_repo_url&gt;&quot;<br>}<br><br>inputs = {<br>  AWS_ACCESS_KEY_ID = &quot;&lt;your_aws_access_key_id&gt;&quot;<br>  AWS_SECRET_ACCESS_KEY = &quot;&lt;your_aws_secret_access_key&gt;&quot;<br>  AWS_REGION = &quot;&lt;your_aws_region&gt;&quot;<br>  iam_policy_statements = [<br>    {<br>      sid = &quot;AllowEC2AssumeRole&quot;<br>      effect = &quot;Allow&quot;<br>      principals = {<br>        type        = &quot;Service&quot;<br>        identifiers = [&quot;ec2.amazonaws.com&quot;]<br>      }<br>      actions   = [&quot;sts:AssumeRole&quot;]<br>      resources = []<br>    }<br>  ]<br>  iam_role_name = &quot;EC2RoleForSSM&quot;<br>  iam_role_description = &quot;Allows EC2 instance to be managed by Systems Manager&quot;<br>  iam_role_path = &quot;/&quot;<br>  other_policy_arns = [&quot;arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore&quot;]<br>  instance_profile_name = &quot;EC2InstanceProfileForSSM&quot;<br>  tags = {<br>    Name = &quot;dev-ssm-instance-profile&quot;<br>  }<br>}</pre><p>This module allows us to use an AWS-managed IAM policy (<strong>AmazonSSMManagedInstanceCore</strong>) that grants <strong>Systems Manager</strong> the permissions it needs to manage an EC2 instance. This policy will then be attached to an IAM role (whose name we’ve defined as <strong>EC2RoleForSSM</strong> here) that will be created by the <strong>instance profile</strong> building block and attached to the created instance profile (that we’ve named <strong>EC2InstanceProfileForSSM</strong> here).</p><p><strong>ec2-live/dev/apache-server/ec2-web-server/terragrunt.hcl</strong></p><pre>include &quot;root&quot; {<br>  path = find_in_parent_folders()<br>}<br><br>terraform {<br>  source = &quot;&lt;path_to_local_ec2_instance_building_block_or_git_repo_url&gt;&quot;<br>}<br><br>dependency &quot;key-pair&quot; {<br>  config_path = &quot;../ec2-key-pair&quot; # Path to Terragrunt ec2-key-pair module<br>}<br><br>dependency &quot;instance-profile&quot; {<br>  config_path = &quot;../ssm-instance-profile&quot; # Path to Terragrunt ssm-instance-profile module<br>}<br><br>inputs = {<br>  AWS_ACCESS_KEY_ID = &quot;&lt;your_aws_access_key_id&gt;&quot;<br>  AWS_SECRET_ACCESS_KEY = &quot;&lt;your_aws_secret_access_key&gt;&quot;<br>  AWS_REGION = &quot;&lt;your_aws_region&gt;&quot;<br>  most_recent_ami = true<br>  owners = [&quot;amazon&quot;]<br>  ami_name_filter = &quot;name&quot;<br>  ami_values_filter = [&quot;al2023-ami-2023.*-x86_64&quot;]<br>  instance_profile_name = dependency.instance-profile.outputs.instance_profile_name<br>  instance_type = &quot;t3.micro&quot;<br>  subnet_id = &quot;&lt;copied_subnet_id&gt;&quot;<br>  associate_public_ip_address = true # Set to true so that our instance can be assigned a public IP address<br>  vpc_security_group_ids = [&quot;&lt;copied_security_group_id&gt;&quot;]<br>  has_user_data = true<br>  user_data_path = &quot;user-data.sh&quot;<br>  user_data_replace_on_change = true<br>  instance_name = &quot;Apache Server&quot;<br>  uses_ssh = true # Set to true so that the building block knows to uses the input below<br>  key_name = dependency.key-pair.outputs.key_name<br>  tags = {}<br>}</pre><p>This module depends on both the EC2 key pair and EC2 instance profile modules as indicated by the <strong>dependency </strong>blocks (as well as the values of the <strong>instance_profile_name</strong> and <strong>key_name</strong> inputs).<br>It will use the most recent version of the AWS <strong>Amazon Linux 2023</strong> AMI (as the values for <strong>most_recent_ami</strong>, <strong>owners</strong>, <strong>ami_name_filter,</strong> and <strong>ami_values_filter</strong> indicate) and will create an instance of type <strong>t3.micro, </strong>belonging to a public subnet in our VPC (whose ID we previously copied and should paste as the value of the <strong>subnet_id</strong> input) and also using the security group we created above (whose ID we also previously copied and should paste as a value in the array of values of the <strong>vpc_security_group_ids</strong> input).</p><p>The <strong>user_data_path</strong> input expects to receive the path to a script that will be executed only when the EC2 instance is first created. This script is the <strong>user-data.sh</strong> file that will contain instructions to deploy an Apache web server to our EC2 instance as shown below:</p><p><strong>ec2-live/dev/apache-server/ec2-web-server/user-data.sh</strong></p><pre>#!/bin/bash<br>yum update -y<br>yum install -y httpd<br>systemctl start httpd<br>systemctl enable httpd<br>echo &quot;&lt;h1&gt;Hello World from $(hostname -f)&lt;/h1&gt;&quot; &gt; /var/www/html/index.html</pre><p>This script does the following:<br>a) Updates the Amazon Linux 2023 system (<strong>yum update -y</strong>)<br>b) Installs <strong>httpd</strong> which is the Apache web server (<strong>yum install -y httpd</strong>)<br>c) Starts the Apache service (<strong>systemctl start httpd</strong>)<br>d) Ensures the Apache service is started whenever the server restarts (<strong>systemctl enable httpd</strong>)<br>e) Copies the string “&lt;h1&gt;Hello World from $(hostname -f)&lt;/h1&gt;” into the <strong>index.html</strong> file located in the <strong>/var/www/html/</strong> directory. This will make the server display this string in bold, replacing <strong>$(hostname -f)</strong> with the hostname of the EC2 instance.</p><p><strong>Putting it all together</strong></p><p>Our Terraform and Terragrunt configuration is now ready, so we can create the resources using the following Terragrunt command from within the <strong>ec2-live/dev/apache-server/</strong> directory. Enter <strong>y</strong> when prompted to confirm the creation of the resources.</p><pre>terragrunt apply-all</pre><p>The last output lines following the successful execution of this command should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8tdNRs3Lj_46ouWAeHV0IQ.png" /><figcaption>EC2 resources created successfully</figcaption></figure><p>From the list of outputs, we are most concerned with the <strong>instance_public_dns</strong> and <strong>instance_public_ip</strong>, whose values will allow us to access our web server from our browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xhl2o4IALRONkf6xG63DdQ.png" /><figcaption>Accessing web server via its public IP address</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DTwy-9MZMTJey8zCJHwGpA.png" /><figcaption>Accessing web server via its public DNS name</figcaption></figure><p>As you can see, both the public IP address and public DNS name return the same result when accessed from a browser.<br>You can also see that the message is the same as that which was set in the user data script, and it has replaced <strong>$(hostname -f)</strong> with the hostname of the created EC2 instance.</p><p><strong>Bonus — Systems Manager</strong></p><p>We can now access the AWS management console to check if our EC2 instance is managed by Systems Manager. To do this, we need to:<br>1. log in to the AWS management console,<br>2. then search for the <strong>Systems Manager</strong> service from the search bar. We can pick the <strong>Systems Manager</strong> option that is presented to us. This will take us to the Systems Manager console, where we can scroll down the menu and select <strong>Session Manager</strong> (under the <strong>Node Management</strong> section).<br>3. We’ll see a button labeled <strong>Start session</strong> that we should click on and we’ll be presented with a list of target instances.<br>4. Our instance will be in this list, so we can select its radio button and click on the <strong>Start session</strong> button at the bottom to log in to the instance.<br>Voilà!</p><p><strong>Conclusion</strong></p><p>Given that we can now easily deploy an Apache web server to an EC2 instance using both Terraform and Terragrunt, we should delete the resources we created to avoid incurring unexpected costs. We should do this from both the <strong>vpc-live/dev</strong> and <strong>ec2-live/dev/apache-server</strong> directories using the command below. Enter <strong>y</strong> when prompted to confirm the destruction of these resources.</p><pre>terragrunt destroy-all</pre><p>In the next article, we’ll create a second instance in a private subnet, and see how to use Ansible, a configuration management tool, to manage the configuration of our public and private instances.</p><p>Until then, happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fba9d51fc21e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Terraform & Terragrunt to Create a VPC and its Components (Part II)]]></title>
            <link>https://stephanenoutsa.medium.com/terraform-terragrunt-to-create-a-vpc-and-its-components-part-ii-8f34a1d8d365?source=rss-8f915bc52368------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f34a1d8d365</guid>
            <category><![CDATA[terragrunt]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[iac]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Stéphane Noutsa]]></dc:creator>
            <pubDate>Tue, 04 Jul 2023 06:38:30 GMT</pubDate>
            <atom:updated>2023-07-04T06:38:30.056Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ixqIFlcBJCItbUWFae-F3Q.jpeg" /><figcaption>Terraform &amp; Terragrunt to Create a VPC and its Components (Part II)</figcaption></figure><p>Terragrunt is a powerful open-source tool that serves as a wrapper around Terraform, providing enhanced features and simplifying the management of Terraform deployments. With Terragrunt, infrastructure as code (IaC) practitioners can achieve more effective and scalable infrastructure management in complex environments. By abstracting common Terraform tasks, Terragrunt facilitates the creation, deployment, and maintenance of infrastructure resources, enabling teams to efficiently manage infrastructure with consistency and ease.</p><p>In the <a href="https://stephanenoutsa.medium.com/terraform-terragrunt-to-create-a-vpc-and-its-components-part-i-4de01b78e46f">previous article</a>, we created Terraform building blocks which we’ll use in this article to orchestrate the creation of a VPC with the components below.<br>This article assumes some familiarity with Terraform and Terragrunt.</p><ol><li>A VPC (obviously 😅)</li><li>An Internet Gateway</li><li>A route table for the public subnet (which we’ll just call <strong>public route table</strong>)</li><li>A public subnet</li><li>An Elastic IP (EIP) for the NAT Gateway</li><li>A NAT Gateway</li><li>A route table for the private subnet (which we’ll just call <strong>private route table</strong>)</li><li>A private subnet</li><li>A Network Access Control List (NACL)</li></ol><p>Our Terragrunt project will have the following folder structure and files:</p><pre>vpc-live/<br>  &lt;environment&gt;/<br>    &lt;module_1&gt;/<br>      terragrunt.hcl<br>    &lt;module_2&gt;/<br>      terragrunt.hcl<br>    ...<br>    &lt;module_n&gt;/<br>      terragrunt.hcl<br>  terragrunt.hcl</pre><p>Basically, we’ll have a parent directory which we’ll call <strong>vpc-live</strong>. This directory will contain a root <strong>terragrunt.hcl</strong> file and a directory for each environment we’ll want to create our resources in (e.g <strong>dev</strong>, <strong>staging</strong>, <strong>prod</strong>). For our article, we’ll only have a <strong>dev</strong> directory. This directory will contain directories that will represent the different specific resources we’ll want to create.</p><p>Our final folder structure will be:</p><pre>vpc-live/<br>  dev/<br>    elastic-ip/<br>      terragrunt.hcl<br>    internet-gateway/<br>      terragrunt.hcl<br>    nacl/<br>      terragrunt.hcl<br>    nat-gateway/<br>      terragrunt.hcl<br>    private-route-table/<br>      terragrunt.hcl<br>    private-subnet/<br>      terragrunt.hcl<br>    public-route-table/<br>      terragrunt.hcl<br>    public-subnet/<br>      terragrunt.hcl<br>    vpc/<br>      terragrunt.hcl<br>  terragrunt.hcl</pre><p>0.<strong> Root terragrunt.hcl file</strong></p><p>Our root <strong>terragrunt.hcl</strong> file will contain the configuration for our remote Terraform state. We’ll use an S3 bucket in AWS to store our Terraform state file, and the name of our S3 bucket must be unique for it to be successfully created. My S3 bucket is in the Paris region (eu-west-3).</p><p><strong>vpc-live/terragrunt.hcl</strong></p><pre>generate &quot;backend&quot; {<br>  path      = &quot;backend.tf&quot;<br>  if_exists = &quot;overwrite_terragrunt&quot;<br>  contents = &lt;&lt;EOF<br>terraform {<br>  backend &quot;s3&quot; {<br>    bucket         = &quot;snk-terraform-state&quot;<br>    key            = &quot;${path_relative_to_include()}/terraform.tfstate&quot;<br>    region         = &quot;eu-west-3&quot;<br>    encrypt        = true<br>  }<br>}<br>EOF<br>}</pre><p>It should be noted that our module <strong>terragrunt.hcl</strong> files’ Terraform source could either be the path to the local building block or the URL of the Git repository hosting our building block’s code.<br>(We created the different building blocks in our <a href="https://stephanenoutsa.medium.com/terraform-terragrunt-to-create-a-vpc-and-its-components-part-i-4de01b78e46f">previous article</a>)</p><ol><li><strong>VPC</strong></li></ol><p>This module uses the <strong>VPC</strong> building block as its Terraform source.</p><p><strong>vpc-live/dev/vpc/terragrunt.hcl</strong></p><pre>include &quot;root&quot; {<br>  path = find_in_parent_folders()<br>}<br><br>terraform {<br>  source = &lt;path_to_local_vpc_building_block_or_git_repo_url&gt;<br>}<br><br>inputs = {<br>  vpc_cidr = &quot;10.0.0.0/16&quot;<br>  vpc_name = &quot;dev-vpc&quot;<br>  instance_tenancy = &quot;default&quot;<br>  enable_dns_support = true<br>  enable_dns_hostnames = true<br>  assign_generated_ipv6_cidr_block = false<br>  vpc_tags = {}<br>}</pre><p>The <strong>include</strong> block will include the root <strong>terragrunt.hcl</strong> file (with the backend configuration), and will substitute the key of our bucket configuration with the path to each module’s <strong>terragrunt.hcl </strong>file.</p><p>The values passed in the inputs section are the variables that are defined in the building blocks.</p><p>For this module and the following modules, we won’t be passing the variables <strong>AWS_ACCESS_KEY_ID</strong>,<strong> AWS_SECRET_ACCESS_KEY</strong>, and <strong>AWS_REGION </strong>since such credentials (bar the <strong>AWS_REGION</strong> variable) are sensitive). You’ll have to add them yourself since they’re required.</p><p><strong>NB:</strong> Please don’t commit these credentials to version control systems as that is not secure. Ideally, you’ll have a pipeline whose job runner will have the credentials configured as the default profile, or the runner will be able to assume a role that will allow it to create the resources.</p><p>2. <strong>Internet Gateway</strong></p><p>This module uses the <strong>Internet Gateway</strong> building block as its Terraform source.</p><p><strong>vpc-live/dev/internet-gateway/terragrunt.hcl</strong></p><pre>include &quot;root&quot; {<br>  path = find_in_parent_folders()<br>}<br><br>terraform {<br>  source = &lt;path_to_local_internet_gateway_building_block_or_git_repo_url&gt;<br>}<br><br>dependency &quot;vpc&quot; {<br>  config_path = &quot;../vpc&quot;<br>}<br><br>inputs = {<br>  vpc_id = dependency.vpc.outputs.vpc_id<br>  name = &quot;dev-igw&quot;<br>  tags = {}<br>}</pre><p>The <strong>dependency</strong> block indicates that this module requires outputs (the VPC ID) from the <strong>VPC </strong>module which we created in step 1.</p><p>3. <strong>Public Route Table</strong></p><p>This module uses the <strong>Route Table</strong> building block as its Terraform source.</p><p><strong>vpc-live/dev/public-route-table/terragrunt.hcl</strong></p><pre>include &quot;root&quot; {<br>  path = find_in_parent_folders()<br>}<br><br>terraform {<br>  source = &lt;path_to_local_route_table_building_block_or_git_repo_url&gt;<br>}<br><br>dependency &quot;vpc&quot; {<br>  config_path = &quot;../vpc&quot;<br>}<br><br>dependency &quot;igw&quot; {<br>  config_path = &quot;../internet-gateway&quot;<br>}<br><br>inputs = {<br>  route_tables = [<br>    {<br>      name      = &quot;dev-public-rt&quot;<br>      vpc_id    = dependency.vpc.outputs.vpc_id<br>      is_igw_rt = true<br><br>      routes = [<br>        {<br>          cidr_block = &quot;0.0.0.0/0&quot;<br>          igw_id     = dependency.igw.outputs.igw_id<br>        }<br>      ]<br><br>      tags = {}<br>    }<br>  ]<br>}</pre><p>This module requires outputs from both the <strong>VPC</strong> and <strong>Internet Gateway</strong> modules.</p><p>4. <strong>Public Subnet</strong></p><p>This module uses the <strong>Subnet</strong> building block as its Terraform source.</p><p><strong>vpc-live/dev/public-subnet/terragrunt.hcl</strong></p><pre>include &quot;root&quot; {<br>  path = find_in_parent_folders()<br>}<br><br>terraform {<br>  source = &lt;path_to_local_subnet_building_block_or_git_repo_url&gt;<br>}<br><br>dependency &quot;vpc&quot; {<br>  config_path = &quot;../vpc&quot;<br>}<br><br>dependency &quot;public-route-table&quot; {<br>  config_path = &quot;../public-route-table&quot;<br>}<br><br>inputs = {<br>  subnets = [<br>    {<br>      name                                = &quot;dev-public-subnet&quot;<br>      vpc_id                              = dependency.vpc.outputs.vpc_id<br>      cidr_block                          = &quot;10.0.0.0/24&quot;<br>      availability_zone                   = &quot;eu-west-3a&quot;<br>      map_public_ip_on_launch             = true<br>      private_dns_hostname_type_on_launch = &quot;resource-name&quot;<br>      is_public                           = true<br>      route_table_id                      = dependency.public-route-table.outputs.route_table_ids[0]<br>      tags                                = {}<br>    }<br>  ]<br>}</pre><p>This module requires outputs from both the <strong>VPC</strong> and <strong>Public Route Table</strong> modules.</p><p>5. <strong>Elastic IP (EIP)</strong></p><p>This module will create an EIP which will be attached to the NAT Gateway that we’ll create.<br>It uses the <strong>Elastic IP</strong> building block as its Terraform source.</p><p><strong>vpc-live/dev/elastic-ip/terragrunt.hcl</strong></p><pre>include &quot;root&quot; {<br>  path = find_in_parent_folders()<br>}<br><br>terraform {<br>  source = &lt;path_to_local_elastic_ip_building_block_or_git_repo_url&gt;<br>}<br><br>inputs = {<br>  in_vpc = true<br>  tags = {}<br>}</pre><p>This module does not depend on any other module, so it will actually be created before other modules which have dependencies.</p><p>6. <strong>NAT Gateway</strong></p><p>This module uses the <strong>NAT Gateway</strong> building block as its Terraform source.</p><p><strong>vpc-live/dev/nat-gateway/terragrunt.hcl</strong></p><pre>include &quot;root&quot; {<br>  path = find_in_parent_folders()<br>}<br><br>terraform {<br>  source = &lt;path_to_local_nat_gateway_building_block_or_git_repo_url&gt;<br>}<br><br>dependency &quot;eip&quot; {<br>  config_path = &quot;../elastic-ip&quot;<br>}<br><br>dependency &quot;public-subnet&quot; {<br>  config_path = &quot;../public-subnet&quot;<br>}<br><br>inputs = {<br>  eip_id = dependency.eip.outputs.eip_id<br>  subnet_id = dependency.public-subnet.outputs.public_subnets[0]<br>  name = &quot;dev-nat-gw&quot;<br>  tags = {}<br>}</pre><p>This module requires outputs from both the <strong>Elastic IP</strong> and <strong>Public Subnet</strong> modules, given that the NAT Gateway needs (a) to have a public IP address and (b) to be in a public subnet.</p><p>7. <strong>Private Route Table</strong></p><p>This module uses the <strong>Route Table</strong> building block as its Terraform source.</p><p><strong>vpc-live/dev/private-route-table/terragrunt.hcl</strong></p><pre>include &quot;root&quot; {<br>  path = find_in_parent_folders()<br>}<br><br>terraform {<br>  source = &lt;path_to_local_route_table_building_block_or_git_repo_url&gt;<br>}<br><br>dependency &quot;vpc&quot; {<br>  config_path = &quot;../vpc&quot;<br>}<br><br>dependency &quot;nat-gateway&quot; {<br>  config_path = &quot;../nat-gateway&quot;<br>}<br><br>inputs = {<br>  route_tables = [<br>    {<br>      name      = &quot;dev-private-rt&quot;<br>      vpc_id    = dependency.vpc.outputs.vpc_id<br>      is_igw_rt = false<br><br>      routes = [<br>        {<br>          cidr_block = &quot;0.0.0.0/0&quot;<br>          nat_gw_id  = dependency.nat-gateway.outputs.nat_gw_id<br>        }<br>      ]<br><br>      tags = {}<br>    }<br>  ]<br>}</pre><p>This module requires outputs from both the <strong>VPC</strong> and <strong>NAT Gateway </strong>modules.</p><p>8. <strong>Private Subnet</strong></p><p>This module uses the <strong>Subnet</strong> building block as its Terraform source.</p><p><strong>vpc-live/dev/private-subnet/terragrunt.hcl</strong></p><pre>include &quot;root&quot; {<br>  path = find_in_parent_folders()<br>}<br><br>terraform {<br>  source = &lt;path_to_local_subnet_building_block_or_git_repo_url&gt;<br>}<br><br>dependency &quot;vpc&quot; {<br>  config_path = &quot;../vpc&quot;<br>}<br><br>dependency &quot;private-route-table&quot; {<br>  config_path = &quot;../private-route-table&quot;<br>}<br><br>inputs = {<br>  subnets = [<br>    {<br>      name                                = &quot;dev-private-subnet&quot;<br>      vpc_id                              = dependency.vpc.outputs.vpc_id<br>      cidr_block                          = &quot;10.0.1.0/24&quot;<br>      availability_zone                   = &quot;eu-west-3a&quot;<br>      map_public_ip_on_launch             = false<br>      private_dns_hostname_type_on_launch = &quot;resource-name&quot;<br>      is_public                           = false<br>      route_table_id                      = dependency.private-route-table.outputs.route_table_ids[0]<br>      tags                                = {}<br>    }<br>  ]<br>}</pre><p>This module requires outputs from both the <strong>VPC</strong> and <strong>Private Route Table</strong> modules.</p><p>9. <strong>Network Access Control List (NACL)</strong></p><p>This module uses the <strong>NACL</strong> building block as its Terraform source.</p><p><strong>vpc-live/dev/nacl/terragrunt.hcl</strong></p><pre>include &quot;root&quot; {<br>  path = find_in_parent_folders()<br>}<br><br>terraform {<br>  source = &lt;path_to_local_nacl_building_block_or_git_repo_url&gt;<br>}<br><br>dependency &quot;vpc&quot; {<br>  config_path = &quot;../vpc&quot;<br>}<br><br>dependency &quot;public-subnet&quot; {<br>  config_path = &quot;../public-subnet&quot;<br>}<br><br>dependency &quot;private-subnet&quot; {<br>  config_path = &quot;../private-subnet&quot;<br>}<br><br>inputs = {<br>  nacls = [<br>    {<br>      name   = &quot;open-public-nacl&quot;<br>      vpc_id = dependency.vpc.outputs.vpc_id<br>      egress = [<br>        {<br>          protocol   = &quot;-1&quot;<br>          rule_no    = 100<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>      ingress = [<br>        {<br>          protocol   = &quot;-1&quot;<br>          rule_no    = 100<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>      subnet_id = dependency.public-subnet.outputs.public_subnets[0]<br>      tags      = {}<br>    },<br>    {<br>      name   = &quot;open-private-nacl&quot;<br>      vpc_id = dependency.vpc.outputs.vpc_id<br>      egress = [<br>        {<br>          protocol   = &quot;-1&quot;<br>          rule_no    = 100<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>      ingress = [<br>        {<br>          protocol   = &quot;-1&quot;<br>          rule_no    = 100<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>      subnet_id = dependency.private-subnet.outputs.private_subnets[0]<br>      tags      = {}<br>    }<br>  ]<br>}</pre><p>This module creates two NACLs: one for the public subnet and one for the private subnet. Their security rules allow traffic from and to all sources for simplicity, and that’s not secure. You should modify the values for ingress and egress to only allow the traffic you desire, making the rules more secure.</p><p>The module requires outputs from the <strong>VPC</strong>, <strong>Public Subnet</strong>, and <strong>Private Subnet</strong> modules.</p><p>10. <strong>Creating the Resources</strong></p><p>Terragrunt will allow us to orchestrate the creation of our VPC and its components through the modules we’ve created above.</p><p>First, we’ll need to <strong>cd</strong> into our environment’s directory from the terminal:</p><pre>cd vpc-live/dev</pre><p>Here, we can now run the following command to instruct Terragrunt to loop through all the module directories and create the different resources:</p><pre>terragrunt apply-all</pre><p>We should then see a similar prompt in our terminal. Enter <strong>y</strong> to confirm the creation of all the resources:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ngkl1bEm6OGpV5-08GWeqA.png" /><figcaption>terragrunt apply-all</figcaption></figure><p>You should then see the outputs as each resource is created until it’s all done!</p><p><strong>Conclusion</strong></p><p>We’ve seen how to orchestrate the creation of a VPC and its components with Terragrunt, using basic Terraform building blocks.</p><p>We could create as many building blocks as we’d like with Terraform, then use Terragrunt to orchestrate the creation of an architecture that fits the needs of different projects (and in different environments) by simply reusing these building blocks. This will help us to keep our code DRY.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f34a1d8d365" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Terraform & Terragrunt to Create a VPC and its Components (Part I)]]></title>
            <link>https://stephanenoutsa.medium.com/terraform-terragrunt-to-create-a-vpc-and-its-components-part-i-4de01b78e46f?source=rss-8f915bc52368------2</link>
            <guid isPermaLink="false">https://medium.com/p/4de01b78e46f</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[iac]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Stéphane Noutsa]]></dc:creator>
            <pubDate>Mon, 03 Jul 2023 17:11:27 GMT</pubDate>
            <atom:updated>2023-07-03T17:11:27.574Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IFDP2EgNsSrY4rmXFJb5Cg.png" /><figcaption>Infrastructure as Code (IaC) with Terraform</figcaption></figure><p>In the era of cloud computing, infrastructure as code (IaC) has gained immense popularity due to its ability to provision and manage infrastructure resources in a consistent and automated manner. Terraform, an open-source IaC tool by HashiCorp, has emerged as a leading choice for provisioning and managing cloud resources, including those offered by Amazon Web Services (AWS).</p><p>In this article, we will explore the process of using Terraform to create basic AWS modules (which we’ll call building blocks), enabling you to deploy and manage infrastructure easily and efficiently. We’ll create the following building blocks:</p><ol><li>A VPC (obviously)</li><li>An internet gateway</li><li>A route table</li><li>A subnet</li><li>An elastic IP (EIP)</li><li>A NAT gateway</li><li>A NACL for the subnets</li></ol><p>This is the first article in a 2-part series on how to use Terraform and Terragrunt to create a VPC with its components, and it assumes some familiarity with Terraform.</p><p><strong>0. Common Files<br></strong>Our Terraform building blocks will be independent projects which will, however, share common files — the <strong>provider.tf</strong> and <strong>variables.tf</strong> files.</p><p><strong>variables.tf</strong></p><pre>variable &quot;AWS_ACCESS_KEY_ID&quot; {<br>  type = string<br>}<br><br>variable &quot;AWS_SECRET_ACCESS_KEY&quot; {<br>  type = string<br>}<br><br>variable &quot;AWS_REGION&quot; {<br>  type = string<br>}</pre><p>It should be noted that each building block will add more variables to its <strong>variables.tf</strong> file depending on its requirements.</p><p><strong>provider.tf</strong></p><pre>terraform {<br>  required_version = &quot;&gt;= 1.4.2&quot;<br><br>  required_providers {<br>    aws = {<br>      source  = &quot;hashicorp/aws&quot;<br>      version = &quot;~&gt; 4.0&quot;<br>    }<br>  }<br>}<br><br>provider &quot;aws&quot; {<br>  access_key = var.AWS_ACCESS_KEY_ID<br>  secret_key = var.AWS_SECRET_ACCESS_KEY<br>  region     = var.AWS_REGION<br>}</pre><ol><li><strong>VPC</strong></li></ol><p>The VPC will be the main building block that will contain all the other building blocks.<br>(Take note of the output section which outputs the VPC’s ID)</p><p><strong>main.tf</strong></p><pre>resource &quot;aws_vpc&quot; &quot;vpc&quot; {<br>  cidr_block                       = var.vpc_cidr<br>  instance_tenancy                 = var.instance_tenancy<br>  enable_dns_support               = var.enable_dns_support<br>  enable_dns_hostnames             = var.enable_dns_hostnames<br>  assign_generated_ipv6_cidr_block = var.assign_generated_ipv6_cidr_block<br><br>  tags = merge(var.vpc_tags, {<br>    Name = var.vpc_name<br>  })<br>}<br><br>output &quot;vpc_id&quot; {<br>  value = aws_vpc.vpc.id<br>}</pre><p><strong>variables.tf </strong>(additional variables)</p><pre>variable &quot;vpc_cidr&quot; {<br>  type = string<br>}<br><br>variable &quot;vpc_name&quot; {<br>  type = string<br>}<br><br>variable &quot;instance_tenancy&quot; {<br>  type    = string<br>  default = &quot;default&quot;<br>}<br><br>variable &quot;enable_dns_support&quot; {<br>  type    = bool<br>  default = true<br>}<br><br>variable &quot;enable_dns_hostnames&quot; {<br>  type = bool<br>}<br><br>variable &quot;assign_generated_ipv6_cidr_block&quot; {<br>  type    = bool<br>  default = false<br>}<br><br>variable &quot;vpc_tags&quot; {<br>  type = map(string)<br>}</pre><p>2. <strong>Internet Gateway</strong></p><p>The internet gateway will allow two-way communication between the internet and resources in the VPC (in the public subnet to be more precise).</p><p><strong>main.tf</strong></p><pre>resource &quot;aws_internet_gateway&quot; &quot;igw&quot; {<br>  vpc_id = var.vpc_id<br><br>  tags = merge(var.tags, {<br>    Name = var.name<br>  })<br>}<br><br>output &quot;igw_id&quot; {<br>  value = aws_internet_gateway.igw.id<br>}</pre><p><strong>variables.tf</strong> (additional variables)</p><pre>variable &quot;vpc_id&quot; {<br>  type = string<br>}<br><br>variable &quot;name&quot; {<br>  type = string<br>}<br><br>variable &quot;tags&quot; {<br>  type = map(string)<br>}</pre><p>3. <strong>Route Table</strong></p><p>The route table will have a route that will allow resources in public and private subnets to communicate with the Internet through an Internet Gateway (for public subnets) or a NAT Gateway (for private subnets).</p><p><strong>main.tf</strong></p><pre>resource &quot;aws_route_table&quot; &quot;route_tables&quot; {<br>  for_each = { for rt in var.route_tables : rt.name =&gt; rt }<br><br>  vpc_id = each.value.vpc_id<br><br>  dynamic &quot;route&quot; {<br>    for_each = { for route in each.value.routes : route.cidr_block =&gt; route if each.value.is_igw_rt }<br><br>    content {<br>      cidr_block = route.value.cidr_block<br>      gateway_id = route.value.igw_id<br>    }<br>  }<br><br>  dynamic &quot;route&quot; {<br>    for_each = { for route in each.value.routes : route.cidr_block =&gt; route if !each.value.is_igw_rt }<br><br>    content {<br>      cidr_block     = route.value.cidr_block<br>      nat_gateway_id = route.value.nat_gw_id<br>    }<br>  }<br><br>  tags = merge(each.value.tags, {<br>    Name = each.value.name<br>  })<br>}<br><br>output &quot;route_table_ids&quot; {<br>  value = values(aws_route_table.route_tables)[*].id<br>}</pre><p>The <strong>route</strong> blocks use conditional statements to determine which entries to create for the route table.</p><p><strong>variables.tf </strong>(additional variables)</p><pre>variable &quot;route_tables&quot; {<br>  type = list(object({<br>    name      = string<br>    vpc_id    = string<br>    is_igw_rt = bool<br><br>    routes = list(object({<br>      cidr_block = string<br>      igw_id     = optional(string)<br>      nat_gw_id  = optional(string)<br>    }))<br><br>    tags = map(string)<br>  }))<br>}</pre><p>4. <strong>Subnet</strong></p><p>This building block will allow the creation of public subnets or private subnets, depending on the values passed to its variables.</p><p><strong>main.tf</strong></p><pre># Create public subnets<br>resource &quot;aws_subnet&quot; &quot;public_subnets&quot; {<br>  for_each = { for subnet in var.subnets : subnet.name =&gt; subnet if subnet.is_public }<br><br>  vpc_id                              = each.value.vpc_id<br>  cidr_block                          = each.value.cidr_block<br>  availability_zone                   = each.value.availability_zone<br>  map_public_ip_on_launch             = each.value.map_public_ip_on_launch<br>  private_dns_hostname_type_on_launch = each.value.private_dns_hostname_type_on_launch<br><br>  tags = merge(each.value.tags, {<br>    Name = each.value.name<br>  })<br>}<br><br># Associate public subnets with their route table<br>resource &quot;aws_route_table_association&quot; &quot;public_subnets&quot; {<br>  for_each = { for subnet in var.subnets : subnet.name =&gt; subnet if subnet.is_public }<br><br>  subnet_id      = aws_subnet.public_subnets[each.value.name].id<br>  route_table_id = each.value.route_table_id<br>}<br><br># Create private subnets<br>resource &quot;aws_subnet&quot; &quot;private_subnets&quot; {<br>  for_each = { for subnet in var.subnets : subnet.name =&gt; subnet if !subnet.is_public }<br><br>  vpc_id                              = each.value.vpc_id<br>  cidr_block                          = each.value.cidr_block<br>  availability_zone                   = each.value.availability_zone<br>  private_dns_hostname_type_on_launch = each.value.private_dns_hostname_type_on_launch<br><br>  tags = merge(each.value.tags, {<br>    Name = each.value.name<br>  })<br>}<br><br># Associate private subnets with their route table<br>resource &quot;aws_route_table_association&quot; &quot;private_subnets&quot; {<br>  for_each = { for subnet in var.subnets : subnet.name =&gt; subnet if !subnet.is_public }<br><br>  subnet_id      = aws_subnet.private_subnets[each.value.name].id<br>  route_table_id = each.value.route_table_id<br>}</pre><p><strong>variables.tf </strong>(additional variables)</p><pre>variable &quot;subnets&quot; {<br>  type = list(object({<br>    name                                = string<br>    vpc_id                              = string<br>    cidr_block                          = string<br>    availability_zone                   = optional(string)<br>    map_public_ip_on_launch             = optional(bool, true)<br>    private_dns_hostname_type_on_launch = optional(string, &quot;resource-name&quot;)<br>    is_public                           = optional(bool, true)<br>    route_table_id                      = string<br>    tags                                = map(string)<br>  }))<br>}</pre><p>5. <strong>Elastic IP (EIP)</strong></p><p>The EIP can be used to assign a static public IP to a resource such as an EC2 instance or a NAT Gateway. In our case, it will be attached to the NAT Gateway that we’ll create.</p><p><strong>main.tf</strong></p><pre>resource &quot;aws_eip&quot; &quot;eip&quot; {<br>  vpc = var.in_vpc<br><br>  tags = merge(var.tags, {})<br>}<br><br>output &quot;eip_id&quot; {<br>  value = aws_eip.eip.id<br>}</pre><p><strong>variables.tf</strong> (additional variables)</p><pre>variable &quot;in_vpc&quot; {<br>  type = bool<br>}<br><br>variable &quot;tags&quot; {<br>  type = map(string)<br>}</pre><p>6. <strong>Network Address Translation (NAT) Gateway</strong></p><p>The NAT Gateway will allow resources in private subnets to make one-way requests to the Internet (and receive responses). It has to be placed in a public subnet and should have a public IP address (which is why an EIP will first be created).</p><p><strong>main.tf</strong></p><pre>resource &quot;aws_nat_gateway&quot; &quot;nat_gw&quot; {<br>  allocation_id = var.eip_id<br>  subnet_id     = var.subnet_id<br><br>  tags = merge(var.tags, {<br>    Name = var.name<br>  })<br>}<br><br>output &quot;nat_gw_id&quot; {<br>  value = aws_nat_gateway.nat_gw.id<br>}</pre><p><strong>variables.tf</strong> (additional variables)</p><pre>variable &quot;name&quot; {<br>  type = string<br>}<br><br>variable &quot;eip_id&quot; {<br>  type = string<br>}<br><br>variable &quot;subnet_id&quot; {<br>  type        = string<br>  description = &quot;The ID of the public subnet in which the NAT Gateway should be placed&quot;<br>}<br><br>variable &quot;tags&quot; {<br>  type = map(string)<br>}</pre><p>7. <strong>Network Access Control List (NACL)</strong></p><p>The NACL acts like a firewall at the subnet level, allowing or denying traffic into or out of the subnet.<br>After a NACL is created, it has to be associated with a subnet before it can start filtering its traffic.</p><p><strong>main.tf</strong></p><pre>resource &quot;aws_network_acl&quot; &quot;nacls&quot; {<br>  for_each = { for nacl in var.nacls : nacl.name =&gt; nacl }<br><br>  vpc_id = each.value.vpc_id<br><br>  dynamic &quot;egress&quot; {<br>    for_each = { for rule in each.value.egress : rule.rule_no =&gt; rule }<br><br>    content {<br>      protocol   = egress.value.protocol<br>      rule_no    = egress.value.rule_no<br>      action     = egress.value.action<br>      cidr_block = egress.value.cidr_block<br>      from_port  = egress.value.from_port<br>      to_port    = egress.value.to_port<br>    }<br>  }<br><br>  dynamic &quot;ingress&quot; {<br>    for_each = { for rule in each.value.ingress : rule.rule_no =&gt; rule }<br><br>    content {<br>      protocol   = ingress.value.protocol<br>      rule_no    = ingress.value.rule_no<br>      action     = ingress.value.action<br>      cidr_block = ingress.value.cidr_block<br>      from_port  = ingress.value.from_port<br>      to_port    = ingress.value.to_port<br>    }<br>  }<br><br>  tags = merge(each.value.tags, {<br>    Name = each.value.name<br>  })<br>}<br><br>resource &quot;aws_network_acl_association&quot; &quot;nacl_associations&quot; {<br>  for_each = { for nacl in var.nacls : &quot;${nacl.name}_${nacl.subnet_id}&quot; =&gt; nacl }<br><br>  network_acl_id = aws_network_acl.nacls[each.value.name].id<br>  subnet_id      = each.value.subnet_id<br>}</pre><p><strong>variables.tf</strong></p><pre>variable &quot;nacls&quot; {<br>  type = list(object({<br>    name   = string<br>    vpc_id = string<br>    egress = list(object({<br>      protocol   = string<br>      rule_no    = number<br>      action     = string<br>      cidr_block = string<br>      from_port  = number<br>      to_port    = number<br>    }))<br>    ingress = list(object({<br>      protocol   = string<br>      rule_no    = number<br>      action     = string<br>      cidr_block = string<br>      from_port  = number<br>      to_port    = number<br>    }))<br>    subnet_id = string<br>    tags      = map(string)<br>  }))<br>}</pre><p><strong>Conclusion</strong></p><p>After creating all these building blocks, we can proceed to orchestrate the creation of a VPC with its components depending on its specific needs. This orchestration can be done using another IaC tool called <strong>Terragrunt</strong>. We’ll look at that in the second (and last) part of this series.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4de01b78e46f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Amazon EC2 Instances or AWS Lambda Functions?]]></title>
            <link>https://stephanenoutsa.medium.com/amazon-ec2-instances-or-aws-lambda-functions-10efc1ac9d84?source=rss-8f915bc52368------2</link>
            <guid isPermaLink="false">https://medium.com/p/10efc1ac9d84</guid>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[ec2]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[web-hosting]]></category>
            <dc:creator><![CDATA[Stéphane Noutsa]]></dc:creator>
            <pubDate>Tue, 27 Jun 2023 16:38:12 GMT</pubDate>
            <atom:updated>2023-06-27T16:38:12.351Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Amazon EC2 vs AWS Lambda" src="https://cdn-images-1.medium.com/max/800/1*rGnGpk2uHjGWsXjquTtk4w.jpeg" /></figure><p>Once upon a time, in the enchanted world of cloud computing, there were two services, Amazon EC2 and AWS Lambda, that were always in competition with each other. Each believed they were the best and, often disagreed about who should handle specific computing workloads.</p><p>The first contender in this tale of the cloud world is Amazon Elastic Compute Cloud (EC2), which was launched first (August 2006) and has been around much longer.</p><p>Now, EC2 is kind of like a fancy hotel, where you can rent a room for as long as you need, and you’re responsible for bringing all your stuff and doing all the chores yourself.</p><p>On the other hand, AWS Lambda is more like a hotel with a very attentive staff. They give you a room, take care of all your needs, and when you’re done, you just leave! You don’t have to worry about bringing your luggage, doing your laundry, or even cleaning up after yourself.</p><p>Now, initially, both services believed they could handle any workload that came their way. But slowly, they started to discover the areas where they truly stood out from each other.</p><p>For instance, EC2 is great when you need to run a big, complex application that requires a lot of dedicated resources and an extended period to complete. Take the example of a group of developers working on a new software application. They require a lot of storage space, network connectivity, and computing power to run the application and put it through its paces. This kind of workload requires the ability to adjust resources and configurations, which makes EC2 the best option.</p><p>AWS Lambda, on the other hand, is the perfect candidate when you only need to use computing resources for small units of time. It’s like asking the hotel staff to wake you up with a cup of coffee in the morning. You don’t need your laptop to boot up and run your email server, you only need it to send an email. This is where AWS Lambda comes into its own.</p><p>The serverless model of AWS Lambda means that you don’t have to worry about the underlying infrastructure and configuration of the resources. Instead, you can just upload your code, and AWS will take care of the rest. Despite being launched much later (November 2014), AWS Lambda quickly made a name for itself by providing a highly efficient means of executing code.</p><p>Of course, this didn’t sit well with EC2. They felt like AWS Lambda was encroaching on their turf. So they started pointing out the areas they believe their service far outdid AWS Lambda. This includes any workload that requires extensive data processing, storage, or networking requirements, which is EC2’s bread and butter.</p><p>For instance, let’s imagine that you’re running a machine-learning model for a project. EC2 is your perfect partner because it requires a lot of resources to train the algorithm correctly. The workflow includes installing and configuring libraries such as TensorFlow, PyTorch, and Scikit-learn, which would take up a considerable portion of your time. As for AWS Lambda, it is unsuitable for this kind of workload as it has a cold start time and a maximum execution timeout of 15 minutes. This means that it would take more time initially to spin up the computing environment before running the model, and the model will need to be trained within the 15-minute execution time limit.</p><p>But then, AWS Lambda was not going down without a fight. They soon discovered that their serverless offering is a perfect fit for any application that requires immediate scaling, such as real-time responses for sensors, IoT devices, and data exchanges.</p><p>For example, let’s say you want to build a chatbot that requires real-time responses and supports many concurrent users. You can use AWS Lambda to develop a scaled-up version of it. AWS Lambda can easily execute multiple concurrent instances of code per user and provide extremely low latency, ensuring a seamless user experience. With EC2, you would have to spin up extra instances whenever traffic increases or have fewer instances running when traffic is low, which can add significant administrative overhead (an autoscaling group could mitigate this issue though, especially if its launch template uses a custom AMI — Amazon Machine Image — that has all the requirements already pre-installed).</p><p>EC2 then took it a step further by highlighting the transparency of its service compared to AWS Lambda. They pointed out that EC2 gives you much more control over how your resources are configured, how applications are deployed, and the level of customization you can achieve.</p><p>AWS Lambda, on the other hand, takes care of most of the configuration details automatically, which also means relinquishing some control and flexibility in processes.</p><p>In conclusion, it’s essential to understand when to use each of these services based on their strengths. EC2 is the perfect candidate when you require a large data processing workload, extensive storage, and complex networking requirements. AWS Lambda, on the other hand, is ideal where you only need to execute small units of code and applications with immediate scaling requirements.<br>The bottom line is to choose the service that best matches your project’s specific requirements and enjoy the benefits of the cloud!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10efc1ac9d84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a Secure VPC with SSM-Managed Private EC2 Instances Using the AWS CLI]]></title>
            <link>https://stephanenoutsa.medium.com/create-a-secure-vpc-with-ssm-managed-private-ec2-instances-using-the-aws-cli-6cbb67f900e0?source=rss-8f915bc52368------2</link>
            <guid isPermaLink="false">https://medium.com/p/6cbb67f900e0</guid>
            <category><![CDATA[aws-cli]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-alb]]></category>
            <category><![CDATA[aws-ssm]]></category>
            <category><![CDATA[aws-ec2]]></category>
            <dc:creator><![CDATA[Stéphane Noutsa]]></dc:creator>
            <pubDate>Tue, 16 May 2023 00:47:22 GMT</pubDate>
            <atom:updated>2023-05-16T00:47:22.269Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wD_tauOT2NPPJSlgQwdNkg.png" /><figcaption>Sample AWS Architecture</figcaption></figure><p>In this blog post, we will walk through how to create a secure VPC in AWS with EC2 instances in private subnets that are managed by Systems Manager (SSM), are in an Auto Scaling Group (ASG), and are fronted by an Application Load Balancer (ALB), all using the AWS CLI. This setup will allow you to run your applications in a secure, highly available, fault-tolerant, and scalable environment.</p><p>I’m going to assume that you have a basic understanding of what a VPC, a subnet (private or public), security groups, Network Access Control Lists (NACLs), an ALB, an ASG, an Internet Gateway (IGW), and a NAT Gateway are.</p><p>That said, SSM is a service that helps you automate and manage your AWS resources at scale. You can use SSM to run commands, patch software, configure settings, and monitor the performance of your EC2 instances.</p><p>To create a secure VPC with EC2 instances in private subnets that are managed by SSM and fronted by an ALB, we’ll need to perform the steps listed below (you’ll need to have the AWS CLI installed and configured for your account to be able to follow along)</p><p><strong>We’ll start by creating a VPC with four subnets: two public subnets and two private subnets in two AZs. This</strong> VPC will have a CIDR block of 10.0.0.0/16:</p><pre>aws ec2 create-vpc --cidr-block 10.0.0.0/16</pre><p>Then we’ll create an IGW and attach it to our VPC so that the VPC will be able to communicate with the Internet:</p><pre>aws ec2 create-internet-gateway</pre><pre>aws ec2 attach-internet-gateway --internet-gateway-id igw-xxxxxxxx --vpc-id vpc-xxxxxxxx</pre><p>Note that you would have to replace igw-xxxxxxxx and vpc-xxxxxxxx respectively with the IDs of the IGW and VPC we would have previously created.</p><p>We’ll then create four subnets in our VPC, two in the us-east-1a Availability Zone (AZ) and two in the us-east-1b AZ (I’m creating the resources in the N. Virginia region, us-east-1). They’ll have the CIDR blocks <strong>10.0.0.0/24</strong>, <strong>10.0.1.0/24</strong>, <strong>10.0.2.0/24</strong> and <strong>10.0.3.0/24</strong>:</p><pre>aws ec2 create-subnet --vpc-id vpc-xxxxxxxx --cidr-block 10.0.0.0/24 --availability-zone us-east-1a<br>aws ec2 create-subnet --vpc-id vpc-xxxxxxxx --cidr-block 10.0.1.0/24 --availability-zone us-east-1b<br>aws ec2 create-subnet --vpc-id vpc-xxxxxxxx --cidr-block 10.0.2.0/24 --availability-zone us-east-1a<br>aws ec2 create-subnet --vpc-id vpc-xxxxxxxx --cidr-block 10.0.3.0/24 --availability-zone us-east-1b</pre><p>A prerequisite to allow SSM to manage our private EC2 instances is to create VPC interface endpoints, and associate them to our private subnets. Note that the private DNS setting needs to be enabled to allow communication with the SSM service:</p><pre>aws ec2 create-vpc-endpoint --vpc-endpoint-type Interface --vpc-id vpc-xxxxxxxx --service-name com.amazonaws.us-east-1.ssm --subnet-ids subnet-33333333 subnet-44444444 --private-dns-enabled<br>aws ec2 create-vpc-endpoint --vpc-endpoint-type Interface --vpc-id vpc-xxxxxxxx --service-name com.amazonaws.us-east-1.ssmmessages --subnet-ids subnet-33333333 subnet-44444444 --private-dns-enabled<br>aws ec2 create-vpc-endpoint --vpc-endpoint-type Interface --vpc-id vpc-xxxxxxxx --service-name com.amazonaws.us-east-1.ec2messages --subnet-ids subnet-33333333 subnet-44444444 --private-dns-enabled</pre><p>In order to secure our subnets, we’ll create NACLs for the private and public subnets, and attach them to their respective subnets.</p><p>We’ll start by creating the NACLs for the public and private subnets:</p><pre>aws ec2 create-network-acl --vpc-id vpc-xxxxxxxx<br>aws ec2 create-network-acl --vpc-id vpc-xxxxxxxx</pre><p>We’ll then create two entries that respectively allow inbound traffic from the Internet and outbound traffic for the Internet, for the public subnet:</p><pre>aws ec2 create-network-acl-entry --network-acl-id acl-11111111 --ingress --rule-number 100 --protocol tcp --cidr-block 0.0.0.0/0 --rule-action allow<br>aws ec2 create-network-acl-entry --network-acl-id acl-11111111 --egress --rule-number 100 --protocol tcp --cidr-block 0.0.0.0/0 --rule-action allow</pre><p>We then create entries that respectively allow inbound traffic from the ALB and outbound traffic to the ephemeral ports (make sure to replace the CIDR block value with the IP address of the ALB after creating it):</p><pre>aws ec2 create-network-acl-entry --network-acl-id acl-22222222 --ingress --rule-number 100 --protocol tcp --port-range From=443,To=443 --cidr-block x.x.x.x/32 --rule-action allow<br>aws ec2 create-network-acl-entry --network-acl-id acl-22222222 --egress --rule-number 100 --protocol tcp --port-range From=443,To=443 --cidr-block 0.0.0.0/0 --rule-action allow<br>aws ec2 create-network-acl-entry --network-acl-id acl-22222222 --egress --rule-number 200 --protocol tcp --port-range From=1024,To=65535 --cidr-block x.x.x.x/32 --rule-action allow</pre><p>Next, we allocate two Elastic IP addresses for the NAT gateways that will be provisioned in our public subnets:</p><pre>aws ec2 allocate-address --domain vpc --output text --query ‘AllocationId’<br>aws ec2 allocate-address --domain vpc --output text --query ‘AllocationId’</pre><p>These commands return the allocation IDs of the Elastic IP addresses, such as eipalloc-11111111 and eipalloc-22222222.</p><p>We’ll then create a NAT Gateway in each of our public subnets:</p><pre>aws ec2 create-nat-gateway --subnet-id subnet-11111111 --allocation-id eipalloc-11111111 --output text --query ‘NatGateway.NatGatewayId’<br>aws ec2 create-nat-gateway --subnet-id subnet-22222222 --allocation-id eipalloc-22222222 --output text --query ‘NatGateway.NatGatewayId’</pre><p>These commands return the NAT gateway IDs, such as nat-xxxxxxxxxxxxxxxx and nat-yyyyyyyyyyyyyyyy.</p><p>We’ll wait for our newly created NAT Gateways to become available before proceeding. While waiting, we can check the status of the NAT Gateways by running the following command:</p><pre>aws ec2 describe-nat-gateways --nat-gateway-ids nat-xxxxxxxxxxxxxxxx nat-yyyyyyyyyyyyyyyy --output table</pre><p>The command returns a table with information about the NAT gateways, such as their state, subnet ID, and elastic IP address. When the state of both NAT gateways is <strong>available</strong>, you can proceed to the next step.</p><p>We’ll then create a route table for the private subnets and add routes to the NAT gateways:</p><pre>aws ec2 create-route-table --vpc-id vpc-xxxxxxxx --output text --query ‘RouteTable.RouteTableId’<br><br>aws ec2 create-route --route-table-id rtb-11111111 --destination-cidr-block 0.0.0.0/0 --nat-gateway-id nat-xxxxxxxxxxxxxxxx<br>aws ec2 create-route --route-table-id rtb-11111111 --destination-cidr-block 0.0.0.0/0 --nat-gateway-id nat-yyyyyyyyyyyyyyyy</pre><p>The first command creates a route table for the VPC with ID vpc-xxxxxxxx and returns the route table ID, such as rtb-11111111. The second and third commands add routes to the NAT gateways for all destinations (0.0.0.0/0) in the route table.</p><p>Next, we’ll associate the route table with the private subnets:</p><pre>aws ec2 associate-route-table --route-table-id rtb-11111111 --subnet-id subnet-33333333<br>aws ec2 associate-route-table --route-table-id rtb-11111111 --subnet-id subnet-44444444</pre><p>These commands will allow resources provisioned in the private subnets to make requests to the Internet through the NAT Gateway, but they won’t be reachable from the Internet.</p><p>Next, we’ll create a route table and associate it with our public subnets:</p><pre>aws ec2 create-route-table --vpc-id vpc-xxxxxxxx<br><br>aws ec2 associate-route-table --route-table-id rtb-22222222 --subnet-id subnet-11111111<br>aws ec2 associate-route-table --route-table-id rtb-22222222 --subnet-id subnet-22222222</pre><p>We’ll then create a route in the route table that points to the internet gateway:</p><pre>aws ec2 create-route --route-table-id rtb-22222222 --destination-cidr-block 0.0.0.0/0 --gateway-id igw-xxxxxxxx</pre><p>The next thing we’ll do is create an ALB that will redirect traffic to our private EC2 instances in an ASG. For this, we’ll first need to create a public security group that will allow inbound HTTPS traffic (port 443) from the Internet (0.0.0.0/0). For convenience, our created security group will have the ID sg-11111111:</p><pre>aws ec2 create-security-group --group-name alb-sg --description &quot;Security group for ALB&quot; --vpc-id vpc-xxxxxxxx<br>aws ec2 authorize-security-group-ingress --group-id sg-11111111 --protocol tcp --port 443 --cidr 0.0.0.0/0</pre><p>We’ll then create our ALB, without specifying its target groups (we’ll do this later):</p><pre>aws elbv2 create-load-balancer --name alb --type application --subnets subnet-11111111 subnet-22222222 --security-groups sg-11111111 --scheme internet-facing</pre><p>Given that our ALB needs to forward traffic to target groups, we’ll create a security group for our private EC2 instances that will be in an ASG, which will serve as our ALB’s target group:</p><pre>aws ec2 create-security-group --group-name private-sg --description &quot;Security group for private EC2 instances&quot; --vpc-id vpc-xxxxxxxx</pre><p>Next, we’ll add rules to our private security group (with ID sg-22222222 for convenience) that allow inbound traffic from our ALB on port 80 (HTTP) and port 443 (HTTPS):</p><pre>aws ec2 authorize-security-group-ingress --group-id sg-22222222 --protocol tcp --port 80 --source-group arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/alb/xxxxxxxxxxxxxxxx<br>aws ec2 authorize-security-group-ingress --group-id sg-22222222 --protocol tcp --port 443 --source-group arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/alb/xxxxxxxxxxxxxxxx</pre><p>Then we’ll add rules to the security group that allow outbound traffic to the internet (CIDR block 0.0.0.0/0) on port 80 (HTTP) and port 443 (HTTPS):</p><pre>aws ec2 authorize-security-group-egress --group-id sg-22222222 --protocol tcp --port 80 --cidr 0.0.0.0/0<br>aws ec2 authorize-security-group-egress --group-id sg-22222222 --protocol tcp --port 443 --cidr 0.0.0.0/0</pre><p>In order to allow our EC2 instances to be managed by SSM, we’ll need to create an IAM role which will be used as the EC2 instance profile.</p><p>First, we’ll create a trust policy document that allows SSM to assume the role. You can use the following JSON template and save it as <strong>trustpolicy.json</strong>:</p><pre>{<br>  &quot;Version&quot;: &quot;2012-10-17&quot;,<br>  &quot;Statement&quot;: [<br>    {<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Principal&quot;: {<br>        &quot;Service&quot;: &quot;ssm.amazonaws.com&quot;<br>      },<br>      &quot;Action&quot;: &quot;sts:AssumeRole&quot;<br>    }<br>  ]<br>}</pre><p>Then we’ll create an IAM role called <strong>EC2RoleForSSM</strong> using the trust policy document:</p><pre>aws iam create-role --role-name EC2RoleForSSM --assume-role-policy-document file://trustpolicy.json</pre><p>Then we’ll attach the AWS-managed policy, <strong>AmazonSSMManagedInstanceCore</strong>, to the IAM role that grants SSM the necessary permissions to manage our EC2 instances:</p><pre>aws iam attach-role-policy --role-name EC2RoleForSSM --policy-arn arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore</pre><p>Next, we’ll create an instance profile (<strong>ec2-ssm-profile</strong>) for our IAM role <strong>EC2RoleForSSM</strong>, and add the IAM role to the instance profile:</p><pre>aws iam create-instance-profile --instance-profile-name ec2-ssm-profile<br>aws iam add-role-to-instance-profile --instance-profile-name ec2-ssm-profile --role-name EC2RoleForSSM</pre><p>We’ll then create a launch template that specifies the configuration of our private EC2 instances, such as their AMI ID, instance type, instance profile, and security group. We won’t create or use an SSH key pair because we’ll manage our instances using SSM instead.<br>We’ll use the latest version of the Amazon Linux 2023 AMI in the N. Virginia region (us-east-1), because it comes with an SSM agent preinstalled (its ID at the time of writing is <strong>ami-0889a44b331db0194</strong>), and call this launch template <strong>private-launch-template</strong>:</p><pre>aws ec2 create-launch-template \<br>--launch-template-name private-launch-template \<br>--version-description &quot;Initial version&quot; \<br>--launch-template-data \<br>&#39;{&quot;ImageId&quot;:&quot;ami-0889a44b331db0194&quot;,&quot;InstanceType&quot;:&quot;t2.micro&quot;, &quot;IamInstanceProfile&quot;: {&quot;Name&quot;: &quot;ec2-ssm-profile&quot;},&quot;SecurityGroupIds&quot;:[&quot;sg-11111111&quot;]}&#39;</pre><p>We can now create our ASG that will use the launch template we just created, and will specify the desired capacity, minimum size, maximum size, and availability zones. We’ll need to provide a name for the ASG (<strong>private-asg</strong>) and a health check type (ELB in this case, so as to use the ALB’s health checks). We’ll assume our created launch template’s ID is <strong>lt-xxxxxxxxxxxxxxxx</strong>:</p><pre>aws autoscaling create-auto-scaling-group \<br>--auto-scaling-group-name private-asg \<br>--launch-template &quot;LaunchTemplateId=lt-xxxxxxxxxxxxxxxx,Version=1&quot; \<br>--min-size 2 \<br>--max-size 4 \<br>--desired-capacity 2 \<br>--availability-zones us-east-1a us-east-1b \<br>--health-check-type ELB</pre><p>The next step will be to create our ALB’s target group (<strong>alb-tg</strong>) which will listen on port 443 (HTTPS):</p><pre>aws elbv2 create-target-group \<br>--name alb-tg \<br>--protocol HTTP \<br>--port 443 \<br>--vpc-id vpc-xxxxxxxx</pre><p>Finally, we’ll attach our target group <strong>alb-tg</strong> to our previously created ASG. Be sure to use the right Amazon Resource Name (ARN) for the target group we just created:</p><pre>aws autoscaling attach-load-balancer-target-groups \<br>--auto-scaling-group-name private-asg \<br>--target-group-arns arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/alb-tg/1234567890abcdef</pre><p>Having created our ALB and target groups and their respective security groups, we’ll now create a listener that forwards requests on port 443 of the ALB to our target group. We’ll assume that we had previously requested a certificate from ACM and its ARN is <strong>arn:aws:acm:us-east-1:123456789012:certificate/abcdef12–3456–7890-abcd-ef1234567890</strong>. :</p><pre>aws elbv2 create-listener --load-balancer-arn arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/alb/xxxxxxxxxxxxxxxx --protocol HTTPS --port 443 --certificates CertificateArn=arn:aws:acm:us-east-1:123456789012:certificate/abcdef12-3456-7890-abcd-ef1234567890 --default-actions Type=forward,TargetGroupArn=arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/alb-tg/xxxxxxxxxxxxxxxx</pre><p>We can now test our setup by accessing our ALB’s DNS name from a web browser. Since we haven’t installed any application on our servers, we’ll get an empty response.</p><p>Congratulations! You have successfully created a secure VPC in AWS with EC2 instances in private subnets that are managed by Systems Manager and fronted by an Application Load Balancer.</p><p>PS: Please feel free to leave questions or comments on how to improve the security of this VPC. We learn every day!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6cbb67f900e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>