Table des matières

Déploiement AWS avec Terraform (EC2 + SSH)

Objectif

Mettre en place une instance EC2 sur AWS avec :

Prérequis

1. Configuration du provider

Fichier main.tf :

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

2. Déclaration de la variable SSH

variable "public_key_path" {
  description = "Chemin vers la clé publique SSH"
  type        = string
}

3. Création de la clé AWS

resource "aws_key_pair" "zerp_key" {
  key_name   = "zerp-key"
  public_key = file(var.public_key_path)
}

4. Security Group (SSH)

resource "aws_security_group" "zerp_sg" {
  name = "zerp-sg"

  ingress {
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

5. Création de l'instance EC2

resource "aws_instance" "zerp_ec2" {
  ami           = "ami-xxxxxxxx"
  instance_type = "t2.micro"

  key_name = aws_key_pair.zerp_key.key_name
  vpc_security_group_ids = [
    aws_security_group.zerp_sg.id
  ]
  tags = {
    Name = "zerp-ec2"
  }
}

6. Fichier terraform.tfvars

public_key_path = "C:/Users/ton_user/.ssh/id_rsa.pub"

7. Initialisation Terraform

terraform init

8. Déploiement

terraform apply

Valider avec : yes

9. Récupération de l’IP

terraform show

Chercher :

public_ip = "xxx.xxx.xxx.xxx"

10. Connexion SSH

Amazon Linux

ssh -i $HOME/.ssh/id_rsa ec2-user@IP

Ubuntu

ssh -i  $ HOME/.ssh/id_rsa ubuntu@IP

11. Vérification

Si tout fonctionne :

[ec2-user@ip-xxx-xxx-xxx-xxx ~] $ 

Problèmes courants

Permission denied

Mauvais utilisateur (ec2-user vs ubuntu)

Connection timed out

Port 22 non ouvert Security group mal configuré

Bonnes pratiques