Terraform-Day-2
### Hands-On Lab: Setting Up Remote Backend for Terraform with S3 and DynamoDB
### Scenario
Configure Terraform to use a remote backend (Amazon S3) for storing the state file and DynamoDB for state locking. Additionally, create an EC2 instance using Terraform.
### Prerequisites
1. AWS account with permissions to create EC2, S3, and DynamoDB resources.
2. Terraform installed locally.
3. AWS CLI installed and configured with necessary IAM credentials.
### Step 1: Create S3 Bucket and DynamoDB Table for Terraform State
#### 1.1 Create an S3 Bucket via AWS Console
1. Navigate to the S3 service in the AWS Management Console.
2. Click Create bucket.
3. Set the bucket name: `my-terraform-state-bucket` (ensure it is globally unique).
4. Choose a region (e.g., `us-west-2`).
5. Click Create using default settings.
#### 1.2 Create a DynamoDB Table for State Locking via AWS Console
1. Open the DynamoDB service in the AWS Management Console.
2. Click Create table.
3. Set the table name: `terraform-state-lock`.
4. Define the Partition key: `LockID` (String type).
5. Click Create using default settings.
#### 1.3 Create S3 Bucket and DynamoDB Table via AWS CLI
- Create S3 Bucket:
aws s3api create-bucket --bucket my-terraform-state-bucket --region us-west-2 --create-bucket-configuration LocationConstraint=us-west-2
- Create DynamoDB Table:
aws dynamodb create-table --table-name terraform-state-lock \
--attribute-definitions AttributeName=LockID,AttributeType=S \
--key-schema AttributeName=LockID,KeyType=HASH \
--provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5 \
--region us-west-2
### Step 2: Set Up Terraform Configuration for Remote Backend
#### 2.1 Create a New Directory for Terraform
mkdir terraform-ec2-backend
cd terraform-ec2-backend
#### 2.2 Create `backend.tf` for Remote Backend Configuration
`backend.tf`:
terraform {
backend "s3" {
bucket = "my-terraform-state-bucket"
key = "terraform.tfstate"
region = "us-west-2"
encrypt = true
dynamodb_table = "terraform-state-lock"
acl = "private"
}
}
#### 2.3 Create `main.tf` for EC2 Instance
`main.tf`:
provider "aws" {
region = "us-west-2"
}
resource "aws_instance" "my_ec2" {
ami = "ami-0c55b159cbfafe1f0" # Amazon Linux 2 AMI
instance_type = "t2.micro"
key_name = "my-ec2-key" # Replace with your key pair name
tags = {
Name = "MyTerraformEC2"
}
}
### Step 3: Plan and Apply the Terraform Configuration
#### 3.1 Initialize Terraform
terraform init
Expected Output:
Initializing the backend...
Successfully configured the backend "s3"! Terraform will automatically use this backend unless the configuration changes.
#### 3.2 Preview the Plan
terraform plan
Expected Output:
Plan: 1 to add, 0 to change, 0 to destroy.
#### 3.3 Apply the Configuration
terraform apply
- Confirm the execution by typing `yes`.
Expected Output:
aws_instance.my_ec2: Creating...
aws_instance.my_ec2: Creation complete after 30s...
### Step 4: Verify the Resources
1. Verify EC2 Instance:
- Open the EC2 Dashboard in the AWS Console.
- Locate the instance named `MyTerraformEC2`.
2. Verify S3 Bucket:
- Navigate to the S3 service in the AWS Console.
- Check that `terraform.tfstate` exists in the `my-terraform-state-bucket`.
3. Verify DynamoDB Table:
- Open the DynamoDB service.
- Ensure `terraform-state-lock` contains records for state locking.
### Step 5: Modify Configuration and Re-Apply
1. Update the EC2 instance type in `main.tf`:
instance_type = "t2.small"
2. Apply the updated configuration:
terraform apply
3. Confirm the changes by typing `yes`.
### Step 6: Clean Up Resources
1. Run Terraform Destroy to delete all resources:
terraform destroy
2. Confirm deletion by typing `yes`.
### Command Syntax Explanation
- `terraform init`: Initializes the working directory and configures the backend.
- `terraform plan`: Shows the proposed infrastructure changes.
- `terraform apply`: Applies the changes to the infrastructure.
- `terraform destroy`: Deletes all resources managed by Terraform.
### Validation
1. Verify the EC2 instance in the AWS EC2 Dashboard.
2. Check the `terraform.tfstate` file in the S3 bucket.
3. Confirm state lock records in the DynamoDB table.
### Conclusion
You successfully configured Terraform with a remote backend using S3 and DynamoDB, created an EC2 instance, and securely managed the Terraform state. This setup enhances collaboration and ensures secure, consistent infrastructure management.
# Hands-on Lab: Terraform State Commands
.## Scenario:
You will use Terraform to create some AWS resources and learn how to interact with the Terraform state using the various state commands, including `terraform state list`, `terraform state show`, `terraform state rm`, `terraform state mv`, and others.
## Prerequisites:
1. Terraform installed locally.
2. An AWS account with the ability to create EC2 instances.
3. AWS CLI installed and configured on your local machine (with the necessary IAM credentials).
4. A remote backend (S3 and DynamoDB) for state management (optional if using local state).
## Step 1: Setting Up Terraform Project
### Create a new directory for your Terraform project:
mkdir terraform-state-lab
cd terraform-state-lab
### Create a new `main.tf` file with the following content, which will create an EC2 instance:
provider "aws" {
region = "us-west-2"
}
resource "aws_instance" "example" {
ami = "ami-0c55b159cbfafe1f0" # Amazon Linux 2 AMI (Replace with your region's AMI)
instance_type = "t2.micro"
tags = {
Name = "MyTerraformEC2"
}
}
## Step 2: Initialize the Terraform Configuration
Run the following command to initialize the Terraform working directory:
terraform init
### Expected Output:
Initializing the backend...
Successfully configured the backend "local"! Terraform will automatically use this backend unless the configuration changes.
## Step 3: Apply the Configuration
Now, apply the Terraform configuration to create the EC2 instance.
terraform apply
Terraform will show the execution plan and ask for confirmation.
Type `yes` to apply the changes and create the resources.
### Expected Output:
aws_instance.example: Creating...
aws_instance.example: Creation complete after 30s...
After applying the configuration, Terraform will create an EC2 instance.
## Step 4: Interact with the Terraform State
Once the resources are created, you can use several `terraform state` commands to interact with and manage the state file.
### 4.1 List All Resources in State
Use the `terraform state list` command to list all resources in the Terraform state:
terraform state list
### Expected Output:
aws_instance.example
This command will display the resources that Terraform is managing. In this case, it will show the EC2 instance created in `main.tf`.
### 4.2 Show Detailed Information about a Resource
Use the `terraform state show` command to display detailed information about a specific resource in the Terraform state. For example:
terraform state show aws_instance.example
### Expected Output:
# aws_instance.example:
resource "aws_instance" "example" {
ami = "ami-0c55b159cbfafe1f0"
arn = "arn:aws:ec2:us-west-2:123456789012:instance/i-0abc1234567890def"
availability_zone = "us-west-2a"
instance_id = "i-0abc1234567890def"
instance_type = "t2.micro"
key_name = "my-ec2-key"
monitoring = false
subnet_id = "subnet-abc123"
vpc_security_group_ids = ["sg-0123456789abcdef"]
...
}
This command will show all the attributes and values of the EC2 instance.
### 4.3 Remove a Resource from State
You may need to remove a resource from the Terraform state without destroying it. Use the `terraform state rm` command:
terraform state rm aws_instance.example
### Expected Output:
Removed aws_instance.example
This will remove the EC2 instance from Terraform’s state but will not destroy the actual EC2 instance in AWS.
### 4.4 Move a Resource to Another Resource Name
Use the `terraform state mv` command to rename a resource in the state file:
terraform state mv aws_instance.example aws_instance.new_example
### Expected Output:
Moved aws_instance.example to aws_instance.new_example
This will rename the resource in the Terraform state without changing the actual infrastructure.
### 4.5 Check the Terraform State File
Inspect the `.terraform` directory where Terraform keeps the state file (usually `terraform.tfstate`). To view the raw JSON representation:
cat terraform.tfstate
### Expected Output:
json
{
"version": 4,
"terraform_version": "0.14.9",
"resources": [
{
"type": "aws_instance",
"name": "example",
"provider": "provider.aws",
"instances": [
{
"schema_version": 2,
"attributes": {
"ami": "ami-0c55b159cbfafe1f0",
"instance_type": "t2.micro",
...
}
}
]
}
]
}
### 4.6 Move State to a Remote Backend (Optional)
If you initially created resources using a local state file, you can migrate to a remote backend (e.g., S3):
1. Update your `backend.tf` to use S3 and DynamoDB for locking.
2. Run:
terraform init -migrate-state
This command will migrate the state from the local backend to the remote backend.
## Step 5: Clean Up Resources
After completing the lab, clean up the resources to avoid unnecessary charges:
terraform destroy
Terraform will ask for confirmation. Type `yes` to confirm and destroy the resources.
## Command Syntax Explanation
- `terraform state list`: Lists all resources in the current Terraform state.
- `terraform state show <resource>`: Displays detailed information about a specific resource in the state.
- `terraform state rm <resource>`: Removes a resource from the Terraform state without destroying it.
- `terraform state mv <old_resource> <new_resource>`: Renames a resource in the Terraform state.
- `terraform init`: Initializes the Terraform working directory and configures the backend.
- `terraform init -migrate-state`: Migrates the Terraform state to a new backend (e.g., from local to remote).
- `terraform destroy`: Destroys all the resources managed by Terraform.
Hands-on Lab: Using Terraform Data Sources for AMI (Amazon Machine Image)
Overview:
In this lab, we will explore how to use Terraform Data Sources to fetch information about existing resources, specifically how to retrieve the AMI (Amazon Machine Image) ID dynamically. This is a common use case when working with AWS, as it allows you to always use the latest AMI for EC2 instances, without hardcoding the AMI ID.
Scenario:
We will create a simple EC2 instance using an AMI Data Source to automatically fetch the latest Amazon Linux 2 AMI ID. By doing so, we ensure that every time we apply the Terraform configuration, it uses the most recent AMI, rather than relying on a static AMI ID.
Prerequisites:
- Terraform installed locally.
- An AWS account with the ability to create EC2 instances.
- AWS CLI installed and configured on your local machine (with the necessary IAM credentials).
- Terraform S3 Backend (Optional if you want to use a remote backend for state management).
Step 1: Set Up Terraform Project
1. Create a new directory for your Terraform project:
mkdir terraform-ami-data-source
cd terraform-ami-data-source
2. Create a new `main.tf` file with the following content, which uses the AMI data source to fetch the latest Amazon Linux 2 AMI and then creates an EC2 instance.
provider "aws" {
region = "us-west-2" # Replace with your region
}
# Fetch the latest Amazon Linux 2 AMI ID
data "aws_ami" "latest_amazon_linux" {
most_recent = true
owners = ["amazon"]
# Filters to get Amazon Linux 2
filter {
name = "name"
values = ["amzn2-ami-hvm-*-x86_64-gp2"]
}
}
# Create an EC2 instance using the latest Amazon Linux 2 AMI
resource "aws_instance" "example" {
ami = data.aws_ami.latest_amazon_linux.id
instance_type = "t2.micro"
tags = {
Name = "Terraform-AMI-Example"
}
}
Explanation of the Code:
- Provider Block: Specifies the AWS provider and the region where the resources will be created (e.g., `us-west-2`).
- AMI Data Source:
- The `aws_ami` data source is used to search for the most recent Amazon Linux 2 AMI in the `us-west-2` region.
- The `most_recent = true` argument ensures that Terraform fetches the most recent AMI.
- The `filter` block filters AMIs by name (e.g., `amzn2-ami-hvm-*-x86_64-gp2`) to match Amazon Linux 2 images.
- EC2 Resource: Creates an EC2 instance using the AMI ID fetched by the data source.
Step 2: Initialize Terraform
Run the following command to initialize the Terraform configuration:
terraform init
Expected Output:
Initializing the backend...
Successfully configured the backend "local"! Terraform will automatically use this backend unless the configuration changes.
This command sets up the working directory and prepares the required provider plugins.
Step 3: Apply the Configuration
Run the following command to apply the Terraform configuration:
terraform apply
Terraform will show an execution plan, asking you to review the resources it plans to create (in this case, an EC2 instance). Type `yes` to confirm and allow Terraform to create the resources.
Expected Output:
aws_instance.example: Creating...
aws_instance.example: Creation complete after 30s...
This will create an EC2 instance using the most recent Amazon Linux 2 AMI.
Step 4: Inspect the AMI ID
After the EC2 instance is created, you can use the `terraform show` command to inspect the details of the resources created:
terraform show
You should see the AMI ID for the EC2 instance as part of the output, which corresponds to the latest Amazon Linux 2 AMI ID that was fetched dynamically by the AMI Data Source.
Step 5: Clean Up Resources
After completing the lab, you can clean up the resources by running the following command:
terraform destroy
Terraform will ask for confirmation. Type `yes` to confirm and destroy the resources.
Expected Output:
aws_instance.example: Destroying... [id=i-0abcd1234efgh5678]
aws_instance.example: Destruction complete after 30s...
This will delete the EC2 instance and all other resources created by Terraform.
Command Syntax Explanation:
- `terraform init`: Initializes the Terraform working directory and downloads necessary provider plugins.
- `terraform apply`: Applies the configuration to create or modify infrastructure resources based on the configuration.
- `terraform show`: Displays the state of the infrastructure managed by Terraform, including the attributes of the resources created.
- `terraform destroy`: Destroys all resources created by Terraform, cleaning up the infrastructure.
# Hands-on Lab: Using Output Values in Terraform
In this lab, we will explore how to use output values in Terraform to display information about the resources created during the provisioning process. We'll create an EC2 instance and output its details, such as the public IP address and instance ID.
## Scenario
You need to create an EC2 instance using Terraform and display useful information such as the instance ID and public IP address once the provisioning is complete. Terraform's output values allow you to reference and display this information after the `apply` phase.
## Prerequisites
1. Terraform installed on your local machine.
2. AWS CLI installed and configured with the necessary permissions.
3. AWS account and IAM roles for creating EC2 instances.
## Step 1: Set Up the Project Directory
1. Create a new directory for your Terraform project:
mkdir terraform-output-lab
cd terraform-output-lab
2. Create the following Terraform files:
- `main.tf`: Contains the EC2 instance resource and provider configuration.
- `variables.tf` (optional): Defines variables for instance configuration.
- `outputs.tf`: Specifies the output values for EC2 instance details.
## Step 2: Define the EC2 Instance Resource in `main.tf`
Create a file called `main.tf` and define the EC2 instance resource:
provider "aws" {
region = "us-west-2"
}
resource "aws_instance" "example" {
ami = "ami-0abcdef1234567890" # Replace with a valid AMI ID
instance_type = "t2.micro"
tags = {
Name = "Terraform-EC2"
}
}
### Explanation
- AMI ID: Replace the placeholder `ami-0abcdef1234567890` with a valid AMI ID (e.g., Amazon Linux 2 or Ubuntu).
- Instance Type: Specifies the type of EC2 instance (e.g., `t2.micro`).
## Step 3: Define Output Values in `outputs.tf`
Create a file called `outputs.tf` to specify the output values for the EC2 instance details:
output "instance_id" {
description = "The ID of the EC2 instance"
value = aws_instance.example.id
}
output "public_ip" {
description = "The public IP of the EC2 instance"
value = aws_instance.example.public_ip
}
### Explanation
- `instance_id`: Outputs the unique ID of the EC2 instance.
- `public_ip`: Outputs the public IP address of the EC2 instance.
## Step 4: Initialize Terraform
Run the following command to initialize your project and download required provider plugins:
terraform init
## Step 5: Apply the Configuration
1. Run the following command to provision the resources defined in `main.tf`:
terraform apply
2. Terraform will display an execution plan and ask for confirmation before making changes. Type `yes` to confirm.
3. After provisioning, Terraform will display the output values defined in `outputs.tf`:
plaintext
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
Outputs:
instance_id = i-1234567890abcdef0
public_ip = 203.0.113.0
## Step 6: View Output Values
After applying, you can view the output values again using:
terraform output
### Example Output
plaintext
instance_id = i-1234567890abcdef0
public_ip = 203.0.113.0
## Step 7: Use Output Values in Other Resources (Optional)
You can reference output values in other resources. For example, to create a security group and associate it with the EC2 instance:
resource "aws_security_group" "example" {
name = "example-sg"
description = "Allow inbound traffic on port 80"
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
tags = {
Name = "example-sg"
}
}
resource "aws_instance" "example" {
ami = "ami-0abcdef1234567890"
instance_type = "t2.micro"
security_groups = [aws_security_group.example.name]
tags = {
Name = "Terraform-EC2"
}
}
## Step 8: Destroy Resources
To clean up resources and avoid charges, destroy the infrastructure using:
terraform destroy
Terraform will ask for confirmation. Type `yes` to delete the resources.
## Conclusion
In this lab, you:
1. Created an EC2 instance using Terraform.
2. Defined output values to display the instance's ID and public IP address.
3. Used the `terraform output` command to view output values.
4. Optionally referenced output values in other resources.
5. Cleaned up resources with `terraform destroy`.
This demonstrates how output values in Terraform help capture and share important information, improving modularity and debugging capabilities.
# Hands-on Lab: Using Terraform Variables
In this lab, we will explore how to use Terraform variables to make configurations more dynamic and reusable. Variables allow you to define values outside the Terraform code and make the configuration flexible and maintainable. We'll create a simple infrastructure that uses variables for EC2 instance configuration.
### Scenario
You need to provision an EC2 instance in AWS using Terraform, where you can customize the instance type and the region by passing values as variables. This makes the Terraform configuration reusable for different environments and instances without modifying the core code.
### Prerequisites
- Terraform installed locally.
- An AWS account with necessary IAM permissions to create EC2 instances.
- AWS CLI installed and configured.
### Step 1: Set Up the Project Directory
1. Create a new directory for your Terraform project:
mkdir terraform-variables-lab
cd terraform-variables-lab
2. Create the following files:
- `main.tf`: Contains the main infrastructure code.
- `variables.tf`: Defines the variables.
- `terraform.tfvars`: Specifies variable values.
### Step 2: Define Variables
Create the `variables.tf` file to define the variables for the EC2 instance.
`variables.tf`:
# Define a variable for the region
variable "region" {
description = "AWS region for the EC2 instance"
type = string
default = "us-west-2" # Default value if not provided
}
# Define a variable for the instance type
variable "instance_type" {
description = "EC2 instance type"
type = string
default = "t2.micro"
}
# Define a variable for the AMI ID
variable "ami_id" {
description = "The AMI ID to launch the EC2 instance"
type = string
}
# Define a variable for the instance name tag
variable "instance_name" {
description = "The name tag for the EC2 instance"
type = string
default = "Terraform-EC2"
}
Explanation:
- `region`: AWS region where the EC2 instance will be created.
- `instance_type`: Type of EC2 instance (default: `t2.micro`).
- `ami_id`: AMI ID used to launch the instance.
- `instance_name`: Name tag for the EC2 instance (default: `Terraform-EC2`).
### Step 3: Create the Infrastructure
Create the `main.tf` file to use the variables defined in `variables.tf`.
`main.tf`:
provider "aws" {
region = var.region # Use the region variable
}
# Create an EC2 instance using the specified variables
resource "aws_instance" "example" {
ami = var.ami_id # Use the AMI ID variable
instance_type = var.instance_type # Use the instance type variable
tags = {
Name = var.instance_name # Use the instance name variable
}
}
Explanation:
- The `provider` block uses the `region` variable.
- The `aws_instance` resource uses `ami_id`, `instance_type`, and `instance_name` variables.
### Step 4: Pass Variable Values
Create the `terraform.tfvars` file to specify values for the variables.
`terraform.tfvars`:
region = "us-west-1" # Specify the AWS region
instance_type = "t2.medium" # Specify the EC2 instance type
ami_id = "ami-0abcdef1234567890" # Replace with a valid AMI ID
instance_name = "MyTerraformEC2" # Set the instance name
### Step 5: Initialize the Terraform Project
Run the following command to initialize your Terraform project:
terraform init
Expected Output:
Initializing provider plugins...
Terraform has been successfully initialized!
### Step 6: Plan the Deployment
Run `terraform plan` to preview the resources that will be created:
terraform plan
Expected Output:
Plan: 1 to add, 0 to change, 0 to destroy.
### Step 7: Apply the Configuration
Apply the configuration to create the EC2 instance:
terraform apply
Type `yes` to confirm the execution plan.
Expected Output:
aws_instance.example: Creating...
aws_instance.example: Creation complete after 30s...
### Step 8: Verify the EC2 Instance
Log in to the AWS Management Console and verify:
- The EC2 instance is in the specified region.
- The instance type matches the configuration.
- The Name tag matches the value in `terraform.tfvars`.
### Step 9: Clean Up Resources
After completing the lab, destroy the resources:
terraform destroy
Type `yes` to confirm.
Expected Output:
aws_instance.example: Destroying... [id=i-0abcd1234efgh5678]
aws_instance.example: Destruction complete after 10s...
### Command Syntax Explanation
- `terraform init`: Initializes the working directory and downloads required provider plugins.
- `terraform plan`: Previews the changes Terraform will make.
- `terraform apply`: Provisions the infrastructure as per the configuration.
- `terraform destroy`: Destroys all resources managed by Terraform.
### Conclusion
In this lab, we:
- Learned to use Terraform variables for flexible configuration.
- Provisioned an EC2 instance by passing variable values.
- Used `terraform.tfvars` to pass custom values.
- Verified the resources and cleaned them up after use.
Using variables in Terraform makes configurations more reusable, maintainable, and scalable for various environments.
# Hands-on Lab: Different Ways to Pass Terraform Variables
Terraform variables are crucial for creating dynamic and reusable infrastructure code. This lab demonstrates multiple ways to pass variable values to Terraform configurations.
## Scenario
You need to create an EC2 instance in AWS using Terraform and explore the following methods to pass variables:
1. Default values in the `variables.tf` file.
2. `.tfvars` files.
3. Command-line input.
4. Environment variables.
## Prerequisites
- Terraform installed.
- AWS CLI installed and configured.
- AWS account with IAM permissions to create EC2 instances.
## Step 1: Set Up the Project Directory
Create a new directory for the Terraform project:
mkdir terraform-variable-passing
cd terraform-variable-passing
Create the following files:
- `main.tf`: To create the EC2 instance.
- `variables.tf`: To define variables.
- `terraform.tfvars`: To pass variable values.
- `outputs.tf`: To output the EC2 instance's public IP.
## Step 2: Define Variables in `variables.tf`
### `variables.tf`
# Define the AWS region
variable "region" {
description = "AWS region for EC2 instance"
type = string
default = "us-west-2"
}
# Define the instance type
variable "instance_type" {
description = "EC2 instance type"
type = string
default = "t2.micro"
}
# Define the AMI ID
variable "ami_id" {
description = "AMI ID to launch the EC2 instance"
type = string
}
# Define the instance name tag
variable "instance_name" {
description = "Name tag for the EC2 instance"
type = string
default = "Terraform-EC2"
}
## Step 3: Create the EC2 Instance in `main.tf`
### `main.tf`
provider "aws" {
region = var.region
}
resource "aws_instance" "example" {
ami = var.ami_id
instance_type = var.instance_type
tags = {
Name = var.instance_name
}
}
## Step 4: Method 1 — Pass Variables via `terraform.tfvars`
### `terraform.tfvars`
region = "us-east-1"
instance_type = "t2.medium"
ami_id = "ami-0abcdef1234567890" # Replace with a valid AMI ID
instance_name = "MyTerraformEC2"
Explanation: The `terraform.tfvars` file is automatically loaded by Terraform. It overrides default values defined in `variables.tf`.
## Step 5: Method 2 — Pass Variables via Command Line
Pass variables using the `-var` flag:
terraform apply -var="region=us-east-1" -var="instance_type=t2.medium" -var="ami_id=ami-0abcdef1234567890" -var="instance_name=MyTerraformEC2"
Explanation: Use this method for quick overrides without modifying files.
## Step 6: Method 3 — Pass Variables via Environment Variables
Set variables using the `TF_VAR_<variable_name>` format:
export TF_VAR_region="us-east-1"
export TF_VAR_instance_type="t2.medium"
export TF_VAR_ami_id="ami-0abcdef1234567890"
export TF_VAR_instance_name="MyTerraformEC2"
Run Terraform:
terraform apply
Explanation: Environment variables are useful in CI/CD pipelines or automated environments.
## Step 7: Method 4 — Use Input Prompt for Variables
Run Terraform without specifying variable values:
terraform apply
If a required variable is not set, Terraform will prompt for it:
var.ami_id
The AMI ID to launch the EC2 instance
Enter a value: ami-0abcdef1234567890
Explanation: This method allows interactive input during development.
## Step 8: Validate the Configuration
Run `terraform plan` to preview the changes:
terraform plan
Expected Output:
text
Plan: 1 to add, 0 to change, 0 to destroy.
## Step 9: Apply the Configuration
Apply the changes to create the EC2 instance:
terraform apply
Type `yes` to confirm.
## Step 10: Output EC2 Instance Information
### `outputs.tf`
output "ec2_public_ip" {
value = aws_instance.example.public_ip
}
Run the following command to view the EC2 instance's public IP:
terraform output ec2_public_ip
## Step 11: Clean Up Resources
Destroy the infrastructure to avoid costs:
terraform destroy
Type `yes` to confirm.
## Conclusion
In this lab, you explored multiple ways to pass variables in Terraform:
1. Default values in `variables.tf`.
2. Using `terraform.tfvars`.
3. Command-line input with `-var`.
4. Environment variables with `TF_VAR_<variable_name>`.
5. Interactive input prompts.
Each method offers flexibility for different scenarios, making your Terraform code dynamic and reusable.
# Hands-on Lab: Terraform Workspaces (Updated with Instance Type)
In this updated lab, you will configure EC2 instances in different environments (`dev`, `staging`, `production`) using Terraform workspaces. Each workspace will have a unique EC2 instance type (`t2.micro`, `t2.medium`, `t2.large`).
## Scenario
You need to deploy EC2 instances in multiple environments, each with a specific instance type. Terraform workspaces provide isolation for these environments, allowing you to manage them effectively.
## Prerequisites
- Terraform installed.
- AWS CLI installed and configured.
- AWS account with permissions to create EC2 instances.
## Step 1: Set Up the Project Directory
Create the project directory and necessary files:
mkdir terraform-workspaces
cd terraform-workspaces
Create the following files:
- `main.tf`
- `variables.tf`
- `outputs.tf`
## Step 2: Define Variables in `variables.tf`
Define variables for the EC2 instance type and name.
variable "instance_type" {
description = "Type of EC2 instance"
type = string
default = "t2.micro"
}
variable "instance_name" {
description = "Name of the EC2 instance"
type = string
default = "Terraform-EC2"
}
## Step 3: Define the EC2 Resource in `main.tf`
Provision the EC2 instance using the defined variables.
provider "aws" {
region = "us-west-2"
}
resource "aws_instance" "example" {
ami = "ami-0abcdef1234567890" # Replace with a valid AMI ID
instance_type = var.instance_type
tags = {
Name = var.instance_name
}
}
## Step 4: Define Outputs in `outputs.tf`
Output the public IP of the EC2 instance.
output "ec2_public_ip" {
value = aws_instance.example.public_ip
}
## Step 5: Initialize Terraform
Run the following command to initialize the project:
terraform init
## Step 6: Create and Use Workspaces
### Create the `dev` Workspace
terraform workspace new dev
terraform workspace select dev
### Define Variables for `dev` (Using `dev.tfvars`)
instance_type = "t2.micro"
instance_name = "dev-instance"
### Apply the Configuration
terraform apply -var-file="dev.tfvars"
## Step 7: Switch to the `staging` Workspace
### Create the `staging` Workspace
terraform workspace new staging
terraform workspace select staging
### Define Variables for `staging` (Using `staging.tfvars`)
instance_type = "t2.medium"
instance_name = "staging-instance"
### Apply the Configuration
terraform apply -var-file="staging.tfvars"
## Step 8: Switch to the `production` Workspace
### Create the `production` Workspace
terraform workspace new production
terraform workspace select production
### Define Variables for `production` (Using `production.tfvars`)
instance_type = "t2.large"
instance_name = "production-instance"
### Apply the Configuration
terraform apply -var-file="production.tfvars"
## Step 9: Check the EC2 Instance in Each Workspace
### List Workspaces
terraform workspace list
### Output EC2 Public IP
terraform output ec2_public_ip
## Step 10: Clean Up Resources
### Destroy Resources for Each Workspace
Switch to each workspace and destroy its resources:
terraform workspace select dev
terraform destroy -var-file="dev.tfvars"
terraform workspace select staging
terraform destroy -var-file="staging.tfvars"
terraform workspace select production
terraform destroy -var-file="production.tfvars"
## Conclusion
In this lab, you learned to:
1. Create and manage Terraform workspaces.
2. Use workspace-specific configurations with `.tfvars` files.
3. Provision and manage resources across multiple environments (`dev`, `staging`, `production`).
4. Clean up resources efficiently.
Terraform workspaces enable structured environment management, making it easier to isolate and manage resources in different stages of development.