Skip to main content

Installation and configuration


Chapter objectives

  • Install Terraform on different OSes
  • Configure autocompletion
  • Configure cloud providers
  • Validate the installation

1 - Installing Terraform

Architecture

Linux (Ubuntu/Debian)

# Méthode 1: Via APT (recommandé)
wget -O- https://apt.releases.hashicorp.com/gpg | \
sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg

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

sudo apt update
sudo apt install terraform

# Méthode 2: Téléchargement manuel
wget https://releases.hashicorp.com/terraform/1.6.0/terraform_1.6.0_linux_amd64.zip
unzip terraform_1.6.0_linux_amd64.zip
sudo mv terraform /usr/local/bin/

Linux (RHEL/CentOS)

sudo yum install -y yum-utils
sudo yum-config-manager --add-repo https://rpm.releases.hashicorp.com/RHEL/hashicorp.repo
sudo yum install terraform

macOS

# Via Homebrew
brew tap hashicorp/tap
brew install hashicorp/tap/terraform

# Mise à jour
brew upgrade hashicorp/tap/terraform

Windows

# Via Chocolatey
choco install terraform

# Via Scoop
scoop install terraform

# Ou téléchargement manuel
# https://developer.hashicorp.com/terraform/downloads
# Ajouter au PATH

2 - Verifying the installation

# Vérifier la version
terraform version

# Résultat attendu
Terraform v1.6.0
on linux_amd64

# Aide
terraform -help

# Commandes disponibles
terraform -help plan

3 - Autocompletion

Bash

# Activer l'autocomplétion
terraform -install-autocomplete

# Recharger le shell
source ~/.bashrc

Zsh

# Activer l'autocomplétion
terraform -install-autocomplete

# Recharger le shell
source ~/.zshrc

PowerShell

# Ajouter au profil PowerShell
terraform -install-autocomplete

4 - Configuring cloud providers

AWS

Method 1: AWS CLI

# Installer AWS CLI
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install

# Configurer les credentials
aws configure

# Entrer:
# AWS Access Key ID
# AWS Secret Access Key
# Default region (ex: eu-west-1)
# Default output format (json)

Method 2: Environment variables

export AWS_ACCESS_KEY_ID="votre_access_key"
export AWS_SECRET_ACCESS_KEY="votre_secret_key"
export AWS_DEFAULT_REGION="eu-west-1"

Method 3: Credentials file

# ~/.aws/credentials
[default]
aws_access_key_id = AKIAXXXXXXXXXXXXXXXX
aws_secret_access_key = xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

[production]
aws_access_key_id = AKIAYYYYYYYYYYYYYYYY
aws_secret_access_key = yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy
# Utiliser un profil spécifique
provider "aws" {
region = "eu-west-1"
profile = "production"
}

Azure

# Installer Azure CLI
curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash

# Se connecter
az login

# Lister les subscriptions
az account list --output table

# Définir la subscription par défaut
az account set --subscription "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
# Provider Azure
provider "azurerm" {
features {}
subscription_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
}

Google Cloud

# Installer gcloud CLI
curl https://sdk.cloud.google.com | bash
exec -l $SHELL

# Se connecter
gcloud auth application-default login

# Définir le projet
gcloud config set project my-project-id
# Provider GCP
provider "google" {
project = "my-project-id"
region = "europe-west1"
}

5 - Project structure

Standard files

my-terraform-project/
├── main.tf # Ressources principales
├── variables.tf # Déclaration des variables
├── outputs.tf # Valeurs de sortie
├── providers.tf # Configuration providers
├── versions.tf # Versions requises
├── terraform.tfvars # Valeurs des variables
├── .gitignore # Fichiers à ignorer
└── modules/ # Modules locaux
└── vpc/
├── main.tf
├── variables.tf
└── outputs.tf

The .gitignore file

# .gitignore pour Terraform

# Local .terraform directories
**/.terraform/*

# .tfstate files
*.tfstate
*.tfstate.*

# Crash log files
crash.log
crash.*.log

# Exclude all .tfvars files, which might contain sensitive data
*.tfvars
*.tfvars.json

# Ignore override files
override.tf
override.tf.json
*_override.tf
*_override.tf.json

# Ignore CLI configuration files
.terraformrc
terraform.rc

# Ignore lock file (optionnel)
# .terraform.lock.hcl

6 - Terraform configuration

Version and providers

# versions.tf
terraform {
required_version = ">= 1.5.0"

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

Version constraints

OperatorMeaningExample
=Exact version= 5.0.0
!=Different from!= 5.0.0
>, >=Greater>= 5.0.0
<, <=Lower< 6.0.0
~>Pessimistic~> 5.0 (5.x.x)

7 - Initializing a project

The init command

# Créer le répertoire projet
mkdir my-project && cd my-project

# Créer la configuration minimale
cat > main.tf << 'EOF'
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}

provider "aws" {
region = "eu-west-1"
}

resource "aws_s3_bucket" "example" {
bucket = "my-unique-bucket-name-12345"
}
EOF

# Initialiser
terraform init

The init result

Initializing the backend...

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

Terraform has been successfully initialized!

Created files

my-project/
├── .terraform/
│ └── providers/
│ └── registry.terraform.io/
│ └── hashicorp/
│ └── aws/
│ └── 5.31.0/
│ └── linux_amd64/
│ └── terraform-provider-aws_v5.31.0
├── .terraform.lock.hcl # Lock des versions
└── main.tf

8 - Development environments

VS Code Extensions

// Recommended extensions
{
"recommendations": [
"hashicorp.terraform",
"hashicorp.hcl",
"4ops.terraform-autocomplete"
]
}

VS Code configuration

// settings.json
{
"[terraform]": {
"editor.defaultFormatter": "hashicorp.terraform",
"editor.formatOnSave": true
},
"[terraform-vars]": {
"editor.defaultFormatter": "hashicorp.terraform",
"editor.formatOnSave": true
},
"terraform.experimentalFeatures.validateOnSave": true
}

Complementary tools

ToolDescriptionInstallation
tflintTerraform linterbrew install tflint
terraform-docsDocumentation generationbrew install terraform-docs
tfsecSecurity scanbrew install tfsec
checkovPolicy as Codepip install checkov
infracostCost estimationbrew install infracost
# Installer les outils
brew install tflint terraform-docs tfsec

# Utilisation
tflint # Linter
terraform-docs markdown . # Générer docs
tfsec . # Scan sécurité

9 - First execution

Complete workflow

# 1. Initialiser
terraform init

# 2. Valider la syntaxe
terraform validate

# 3. Formater le code
terraform fmt

# 4. Prévisualiser
terraform plan

# 5. Appliquer (avec confirmation)
terraform apply

# 6. Voir l'état
terraform show

# 7. Détruire (optionnel)
terraform destroy

Summary

Key points
  • Terraform is a single binary with no dependencies
  • Configure your cloud credentials before starting
  • Use terraform init to initialize each project
  • The .terraform.lock.hcl file locks the versions
  • Enable autocompletion for more productivity

Practical exercises

  1. Install Terraform on your machine
  2. Configure the AWS credentials (or another cloud)
  3. Create a project with the recommended structure
  4. Initialize the project with terraform init

← Introduction | HCL syntax →