Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added solution.md for Day 1 of TerraWeek: Introduction to Terraform Basics and AWS Setup #21

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
221 changes: 221 additions & 0 deletions day01/solution.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,221 @@
# TerraWeek Day 1

### **Day 1: Introduction to Terraform and Terraform Basics**

#### **What is Terraform, and how can it help you manage Infrastructure as Code?**
Terraform is an open-source tool by HashiCorp that allows you to define, manage, and provision infrastructure as code (IaC). It uses a declarative configuration language, HCL (HashiCorp Configuration Language), to describe the desired state of infrastructure. By applying these configurations, Terraform ensures that the actual infrastructure matches the desired state.


Key benefits of Terraform:

- **Consistency:** The same configurations can be reused across environments (e.g., dev, staging, production).
- **Version Control:** Infrastructure definitions are stored in source control systems like Git.
- **Automation:** Removes the need for manual intervention during resource creation.
- **Cloud-Agnostic:** Supports multiple cloud providers like AWS, Azure, GCP, and even on-prem solutions.

---

#### **Why do we need Terraform, and how does it simplify infrastructure provisioning?**
1. **Eliminates Manual Effort:** Automates the provisioning, scaling, and configuration of resources.
2. **Infrastructure as Code:** Maintains infrastructure as code for better tracking, auditing, and collaboration.
3. **Cross-Cloud Compatibility:** Provides a unified approach to managing multi-cloud and hybrid environments.
4. **Dependency Management:** Automatically understands and manages dependencies between resources.
5. **Cost and Time Efficiency:** Reduces operational overhead and human error, enabling rapid infrastructure changes.

---

#### **How Can You Install Terraform and Set Up the Environment for AWS?**

#### **Before You Begin: Create an EC2 Instance for Running Commands**

To execute the following commands in an isolated environment, create an Ubuntu EC2 instance using AWS Management Console:

##### **Launch an EC2 Instance:**

1. Go to the **EC2 Dashboard** on AWS.
2. Click **Launch Instance**.
3. Configure:
- **Name:** Terraform-Setup
- **AMI:** Ubuntu Server 22.04 LTS
- **Instance Type:** t2.micro (free tier eligible)
- **Key Pair:** Create or select an existing key pair.
- **Network Settings:** Allow SSH traffic (port 22) from your IP address.
- **Storage:** Keep the default 8 GiB or adjust as needed.

Comment on lines +35 to +44
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Enhance EC2 instance security recommendations

The EC2 instance setup instructions should include additional security best practices:

  1. Use VPC with private subnet and NAT Gateway
  2. Enable IMDSv2
  3. Apply security group rules with minimum required permissions
  4. Enable detailed monitoring
  5. Add proper resource tags

Consider adding these security configurations to the EC2 launch instructions.

##### **Connect to the Instance:**

Use an SSH client or AWS CloudShell to connect:

```bash
ssh -i "your-key-pair.pem" ubuntu@<EC2-Public-IP>
```

##### **Update the Instance:**

Run the following commands after connecting:

```bash
sudo apt update && sudo apt upgrade -y
```

Now proceed with the installation of Terraform and setting up AWS credentials.


##### 1. **Install Terraform on Ubuntu:**

To install Terraform on Ubuntu, follow these steps:

- **Add the HashiCorp GPG Key and Repository:**

```bash
wget -O - https://apt.releases.hashicorp.com/gpg | sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg
echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/hashicorp.list
```
Comment on lines +70 to +73
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Improve security of GPG key installation

The current GPG key installation pipes wget directly to sudo, which is not the most secure approach. Consider downloading the key first and then importing it.

-wget -O - https://apt.releases.hashicorp.com/gpg | sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg
+# Download the GPG key first
+wget -O hashicorp.asc https://apt.releases.hashicorp.com/gpg
+# Verify the fingerprint (optional but recommended)
+gpg --show-keys hashicorp.asc
+# Import the key
+sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg hashicorp.asc
+# Clean up
+rm hashicorp.asc


- **Update the Package List and Install Terraform:**

```bash
sudo apt update && sudo apt install terraform
```

- **Verify Installation:**

Confirm that Terraform is installed correctly by checking its version:

```bash
terraform version
```

---

##### 2. **Set Up Terraform for AWS:**

- **Create an IAM User in AWS:**

- Go to the **IAM Management Console** in AWS.
- Create a new IAM user with **programmatic access**.
- Attach the necessary policies (e.g., `AdministratorAccess` or policies tailored to your use case).
- Note down the **Access Key ID** and **Secret Access Key**.
Comment on lines +96 to +98
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Revise IAM permissions recommendation

