An example of creating and implementing modular code with Terraform

Example

The following code will provide a simple example. The first bit of code will create a VPC with one public subnet. We’ll have our declaration of using Terraform Remote State in that very same folder. We will also create an “output” to our Terraform Remote State that provides the “VPC ID” and “Public Subnet ID.”

The second bit of code will create an EC2 resource in the public subnet. It knows the VPC already deployed and subnet information to place the EC2 resource by using a data statement to get remote state information to get the VPC ID and public subnet ID.

Requirements

  • Must have an AWS account
  • Install AWS CLIConfigure AWS CLI, and Install Terraform on your computer or development environment
  • Must create an S3 bucket that will hold Terraform Remote State before running the following code
  • AWS Administrator account or an account with the following permissions:
    • create, edit and delete S3 buckets
    • create VPC, subnets, routing, and security groups
    • create EC2 Instances and manage EC2 resources

Create the VPC

So for our example, we’ll need two folders. One folder is named VPC. The second folder is named “EC2”.

VPC.tf

Place the following code into the VPC folder.

EC2 resource

Now place the following code in a different folder.

EC2.tf

An S3 bucket must exist before launching each of the codes above.

Be sure to edit the parameters in each of the above files, and change the bucket, key, and region!

In your terminal, go to the VPC folder and execute the following commands:

  1. Terraform init
  2. terraform validate
  3. Terraform apply

Once the VPC is up and running, go to the EC2 resource folder and execute the same commands as shown above. I you successfully created an S3 bucket prior to using the above code and correctly renamed the parameters appropriate for your region, you should have an EC2 resource created from modular code.

Author: Joseph OMara

Solution Architect for Information Technology. Hobbies include amateur photography, backpacking, camping, hiking, and travel

One thought on “An example of creating and implementing modular code with Terraform”

Leave a ReplyCancel reply

Discover more from Joseph O'Mara

Subscribe now to keep reading and get access to the full archive.

Continue reading

Exit mobile version
%%footer%%