Dry Code (reusable and repeatable)
Dry code (the principle of “do not repeat yourself“) means creating lines of code once and using or referencing that code many times. The benefit to everyone is re-usable code.
- The benefit
- reduces mistakes
- creates reusable code
- creates code that can be shared
- Writing code once, instead of repeating the writing of code
- Someone writes a bit of code and puts the code in a shared location
- This allows other team members to copy the code or make references to the code
- Everyone uses the same code but varies the utilization of code with variables
It makes sense to test and validate code in a test environment, then deploy the same code in production using variables that change the parameters of deployment.
We can accomplish dry code in Terraform by placing the “Infrastructure as Code” in a shared location such as Git, GitHub, AWS S3 buckets, shared files on your network, or a folder structure on your workstation. Then using the shared code in different deployments simply by using environment variables.
Example
Write code that creates a VPC in AWS using variables, like a variable for the VPC name and another variable for the VPC IP address block.
Then place that VPC code in a shared folder.
Team A needs a VPC for testing a new load-balanced application. Team A uses VPC code in a shared folder and assigns attributes to the variables to make the deployment unique to the test environment.
Team B needs to deploy a CRM into production and requires a new VPC. Team B uses the very same VPC code from the shared folder and assigns attributes to the variables to make the deployment unique to the production environment.
Both teams used the same code to build a VPC, one for a test environment and the other for a production environment. Neither team had to write code to create a VPC. Both used a shared code to create a VPC and assign values to the variables to meet their requirements.