How to use Terraform with AWS Lab (MacOS)
In this exercise, you will provision an EC2 instance on Amazon Web Services using Terraform. EC2 instances are virtual machines running on AWS, and a common component of many infrastructure projects. This is How to use Terraform with AWS Lab (MacOS).
We first need to install Terraform and then we will continue with completing our very first Terraform lifecycle. Follow along in these two videos as we install Terraform to a Mac then proceed with the instructions.
Installing Terraform to Mac
brew install terraform
terraform -install-autocomplete
Running your first Terraform
With Terraform there is a lifecycle for a resource and it can be broken down into four phases: Init, Plan, Apply, and Destroy.
init — Init. Initialize the (local) Terraform environment. Usually executed only once per session.
plan — Plan. Compare the Terraform state with the as-is state in the cloud, build and display an execution plan. This does not change the deployment (read-only).
apply — Apply the plan from the plan phase. This potentially changes the deployment (read and write).
destroy — Destroy all resources that are governed by this specific terraform environment.
This KB assumes that you have created an AWS account and subscription. The first thing we will do is install the AWS CLI tools and configure it to be used with terraform.
Download the file using the curl command. The -o option specifies the file name that the downloaded package is written to. In this example, the file is written to AWSCLIV2.pkg in the current folder.
curl “https://awscli.amazonaws.com/AWSCLIV2.pkg" -o “AWSCLIV2.pkg”
Run the standard macOS installer program, specifying the downloaded .pkg file as the source.
sudo installer -pkg AWSCLIV2.pkg -target /
Now the next thing we need to do is create access keys so that the AWS CLI can access your AWS account. For this let’s switch to a web browser and go to your AWS console. I recommend not using your AWS root user but if you don’t use AWS for anything yet, it might be OK. In my case I have created a separate user for this exercise and I will login directly to my console with this user.
Click on the user in the top right of the portal and go to security credentials.
Scroll down to access keys and click the button to create an access key.
Select the Command Line Interface option and click next.
Click create access key.
Now this is the only time you’ll be able to view the access key secret. If you need it again you’ll have to create a new key. Store it in your password manager or the safest way you have at your disposal.
Now lets go back to the terminal. To use your IAM credentials to authenticate the Terraform AWS provider, set the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables to the key values we just got.
export AWS_ACCESS_KEY_ID=
export AWS_SECRET_ACCESS_KEY=
Now we’re all set up to use AWS with Terraform!
Writing the Configuration
Let’s write the configuration. Each Terraform configuration must be in its own working directory. Create a directory for your configuration.
mkdir learn-terraform-aws-instance
Change into the directory.
cd learn-terraform-aws-instance
Open main.tf in visual studio code on Mac.
brew install —cask visual-studio-code
code main.tf
Paste in the configuration. Save the file.
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 4.16"
}
}
required_version = ">= 1.2.0"
}
provider "aws" {
region = "us-west-2"
}
resource "aws_instance" "app_server" {
ami = "ami-830c94e3"
instance_type = "t2.micro"
tags = {
Name = "ExampleAppServerInstance"
}
}
This is a complete configuration that you can deploy with Terraform. The following sections review each block of this configuration in more detail.
Terraform Block
The terraform {} block contains Terraform settings, including the required providers Terraform will use to provision your infrastructure. For each provider, the source attribute defines an optional hostname, a namespace, and the provider type. Terraform installs providers from the Terraform Registry by default. In this example configuration, the aws provider’s source is defined as hashicorp/aws, which is shorthand for registry.terraform.io/hashicorp/aws.
You can also set a version constraint for each provider defined in the required_providers block. The version attribute is optional, but we recommend using it to constrain the provider version so that Terraform does not install a version of the provider that does not work with your configuration. If you do not specify a provider version, Terraform will automatically download the most recent version during initialization.
Providers
The provider block configures the specified provider, in this case aws. A provider is a plugin that Terraform uses to create and manage your resources.
You can use multiple provider blocks in your Terraform configuration to manage resources from different providers. You can even use different providers together. For example, you could pass the IP address of your AWS EC2 instance to a monitoring resource from DataDog.
Resources
Use resource blocks to define components of your infrastructure. A resource might be a physical or virtual component such as an EC2 instance, or it can be a logical resource such as a Heroku application.
Resource blocks have two strings before the block: the resource type and the resource name. In this example, the resource type is aws_instance and the name is app_server. The prefix of the type maps to the name of the provider. In the example configuration, Terraform manages the aws_instance resource with the aws provider. Together, the resource type and resource name form a unique ID for the resource. For example, the ID for your EC2 instance is aws_instance.app_server.
Resource blocks contain arguments which you use to configure the resource. Arguments can include things like machine sizes, disk image names, or VPC IDs. The provider’s reference lists the required and optional arguments for each resource. For your EC2 instance, the example configuration sets the AMI ID to an Ubuntu image, and the instance type to t2.micro, which qualifies for AWS’ free tier. It also sets a tag to give the instance a name.
Initialize the directory
When you create a new configuration — or check out an existing configuration from version control — you need to initialize the directory with terraform init.
Initializing a configuration directory downloads and installs the providers defined in the configuration, which in this case is the aws provider.
Initialize the directory.
terraform init
Terraform downloads the aws provider and installs it in a hidden subdirectory of your current working directory, named .terraform. The terraform init command prints out which version of the provider was installed. Terraform also creates a lock file named .terraform.lock.hcl which specifies the exact provider versions used, so that you can control when you want to update the providers used for your project.
Format and validate the configuration
We recommend using consistent formatting in all of your configuration files. The terraform fmt command automatically updates configurations in the current directory for readability and consistency.
Format your configuration. Terraform will print out the names of the files it modified, if any.
terraform fmt
You can also make sure your configuration is syntactically valid and internally consistent by using the terraform validate command.
Validate your configuration. The example configuration is valid, so Terraform will return a success message.
terraform validate
Create infrastructure
Apply the configuration now with the terraform apply command.
terraform apply
Before it applies any changes, Terraform prints out the execution plan which describes the actions Terraform will take in order to change your infrastructure to match the configuration.
The output format is similar to the diff format generated by tools such as Git. The output has a + next to aws_instance.app_server, meaning that Terraform will create this resource. Beneath that, it shows the attributes that will be set. When the value displayed is known after apply, it means that the value will not be known until the resource is created. For example, AWS assigns Amazon Resource Names (ARNs) to instances upon creation, so Terraform cannot know the value of the arn attribute until you apply the change and the AWS provider returns that value from the AWS API.
Terraform will now pause and wait for your approval before proceeding. If anything in the plan seems incorrect or dangerous, it is safe to abort here before Terraform modifies your infrastructure.
In this case the plan is acceptable, so type yes at the confirmation prompt to proceed. Executing the plan will take a few minutes since Terraform waits for the EC2 instance to become available.
yes
You have now created infrastructure using Terraform! Visit the EC2 console and find your new EC2 instance. Make sure you are in the right region to see your EC2 instance, in this case it is US-WEST-2.
Terraform Destroy
Lastly, the Terraform Destroy command will destroy all resources created. It reads the .tfstate file created in your working directory to know which resources were created thus which need to be destroyed. Issue the Terraform Destroy command now.
terraform destroy
And that completes the lifecycle of initializing, planning, applying and destroying AWS infrastructure with Terraform. As of now, you understand how the Terraform lifecycle works and have configured both Azure and AWS with Terraform so that you can continue your learning. If you would like to continue your learning with Terraform, I’d highly recommend the Udemy course Terraform for Absolute Beginners with Labs. This innovative course from KodeKloud walks you through creating a Terraform file from scratch with lectures and by using their proprietary lab platform KodeKloud. The only reason I recommend it is because I took it myself and thought it was a fantastic course.
Wrapping Up
After taking the course from KodeKloud, I scored a 60% on the Hashicorp Terraform Associate certification. 70% is required to pass the exam. There are some things the course doesn’t cover about Terraform Cloud and Hashicorp Vault that really got me. I grabbed some practice tests from Udemy and passed the Terraform Associate exam.
Tyler Wall is the founder of Cyber NOW Education. He holds bills for a Master of Science from Purdue University and CISSP, CCSK, CFSR, CEH, Sec+, Net+, and A+ certifications. He mastered the SOC after having held every position from analyst to architect and is the author of three books, 100+ professional articles, and ten online courses specifically for SOC analysts.
You can connect with him on LinkedIn.
You can sign up for a Lifetime Membership of Cyber NOW® with a special deal for 15% off with coupon code "KB15OFF" which includes all courses, certification, the cyber range, the hacking lab, webinars, the extensive knowledge base, forums, and spotlight eligibility, to name a few benefits.
Download the Azure Security Labs eBook from the Secure Style Store. These labs walk you through several hands-on fun labs in Microsoft Azure, leaving you with the know-how to create a gig in Fiverr or Upwork to start your cybersecurity freelancing.
Some of our free resources include the Forums, the Knowledge Base, our True Entry Level SOC Analyst Jobs, Job Hunting Application Tracker, Resume Template, and Weekly Networking Checklist. Ensure you create an account or enter your email to stay informed of our free giveaways and promos, which we often offer.
Check out my latest book, Jump-start Your SOC Analyst Career: A Roadmap to Cybersecurity Success, 2nd edition, published June 1st, 2024, and winner of the 2024 Cybersecurity Excellence Awards and a finalist in the Best Book Awards. If you enjoy audiobooks, I suggest the Audible version, but you can also get it in beautiful paperback, kindle, or PDF versions. The downloadable PDF version can be grabbed here
Commentaires