<?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 Carlo Cayos on Medium]]></title>
        <description><![CDATA[Stories by Carlo Cayos on Medium]]></description>
        <link>https://medium.com/@carlocayos?source=rss-1f077a1a20e3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lMCrkDpRfa6wAkCEc_zqBw.jpeg</url>
            <title>Stories by Carlo Cayos on Medium</title>
            <link>https://medium.com/@carlocayos?source=rss-1f077a1a20e3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 09:03:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@carlocayos/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[Terraforming an AWS VPC Part 4 — using modules]]></title>
            <link>https://carlocayos.medium.com/terraforming-an-aws-vpc-part-4-using-modules-3fd39fabbb7f?source=rss-1f077a1a20e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/3fd39fabbb7f</guid>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Carlo Cayos]]></dc:creator>
            <pubDate>Mon, 27 Jul 2020 04:52:33 GMT</pubDate>
            <atom:updated>2021-04-02T06:14:20.642Z</atom:updated>
            <content:encoded><![CDATA[<h3>Terraforming an AWS VPC Part 4 — using modules</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*dlA9qvr_2gAL1wsP.png" /></figure><p>This is the fourth and final part of a series of articles on how to set up an AWS VPC using Terraform version 0.12.29.</p><p>Up until now we are setting up our VPC using Terraform the <strong>hard way</strong>. There is a better and easier way to provision the AWS resources using the third-party <a href="https://registry.terraform.io/modules/terraform-aws-modules/vpc/aws/2.44.0">Terraform AWS VPC module</a>.</p><p>In this post, we will create a new Terraform project with significantly fewer codes. It should run as a standalone project, with no dependency on the steps we did from <strong>Parts </strong><a href="https://medium.com/@carlocayos/terraforming-an-aws-vpc-part-1-b496b40f9e56"><strong>1</strong></a><strong>, </strong><a href="https://medium.com/@carlocayos/terraforming-an-aws-vpc-part-2-dd4d491a0f84"><strong>2</strong></a><strong>, and </strong><a href="https://medium.com/@carlocayos/terraforming-an-aws-vpc-part-3-515012f0e26c"><strong>3</strong></a>.</p><h3>VPC Diagram</h3><ul><li>AWS VPC</li><li>Internet Gateway</li><li>3x Public subnet — one for each AZ</li><li>3x Private subnet — one for each AZ</li><li>3x Database subnet — one for each AZ</li><li>Public subnet route table</li><li>Private subnet route table</li><li>Database subnet route table</li><li>EC2 Bastion Host</li><li>Elastic IP Address</li><li>NAT Gateway</li></ul><p>The diagram below is to help you visualize what we will create.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YfgbPvglAbJ4nTIE.png" /></figure><h3>Set up a Terraform Project with AWS Provider</h3><blockquote><em>❌ The AWS on-demand resources we will be provisioning in this section will incur cost. Make sure you terminate all resources when you are done. You can do it manually or by running </em><em>terraform destroy</em></blockquote><p>Create a new project folder with files main.tf, outputs.tf, variables.tf. Then create a directory env/dev, env/uat, env/prod, each will have vpc.tfvars file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/317/0*MP5QDDLCd27A1jrw.png" /></figure><p>Open the file main.tf and add the <a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs">AWS Provider</a>.</p><pre>#-------------------------------<br># AWS Provider<br>#-------------------------------<br>provider &quot;aws&quot; {<br>  region = var.aws_region<br>}</pre><p>Initialize Terraform by running this command. It should set up the project and download the defined AWS Provider.</p><pre>$ terraform init</pre><p>Create a DEV workspace, similar to what we did in <a href="https://medium.com/@carlocayos/terraforming-an-aws-vpc-part-2-dd4d491a0f84">Part 2</a>.</p><pre>$ terraform workspace new dev<br>$ terraform workspace list</pre><h3>VPC Environment-Specific Variables</h3><p>Open variables.tf and add these variable declarations.</p><pre>variable &quot;aws_region&quot; {<br>  description = &quot;AWS Region&quot;<br>}<br>variable &quot;vpc_cidr_block&quot; {<br>  description = &quot;Main VPC CIDR Block&quot;<br>}</pre><pre>variable &quot;availability_zones&quot; {<br>  type = list(string)<br>}</pre><pre>variable &quot;public_subnet&quot; {<br>  type = list(string)<br>}</pre><pre>variable &quot;private_subnet&quot; {<br>  type = list(string)<br>}</pre><pre>variable &quot;database_subnet&quot; {<br>  type = list(string)<br>}</pre><p>Open env/dev/vpc.tfvars and set the environment-specific values for the DEV workspace. In here we set the AWS region to Sydney and the VPC configurations.</p><pre>aws_region         = &quot;ap-southeast-2&quot;<br>vpc_cidr_block     = &quot;10.0.0.0/16&quot;<br>availability_zones = [&quot;ap-southeast-2a&quot;, &quot;ap-southeast-2b&quot;, &quot;ap-southeast-2c&quot;]<br>public_subnet      = [&quot;10.0.0.0/24&quot;, &quot;10.0.1.0/24&quot;, &quot;10.0.2.0/24&quot;]<br>private_subnet     = [&quot;10.0.101.0/24&quot;, &quot;10.0.102.0/24&quot;, &quot;10.0.103.0/24&quot;]<br>database_subnet    = [&quot;10.0.201.0/24&quot;, &quot;10.0.202.0/24&quot;, &quot;10.0.203.0/24&quot;]</pre><h3>Adding the Terraform AWS VPC Module</h3><p>Now it’s time to demonstrate how to use the AWS VPC Module with our DEV VPC configuration.</p><p>Open main.tf file and add the <a href="https://registry.terraform.io/modules/terraform-aws-modules/vpc/aws/2.44.0">Terraform AWS VPC Module</a>.</p><pre>#-------------------------------<br># AWS VPC<br>#-------------------------------<br>module &quot;vpc&quot; {<br>  source  = &quot;terraform-aws-modules/vpc/aws&quot;<br>  version = &quot;2.44.0&quot;</pre><pre>  name = &quot;my-vpc-terraform-module-${terraform.workspace}&quot;<br>  cidr = var.vpc_cidr_block</pre><pre>  azs              = var.availability_zones<br>  public_subnets   = var.public_subnet<br>  private_subnets  = var.private_subnet<br>  database_subnets = var.database_subnet</pre><pre>  create_igw         = true<br>  enable_nat_gateway = true<br>  single_nat_gateway = true</pre><pre>tags = {<br>    Terraform   = &quot;true&quot;<br>    Environment = terraform.workspace<br>  }<br>}</pre><p>Run terraform init to download the module.</p><p>Inspect the codes we have added. In just around <strong>20 lines</strong> we have defined the VPC configuration similar to what we did in <strong>Parts 1–3</strong>. But this time we let the module handle all the boilerplate codes!</p><p>We only used the VPC module inputs we needed for this example. An exhaustive list of the inputs can be found in <a href="https://registry.terraform.io/modules/terraform-aws-modules/vpc/aws/2.44.0?tab=inputs">Terraform AWS VPC Module Input</a></p><p>A quick run through in our VPC Module configuration.</p><ul><li>azs - this is the list of availability zones. We set it to Sydney region AZs.</li><li>public_subnets - public subnet, set this with CIDR block list</li><li>private_subnets - private subnet, set this with CIDR block list</li><li>database_subnets - database subnet, set this with CIDR block list</li><li>create_igw - flag to indicate creation of an Internet Gateway, default is true</li><li>enable_nat_gateway - set to true to provision a NAT Gateway</li><li>single_nat_gateway - set to true to provision a single shared NAT Gateway, otherwise it will create a NAT gateway in each public subnet</li><li>tags - a map of tags to add to ALL taggable resources created through this module</li></ul><p>And that’s it! All of these in just <strong>20 lines of codes</strong>. Let’s now provision these resources, run these commands.</p><pre>$ terraform workspace select dev<br>$ terraform apply -var-file=env/dev/vpc.tfvars</pre><p>In the logs, you should see that Terraform will create the VPC with 27 AWS resources.</p><pre>+ resource &quot;aws_db_subnet_group&quot; &quot;database&quot;...<br>+ resource &quot;aws_eip&quot; &quot;nat&quot;...<br>+ resource &quot;aws_internet_gateway&quot; &quot;this&quot;...<br>+ resource &quot;aws_nat_gateway&quot; &quot;this&quot;...<br>+ resource &quot;aws_route&quot; &quot;private_nat_gateway&quot;...<br>+ resource &quot;aws_route&quot; &quot;public_internet_gateway&quot;...<br>+ resource &quot;aws_route_table&quot; &quot;private&quot;...<br>+ resource &quot;aws_route_table&quot; &quot;public&quot;...<br>+ resource &quot;aws_route_table_association&quot; &quot;database&quot;...<br>+ resource &quot;aws_route_table_association&quot; &quot;database&quot;...<br>+ resource &quot;aws_route_table_association&quot; &quot;database&quot;...<br>+ resource &quot;aws_route_table_association&quot; &quot;private&quot;...<br>+ resource &quot;aws_route_table_association&quot; &quot;private&quot;...<br>+ resource &quot;aws_route_table_association&quot; &quot;private&quot;...<br>+ resource &quot;aws_route_table_association&quot; &quot;public&quot;...<br>+ resource &quot;aws_route_table_association&quot; &quot;public&quot;...<br>+ resource &quot;aws_route_table_association&quot; &quot;public&quot;...<br>+ resource &quot;aws_subnet&quot; &quot;database&quot;...<br>+ resource &quot;aws_subnet&quot; &quot;database&quot;...<br>+ resource &quot;aws_subnet&quot; &quot;database&quot;...<br>+ resource &quot;aws_subnet&quot; &quot;private&quot;...<br>+ resource &quot;aws_subnet&quot; &quot;private&quot;...<br>+ resource &quot;aws_subnet&quot; &quot;private&quot;...<br>+ resource &quot;aws_subnet&quot; &quot;public&quot;...<br>+ resource &quot;aws_subnet&quot; &quot;public&quot;...<br>+ resource &quot;aws_subnet&quot; &quot;public&quot;...<br>+ resource &quot;aws_vpc&quot; &quot;this&quot;...</pre><pre>Apply complete! Resources: 27 added, 0 changed, 0 destroyed.</pre><h3>Terraform Output</h3><p>The module also provides information of the created resources through the <a href="https://registry.terraform.io/modules/terraform-aws-modules/vpc/aws/2.44.0?tab=outputs">Terraform AWS VPC Module Output</a>.</p><p>To demonstrate how to use it, create the file outputs.tf and add these codes.</p><pre>output &quot;vpc_id&quot; {<br>  value = module.vpc.vpc_id<br>}</pre><pre>output &quot;vpc_cidr_block&quot; {<br>  value = module.vpc.vpc_cidr_block<br>}</pre><pre>output &quot;azs&quot; {<br>  value = module.vpc.azs<br>}</pre><pre>output &quot;private_subnets_cidr_blocks&quot; {<br>  value = module.vpc.private_subnets_cidr_blocks<br>}</pre><pre>output &quot;public_subnets_cidr_blocks&quot; {<br>  value = module.vpc.public_subnets_cidr_blocks<br>}</pre><pre>output &quot;database_subnets_cidr_blocks&quot; {<br>  value = module.vpc.database_subnets_cidr_blocks<br>}</pre><p>Apply the output changes.</p><pre>$ terraform apply -var-file=env/dev/vpc.tfvars<br>$ terraform output</pre><p>You should see details of your cloud infrastructure as what you have defined in the outputs.tf file.</p><pre>azs = [<br>  &quot;ap-southeast-2a&quot;,<br>  &quot;ap-southeast-2b&quot;,<br>  &quot;ap-southeast-2c&quot;,<br>]<br>...<br>vpc_cidr_block = 10.0.0.0/16<br>vpc_id = vpc-0918ff5d446d5a6b4</pre><h3>Helper Script</h3><p>Up until now we are running the commands like so:</p><pre>$ terraform workspace select dev<br>$ terraform apply -var-file=env/dev/vpc.tfvars</pre><p>This 2-step process is prone to error as you might run the command terraform apply with the variable for dev environment in an incorrect workspace (i.e. uat or prod).</p><p>I made a simple helper script to avoid this type of human error. Create a new file terraform_helper.sh and copy this script.</p><pre>#!/usr/bin/env bash</pre><pre>#-----------------------------------<br># Check valid subcommand<br>#-----------------------------------<br>subcommand_arr=(&quot;plan&quot; &quot;refresh&quot; &quot;apply&quot; &quot;destroy&quot;)</pre><pre>valid_subcommand=0</pre><pre>for c in &quot;${subcommand_arr[@]}&quot;<br>do<br>    if [[ &quot;${c}&quot; == &quot;$1&quot; ]]<br>    then<br>        valid_subcommand=1<br>        break<br>    fi<br>done</pre><pre># Check if subcommand is valid<br>if [[ ${valid_subcommand} -eq 0 ]]<br>    then<br>        echo &quot;Invalid subcommand.\n Usage: &#39;./terraform_helper.sh &lt;subcommand&gt; &lt;workspace&gt;&#39;&quot;<br>        exit 1<br>fi</pre><pre>#-----------------------------------<br># Check valid workspace<br>#-----------------------------------<br>workspace_arr=(`ls -1 env`)</pre><pre>valid_workspace=0</pre><pre>for workspace in &quot;${workspace_arr[@]}&quot;<br>do<br>    if [[ &quot;${workspace}&quot; == &quot;$2&quot; ]]<br>    then<br>        valid_workspace=1<br>        break<br>    fi<br>done</pre><pre># Check if workspace is valid<br>if [[ ${valid_workspace} -eq 0 ]]<br>    then<br>        echo &quot;Invalid argument.\n Usage: &#39;./terraform_helper.sh &lt;subcommand&gt; &lt;workspace&gt;&#39;&quot;<br>        exit 1<br>fi</pre><pre># Set the workspace<br>workspace_command=&quot;terraform workspace select $2&quot;<br>echo &quot;Selecting workspace... ${workspace_command}\n&quot;</pre><pre>eval ${workspace_command}<br>if [ $? -ne 0 ]; then<br>    exit 1<br>fi</pre><pre># Run the command<br>terraform_command=&quot;terraform $1 -var-file=env/$2/vpc.tfvars&quot;<br>echo &quot;Running command... ${terraform_command}\n&quot;</pre><pre>eval ${terraform_command}<br>if [ $? -ne 0 ]; then<br>    exit 1<br>fi</pre><p>The script accepts two arguments; a &lt;subcommand&gt; (“plan” “refresh” “apply” “destroy”), and the target &lt;workspace&gt;. It would change to the target workspace and set the environment-specific values to the variables. One caveat is that the workspace name (e.g. dev) should match the directory where you store the variables (e.g. env/<strong>dev</strong>/vpc.tfvars).</p><pre>$ ./terraform_helper.sh apply dev</pre><h3>Spinning up AWS EC2 instances</h3><p>The information from the <a href="https://registry.terraform.io/modules/terraform-aws-modules/vpc/aws/2.44.0?tab=outputs">Terraform AWS VPC Module Output</a> we discussed in the previous section can also be used to create other resources. In this section, we will create an EC2 instance bastion host using the information from the module output.</p><p>Create a key pair to connect to the EC2 instance. Create it manually by following the steps in the <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html#prepare-key-pair">AWS documentation</a>. Use the Sydney region for our DEV workspace. Take note of the key pair name.</p><p>Create a new file server.tf and add the script below. Replace the key_name = &quot;my-keypair&quot; value with your key pair name.</p><pre>data &quot;aws_ami&quot; &quot;ubuntu&quot; {<br>  most_recent = true</pre><pre>filter {<br>    name   = &quot;name&quot;<br>    values = [&quot;ubuntu/images/hvm-ssd/ubuntu-bionic-18.04-amd64-server-*&quot;]<br>  }</pre><pre>filter {<br>    name   = &quot;virtualization-type&quot;<br>    values = [&quot;hvm&quot;]<br>  }</pre><pre>owners = [&quot;099720109477&quot;] # Canonical<br>}</pre><pre>resource &quot;aws_security_group&quot; &quot;bastion_host_sg&quot; {<br>  name   = &quot;bastion_host_sg&quot;<br>  vpc_id = module.vpc.vpc_id</pre><pre>ingress {<br>    from_port = 22<br>    to_port   = 22<br>    protocol  = &quot;tcp&quot;</pre><pre>// Not the safest thing to do, but you can replace this with your public IP<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }</pre><pre>egress {<br>    from_port   = 0<br>    to_port     = 0<br>    protocol    = &quot;-1&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }</pre><pre>tags = {<br>    Name = &quot;my-bastion-host-security-group-p4&quot;<br>  }<br>}</pre><pre>resource &quot;aws_instance&quot; &quot;bastion_host&quot; {<br>  ami                         = data.aws_ami.ubuntu.id<br>  instance_type               = &quot;t3.micro&quot;<br>  subnet_id                   = module.vpc.public_subnets[0]<br>  associate_public_ip_address = true<br>  key_name                    = &quot;my-keypair&quot; // change this<br>  vpc_security_group_ids      = [aws_security_group.bastion_host_sg.id]<br>  tags = {<br>    Name = &quot;My Bastion Host - Part 4&quot;<br>  }<br>}</pre><p>Inspect the codes, you will notice that there are two lines where we use the module output to set the resource meta-argument.</p><pre>1) In the aws_security_group resource<br>vpc_id = module.vpc.vpc_id</pre><pre>2) In the aws_instance resource<br>subnet_id = module.vpc.public_subnets[0]</pre><p>Run terraform apply to create the EC2 instance.</p><pre>$ terraform apply -var-file=env/dev/vpc.tfvars</pre><p>Or if you are using the helper script.</p><pre>$ ./terraform_helper.sh apply dev</pre><h3>Removing Terraform-managed resources</h3><blockquote><em>❌ </em><strong><em>DO NOT SKIP THIS STEP!</em></strong><em> Terminate all created resources to stop your account from incurring charges.</em></blockquote><p>Destroy all created resources in the DEV workspace.</p><pre>$ terraform workspace select dev<br>$ terraform destroy -var-file=env/dev/vpc.tfvars</pre><p>Or if you are using the helper script.</p><pre>$ ./terraform_helper.sh destroy dev</pre><p>If you used the other workspaces, then make sure you destroy it all too.</p><pre># UAT<br>$ terraform workspace select uat<br>$ terraform destroy -var-file=env/uat/vpc.tfvars</pre><pre># PROD<br>$ terraform workspace select prod<br>$ terraform destroy -var-file=env/prod/vpc.tfvars</pre><h3>Review</h3><p>This ends the tutorial series on Terraform and how to use it to create a shared and configurable infrastructure as code project.</p><p>By now you should be familiar with Terraform, its syntax, the available providers, and its resources. We started doing it the <strong>hard way</strong> to cover the basics of Terraform. Then we used a third-party AWS VPC module to demonstrate how it can significantly reduce the lines of codes in our project.</p><p>Next step is for you to explore the other Terraform providers and create your own module. It might be a combination of other modules or something you created by yourself.</p><p>Hope that you find my Terraform tutorial series informative.</p><h3>Project Codes</h3><p>Download the complete codes in <a href="https://github.com/carlocayos/terraform-vpc-module-tutorial">https://github.com/carlocayos/terraform-vpc-module-tutorial</a>.</p><p><em>Disclaimer: All views expressed on this site are my own and do not represent the opinions of any entity whatsoever with which I have been, am now, or will be affiliated</em></p><p><em>Originally published at </em><a href="https://carlocayos.com/"><em>carlocayos.com</em></a><em>. Updated to Terraform </em>version 0.12.29.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3fd39fabbb7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Terraforming an AWS VPC — Part 3]]></title>
            <link>https://carlocayos.medium.com/terraforming-an-aws-vpc-part-3-515012f0e26c?source=rss-1f077a1a20e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/515012f0e26c</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <dc:creator><![CDATA[Carlo Cayos]]></dc:creator>
            <pubDate>Sun, 26 Jul 2020 02:46:20 GMT</pubDate>
            <atom:updated>2021-04-02T06:14:05.173Z</atom:updated>
            <content:encoded><![CDATA[<h3>Terraforming an AWS VPC — Part 3</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YgcxltiHal2hG65zNMhJTw.png" /></figure><p>This is the third part of a series of articles on how to set up an AWS VPC using Terraform version 0.12.29.</p><p>We have created our first Terraform project in <a href="https://medium.com/@carlocayos/terraforming-an-aws-vpc-part-1-b496b40f9e56">Part 1</a> and had our introduction to remote state files and workspaces in <a href="https://medium.com/@carlocayos/terraforming-an-aws-vpc-part-2-dd4d491a0f84">Part 2</a>. In this post, we will finish creating our VPC by adding these resources:</p><ul><li>AWS VPC (done)</li><li>Internet Gateway</li><li>3x Public subnet — one for each AZ</li><li>3x Private subnet — one for each AZ</li><li>3x Database subnet — one for each AZ</li><li>Public subnet route table</li><li>Private subnet route table</li><li>Database subnet route table</li><li>EC2 Bastion Host</li><li>Elastic IP Address</li><li>NAT Gateway</li></ul><blockquote><em>ℹ️ The instructions here is the hard way of doing it! We will add each AWS resource one by one to get you acquainted with Terraform. An easier way to create a VPC is using a third party Terraform AWS VPC module which we will cover in the next and final post of the series.</em></blockquote><h3>VPC Diagram</h3><p>The diagram below is to help you visualize what we will create.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EuLG84PElW_2MzXE.png" /></figure><h3>Provisioning AWS Resources</h3><blockquote><em>❌ The AWS on-demand resources we will be provisioning in this section will incur cost. Make sure you terminate all resources when you are done. You can do it manually or by running </em><em>terraform destroy</em></blockquote><h3>Updating the VPC</h3><p>Switch to the DEV workspace.</p><pre>$ terraform workspace select dev<br>$ terraform workspace list</pre><p>Open main.tf, this is where we will add all the VPC Terraform resources. After each section, we will run terraform apply to do incremental updates to our VPC.</p><p><a href="https://www.terraform.io/docs/providers/aws/r/internet_gateway.html"><strong>Internet Gateway</strong></a></p><pre>#-------------------------------<br># Internet Gateway<br>#-------------------------------<br>resource &quot;aws_internet_gateway&quot; &quot;gw&quot; {<br>  vpc_id = aws_vpc.main.id</pre><pre>tags = {<br>    Name = &quot;my-internet-gateway-${terraform.workspace}&quot;<br>  }<br>}</pre><p>This will open communication from our VPC to the internet. Apply the change.</p><pre>$ terraform apply -var-file=env/dev/vpc.tfvars</pre><p><a href="https://www.terraform.io/docs/providers/aws/r/subnet.html"><strong>Subnets</strong></a></p><p>We will create three subnets (public, private, database subnet) for each Availability Zones. There are 3 AZs for the Sydney Region defined in our DEV workspace. Giving us a total of 9 subnets.</p><p>Terraform uses <a href="https://www.terraform.io/docs/configuration/variables.html">input variables</a> to make the script more flexible and sharable. We will create the variables and set the values in the DEV workspace. This will allow us to re-use the Terraform scripts to provision multiple environments.</p><p>Open variables.tf and add the map variable declarations below. These will be set to the AZ values distinct to each workspace. Remember that in <a href="https://medium.com/@carlocayos/terraforming-an-aws-vpc-part-1-b496b40f9e56">Part 1</a> we set each environment to use different AWS regions.</p><pre>#-------------------------------<br># Variables<br>#-------------------------------<br>variable &quot;az_public_subnet&quot; {<br>  type = map(string)<br>}</pre><pre>variable &quot;az_private_subnet&quot; {<br>  type = map(string)<br>}</pre><pre>variable &quot;az_database_subnet&quot; {<br>  type = map(string)<br>}</pre><p>Now the customization part, open the file env/dev/vpc.tfvars and set the key-value pairs for the DEV workspace. These are the CIDR blocks assigned to each subnet as shown in the diagram above.</p><pre>az_public_subnet   = { &quot;ap-southeast-2a&quot; : &quot;10.0.0.0/24&quot;, &quot;ap-southeast-2b&quot; : &quot;10.0.1.0/24&quot;, &quot;ap-southeast-2c&quot; : &quot;10.0.2.0/24&quot; }</pre><pre>az_private_subnet  = { &quot;ap-southeast-2a&quot; : &quot;10.0.101.0/24&quot;, &quot;ap-southeast-2b&quot; : &quot;10.0.102.0/24&quot;, &quot;ap-southeast-2c&quot; : &quot;10.0.103.0/24&quot; }</pre><pre>az_database_subnet = { &quot;ap-southeast-2a&quot; : &quot;10.0.201.0/24&quot;, &quot;ap-southeast-2b&quot; : &quot;10.0.202.0/24&quot;, &quot;ap-southeast-2c&quot; : &quot;10.0.203.0/24&quot; }</pre><p>Re-open main.tf and add the Terraform subnet resources. We are using the resource meta-argument <a href="https://www.terraform.io/docs/configuration/resources.html#for_each-multiple-resource-instances-defined-by-a-map-or-set-of-strings">for-each</a>. It will provision an AWS subnet resource multiplied by the number of items in the map variables var.az_public_subnet, var.az_private_subnet, and var.az_database_subnet, creating a total of 9 subnets.</p><pre># Public Subnet<br>resource &quot;aws_subnet&quot; &quot;public_subnet&quot; {<br>  for_each = var.az_public_subnet</pre><pre>vpc_id = aws_vpc.main.id</pre><pre>availability_zone = each.key<br>  cidr_block        = each.value</pre><pre>tags = {<br>    Name = &quot;my-public-subnet-${each.key}-${terraform.workspace}&quot;<br>    Tier = &quot;public&quot;<br>  }<br>}</pre><pre># Private Subnet<br>resource &quot;aws_subnet&quot; &quot;private_subnet&quot; {<br>  for_each = var.az_private_subnet</pre><pre>vpc_id = aws_vpc.main.id</pre><pre>availability_zone = each.key<br>  cidr_block        = each.value</pre><pre>tags = {<br>    Name = &quot;my-private-subnet-${each.key}-${terraform.workspace}&quot;<br>    Tier = &quot;private&quot;<br>  }<br>}</pre><pre># Database Subnet<br>resource &quot;aws_subnet&quot; &quot;database_subnet&quot; {<br>  for_each = var.az_database_subnet</pre><pre>vpc_id = aws_vpc.main.id</pre><pre>availability_zone = each.key<br>  cidr_block        = each.value</pre><pre>tags = {<br>    Name = &quot;my-database-subnet-${each.key}-${terraform.workspace}&quot;<br>    Tier = &quot;database&quot;<br>  }<br>}</pre><p>You may run terraform apply at this point to incrementally update our environment.</p><pre>$ terraform apply -var-file=env/dev/vpc.tfvars</pre><p><a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/eip"><strong>Elastic IP Address</strong></a><strong> and </strong><a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/nat_gateway"><strong>NAT Gateway</strong></a></p><p>EC2 instances provisioned in the private subnet might need to connect to the public internet. A <a href="https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html">NAT Gateway</a> allows these instances in the private subnet to initiate outside connection to the internet, or other external AWS services. Add these resources to main.tf.</p><pre># EIP<br>resource &quot;aws_eip&quot; &quot;nat&quot; {<br>  vpc        = true<br>  depends_on = [aws_internet_gateway.gw]<br>}</pre><pre># NAT Gateway<br>resource &quot;aws_nat_gateway&quot; &quot;gw&quot; {<br>  allocation_id = aws_eip.nat.id<br>  subnet_id     = aws_subnet.public_subnet[var.ec2_instance_az].id<br>}</pre><p><a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/route_table"><strong>Route Table</strong></a><strong> and </strong><a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/route_table_association"><strong>Route Table Association</strong></a></p><p>Now that we have all AWS resources defined for our VPC, it’s time to connect them all together using a <a href="https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html">route table</a>.</p><blockquote>A route table contains a set of rules, called routes, that are used to determine where network traffic from your subnet or gateway is directed.</blockquote><p>Open main.tf and add these resources.</p><pre># public subnet route table<br>resource &quot;aws_route_table&quot; &quot;public_subnet_route_table&quot; {<br>  vpc_id = aws_vpc.main.id</pre><pre>route {<br>    cidr_block = &quot;0.0.0.0/0&quot;<br>    gateway_id = aws_internet_gateway.gw.id<br>  }</pre><pre>tags = {<br>    Name = &quot;my-public-subnet-route-table&quot;<br>  }<br>}</pre><pre># public subnet route table association<br>resource &quot;aws_route_table_association&quot; &quot;public_subnet_route_table_association&quot; {<br>  for_each = var.az_public_subnet</pre><pre>subnet_id      = aws_subnet.public_subnet[each.key].id<br>  route_table_id = aws_route_table.public_subnet_route_table.id<br>}</pre><pre># private subnet route table<br>resource &quot;aws_route_table&quot; &quot;private_subnet_route_table&quot; {<br>  vpc_id = aws_vpc.main.id</pre><pre>route {<br>    cidr_block = &quot;0.0.0.0/0&quot;<br>    gateway_id = aws_nat_gateway.gw.id<br>  }</pre><pre>tags = {<br>    Name = &quot;my-private-subnet-route-table&quot;<br>  }<br>}</pre><pre># private subnet route table association<br>resource &quot;aws_route_table_association&quot; &quot;private_subnet_route_table_association&quot; {<br>  for_each = var.az_private_subnet</pre><pre>subnet_id      = aws_subnet.private_subnet[each.key].id<br>  route_table_id = aws_route_table.private_subnet_route_table.id<br>}</pre><pre># database subnet route table<br>resource &quot;aws_route_table&quot; &quot;database_subnet_route_table&quot; {<br>  vpc_id = aws_vpc.main.id</pre><pre>route {<br>    cidr_block = &quot;0.0.0.0/0&quot;<br>    gateway_id = aws_nat_gateway.gw.id<br>  }</pre><pre>tags = {<br>    Name = &quot;my-database-subnet-route-table&quot;<br>  }<br>}</pre><pre># database subnet route table association<br>resource &quot;aws_route_table_association&quot; &quot;database_subnet_route_table_association&quot; {<br>  for_each = var.az_database_subnet</pre><pre>subnet_id      = aws_subnet.database_subnet[each.key].id<br>  route_table_id = aws_route_table.database_subnet_route_table.id<br>}</pre><p>Run terraform apply. Open the AWS Console and verify if these resources were properly provisioned. You should see 3 route tables: a public, private, and database route tables. Each route table should be associated to 3 subnets. Here’s mine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*a7G0vJ81wsQP_1_Y.png" /></figure><p>Public route table with 3 public subnets associated</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_CKkewEuAZxrHzTl.png" /></figure><p>Public route table route destination. Non-local traffic is routed to the Internet Gateway.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*1rKtyS38aCWmlwHH.png" /></figure><p>Private and Database route table route destination. Notice that the non-local traffic is routed to the NAT Gateway instead of the Internet Gateway.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*_YYYAoFCG6feXWnR.png" /></figure><h3>Spinning up AWS EC2 instances</h3><p>The last step is to create an EC2 instance in the public subnet, which will serve as our bastion host.</p><p><a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/instance"><strong>AWS Instance</strong></a></p><p>First, open variables.tf and add the map variable declaration below.</p><pre>variable &quot;ec2_instance_az&quot; {<br>  type = string<br>}</pre><p>Open env/dev/vpc.tfvars and set the key-value pair for the DEV workspace. This will be used to specify which public subnet availability zone we will provision the EC2 instance.</p><pre>ec2_instance_az = &quot;ap-southeast-2a&quot;</pre><p>Next is to create a key pair to connect to the EC2 instance. Create it manually by following the steps in the <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html#prepare-key-pair">AWS documentation</a>. Use the Sydney region for our DEV workspace. Take note of the key pair name.</p><p>Create a new file server.tf and add the script below. Replace the key_name = &quot;my-keypair&quot; value with your key pair name from the previous step.</p><pre>data &quot;aws_ami&quot; &quot;ubuntu&quot; {<br>  most_recent = true</pre><pre>filter {<br>    name   = &quot;name&quot;<br>    values = [&quot;ubuntu/images/hvm-ssd/ubuntu-bionic-18.04-amd64-server-*&quot;]<br>  }</pre><pre>filter {<br>    name   = &quot;virtualization-type&quot;<br>    values = [&quot;hvm&quot;]<br>  }</pre><pre>owners = [&quot;099720109477&quot;] # Canonical<br>}</pre><pre>resource &quot;aws_security_group&quot; &quot;bastion_host_sg&quot; {<br>  name   = &quot;bastion_host_sg&quot;<br>  vpc_id = aws_vpc.main.id</pre><pre>ingress {<br>    from_port = 22<br>    to_port   = 22<br>    protocol  = &quot;tcp&quot;</pre><pre>// Not the safest thing to do, but you can replace<br>    // this with your public IP address - x.x.x.x.x/32<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }</pre><pre>egress {<br>    from_port   = 0<br>    to_port     = 0<br>    protocol    = &quot;-1&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }</pre><pre>tags = {<br>    Name = &quot;my-bastion-host-security-group&quot;<br>  }<br>}</pre><pre>resource &quot;aws_instance&quot; &quot;bastion_host&quot; {<br>  ami           = data.aws_ami.ubuntu.id<br>  instance_type = &quot;t3.micro&quot;</pre><pre>subnet_id                   = aws_subnet.public_subnet[var.ec2_instance_az].id<br>  associate_public_ip_address = true<br>  key_name                    = &quot;my-keypair&quot;<br>  vpc_security_group_ids      = [aws_security_group.bastion_host_sg.id]</pre><pre>tags = {<br>    Name = &quot;My Bastion Host&quot;<br>  }<br>}</pre><p>In the script above, we used a Terraform data source <a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/ami">aws_ami</a>. A data source is a read-only representation of a pre-existing data, in this case, the Ubuntu AMI from Canonical.</p><p>We also used an EC2 <a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/security_group">security group</a> and <a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/instance">EC2 instance</a>.</p><p>Run terraform apply to create the EC2 instance.</p><pre>$ terraform apply -var-file=env/dev/vpc.tfvars</pre><p>Connect to your instance and ping amazon.com.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/0*5jvKi5zmt6I-Y2so.png" /></figure><h3>Terraform Output</h3><p>A convenient way to display important details of the provisioned resources is using <a href="https://www.terraform.io/docs/configuration/outputs.html">Terraform output</a>. Open outputs.tf and add the codes below.</p><pre>output &quot;my-aws-instance-public-ip&quot; {<br>  value = aws_instance.bastion_host.public_ip<br>}</pre><p>This will get the public ip address of the EC2 instance bastion host.</p><pre>$ terraform output<br>my-aws-instance-public-ip = 3.105.229.143</pre><h3>Removing Terraform-managed resources</h3><blockquote><em>❌ </em><strong><em>DO NOT SKIP THIS STEP!</em></strong><em> Terminate all created resources to stop your account from incurring charges.</em></blockquote><p>Destroy all created resources in the DEV workspace.</p><pre>$ terraform workspace select dev<br>$ terraform destroy -var-file=env/dev/vpc.tfvars</pre><p>If you used the other workspaces, then make sure you destroy it all too.</p><pre># UAT<br>$ terraform workspace select uat<br>$ terraform destroy -var-file=env/uat/vpc.tfvars</pre><pre># PROD<br>$ terraform workspace select prod<br>$ terraform destroy -var-file=env/prod/vpc.tfvars</pre><h3>Project Codes</h3><p>Download the complete codes in <a href="https://github.com/carlocayos/terraform-vpc-tutorial">https://github.com/carlocayos/terraform-vpc-tutorial</a>.</p><h3>What’s Next?</h3><p>When creating the VPC using Terraform, it is apparent there are a lot of boilerplate codes. This can be simplified by using a third party <a href="https://registry.terraform.io/modules/terraform-aws-modules/vpc/aws/2.44.0">Terraform AWS VPC module</a>. In the next and <a href="https://medium.com/@carlocayos/terraforming-an-aws-vpc-part-4-using-modules-3fd39fabbb7f">final post</a>, we will see how we can use the module to simplify the AWS VPC creation using Terraform.</p><p><em>Disclaimer: All views expressed on this site are my own and do not represent the opinions of any entity whatsoever with which I have been, am now, or will be affiliated</em></p><p><em>Originally published at </em><a href="https://carlocayos.com/"><em>carlocayos.com</em></a><em>. Updated to Terraform </em>version 0.12.29.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=515012f0e26c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Hammer Analogy on Cloud Platforms]]></title>
            <link>https://carlocayos.medium.com/a-hammer-analogy-on-cloud-platforms-6ac686deed38?source=rss-1f077a1a20e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ac686deed38</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[digitalocean]]></category>
            <category><![CDATA[analogy]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Carlo Cayos]]></dc:creator>
            <pubDate>Tue, 20 Feb 2018 14:01:56 GMT</pubDate>
            <atom:updated>2020-07-23T11:09:39.696Z</atom:updated>
            <content:encoded><![CDATA[<p>If only I get 0.000087 Bitcoin<em>*</em> every time someone argues that cloud provider X is better than cloud provider Y.</p><p>I find it hard explaining it technically to some, so I came up with this simple analogy to explain how I view it.</p><p>Let us take the case of Digital Ocean and AWS. The pricing of DO droplets is one of the most affordable offerings among cloud providers. 1 vCPU, 1GB memory, 25GB SSD would cost around $5/mo. Because of this, it is often compared to AWS EC2 instances. The equivalent in EC2 is a t2.micro + EBS 25GB storage that would cost around $11/mo. It is double the cost for getting the same server specs. Why would I choose AWS then?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*xdLHJHU0AR8Q-9-3fJW5PQ.jpeg" /></figure><p>Here comes my hammering analogy, think of a DO droplet as a hammer, a custom-built aluminum bronze hammer with your name engraved on the handle. It is good at doing one thing, hammering nails. After using it, you notice that aluminum bronze has a distinct sound every time it hits the nail, your hand fits the custom handle perfectly when you grip it, and you now consider pounding nails on the top of your favourite pastimes list. This hammer only costs <strong>$1</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*XiftXTVVj3eXze_XEF2J1A.png" /></figure><p>Now, picture an AWS EC2 instance, also as a hammer, a standard one with nothing special, but it can do the job perfectly, which is hammering nails. You can only buy it as part of a <strong>99-piece tool set</strong>. You cannot buy only the hammer, you must buy the complete set, along with the screwdrivers, wrench, and other tools. The entire tool set would cost you <strong>$3</strong>. I view AWS as a tool set because if you use any of its services, its integration is seamless with other AWS services.</p><p>Imagine you want to build a DIY computer desk. Just a simple desk that you can put your laptop on, no drawers for now. You only need wood and nails to build it. You decided to buy the custom-built hammer for <strong>$1</strong> (DO) instead of a more expensive tool set which costs <strong>$3 </strong>(AWS). Then you use the hammer to build your desk.</p><p>Think of the computer desk as your application running in a server. An application that does its job. You are not using any fancy managed services, because you do not need to.</p><p>Most people are perfectly fine with these desks, it serves their purpose, and they would stop here. But for some people, they prefer desks with drawers because they need it. They need the additional functionality these drawers offer. Because building drawers requires screw drivers and other tools, these people, in hindsight, know that they have to buy the more expensive <strong>tool set</strong> <strong>$3 </strong>(AWS).</p><p>Using a screw driver, and other tools for building drawers is analogous to using other AWS services (e.g. S3, managed services — RDS, SQS) to improve your application, whether building a new feature, using managed services, or automating your deployment process. If you buy the tool set, the hammer comes along with other tools. You may or may not use all the tools for now, but if you need to, it is there. In reality, you have to pay for each service AWS offers, the tool set just symbolizes the seamless integration for these AWS services. On top of my head, here are 2 things I can think of:</p><ul><li>EC2 instance profile — you don’t have to manage IAM user credentials if you need access to an AWS service from an application running outside AWS</li><li>VPC Endpoints — traffic originating from an AWS VPC to AWS services like S3 or DynamoDB will not leave the Amazon network. Improving security since traffic will not go over the internet, it also lowers latency and data transfer cost</li></ul><p>There is nothing wrong in getting the custom-built hammer (DO), in fact, it is the best offering for most use cases. As long as it serves your purpose, why would you pay more? But if this is not enough for your use case, if you need more functionality or you want to leverage the productivity offered by using managed services, then consider the rich tool set offered by AWS.</p><p>In conclusion, you can’t really compare DO and AWS. Both cloud platforms provide excellent services to their target market. Digital Ocean provides the best bang for the buck cloud servers while AWS provides a rich tool set. It is up to you to decide which one suits your team. Or better yet, choose multiple platforms, for a hybrid cloud setup utilizing the best services these different cloud platforms offer.</p><p><em>Disclaimer: All views expressed on this site are my own and do not represent the opinions of any entity whatsoever with which I have been, am now, or will be affiliated</em></p><p><em>* 0.000087 Bitcoin = 1 USD as of clicking the publish button</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ac686deed38" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Terraforming an AWS VPC — Part 2]]></title>
            <link>https://carlocayos.medium.com/terraforming-an-aws-vpc-part-2-dd4d491a0f84?source=rss-1f077a1a20e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd4d491a0f84</guid>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Carlo Cayos]]></dc:creator>
            <pubDate>Tue, 20 Feb 2018 12:52:36 GMT</pubDate>
            <atom:updated>2021-04-02T06:14:46.372Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*UHD1BAS1yXxtk6vIRsmUbg.png" /></figure><p><strong>UPDATE:</strong> This is the second part of a series of articles on how to setup an AWS VPC using <strong>Terraform version 0.12.29</strong>.</p><p>In <a href="https://medium.com/@carlocayos/terraforming-an-aws-vpc-part-1-b496b40f9e56">Part 1</a> of this series of post, we have created our first Terraform project and ran basic commands to generate an execution plan, and then provision our first AWS VPC. In this follow up post, we will continue on updating our script to complete our VPC.</p><h3>Remote State</h3><p>By default, Terraform saves the state file <strong>terraform.tfstate</strong> locally. Remember that the state file keeps a record of your infrastructure. If several users are updating the same environment, then each user would generate a state file locally. Any modification done in the code would not be visible to other users. Fortunately, Terraform supports remote state storage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*WU3z_4n-3cyOFohsw8JACA.png" /></figure><p>In the image above, the state file is saved to a S3 bucket and is shared across all users. A team member with proper IAM credential can access the state file and update it through Terraform as it will know which resource has been modified, added, or destroyed.</p><p>Update the <strong>main.tf</strong> file to configure Terraform to save the state file to S3.</p><pre>#-------------------------------<br># AWS Provider<br>#-------------------------------<br>provider &quot;aws&quot; {<br>  region  = &quot;ap-southeast-2&quot;<br>}</pre><pre>#-------------------------------<br># S3 Remote State<br>#-------------------------------<br>terraform {<br>  backend &quot;s3&quot; {<br>    bucket = &quot;my-terraform-bucket-12345&quot;<br>    key    = &quot;vpc.tfstate&quot;<br>    region = &quot;ap-southeast-2&quot;<br>  }<br>}</pre><pre>#-------------------------------<br># VPC resource<br>#-------------------------------<br>resource &quot;aws_vpc&quot; &quot;main&quot; {<br>  cidr_block = &quot;10.0.0.0/16&quot;</pre><pre>tags = {<br>    Name     = &quot;my-terraform-aws-vpc&quot;<br>  }<br>}</pre><p>This tells Terraform to save the state file into an S3 bucket rather than storing it locally. <strong><em>Set a unique name to your S3 bucket name</em></strong>, and make sure that the IAM credentials you are using have access to this bucket. Now run <strong>terraform init</strong> then <strong>terraform apply</strong>. A new <strong>vpc.tfstate</strong> file should be uploaded to your S3 bucket.</p><pre>$ terraform init<br>Initializing the backend...</pre><pre>Successfully configured the backend &quot;s3&quot;! Terraform will automatically use this backend unless the backend configuration changes.<br>...</pre><h3>Terraform Workspace</h3><p>The ability to reproduce your infrastructure for any environment, in any region, with just running a few commands, is one of the key features of Terraform. It’s ideal to have this in mind when designing our scripts before we move further and write more lines to our code. Terraform supports multiple <a href="https://www.terraform.io/docs/state/workspaces.html">workspaces</a> to provision different configurable environments requiring similar resources.</p><p>Run <strong>terraform workspace list</strong>, it will show us the list of all workspaces.</p><pre>$ terraform workspace list<br>* default</pre><p>As expected, we only have the <strong>default</strong> workspace in the list, and it is the currently selected workspace as indicated by the <strong>*</strong>. What we want is to create a VPC for these environments:</p><ul><li>DEV</li><li>UAT</li><li>PROD</li></ul><p>Let’s create a new workspace by running <strong>terraform workspace new dev</strong>.</p><pre>$ terraform workspace new dev<br>Created and switched to workspace &quot;dev&quot;!</pre><pre>You&#39;re now on a new, empty workspace. Workspaces isolate their state, so if you run &quot;terraform plan&quot; Terraform will not see any existing state for this configuration.</pre><pre>$ terraform workspace list<br>  default<br>* dev</pre><p>We are automatically migrated to the new <strong>dev</strong> workspace. Do the same for <strong>uat</strong> and <strong>prod</strong> workspaces.</p><p>View the remote S3 bucket to see how Terraform stores separate state files for these 3 environments.</p><pre>$ aws s3api list-objects --bucket my-terraform-bucket-12345 --query &#39;Contents[].{Key: Key}&#39;<br>[<br>    {<br>        &quot;Key&quot;: &quot;env:/dev/vpc.tfstate&quot;<br>    },<br>    {<br>        &quot;Key&quot;: &quot;env:/prod/vpc.tfstate&quot;<br>    },<br>    {<br>        &quot;Key&quot;: &quot;env:/uat/vpc.tfstate&quot;<br>    },<br>    {<br>        &quot;Key&quot;: &quot;vpc.tfstate&quot;<br>    }<br>]</pre><p>There are 3 newly created state files, each one persisting an environment’s state. We can ignore the <strong>vpc.tfstate</strong> in the root directory as this was created in the default workspace. It is preferred to use the workspace state file for multiple environments.</p><p>Change back to the <strong>dev</strong> workspace using the command <strong>terraform workspace select dev</strong> and create a VPC in this new environment. Follow the same procedure for the<strong> uat</strong> and <strong>prod</strong> workspace.</p><pre>$ terraform workspace select dev<br>Switched to workspace &quot;dev&quot;.</pre><pre>$ terraform plan<br>...<br>$ terraform apply<br>...</pre><h3>Configurable Environment</h3><p>Different environments have different need. A production environment needs more compute power than a development environment. You also need to consider the location where you provision your environment. For example, if your development team is in Australia, your testers are in Singapore, and your clients are in Japan, then you should build your infrastructure closest to who will be using it, it will lower latency and cost.</p><p>To achieve this, we need to modify our script and add variables. Let’s first start by using variables to set the AWS region where we will provision our VPC, the VPC CIDR block, and resource tag.</p><p>Your project should have <strong>main.tf</strong> and <strong>variables.tf</strong> files. Create a new directory <strong>env</strong>, under it create the subdirectories <strong>dev</strong>, <strong>uat</strong>, and <strong>prod</strong>. In each subdirectory, create a file <strong>vpc.tfvars</strong> to hold all the variable values distinct to each environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/317/1*cjPDAOxQsf21IiR00qYY3w.png" /></figure><p>Set the variables values for each environment. The VPC CIDR block would remain the same for simplicity.</p><p><strong>env/dev/vpc.tfvars</strong> — Asia Pacific (Sydney) region</p><pre>aws_region     = &quot;ap-southeast-2&quot;<br>vpc_cidr_block = &quot;10.0.0.0/16&quot;</pre><p><strong>env/uat/vpc.tfvars</strong> -Asia Pacific (Singapore) region</p><pre>aws_region     = &quot;ap-southeast-1&quot;<br>vpc_cidr_block = &quot;10.0.0.0/16&quot;</pre><p><strong>env/prod/vpc.tfvars</strong> -Asia Pacific (Tokyo) region</p><pre>aws_region     = &quot;ap-northeast-1&quot;<br>vpc_cidr_block = &quot;10.0.0.0/16&quot;</pre><p>Open <strong>variables.tf</strong> and define the following variables.</p><pre>variable &quot;aws_region&quot; {  <br>    description = &quot;AWS Region&quot;<br>}</pre><pre>variable &quot;vpc_cidr_block&quot; {  <br>    description = &quot;Main VPC CIDR Block&quot;<br>}</pre><p>Go to<strong> main.tf</strong> file and use these variables in this format <strong>${var.variable_name}</strong>.</p><pre>#-------------------------------<br># AWS Provider<br>#-------------------------------<br>provider &quot;aws&quot; {<br>  region  = var.aws_region<br>}</pre><pre>#-------------------------------<br># S3 Remote State<br>#-------------------------------<br>terraform {<br>  backend &quot;s3&quot; {<br>    bucket = &quot;my-terraform-bucket-12345&quot;<br>    key    = &quot;vpc.tfstate&quot;<br>    region = &quot;ap-southeast-2&quot;<br>  }<br>}</pre><pre>#-------------------------------<br># VPC resource<br>#-------------------------------<br>resource &quot;aws_vpc&quot; &quot;main&quot; {<br>  cidr_block = var.vpc_cidr_block</pre><pre>tags = {<br>    Name = &quot;my-terraform-aws-vpc-${terraform.workspace}&quot;<br>    Environment = terraform.workspace<br>  }<br>}</pre><p>The variable <strong>${terraform.workspace}</strong> is an interpolation sequence to get the current workspace name to set in our configuration.</p><p>Update the <strong>dev</strong> environment by setting the correct workspace, running <strong>terraform plan</strong> and <strong>apply</strong> while using the attribute <strong>var-file</strong> to tell Terraform which values to substitute to the variables. Do the same for <strong>uat</strong> and <strong>prod</strong>., changing the <strong>vpc.tfvars</strong> location. Go to your AWS console, select the region and search for the created VPC.</p><pre>$ terraform workspace select dev<br>...<br>$ terraform plan -var-file=env/dev/vpc.tfvars<br>...<br>$ terraform apply -var-file=env/dev/vpc.tfvars<br>...</pre><p>Do the same for <strong>uat</strong> and <strong>prod</strong>, by changing the <strong>vpc.tfvars</strong> location. Go to your AWS console, select the region and search for the created VPC.</p><pre># For UAT<br>$ terraform workspace select uat<br>$ terraform plan -var-file=env/uat/vpc.tfvars<br>$ terraform apply -var-file=env/uat/vpc.tfvars</pre><pre># For PROD<br>$ terraform workspace select prod<br>$ terraform plan -var-file=env/prod/vpc.tfvars<br>$ terraform apply -var-file=env/prod/vpc.tfvars</pre><h3>Completing the VPC 🏁</h3><p>We have set up a remote state file and made the code reusable for different environments, it’s time to finish up our VPC in <a href="https://medium.com/@carlocayos/terraforming-an-aws-vpc-part-3-515012f0e26c">Part 3</a>. In order to do this, we will be adding these resources:</p><ul><li>AWS VPC (done)</li><li>Internet Gateway</li><li>3x Public subnet — one for each AZ</li><li>3x Private subnet — one for each AZ</li><li>3x Database subnet — one for each AZ</li><li>Public subnet route table</li><li>Private subnet route table</li><li>Database subnet route table</li><li>EC2 Bastion Host</li><li>Elastic IP Address</li><li>NAT Gateway</li></ul><p>The diagram below shows us how we want to setup the VPC.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-zQGw--urYb_vBa3fCrLgw.png" /></figure><p><em>Disclaimer: All views expressed on this site are my own and do not represent the opinions of any entity whatsoever with which I have been, am now, or will be affiliated</em></p><p><em>Originally published at </em><a href="https://carlocayos.com/"><em>carlocayos.com</em></a><em>. Updated to Terraform </em>version 0.12.29.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd4d491a0f84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Terraforming an AWS VPC — Part 1]]></title>
            <link>https://carlocayos.medium.com/terraforming-an-aws-vpc-part-1-b496b40f9e56?source=rss-1f077a1a20e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/b496b40f9e56</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Carlo Cayos]]></dc:creator>
            <pubDate>Tue, 20 Feb 2018 12:13:09 GMT</pubDate>
            <atom:updated>2021-04-02T06:15:02.326Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*A9yaUubZI-etsJ9vRgu_Ig.png" /></figure><p><strong>UPDATE: </strong>This is part 1 of a series of articles on how to setup an AWS VPC using <strong>Terraform version 0.12.29</strong>.</p><p>Imagine you will be working on a greenfield project where everything will be running in AWS. Because you have watched more AWS tutorial videos than anyone else in your team, you were given the responsibility to set up all the needed AWS resources. Everyone in the team is blocked until you complete it. But you don’t feel any pressure at all because according to one of the tutorial videos you watched, hosting your servers in AWS is child’s play and can be done in a click of a button.</p><p>When you sat on your desk, the first thing you did is login to the AWS console and then started building an AWS VPC. You have managed to setup the VPC, along with an internet gateway and a public subnet in all AZs. Later that week, a developer said that another application will be exclusively used internally, so you created a private subnet for internal apps. Updates from the team kept on coming, and you handled it like a pro, thanks to the tutorial videos and a few button clicks in the AWS console.</p><p>Now, a tester came to you asking for a UAT environment, and pointed out that it should be exactly similar to the DEV environment. You paused for a second and tried thinking of what needs to be done. You realised that not only you have to recall and probably watch all the tutorial videos again to do all the incremental changes you’ve made, you also have to verify if the UAT environment you created is a mirror copy of the DEV environment as per requirement.</p><h3>Infrastructure as Code</h3><p>Infrastructure as code is a technique for provisioning infrastructure configuration by means of codes. It allows you to control and implement changes to your environment through code changes pushed into a source repository, resulting to a more maintainable and predictable infrastructure.</p><p><a href="https://www.terraform.io/">Terraform</a> is an IaC open source software written in Golang by <a href="https://www.hashicorp.com/">Hashicorp</a>.</p><blockquote>Terraform is a tool for building, changing, and versioning infrastructure safely and efficiently. Terraform can manage existing and popular service providers as well as custom in-house solutions.</blockquote><p>The key features of Terraform are:</p><ul><li>Infrastructure as Code</li><li>Execution Plans</li><li>Resource Graph</li><li>Change Automation</li></ul><p>Terraform is agnostic to the underlying platform, it has <strong>providers </strong>which drives the API interaction to different IaaS, PaaS, or SaaS services. For this article, we will be using Terraform’s <a href="https://www.terraform.io/docs/providers/aws/index.html">AWS Provider</a>.</p><h3>Installing Terraform</h3><p>For macOS users, install Terraform using Homebrew. Check the version to confirm if it is installed correctly.</p><pre>$ brew install terraform<br>$ terraform -version<br>Terraform v0.12.29</pre><h3>Terraform Hands-on</h3><p>First, make sure that you have AWS credentials with access to provision resources to your AWS account. The easiest way to do this is installing <strong>AWS cli</strong> and running <strong>aws configure</strong>.</p><p>Let’s create our first Terraform project. Create a new directory, then inside it create three empty files.</p><pre>my-terraform-aws-vpc<br>├── main.tf<br>├── outputs.tf<br>└── variables.tf</pre><p>Open <strong>main.tf</strong> file and add these codes.</p><pre>#-------------------------------<br># AWS Provider<br>#-------------------------------<br>provider &quot;aws&quot; {<br>  region = &quot;ap-southeast-2&quot;<br>}</pre><pre>#-------------------------------<br># VPC resource<br>#-------------------------------<br>resource &quot;aws_vpc&quot; &quot;main&quot; {<br>  cidr_block = &quot;10.0.0.0/16&quot;</pre><pre>tags = {<br>    Name = &quot;my-terraform-aws-vpc&quot;<br>  }<br>}</pre><p>This tells Terraform to configure an AWS provider and set the AWS region to Sydney (ap-southeast-2). It will also create an AWS VPC with a CIDR block of <strong>10.0.0.0/16</strong>.</p><p>In your terminal, go inside the created directory and run <strong>terraform init</strong>. This will download and initialise the AWS provider set in your<strong> main.tf</strong> file.</p><pre>$ terraform init<br>Initializing provider plugins...<br>- Checking for available provider plugins..<br>- Downloading plugin for provider &quot;aws&quot; (1.5.0)...<br>...<br>Terraform has been successfully initialized!<br>...</pre><p>Run <strong>terraform plan</strong> and see what happens!</p><pre>$ terraform plan<br>...<br>An execution plan has been generated and is shown below.<br>Resource actions are indicated with the following symbols:<br>  + create</pre><pre>Terraform will perform the following actions:</pre><pre># aws_vpc.main will be created<br>  + resource &quot;aws_vpc&quot; &quot;main&quot; {<br>      + arn                              = (known after apply)<br>      + assign_generated_ipv6_cidr_block = false<br>      + cidr_block                       = &quot;10.0.0.0/16&quot;<br>      + default_network_acl_id           = (known after apply)<br>      + default_route_table_id           = (known after apply)<br>      + default_security_group_id        = (known after apply)<br>      + dhcp_options_id                  = (known after apply)<br>      + enable_classiclink               = (known after apply)<br>      + enable_classiclink_dns_support   = (known after apply)<br>      + enable_dns_hostnames             = (known after apply)<br>      + enable_dns_support               = true<br>      + id                               = (known after apply)<br>      + instance_tenancy                 = &quot;default&quot;<br>      + ipv6_association_id              = (known after apply)<br>      + ipv6_cidr_block                  = (known after apply)<br>      + main_route_table_id              = (known after apply)<br>      + owner_id                         = (known after apply)<br>      + tags                             = {<br>          + &quot;Name&quot; = &quot;my-terraform-aws-vpc&quot;<br>        }<br>    }</pre><pre>Plan: 1 to add, 0 to change, 0 to destroy.</pre><pre>--------------------------------------------------------------------</pre><pre>Note: You didn&#39;t specify an &quot;-out&quot; parameter to save this plan, so Terraform can&#39;t guarantee that exactly these actions will be performed if &quot;terraform apply&quot; is subsequently run.</pre><p>Notice that it generates an execution plan with<em> 1 VPC resource</em> to be added. The command terraform plan is a way to see an overview of what resource will be added, changed, or destroyed in relation to the code changes, without applying the changes to your infrastructure.</p><p>After reviewing the execution plan, it’s time to implement it by the conveniently named command <strong>terraform apply</strong>.</p><pre>$ terraform apply<br>...<br>Plan: 1 to add, 0 to change, 0 to destroy.</pre><pre>Do you want to perform these actions?<br>  Terraform will perform the actions described above.<br>  Only &#39;yes&#39; will be accepted to approve.</pre><pre>Enter a value: yes</pre><pre>aws_vpc.main: Creating...<br>aws_vpc.main: Creation complete after 3s [id=vpc-00b4438c67901c9cd]<br>Apply complete! Resources: 1 added, 0 changed, 0 destroyed.</pre><p>Login to the AWS console to view the created VPC or run this AWS CLI command.</p><pre>$ aws ec2 describe-vpcs --filters &#39;Name=tag:Name,Values=my-terraform-aws-vpc&#39;</pre><p>To demonstrate how easy it is to spin up your infrastructure via Terraform, we will destroy the created VPC using the command <strong>terraform destroy</strong>.</p><pre>$ terraform destroy<br>...<br>Terraform will perform the following actions:<br>  # aws_vpc.main will be destroyed<br>Plan: 0 to add, 0 to change, 1 to destroy.</pre><pre>Do you really want to destroy all resources?<br>  Terraform will destroy all your managed infrastructure, as shown above.<br>  There is no undo. Only &#39;yes&#39; will be accepted to confirm.</pre><pre>Enter a value: yes</pre><pre>aws_vpc.main: Destroying... [id=vpc-00b4438c67901c9cd]<br>aws_vpc.main: Destruction complete after 0s<br>Destroy complete! Resources: 1 destroyed.</pre><p>Then build it again using <strong>terraform plan </strong>and <strong>terraform apply</strong>.</p><h3>State File</h3><p>Terraform saves the state in a <strong>terraform.tfstate</strong> file in JSON format, this file contains the managed infrastructure details.</p><pre>my-terraform-aws-vpc<br>├── main.tf<br>├── outputs.tf<br>├── terraform.tfstate<br>├── terraform.tfstate.backup<br>└── variables.tf</pre><p>Here’s how it looks like.</p><pre>{<br>  &quot;version&quot;: 4,<br>  &quot;terraform_version&quot;: &quot;0.12.29&quot;,<br>  &quot;serial&quot;: 5,<br>  &quot;lineage&quot;: &quot;62ac4f4b-b60a-2ca0-364a-3e8fcad74c66&quot;,<br>  &quot;outputs&quot;: {},<br>  &quot;resources&quot;: [<br>    {<br>     ...<br>    }<br>  ]<br>}</pre><p>By default, the state file is saved locally. However, when working with a team, this should be saved in a remote location to have a synchronized state across all terraform users.</p><h3>What’s next?</h3><p>We are now familiar on how Terraform works and have created an AWS VPC, but the VPC is still missing critical components to make it useable. In the <a href="https://medium.com/@carlocayos/terraforming-an-aws-vpc-part-2-dd4d491a0f84">second part</a> of this blog post, we would transfer the state file into a remote S3 bucket, discuss how to re-use the code to create multiple environments, and update the Terraform script to complete the VPC setup as depicted in the diagram below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-zQGw--urYb_vBa3fCrLgw.png" /></figure><p><em>Disclaimer: All views expressed on this site are my own and do not represent the opinions of any entity whatsoever with which I have been, am now, or will be affiliated</em></p><p><em>Originally published at </em><a href="https://carlocayos.com/"><em>carlocayos.com</em></a><em>. Updated to Terraform </em>version 0.12.29.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b496b40f9e56" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>