Laravel uses a
.env file to define various configuration options. The best practice is to not commit this to your repository to keep any secrets in there private. This presented an issue when deploying applications via AWS CodeDeploy to EC2 instances.
For ECS/Fargate you would just set environment variables, but on EC2 that isn’t an option. So the solution I came up with is to add parameters to AWS Parameter Store to save them in a persistent, updatable location. Then within the
appspec.yml I add hooks to read from the parameter store based on patterns, and write them to the required location.
This has a few benefits:
- SecureString type parameters are used to limit and securely store credentials as needed.
- The CDK can use parameters to set database credentials, so no need to lookup up variables to set it ahead of time or pass them into CDK/CFN as a CLI parameter.
- I can use the CDK to set other parameters that might be needed in the config, like SQS queue names for example.
- All env files are refreshed on deploy or new instances being created.
- No need to edit EC2 user-data or cfn-init to add these.
- Less AWS technical users can add entries to .env without being familiar with AWS infrastructure tools.
Here is an example script used to do this:
Finally, here is an example of setting a parameter via the CDK for a resource that was created:
self.database = aws_rds.DatabaseInstance(
One thing that is done here is I segregate secrets by path, so there are some shared between environments and apps, so by path I can select which ones are used. Now you just need to allow your EC2 instances permissions to read from the parameter store and you are all set to start adding configurations.