Installation et configuration
Objectifs du chapitre
- Installer Terraform sur différents OS
- Configurer l'autocomplétion
- Configurer les providers cloud
- Valider l'installation
1 - Installation de 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 - Vérification de l'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 - Autocomplétion
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 - Configuration des providers cloud
AWS
Méthode 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)
Méthode 2: Variables d'environnement
export AWS_ACCESS_KEY_ID="votre_access_key"
export AWS_SECRET_ACCESS_KEY="votre_secret_key"
export AWS_DEFAULT_REGION="eu-west-1"
Méthode 3: Fichier credentials
# ~/.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 - Structure de projet
Organisation recommandée
Fichiers standards
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
Fichier .gitignore
# .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 - Configuration Terraform
Version et 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"
}
}
}
Contraintes de version
| Opérateur | Signification | Exemple |
|---|---|---|
= | Version exacte | = 5.0.0 |
!= | Différent de | != 5.0.0 |
>, >= | Supérieur | >= 5.0.0 |
<, <= | Inférieur | < 6.0.0 |
~> | Pessimistic | ~> 5.0 (5.x.x) |
7 - Initialisation d'un projet
Commande init
# 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
Résultat de init
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!
Fichiers créés
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 - Environnements de développement
VS Code Extensions
// Recommended extensions
{
"recommendations": [
"hashicorp.terraform",
"hashicorp.hcl",
"4ops.terraform-autocomplete"
]
}
Configuration VS Code
// settings.json
{
"[terraform]": {
"editor.defaultFormatter": "hashicorp.terraform",
"editor.formatOnSave": true
},
"[terraform-vars]": {
"editor.defaultFormatter": "hashicorp.terraform",
"editor.formatOnSave": true
},
"terraform.experimentalFeatures.validateOnSave": true
}
Outils complémentaires
| Outil | Description | Installation |
|---|---|---|
| tflint | Linter Terraform | brew install tflint |
| terraform-docs | Génération de docs | brew install terraform-docs |
| tfsec | Scan de sécurité | brew install tfsec |
| checkov | Policy as Code | pip install checkov |
| infracost | Estimation coûts | brew 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 - Première exécution
Workflow complet
# 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
Résumé
Points clés
- Terraform est un binaire unique sans dépendances
- Configurez les credentials cloud avant de commencer
- Utilisez
terraform initpour initialiser chaque projet - Le fichier
.terraform.lock.hclverrouille les versions - Activez l'autocomplétion pour plus de productivité
Exercices pratiques
- Installez Terraform sur votre machine
- Configurez les credentials AWS (ou autre cloud)
- Créez un projet avec la structure recommandée
- Initialisez le projet avec
terraform init