« Terraform - Infrastructure-as-a-Code » : différence entre les versions

De Marijan Stajic | Wiki
Aller à la navigation Aller à la recherche
Aucun résumé des modifications
Aucun résumé des modifications
 
(4 versions intermédiaires par le même utilisateur non affichées)
Ligne 1 : Ligne 1 :
<pre class="alert">
Les informations sont posées en vrac pour le moment. À retravailler.
</pre>
= Introduction =
[[Fichier:Terraform Banner.png|none]]
[[Fichier:Terraform Banner.png|none]]


C'est un outil pour définir et provisionner des infrastructures Cloud en utilisant simplement un fichier de configuration (IaC).
Terraform is an '''infrastructure as code''' (IaC) '''tool''' that allows users to '''define''', '''provision''', and '''manage cloud''' and '''on-premises resources''' using a '''declarative configuration language''' (HCL). It enables '''consistent''' and '''repeatableinfrastructure deployment''' across multiple providers like AWS, Azure, and Google Cloud.


---
= Files =
# Fichiers


Il y a différents fichiers de base (.tf) qui sont nécessaire pour le bon fonctionnement de Terraform.
There are different basic files (.tf) needed for Terraform to work properly.


```
<pre class="linux">
project/
project/
├── globals.tfvars
├── variables.tfvars
└── environments/
└── environments/
     └── dev/
     └── dev/
Ligne 16 : Ligne 21 :
         ├── variables.tf
         ├── variables.tf
         └── provider.tf
         └── provider.tf
    └── prod/
</pre>
        ├── main.tf
 
        ├── variables.tf
== Provider ==
        └── provider.tf
```
## Provider


Ce fichier permet de définir :
This file is used to define:


```
<pre class="linux">
terraform {
terraform {
   required_version = ">=1.2"
   required_version = ">=1.2"
Ligne 44 : Ligne 46 :
provider "azurerm" {
provider "azurerm" {
   features {}
   features {}
  }
}
```
</pre>


- Définir la version et le provider requis pour Terraform
* Define the required Terraform version and provider
- Où doit être modifier le tfstate (storage account Azure, S3 sur Exo, ...)
* Set where the tfstate should be stored (Azure Storage Account, S3 on Exo, etc.)
- Le Cloud Provider à utiliser (Azure, AWS, Exoscale, etc.) afin d'avoir accès à la bibliothèque (disponible sur https://registry.terraform.io/)
* Choose the Cloud Provider (Azure, AWS, Exoscale, etc.) to use libraries (available at https://registry.terraform.io/)


## Main
== Main ==


Le fichier main.tf est le fichier principal, part le quel les différentes actions vont agir sur l'infrastructure (création, suppression et modification).
The main.tf file is the main one. It’s where actions on the infrastructure happen (create, delete, or update).


```
<pre class="linux">
resource "azurerm_Resource_group" "example" {
resource "azurerm_Resource_group" "example" {
name    = "example-rg"
  name    = "example-rg"
location = "France Central"
  location = "France Central"
}
}
```
</pre>


- Resource : permet de définir qu'il s'agit d'une ressource
* resource: tells Terraform this is a resource 
- azurerm_Resource_group : RG sur Azure, information trouvable sur la registry
* azurerm_Resource_group: a resource group on Azure (see registry
- example : c'est la variable de la ressource, dans le cas ou on doit la rappeler
* example: the name used to refer to the resource later


## Variables
== Variables ==


Dans les bonnes pratiques de Terraform, il faut :
With Terraform best practices:


```
<pre class="linux">
variables.tf
variables.tf


Ligne 77 : Ligne 79 :
   type        = string
   type        = string
}
}
</pre>


--
<pre class="linux">
 
variables.tfvars
variables.tfvars


resource_group_name = "rg-rd-testmachine-chn"
resource_group_name = "rg-rd-testmachine-chn"
```
</pre>


- Déclarer les variables dans un variable.tf
* Declare variables in a variable.tf file 
- Définir les valeurs des variables du .tf dans un variable.**tfvars**
* Define their values in a variable.tfvars file 


---
= Procedure =
# Procédure


Afin de déployer via du code du Terraform, il est séquencé en trois parties : init, plan & apply.
To deploy Terraform code, the process has three steps: init, plan & apply.


## Init
== Init ==


La première étape est init (initialisation) :
First step is init (initialization):


```
<pre class="linux">
terraform init
terraform init
```
</pre>


- Installation des plugins pour interagir avec le provider
* Installs plugins for the provider
- Initialisation du Backend pour le .tfstat
* Sets up backend for .tfstate 
- Préparation du dossier de travail pour l'execution des autres commandes Terraform
* Prepares folder for running other Terraform commands 


## Plan
== Plan ==


La deuxième étape est plan (planification):
Second step is plan (planning):


```
<pre class="linux">
terraform plan
terraform plan
```
</pre>


- Analyse les fichiers de configurations pour déterminer les ressources à créer, modifier ou supprimer
* Checks config files to see what to create, change or delete 
- Il présente un plan d'exécution afin de voir ce qui va être modifié
* Shows a preview of what will happen 
- Permet d'avoir un review des changements avant d'appliquer
* Lets you review changes before applying 


## Apply
== Apply ==


La dernière étape est apply (application)
Final step is apply (applying changes):


```
<pre class="linux">
terraform apply
terraform apply
```
</pre>


- Confirmation des changement avant d'appliquer
* Confirms changes before applying 
- Une fois confirmer, il va appliquer les changements relatif à vos fichiers de configuration
* Applies changes from your config files 
- Mettre à jour le .tfstat
* Updates the .tfstate file 


---
= .tfstate =
# .tfstate


C'est un fichier crucial afin de maintenir un alignement correcte entre la configuration et l'infrastructure actuel. Après chaque modification, ce fichier doit être mis à jour.
This file keeps your config aligned with real infrastructure. It must be updated after every change.


On peut grâce à lui afficher les ressources managées part Terraform
You can show the managed resources with:


```
<pre class="linux">
terraform show
terraform show
```
</pre>


---
= Destroy =
# Destroy


Il est possible de supprimer tout la configuration générée par Terraform
You can delete all the infrastructure made by Terraform:


```
<pre class="linux">
terraform destroy
terraform destroy
```
</pre>


- Affiche les ressources qui vont être supprimées
* Shows what will be deleted 
- Demande une confirmation avant de supprimer
* Asks for confirmation
- Une fois confirmé, il supprime les ressources
* Deletes after confirmation 


## Suppression d'une ressource
== Removing a resource ==


Afin de supprimer une ressource, il suffit simplement de retirer la ressource du main.tf. Ceci va supprimer la ressource et mettre à jour le .tfstate
To delete a specific resource, just remove it from main.tf. Terraform will update the .tfstate accordingly.


---
= Modules =
# Modules


Terraform, c'est des input sur une infrastructure. Cependant, parfois, il est nécessaire d'utiliser le résultat pour d'autres projets (modules) dans un même gros projet (project).
Terraform uses inputs for infrastructure. Sometimes, you need to reuse them across modules in the same project.


```
<pre class="linux">
project/
project/
├── provider.tf
├── provider.tf
Ligne 175 : Ligne 173 :
         ├── output.tf
         ├── output.tf
         └── variables.tf
         └── variables.tf
```
</pre>
 
* In main.tf you declare a module with source, location, resource_group_name, and variables


- main.tf (main branch) : on doit déclarer un module ainsi que sa source, location, ressource_group_name ainsi que ces variables
== Output ==
## Output


Si nous avons par exemple un resource group sur Azure qui va être créer, et qu'un autre projet à besoin de l'id, il est possible de le récupérer grâce au fichier output
If a project needs the ID of a resource group created by another, you can get it using an output file.

Dernière version du 30 avril 2025 à 21:42

Les informations sont posées en vrac pour le moment. À retravailler.

Introduction

Terraform Banner.png

Terraform is an infrastructure as code (IaC) tool that allows users to define, provision, and manage cloud and on-premises resources using a declarative configuration language (HCL). It enables consistent and repeatableinfrastructure deployment across multiple providers like AWS, Azure, and Google Cloud.

Files

There are different basic files (.tf) needed for Terraform to work properly.

project/
├── variables.tfvars
└── environments/
    └── dev/
        ├── main.tf
        ├── variables.tf
        └── provider.tf

Provider

This file is used to define:

terraform {
  required_version = ">=1.2"
  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "=4.1.0"
    }
  }
    backend "azurerm" {
      resource_group_name  = "rg-rd-tfstate-chn"
      storage_account_name = "rdsttfstate"
      container_name       = "tfstate"
      key                  = "terraform.tfstate"
  }
}

