EC2 — Terraform Example
Progress checklist
What this example does
Section titled “What this example does”This example provisions:
- An S3 bucket (versioning + SSE-S3 enabled)
- An S3 Files file system and mount targets in each provided subnet
- IAM roles (file system role + EC2 instance profile)
- Security groups (compute → mount target on NFS port 2049)
- An Amazon Linux 2023 EC2 instance with
amazon-efs-utilsinstalled and the file system mounted at/mnt/s3files
Access to the instance is through SSM Session Manager — no SSH key pair or bastion host is needed.
-
Confirm prerequisites.
Requirement Minimum version Terraform 1.5 AWS provider 6.40 AWS CLI 2.34.26 (for aws ssm start-session)Install the Session Manager plugin if not already present:
Terminal window aws ssm start-session --versionIf the command is not found, follow the AWS Session Manager plugin installation guide.
-
Clone the example.
Terminal window git clone https://github.com/jajera/terraform-aws-s3-files.gitcd terraform-aws-s3-files/examples/ec2The example directory contains:
Directoryexamples/ec2/
- main.tf
- terraform.tfvars.example
- terraform.tfvars (you create this)
-
Create
terraform.tfvars.Copy the example file and set your VPC and subnet IDs:
Terminal window cp terraform.tfvars.example terraform.tfvarsEdit
terraform.tfvars:vpc_id = "vpc-0123456789abcdef0"subnet_ids = ["subnet-aaaaaaaaaaaaaaaaa", "subnet-bbbbbbbbbbbbbbbbb"]# Optional overrides (defaults shown):# aws_region = "ap-southeast-6"# instance_type = "t3.micro"# bucket_name = null # auto-generated: s3files-demo-<random># bucket_force_destroy = trueVariable Default Required Description vpc_id— yes VPC for mount targets and EC2 instance subnet_ids— yes Subnets for mount targets (one per AZ recommended) instance_subnet_idfirst subnet_idsentryno Subnet for the EC2 instance aws_regionap-southeast-6no AWS region instance_typet3.microno EC2 instance type bucket_nameauto-generated no Leave nullto uses3files-demo-<random>bucket_force_destroytrueno Allow destroy even when bucket contains objects -
Initialise and apply.
Terminal window terraform initterraform planterraform applyWhen apply finishes, note the outputs:
Terminal window terraform outputKey outputs:
Output Description instance_idEC2 instance ID ( i-…)file_system_idS3 Files file system ID bucket_nameBacking S3 bucket name ami_idAmazon Linux 2023 AMI used -
Connect via SSM Session Manager.
Terminal window aws ssm start-session \--target "$(terraform output -raw instance_id)" \--region ap-southeast-6 -
Verify the mount.
Inside the SSM session:
Terminal window df -h /mnt/s3filesls -la /mnt/s3filesWrite a file and confirm it appears in S3:
Terminal window echo "hello from terraform ec2" > /mnt/s3files/test.txtcat /mnt/s3files/test.txtExit the session when done:
Terminal window exit -
Tear down.
Terminal window terraform destroy