SSAEMAll Courses
Log inSign up

Video coming soon

Please continue with the lesson material below.

IaC(Infrastructure as Code) 학습 환경 준비

Log in to save your progress

Lesson Material

Preparing the IaC (Infrastructure as Code) Learning Environment

To learn IaC, you need a code editor, Terraform, Ansible, and the AWS CLI all set up and ready. Follow this guide to install each one, and you will be able to run terraform apply and ansible-playbook right away in the upcoming lessons. Please complete AWS Cloud Environment Preparation first before proceeding.


Prerequisites

The following items must be completed before starting the IaC course.

ItemHow to VerifyReference
AWS account createdCan log in to AWS Console05-cloud-aws Environment Preparation Steps 1-3
AWS CLI installed and configuredaws sts get-caller-identity succeeds05-cloud-aws Environment Preparation Steps 4-5
Python 3.9 or higherpython3 --versionRequired for Ansible installation
Git installedgit --versionFor code version control

Quick AWS CLI Check

aws sts get-caller-identity

Expected Output

{
    "UserId": "AIDAIOSFODNN7EXAMPLE",
    "Account": "123456789012",
    "Arn": "arn:aws:iam::123456789012:user/devops-admin"
}

If this output does not appear, start from 05-cloud-aws Environment Preparation.


Step 1: Install Terraform

Terraform is an IaC tool created by HashiCorp that defines infrastructure using a declarative language called HCL (HashiCorp Configuration Language).

License note: As of Aug 10, 2023, Terraform transitioned from MPL 2.0 to BUSL-1.1 (Business Source License 1.1). In response, OpenTofu — an MPL 2.0 open-source fork — was created (joined the Linux Foundation in Sep 2023, promoted to CNCF Incubating in Apr 2025). HCL syntax, providers, and core commands are identical, so this guide applies to both tools. See 03-terraform-advanced for a detailed comparison. Refs: https://www.hashicorp.com/en/blog/hashicorp-adopts-business-source-license , https://opentofu.org/manifesto/

Windows

Option 1: Using Chocolatey (Recommended)

choco install terraform

Option 2: Manual Installation

  1. Go to https://developer.hashicorp.com/terraform/install
  2. Download the Windows AMD64 zip
  3. Extract and move terraform.exe to a directory included in your PATH

macOS

brew tap hashicorp/tap
brew install hashicorp/tap/terraform

Linux (Ubuntu/Debian)

# Add the HashiCorp GPG key
wget -O- https://apt.releases.hashicorp.com/gpg | sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg

# Add the repository
echo "deb [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

# Install
sudo apt-get update
sudo apt-get install terraform

Verify Installation

terraform version

Expected Output

Terraform v1.9.2
on linux_amd64

If a version number is displayed, the installation is complete.

Practical Tip

Terraform syntax changes slightly between versions. In team projects, it is common practice to lock the version using a .terraform-version file. This is covered in the tfenv Installation section below.


Step 2: Understand the Basic Terraform Directory Structure

Before starting a Terraform project, it helps to understand how files are organized.

Basic Structure

my-infra/
├── main.tf           # Core resource definitions
├── variables.tf      # Variable declarations
├── outputs.tf        # Output value definitions
├── terraform.tfvars  # Variable values (not committed to Git)
├── providers.tf      # Provider settings (AWS, GCP, etc.)
├── versions.tf       # Terraform and provider version pinning
└── .terraform/       # Auto-generated by terraform init (not committed to Git)
FileRoleInclude in Git
main.tfActual infrastructure resource definitionsYes
variables.tfInput variable types and descriptionsYes
outputs.tfOutput values to check after executionYes
terraform.tfvarsActual values for variables (may contain secrets)No
providers.tfProvider settings such as AWSYes
.terraform/Downloaded provider pluginsNo
terraform.tfstateCurrent infrastructure state (very important)No (remote storage recommended)

Note

The terraform.tfstate file contains the actual state of your current infrastructure. If you lose this file, Terraform will not recognize your existing infrastructure and will try to recreate already existing resources. In production, always store it in a remote backend such as S3.

.gitignore Configuration

Add the following to .gitignore in Terraform projects.

# Terraform
.terraform/
*.tfstate
*.tfstate.backup
*.tfvars
crash.log

Step 3: Verify Terraform Is Working

Let's run a quick test to confirm the installation is correct. We will only verify that Terraform initializes properly without actually creating any AWS resources.

Create a Test Directory

mkdir -p ~/terraform-test && cd ~/terraform-test

Write a Test File

Create a main.tf file.