Recommending AdministratorAccess policy is not aligned with the principle of least privilege. Instead, suggest creating custom IAM policies that grant only the necessary permissions for the specific infrastructure being managed.

Consider updating the documentation to recommend:

  1. Creating a custom IAM policy based on the resources being managed
  2. Using AWS managed policies specific to the services being used
  3. Following the principle of least privilege


- **Install the AWS CLI:**

Install the AWS CLI to configure credentials:
```bash
sudo apt update && sudo apt install awscli
```

- **Configure AWS CLI Credentials:**

Run the following command and enter your IAM user details:
```bash
aws configure
```

Provide:
- **Access Key ID**
- **Secret Access Key**
- **Default region** (e.g., `us-east-1`)
- Output format (default: `json`)

Comment on lines +112 to +124
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Recommend using IAM roles instead of access keys

When working with Terraform on EC2 instances, it's more secure to use IAM roles instead of storing AWS credentials directly on the instance.

Consider updating this section to:

  1. Create an IAM role with the necessary permissions
  2. Attach the IAM role to the EC2 instance during creation
  3. Remove the AWS credentials configuration steps as they won't be needed with IAM roles


- **Verify AWS CLI Configuration:**

Check your AWS CLI configuration:
```bash
aws sts get-caller-identity
```

- **Use AWS as a Provider in Terraform:**
Add the provider configuration to your Terraform `.tf` file:

```hcl
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "5.65.0"
}
}
}

provider "aws" {
region = "us-east-1"
}
```

With these steps, your environment is ready to manage AWS infrastructure using Terraform.



#### **Important Terminologies of Terraform**

1. **Provider:**

- Defines the cloud service (e.g., AWS, Azure) or on-premises platform you are interacting with.

- Example:

```hcl
provider "aws" {
region = "us-west-2"
}
```

2. **Resource:**

- A fundamental element (e.g., an EC2 instance, an S3 bucket) described in the Terraform configuration.

- Example:

```hcl
resource "aws_s3_bucket" "example" {
bucket = "example-bucket"
tags = {
Name = "example-bucket"
}
}
```

3. **State:**

- A file that tracks the current state of your infrastructure. It helps Terraform understand the desired state versus the actual state.

- Example:

Terraform generates a `terraform.tfstate` file during execution.

Comment on lines +186 to +193
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add state file security warnings

The state file section should include critical security considerations:

  1. Warning about sensitive data in state files
  2. Recommendation for remote state storage (e.g., S3 with encryption)
  3. State file backup strategies
  4. Access control for state files
  5. State locking mechanisms

Consider expanding this section to cover these important aspects of state management.

Would you like me to provide a detailed example of secure state configuration?


4. **Module:**

- A reusable and logical grouping of resources defined in separate files or directories.

- Example:

```hcl
module "vpc" {
source = "./modules/vpc"
cidr = "10.0.0.0/16"
}
```

5. **Data Source:**

- Allows fetching data from external sources (e.g., the details of an existing AWS AMI).

- Example:
```hcl
data "aws_ami" "ubuntu" {
most_recent = true
filter {
name = "name"
values = ["ubuntu/images/*"]
}
}
```
Comment on lines +214 to +221
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Enhance AMI data source example with additional filters

The current AMI data source example is missing important filters that are typically needed for proper AMI selection, such as virtualization-type and architecture.

 data "aws_ami" "ubuntu" {
   most_recent = true
+  owners      = ["099720109477"] # Canonical
   
   filter {
     name   = "name"
     values = ["ubuntu/images/*"]
   }
+  filter {
+    name   = "virtualization-type"
+    values = ["hvm"]
+  }
+  filter {
+    name   = "architecture"
+    values = ["x86_64"]
+  }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
data "aws_ami" "ubuntu" {
most_recent = true
filter {
name = "name"
values = ["ubuntu/images/*"]
}
}
```
data "aws_ami" "ubuntu" {
most_recent = true
owners = ["099720109477"] # Canonical
filter {
name = "name"
values = ["ubuntu/images/*"]
}
filter {
name = "virtualization-type"
values = ["hvm"]
}
filter {
name = "architecture"
values = ["x86_64"]
}
}


These terminologies form the backbone of understanding and working with Terraform effectively!



Watch this [Reference Video](https://www.youtube.com/live/965CaSveIEI?feature=share)