How To: CloudFormation CodeBuild Project (AWS::CodeBuild::Project) To Mount EFS (Elastic File System) in a VPC with Subnets
These are the steps needed to mount CodeBuild Project to EFS by setting the FileSystemLocation property and referencing it in BuildSpec.yaml
In this example below, EFS is Mounted to 3 different Subnets in 3 different AZ's
FileSystemResource:
Type: 'AWS::EFS::FileSystem'
Properties:
BackupPolicy:
Status: ENABLED
PerformanceMode: maxIO
...
...
...
MountTargetResource1:
Type: AWS::EFS::MountTarget
Properties:
FileSystemId: !Ref FileSystemResource
SubnetId: subnet-4f2e0e48
SecurityGroups:
- !GetAtt MountTargetVPC.DefaultSecurityGroup
MountTargetResource2:
Type: AWS::EFS::MountTarget
Properties:
FileSystemId: !Ref FileSystemResource
SubnetId: subnet-620be258
SecurityGroups:
- !GetAtt MountTargetVPC.DefaultSecurityGroup
MountTargetResource3:
Type: AWS::EFS::MountTarget
Properties:
FileSystemId: !Ref FileSystemResource
SubnetId: subnet-d133f80d
SecurityGroups:
- !GetAtt MountTargetVPC.DefaultSecurityGroup
NOTE: If your EFS is Mounted to 1 or more Subnets in different AZ's, you will need to have the same Subnets mapped in AWS::CodeBuild::Project. This applies to EC2 instances as well, create EFS Mount Targets for each of your EC2 Instance Subnet Locations.
The AWS::CodeBuild::Project example below has 3 Subnets that are the same as the EFS Mounted networks show above.
Project:
Type: AWS::CodeBuild::Project
Properties:
Name: myProjectName
Description: A description about my project
ServiceRole: !GetAtt ServiceRole.Arn
Artifacts:
Type: no_artifacts
Environment:
Type: LINUX_CONTAINER
ComputeType: BUILD_GENERAL1_SMALL
Image: aws/codebuild/java:openjdk-8
EnvironmentVariables:
- Name: varName
Type: varType
Value: varValue
Source:
Location: codebuild-demo-test/0123ab9a371ebf0187b0fe5614fbb72c
Type: S3
TimeoutInMinutes: 10
Tags:
- Key: Key1
Value: Value1
- Key: Key2
Value: Value2
VpcConfig
SecurityGroupIds:
- sg-1f23ed4a29c64cccb
Subnets:
- subnet-4f2e0e48
- subnet-620be258
- subnet-d133f80d
VpcId: vpc-0fdf3d2a773deef1d
FileSystemLocation:
# Identifier will create a environment variable that you can reference in BuildSpec to reference the mounted EFS path
# This is usually the EFS File System Id without a Hyphen
# NOTE: this can be lower case and referenced like $CODEBUILD_fs9325925
Identifier: fs9325925
# Location Format: {efs-file-system-id}.efs.{region}.amazonaws.com:{path}
Location: fs-9325925.efs.us-east-1.amazonaws.com:/
# MountOptions: String
# Local folder to mount to efs to, example: /efs )
MountPoint: /efs
# Type: Valid Values: EFS
Type: EFS
This is the BuildSpec example to reference the Mounted EFS. A environment variable called CODEBUILD_fs9325925 has been created to allow you access the folder that has been mounted to EFS.
In the below example, $CODEBUILD_fs9325925 = /efs
version: 0.2
phases:
build:
commands:
- printenv #Output set environment variables
- cp index.html $CODEBUILD_fs9325925