Get startedGet started for free

Best Practices and a Real Time Scenario

1. Best Practices and a Real Time Scenario

Finally, let’s examine some best practices for using modules. Don’t over-use modules. Modularize your code to keep your codebase DRY. Try not to fixate on eliminating all the duplications in your configurations. Duplication allows for more explicit configuration, and the infrastructure is easier to visualize. If you want to loop over multiple values, use Terraform features such as count or for_each instead of building your own custom scripting. Parameterize modules intelligently only if they make sense for end users to change. For example, in a custom network module, the MTU and routing_mode can be standardized, but its name has to be parameterized to ensure reusability. When considering parameterization, focus on the values that you must change. If a value is always fixed in your environment, hardcoding is okay. Use local modules to organize and encapsulate your code. Using local modules to organize your configuration from the beginning will significantly reduce the burden of maintenance as your infrastructure grows in complexity. Use the public Terraform Registry to find modules. By using modules from the Registry, you can quickly and confidently implement your configuration. Publish and share modules with your team. Modules can be used across your team to create and maintain infrastructure. You can publish modules either publicly or privately. To wrap up the module, let’s view a scenario describing how modules can help manage complex infrastructure in Terraform. In a typical application development environment, when a new feature is added or if an existing feature is modified, code is approved by passing it from development to staging, and then to production. Each environments has the same type of resources but differ in their quantity. Let’s assume that the current directory structure for this application includes development, staging, and production folders. When creating a new resource, the developer will add code to the development environment first. The code is then approved and tested. Without modules, the code is manually copied to staging and then to production. The solution is to define the reusable code within a module named server. Then, any change you make to the module is reflected across all the environments that you plan to reuse. You can now reference the code without having to make the changes manually across all the environments. In the example shown, the development, staging, and production environment can reuse the same module, but have different names and deploy a different number of servers.

2. Let's practice!

Create Your Free Account

or

By continuing, you accept our Terms of Use, our Privacy Policy and that your data is stored in the USA.