Terraform-Day-1
## Terraform Installation Steps for Windows, Amazon EC2 Linux 2, and MacOS
### 1. Install Terraform on Windows
#### Steps
1. Download Terraform:
- Visit the [Terraform Downloads Page](https://www.terraform.io/downloads).
- Download the appropriate `.zip` file for Windows.
2. Extract Terraform:
- Unzip the file into a directory, e.g., `C:\Terraform`.
3. Add to System PATH:
- Add the directory containing `terraform.exe` to the system PATH:
- Open System Properties > Advanced > Environment Variables.
- Edit the `Path` variable under System Variables.
- Add the path to `terraform.exe`, e.g., `C:\Terraform`.
4. Verify Installation:
- Open Command Prompt (cmd) or PowerShell and run:
terraform version
- You should see the installed Terraform version.
### 2. Install Terraform on Amazon EC2 Linux 2
#### Steps
1. Launch and Connect to an EC2 Instance:
- Launch an Amazon Linux 2 EC2 instance.
- Connect via SSH:
ssh -i your-key.pem ec2-user@your-ec2-public-ip
2. Update System and Install Dependencies:
- Run the following commands:
sudo yum update -y
sudo yum install -y wget unzip
3. Download and Install Terraform:
- Download the Terraform binary:
wget https://releases.hashicorp.com/terraform/<VERSION>/terraform_<VERSION>_linux_amd64.zip
Replace `<VERSION>` with the desired version (e.g., `1.6.0`).
- Extract the binary and move it to `/usr/local/bin`:
unzip terraform_<VERSION>_linux_amd64.zip
sudo mv terraform /usr/local/bin/
4. Verify Installation:
- Run the following command:
terraform version
- The installed Terraform version will be displayed.
### 3. Install Terraform on MacOS
#### Steps
1. Using Homebrew (Recommended):
- Install Terraform using Homebrew:
brew install terraform
2. Verify Installation:
- Confirm Terraform is installed:
terraform version
3. Manual Installation (Alternative):
- Download the Terraform binary from the [Terraform Downloads Page](https://www.terraform.io/downloads).
- Extract and move it to `/usr/local/bin`:
unzip terraform_<VERSION>_darwin_amd64.zip
sudo mv terraform /usr/local/bin/
- Verify the installation:
terraform version
### Hands-on Example to Validate Installation
1. Create a Working Directory:
- Create a folder for your Terraform project, e.g., `terraform-example`.
mkdir terraform-example
cd terraform-example
2. Write a Simple Terraform Configuration File:
- Create a file named `main.tf` with the following content:
provider "aws" {
region = "us-east-1"
}
resource "aws_s3_bucket" "example" {
bucket = "example-terraform-bucket"
acl = "private"
}
3. Initialize Terraform:
- Run:
terraform init
4. Validate the Configuration:
- Run:
terraform validate
5. Apply the Configuration:
- Run:
terraform apply
- Type `yes` when prompted to create the resources.
6. Verify Resource Creation:
- Check your AWS Management Console to confirm the S3 bucket was created.
By following these steps, you’ll successfully install and validate Terraform on Windows, EC2 Linux 2, and MacOS.
### Hands-On: Validate Terraform Installation with a Simple Example
#### Scenario
Create an S3 bucket in AWS using Terraform to validate the installation.
#### Steps
1. Create a Terraform Project:
- Open a terminal/PowerShell and create a directory:
mkdir terraform-demo
cd terraform-demo
2. Create a Configuration File:
- Create a new file named `main.tf`:
touch main.tf
- Add the following content to `main.tf`:
provider "aws" {
region = "us-east-1"
}
resource "aws_s3_bucket" "example" {
bucket = "my-unique-tf-bucket-12345"
acl = "private"
}
3. Initialize Terraform:
- Run the following command to initialize the directory:
terraform init
4. Validate the Configuration:
- Check if the configuration file is valid:
terraform validate
5. Preview the Plan:
- Generate an execution plan to review changes:
terraform plan
6. Apply the Configuration:
- Deploy the resources in AWS:
terraform apply
- Confirm with `yes`.
7. Verify the S3 Bucket:
- Log in to the AWS Console and navigate to S3 to confirm the bucket is created.
8. Clean Up Resources:
- Destroy the created resources to avoid costs:
terraform destroy
- Confirm with `yes`.
By following these steps, you’ll successfully install and validate Terraform on Windows, EC2 Linux 2, and MacOS.
Here’s a hands-on lab to understand the usage of the `count` meta-parameter in Terraform by deploying multiple AWS EC2 instances. All steps, explanations, and the full code for the lab are provided below.
### Lab Overview
In this lab, we’ll create a Terraform configuration that deploys three AWS EC2 instances with unique names using the `count` meta-parameter.
### Steps and Code Explanation
#### Step 1: Install Terraform
Ensure Terraform is installed on your system. Verify the installation by running:
terraform -v
If Terraform is not installed, follow the official [Terraform Installation Guide](https://developer.hashicorp.com/terraform/tutorials/aws-get-started/install-cli).
#### Step 2: Set Up Your AWS Credentials
Configure your AWS credentials using the AWS CLI or an IAM user with programmatic access:
aws configure
Provide your Access Key, Secret Key, region, and output format.
#### Step 3: Create a Working Directory
Create and navigate to a new directory for your Terraform configuration:
mkdir terraform-aws-ec2
cd terraform-aws-ec2
#### Step 4: Write the Terraform Configuration
Create a new file named `main.tf` and copy the following code:
# Step 1: Specify the AWS provider
provider "aws" {
region = "us-west-2" # You can change this to your preferred region
}
# Step 2: Use the 'count' meta-parameter to create multiple EC2 instances
resource "aws_instance" "example" {
count = 3 # Creates 3 EC2 instances
ami = "ami-0c55b159cbfafe1f0" # Amazon Machine Image (AMI) ID for the instance
instance_type = "t2.micro" # EC2 instance type
# Step 3: Dynamically assign names to instances based on the 'count.index'
tags = {
Name = "Example-Instance-${count.index}" # Instance names like Example-Instance-0, Example-Instance-1, etc.
}
}
# Step 4: Output instance public IPs
output "instance_ips" {
value = aws_instance.example[*].public_ip # Outputs the public IPs of all instances
}
#### Code Explanation
1. AWS Provider Configuration
provider "aws" {
region = "us-west-2"
}
- Configures the AWS provider and specifies the region where resources will be deployed.
2. Resource Block for EC2 Instances
resource "aws_instance" "example" {
count = 3
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
}
- Creates three EC2 instances (`count = 3`) using the specified AMI and instance type.
3. Dynamic Tagging Using `count.index`
tags = {
Name = "Example-Instance-${count.index}"
}
- Assigns unique names to instances using `count.index` (e.g., `Example-Instance-0`, `Example-Instance-1`, etc.).
4. Output the Public IPs
output "instance_ips" {
value = aws_instance.example[*].public_ip
}
- Outputs a list of public IPs for all created instances.
#### Step 5: Deploying the Configuration
1. Initialize Terraform Working Directory
terraform init
- Downloads required provider plugins and initializes the working directory.
2. Review the Execution Plan
terraform plan
- Displays the resources Terraform will create.
3. Apply the Configuration
terraform apply
- Deploys the resources. Confirm the action by typing `yes` when prompted.
4. View the Output
terraform output instance_ips
- Outputs the public IPs of the EC2 instances created.
#### Step 6: Validate
1. Access the EC2 Instances
- Use the public IPs outputted in the previous step to connect to the instances via SSH.
ssh -i your-key.pem ec2-user@<public-ip>
2. Verify Instance Tags
- Check the AWS Management Console to confirm instance names and tags.
#### Step 7: Clean Up Resources
Destroy the resources to avoid unnecessary costs:
terraform destroy
### Lab Summary
- Created three AWS EC2 instances using the `count` meta-parameter.
- Dynamically named the instances using `count.index`.
- Outputted the public IPs of the instances for easy access.
This lab demonstrates the power of Terraform's `count` parameter for resource scaling and dynamic configurations.
### Lab: Setting Up a `.gitignore` File and Initializing a Git Repository for a Terraform Project
### Step 1: Create the `.gitignore` File
1. Navigate to the directory created in Lab 1.3 (if not already there).
2. Create a `.gitignore` file with the following content:
#### Contents of `.gitignore`:
# Ignore Terraform state files and backups
*.tfstate
*.tfstate.*
# Ignore .terraform directories (Terraform plugins)
.terraform/
### Explanation of the `.gitignore` File:
- `*.tfstate` and `*.tfstate.*`:
- These patterns ignore Terraform state files and their backups.
- Terraform state files contain sensitive infrastructure data and shouldn't be tracked by Git.
- `.terraform/`:
- This ignores the `.terraform/` directory, which stores Terraform plugins and modules.
- Excluding this directory ensures that unnecessary files aren't committed to the repository.
Setting up this `.gitignore` file ensures that sensitive and unnecessary files are excluded from Git version control.
### Step 2: Set Up the Git Repository
#### 1. Initialize the Git Repository
If you haven't already initialized a Git repository in your project directory, run:
git init
This command creates a new Git repository in the current directory.
#### 2. Add Files to the Git Repository
Add all files in the directory (excluding those ignored by `.gitignore`) to the Git staging area:
git add .
#### 3. Commit the Files
Commit the added files to the repository with an appropriate message:
git commit -m "Initial Terraform configuration with .gitignore"
#### 4. Verify Ignored Files
To confirm that the files specified in `.gitignore` are not being tracked by Git, run:
git status
- This command should display the tracked files, excluding the Terraform state files (`*.tfstate`), their backups (`*.tfstate.*`), and the `.terraform/` directory.
### Lab Summary
1. Created a `.gitignore` file to exclude:
- Terraform state files and their backups.
- Terraform plugin directories (`.terraform/`) from version control.
2. Initialized a Git repository, added files, and committed the configuration.
3. Ensured that sensitive and unnecessary files were not tracked by Git.
By following this lab, you’ve ensured that your Terraform project remains secure and clean, adhering to best practices for version control.