# main.tf
terraform {
  required_version = ">= 1.0.0"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

provider "aws" {
  region = "ap-northeast-2"
}

Initialize

terraform init

Expected Output

Initializing the backend...

Initializing provider plugins...
- Finding hashicorp/aws versions matching "~> 5.0"...
- Installing hashicorp/aws v5.60.0...
- Installed hashicorp/aws v5.60.0 (signed by HashiCorp)

Terraform has created a lock file .terraform.lock.hcl to record the provider
selections it made above. Include this file in your version control repository
so that Terraform can guarantee to make the same selections by default when
you run "terraform init" in the future.

Terraform has been successfully initialized!

If you see Terraform has been successfully initialized!, the test is successful.

Clean Up the Test Directory

rm -rf ~/terraform-test

Step 4: Install Ansible

Ansible is a Python-based configuration management tool. It connects to remote servers via SSH to install software and apply configurations.

Note (Windows Users)

Ansible only runs natively on Linux/macOS. On Windows, you must use WSL (Windows Subsystem for Linux).

Windows: Install Ansible After Setting Up WSL

# If WSL is not installed yet (run in PowerShell as Administrator)
wsl --install

# After restarting WSL, run in the Ubuntu terminal
sudo apt update
sudo apt install -y python3 python3-pip
pip3 install ansible

macOS

pip3 install ansible

Or using Homebrew:

brew install ansible

Linux (Ubuntu/Debian)

Option 1: Using pip (Recommended, latest version)

pip3 install ansible

Option 2: Using apt

sudo apt update
sudo apt install -y ansible

Verify Installation

ansible --version

Expected Output

ansible [core 2.17.1]
  config file = None
  configured module search path = ['/home/user/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /home/user/.local/lib/python3.12/site-packages/ansible
  ansible collection location = /home/user/.ansible/collections:/usr/share/ansible/collections
  executable location = /home/user/.local/bin/ansible
  python version = 3.12.3 (main, ...) [GCC 13.2.0]
  jinja version = 3.1.4
  libyaml = True

If ansible [core x.x.x] version information is displayed, the installation was successful.

Practical Tip

When installing Ansible with pip, it may conflict with the system Python. Using a virtual environment (venv) keeps things clean.

python3 -m venv ~/ansible-env
source ~/ansible-env/bin/activate
pip install ansible

However, installing directly on the system is fine for the learning stage.


Step 5: Install VS Code Extensions

Installing the appropriate extensions in your code editor will help catch syntax errors in advance and provide auto-completion.

HashiCorp Terraform Extension

Provides syntax highlighting, auto-completion, and formatting for Terraform .tf files.

  1. Open VS Code
  2. Click the Extensions icon in the left sidebar (or press Ctrl+Shift+X)
  3. Type "HashiCorp Terraform" in the search box
  4. Install the extension from the HashiCorp publisher

After installation, the following features are enabled when you open a .tf file.

  • HCL syntax highlighting (color coding)
  • Resource/variable auto-completion
  • Auto-formatting on save (terraform fmt)
  • Go to Definition

Ansible Extension (Red Hat)

Provides syntax validation and auto-completion for Ansible YAML files.

  1. Type "Ansible" in the VS Code extensions search box
  2. Install the "Ansible" extension from the Red Hat publisher

After installation, the following features are enabled for .yml/.yaml files in Ansible Playbook format.

  • Module name auto-completion
  • Playbook syntax validation
  • Jinja2 template highlighting

Practical Tip

To automatically format Terraform files when saving in VS Code, add the following to your settings.

{
  "[terraform]": {
    "editor.formatOnSave": true,
    "editor.defaultFormatter": "hashicorp.terraform"
  }
}

Open VS Code settings: Ctrl+Shift+P -> "Preferences: Open Settings (JSON)"


Step 6: Install tfenv (Optional)

tfenv is a Terraform version management tool. It is useful when you need to use different Terraform versions across multiple projects.

Why You Need It

When Project A uses Terraform 1.5 and Project B uses Terraform 1.9, tfenv lets you easily switch versions per project.

macOS / Linux

git clone https://github.com/tfutils/tfenv.git ~/.tfenv

# Add to PATH (~/.bashrc or ~/.zshrc)
echo 'export PATH="$HOME/.tfenv/bin:$PATH"' >> ~/.bashrc
source ~/.bashrc

Windows

On Windows, you can use tfenv-windows or manage Terraform with Chocolatey. Setting up tfenv on Windows can be complicated, so it is fine to skip this step during the learning stage.

Usage

# List available versions
tfenv list-remote

# Install a specific version
tfenv install 1.9.2

# Use a specific version
tfenv use 1.9.2

# Check the currently active version
terraform version

Expected Output

$ tfenv install 1.9.2
Installing Terraform v1.9.2
Downloading release tarball from https://releases.hashicorp.com/terraform/1.9.2/...
...
Installation of terraform v1.9.2 successful.

$ tfenv use 1.9.2
Switching default version to v1.9.2
Default version is now: 1.9.2

$ terraform version
Terraform v1.9.2
on linux_amd64

Pin Version Per Project

Creating a .terraform-version file in the project root causes the specified version to be used automatically in that directory.

echo "1.9.2" > .terraform-version

Step 7: Understand AWS Provider Authentication Methods

For Terraform to create resources in AWS, it needs AWS credentials. There are several methods, each with its own characteristics.

Method 1: Environment Variables (Recommended for Learning)

Terraform automatically reads the information configured via aws configure. No additional setup is needed, making this the most convenient method for learning.

# providers.tf - Just specify the region
provider "aws" {
  region = "ap-northeast-2"
}

Terraform searches for credentials in the following order.

  1. Environment variables (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)
  2. The [default] profile in ~/.aws/credentials
  3. IAM Role (when running on an EC2 instance)

If you have already run aws configure, option 2 applies, so you do not need to put keys in the provider block.

Method 2: Specify a Profile

When using multiple AWS accounts, you can distinguish them by profile name.

# Add a profile
aws configure --profile dev-account
# providers.tf
provider "aws" {
  region  = "ap-northeast-2"
  profile = "dev-account"
}

Method 3: Hardcode in Code (Absolutely Prohibited)

# Never do this!
provider "aws" {
  region     = "ap-northeast-2"
  access_key = "AKIAIOSFODNN7EXAMPLE"        # Absolutely prohibited
  secret_key = "wJalrXUtnFEMI/K7MDENG/..."   # Absolutely prohibited
}

Note

If you put authentication keys directly in .tf files, they can be exposed to the entire world the moment they are committed to Git. When AWS keys are exposed on GitHub, bots detect them within minutes and exploit them for malicious purposes. There have been real cases where charges of thousands of dollars were incurred.


Final Verification

Once all installations are complete, run the following commands to verify.

1. Verify Terraform

terraform version

Expected output:

Terraform v1.9.2
on linux_amd64

2. Verify Ansible

ansible --version

Expected output:

ansible [core 2.17.1]
  config file = None
  ...

3. Verify AWS CLI Authentication

aws sts get-caller-identity

Expected output:

{
    "UserId": "AIDAIOSFODNN7EXAMPLE",
    "Account": "123456789012",
    "Arn": "arn:aws:iam::123456789012:user/devops-admin"
}

4. Full Summary

echo "=== Terraform ===" && terraform version && echo "" && echo "=== Ansible ===" && ansible --version | head -1 && echo "" && echo "=== AWS CLI ===" && aws --version

Expected output:

=== Terraform ===
Terraform v1.9.2
on linux_amd64

=== Ansible ===
ansible [core 2.17.1]

=== AWS CLI ===
aws-cli/2.17.20 Python/3.12.5 Linux/6.5.0 source/x86_64

If all three display version information, your IaC learning environment setup is complete.


Troubleshooting

terraform Command Not Found

Symptom: terraform: command not found

Cause: The terraform binary is not included in the PATH.

Solution:

# Check terraform location
which terraform    # Linux/Mac
where terraform    # Windows

# Check PATH
echo $PATH

If you installed via Chocolatey or Homebrew, try closing and reopening the terminal.


Permission Error When Installing Ansible

Symptom: ERROR: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied

Solution:

# Option 1: Use the --user flag
pip3 install --user ansible

# Option 2: Use a virtual environment
python3 -m venv ~/ansible-env
source ~/ansible-env/bin/activate
pip install ansible

Avoid sudo pip install as it can pollute the system Python.


Provider Download Fails During terraform init

Symptom: Error: Failed to query available provider packages

Cause: A network issue, or a corporate/school firewall is blocking the HashiCorp registry.

Solution:

# Check DNS
nslookup registry.terraform.io

# Test direct access
curl -I https://registry.terraform.io

If it is a firewall issue, ask your network administrator to allow HTTPS access to registry.terraform.io.


Next Step

Once the environment preparation is complete, proceed to Why IaC Is Needed. You will learn about the problems with manual infrastructure management and how IaC solves them.

Q&A0

Only students taking this course can post questions.

No questions yet. Be the first to ask!