Concepts Infrastructure as Code
Qu'est-ce que l'IaC ?
Infrastructure as Code (IaC) est la pratique de gérer et provisionner l'infrastructure via des fichiers de configuration plutôt que via des processus manuels.
┌─────────────────────────────────────────────────────────────┐
│ IaC vs MANUEL │
├─────────────────────────────────────────────────────────────┤
│ │
│ PROVISIONING MANUEL │
│ ─────────────────── │
│ 1. Ouvrir la console AWS │
│ 2. Cliquer "Launch Instance" │
│ 3. Configurer manuellement... │
│ 4. Répéter pour chaque ressource │
│ 5. Documenter les paramètres │
│ │
│ Problèmes : │
│ ❌ Non reproductible │
│ ❌ Erreurs humaines │
│ ❌ Pas de versioning │
│ ❌ Documentation obsolète │
│ ❌ Difficile à auditer │
│ │
│ ──────────────────────────────────────────────────────── │
│ │
│ INFRASTRUCTURE AS CODE │
│ ────────────────────── │
│ 1. Écrire un template (YAML/JSON) │
│ 2. Versionner dans Git │
│ 3. Déployer avec CloudFormation │
│ 4. Automatiser via CI/CD │
│ │
│ Avantages : │
│ ✅ Reproductible (même résultat chaque fois) │
│ ✅ Versionné (historique complet) │
│ ✅ Revue de code (peer review) │
│ ✅ Documentation vivante (le code EST la doc) │
│ ✅ Automatisable (CI/CD) │
│ │
└─────────────────────────────────────────────────────────────┘
AWS CloudFormation
Vue d'Ensemble
┌─────────────────────────────────────────────────────────────┐
│ CLOUDFORMATION │
├─────────────────────────────────────────────────────────────┤
│ │
│ COMPOSANTS : │
│ │
│ ┌─────────────┐ │
│ │ TEMPLATE │ Fichier YAML/JSON décrivant │
│ │ (code) │ l'infrastructure souhaitée │
│ └──────┬──────┘ │
│ │ │
│ ▼ │
│ ┌─────────────┐ │
│ │ STACK │ Instance d'un template │
│ │ │ avec des ressources réelles │
│ └──────┬──────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ RESSOURCES AWS │ │
│ │ │ │
│ │ ┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐ │ │
│ │ │ VPC │ │ EC2 │ │ RDS │ │ ALB │ │ SG │ │ │
│ │ └─────┘ └─────┘ └─────┘ └─────┘ └─────┘ │ │
│ │ │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ CYCLE DE VIE : │
│ Create → Update → Delete │
│ (ou Rollback si erreur) │
│ │
└─────────────────────────────────────────────────────────────┘
Structure d'un Template
Sections
AWSTemplateFormatVersion: "2010-09-09"
Description: Description du template
# 1. PARAMETERS - Variables d'entrée
Parameters:
EnvironmentType:
Type: String
Default: dev
AllowedValues: [dev, staging, prod]
# 2. MAPPINGS - Tables de lookup
Mappings:
RegionAMI:
us-east-1:
AMI: ami-0123456789
# 3. CONDITIONS - Logique conditionnelle
Conditions:
IsProd: !Equals [!Ref EnvironmentType, prod]
# 4. RESOURCES - Les ressources à créer (OBLIGATOIRE)
Resources:
MyEC2Instance:
Type: AWS::EC2::Instance
Properties:
ImageId: !FindInMap [RegionAMI, !Ref "AWS::Region", AMI]
InstanceType: t3.micro
# 5. OUTPUTS - Valeurs exportées
Outputs:
InstanceId:
Value: !Ref MyEC2Instance
Export:
Name: MyInstanceId
Types de Ressources Courants
| Type | Description |
|---|---|
AWS::EC2::Instance | Instance EC2 |
AWS::EC2::VPC | VPC |
AWS::EC2::Subnet | Sous-réseau |
AWS::EC2::SecurityGroup | Security Group |
AWS::RDS::DBInstance | Base de données RDS |
AWS::S3::Bucket | Bucket S3 |
AWS::Lambda::Function | Fonction Lambda |
AWS::ElasticLoadBalancingV2::LoadBalancer | ALB/NLB |
Fonctions Intrinsèques
Les Plus Utilisées
Resources:
# !Ref - Référencer un paramètre ou une ressource
MyInstance:
Type: AWS::EC2::Instance
Properties:
InstanceType: !Ref InstanceType # Paramètre
SubnetId: !Ref MySubnet # Ressource
# !GetAtt - Obtenir un attribut d'une ressource
MyDNSRecord:
Type: AWS::Route53::RecordSet
Properties:
Name: app.example.com
ResourceRecords:
- !GetAtt MyInstance.PublicIp # IP publique de l'instance
# !Sub - Substitution de variables
MyBucket:
Type: AWS::S3::Bucket
Properties:
BucketName: !Sub "${AWS::StackName}-${AWS::Region}-data"
# !Join - Concaténer des valeurs
MyTag:
Type: AWS::EC2::Instance
Properties:
Tags:
- Key: Name
Value: !Join ["-", [web, !Ref EnvironmentType, server]]
# !If - Condition
MyVolume:
Type: AWS::EC2::Volume
Properties:
Size: !If [IsProd, 100, 20] # 100 GB en prod, 20 sinon
# !FindInMap - Lookup dans Mappings
MyInstance2:
Type: AWS::EC2::Instance
Properties:
ImageId: !FindInMap [RegionAMI, !Ref "AWS::Region", AMI]
Exemple Complet : Infrastructure Web
AWSTemplateFormatVersion: "2010-09-09"
Description: Infrastructure web simple avec EC2 et Security Group
Parameters:
Environment:
Type: String
Default: dev
AllowedValues: [dev, staging, prod]
Description: Environment name
InstanceType:
Type: String
Default: t3.micro
AllowedValues: [t3.micro, t3.small, t3.medium]
KeyName:
Type: AWS::EC2::KeyPair::KeyName
Description: EC2 Key Pair for SSH access
Mappings:
RegionAMI:
us-east-1:
AMI: ami-0c55b159cbfafe1f0
eu-west-1:
AMI: ami-0d729a60
Resources:
# Security Group
WebSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: Allow HTTP and SSH
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 80
ToPort: 80
CidrIp: 0.0.0.0/0
- IpProtocol: tcp
FromPort: 22
ToPort: 22
CidrIp: 0.0.0.0/0
Tags:
- Key: Name
Value: !Sub "${Environment}-web-sg"
- Key: Environment
Value: !Ref Environment
# EC2 Instance
WebServer:
Type: AWS::EC2::Instance
Properties:
ImageId: !FindInMap [RegionAMI, !Ref "AWS::Region", AMI]
InstanceType: !Ref InstanceType
KeyName: !Ref KeyName
SecurityGroupIds:
- !Ref WebSecurityGroup
Tags:
- Key: Name
Value: !Sub "${Environment}-web-server"
- Key: Environment
Value: !Ref Environment
UserData:
Fn::Base64: |
#!/bin/bash
yum update -y
yum install -y httpd
systemctl start httpd
systemctl enable httpd
echo "<h1>Hello from CloudFormation!</h1>" > /var/www/html/index.html
Outputs:
InstanceId:
Description: Instance ID
Value: !Ref WebServer
Export:
Name: !Sub "${Environment}-WebServerId"
PublicIP:
Description: Public IP address
Value: !GetAtt WebServer.PublicIp
WebsiteURL:
Description: URL of the website
Value: !Sub "http://${WebServer.PublicIp}"
Commandes CLI
# Valider un template
aws cloudformation validate-template \
--template-body file://template.yaml
# Créer une stack
aws cloudformation create-stack \
--stack-name my-web-stack \
--template-body file://template.yaml \
--parameters \
ParameterKey=Environment,ParameterValue=dev \
ParameterKey=KeyName,ParameterValue=my-key
# Voir l'état de la stack
aws cloudformation describe-stacks \
--stack-name my-web-stack
# Voir les événements (debug)
aws cloudformation describe-stack-events \
--stack-name my-web-stack
# Mettre à jour une stack
aws cloudformation update-stack \
--stack-name my-web-stack \
--template-body file://template.yaml \
--parameters \
ParameterKey=Environment,ParameterValue=staging
# Supprimer une stack
aws cloudformation delete-stack \
--stack-name my-web-stack
Bonnes Pratiques
┌─────────────────────────────────────────────────────────────┐
│ BONNES PRATIQUES CLOUDFORMATION │
├─────────────────────────────────────────────────────────────┤
│ │
│ ✅ FAIRE │
│ ──────── │
│ • Versionner les templates dans Git │
│ • Utiliser des paramètres pour la flexibilité │
│ • Ajouter des descriptions claires │
│ • Utiliser des noms logiques significatifs │
│ • Valider avant de déployer │
│ • Utiliser des Change Sets pour preview │
│ • Taguer toutes les ressources │
│ │
│ ❌ ÉVITER │
│ ───────── │
│ • Hardcoder des valeurs (AMIs, IPs...) │
│ • Créer des templates monolithiques (> 500 lignes) │
│ • Ignorer les erreurs de validation │
│ • Déployer sans revue de code │
│ • Oublier les outputs pour les références │
│ │
└─────────────────────────────────────────────────────────────┘
Résumé
| Concept | Description |
|---|---|
| Template | Fichier YAML/JSON décrivant l'infrastructure |
| Stack | Instance déployée d'un template |
| Parameters | Variables d'entrée configurables |
| Resources | Les ressources AWS à créer |
| Outputs | Valeurs exportées pour référence |
| !Ref | Référencer une ressource ou paramètre |
| !GetAtt | Obtenir un attribut d'une ressource |
Prochaine section : Lab CloudFormation