provider "azurerm" {
  features {}
}
  • Define the required Terraform version and provider
  • Set where the tfstate should be stored (Azure Storage Account, S3 on Exo, etc.)
  • Choose the Cloud Provider (Azure, AWS, Exoscale, etc.) to use libraries (available at https://registry.terraform.io/)

Main

The main.tf file is the main one. It’s where actions on the infrastructure happen (create, delete, or update).

resource "azurerm_Resource_group" "example" {
  name     = "example-rg"
  location = "France Central"
}
  • resource: tells Terraform this is a resource
  • azurerm_Resource_group: a resource group on Azure (see registry)
  • example: the name used to refer to the resource later

Variables

With Terraform best practices:

variables.tf

variable "resource_group_name" {
  description = "Nom du groupe de ressources"
  type        = string
}
variables.tfvars

resource_group_name = "rg-rd-testmachine-chn"
  • Declare variables in a variable.tf file
  • Define their values in a variable.tfvars file

Procedure

To deploy Terraform code, the process has three steps: init, plan & apply.

Init

First step is init (initialization):

terraform init
  • Installs plugins for the provider
  • Sets up backend for .tfstate
  • Prepares folder for running other Terraform commands

Plan

Second step is plan (planning):

terraform plan
  • Checks config files to see what to create, change or delete
  • Shows a preview of what will happen
  • Lets you review changes before applying

Apply

Final step is apply (applying changes):

terraform apply
  • Confirms changes before applying
  • Applies changes from your config files
  • Updates the .tfstate file

.tfstate

This file keeps your config aligned with real infrastructure. It must be updated after every change.

You can show the managed resources with:

terraform show

Destroy

You can delete all the infrastructure made by Terraform:

terraform destroy
  • Shows what will be deleted
  • Asks for confirmation
  • Deletes after confirmation

Removing a resource

To delete a specific resource, just remove it from main.tf. Terraform will update the .tfstate accordingly.

Modules

Terraform uses inputs for infrastructure. Sometimes, you need to reuse them across modules in the same project.

project/
├── provider.tf
├── main.tf
└── modules/
    └── azure_rg_module/
        ├── main.tf
        ├── output.tf
        └── variables.tf
    └── azure_resource_module/
        ├── main.tf
        ├── output.tf
        └── variables.tf
  • In main.tf you declare a module with source, location, resource_group_name, and variables

Output

If a project needs the ID of a resource group created by another, you can get it using an output file.