Skip to content

shamimice03/terraform-attach-EFS-on-multiple-EC2-instances

Repository files navigation

Attach EFS to multiple EC2 instances using Terraform

Attach the AWS EFS filesystem to multiple AWS EC2 instances running on different AZs. To automate the whole process from creating an EFS filesystem to attaching it to the EC2 instances, we will use Terraform.

github.small

Following are the steps we will follow to achieve our goal:

  1. Create an AWS VPC with two public subnets on two different AZs.

  2. Create two Security Groups. one is for EC2 instances which will allow inbound SSH traffic on port 22, and another one is for EFS mount targets which will allow inbound traffic on port 2049 only from the EC2 instances security group. And both security groups will allow outbound traffic to any port from anywhere.

  3. Create an EFS file system.

  4. Configure EFS mount targets along with the security group created for EFS mount targets.

  5. Generate a custom script that will help us mount EFS on EC2 instances.

  6. Create AWS key pair so that we can SSH into the EC2 instances.

  7. Deploy two EC2 instances on different subnets created on different AZs. While providing the EC2 instances execute the custom script we created for mounting EFS using terraform remote-exec provisioners.

Test

To test whether the EFS file system is mounted on or not. SSH into the instances and run df -k command to find out all the mounted file systems on your EC2 instances.

Bash Script used to mount file system:

#! /bin/bash
# Update the system packages
sudo yum update -y

# Create a directory for the content
sudo mkdir -p content/test/

# Install the Amazon EFS utilities
sudo yum -y install amazon-efs-utils

# Add an entry to /etc/fstab to mount the EFS file system
sudo su -c  "echo 'fs-0c4c5164674de43ca:/ content/test/ efs _netdev,tls 0 0' >> /etc/fstab"

# Mount the EFS file system
sudo mount content/test/

# Display the disk space usage
df -k