In this lesson, we explore key considerations when using provisioners in Terraform. Provisioners can be very useful for executing tasks such as bootstrapping with a Remote Exec script; however, their use should be limited. Terraform advises caution when using them due to several reasons.Documentation Index
Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
Use this file to discover all available pages before exploring further.
Provisioners often add complexity to your configuration. Their nature of executing arbitrary system-supported commands means that Terraform cannot fully simulate or validate these actions during the planning phase.
Why Use Provisioners Sparingly?
Provisioners in Terraform can execute any system-supported command via the command or inline arguments. This flexibility makes them powerful but also creates challenges:- They increase the overall complexity of your Terraform configuration.
- Due to the dynamic nature of these commands, Terraform cannot accurately predict the outcome during the plan phase.
Example: Remote Exec Provisioner
Below is an example Terraform configuration that employs theremote-exec provisioner to append the host’s IP address to a file on the remote instance.
Connection Block Requirement
For provisioners such as Remote Exec, it is essential to define a connection block to establish network connectivity and authenticate to the target instance. The connection details must be configured correctly on the local machine before the provisioner runs, which might not always be feasible. Consider the following sample configuration:Best Practices: Use Resource-Native Features
To mitigate the challenges associated with provisioners, Terraform recommends leveraging resource-native features. For instance, when working with Amazon Elastic Compute Cloud (EC2), you can utilize the User Data feature, ensuring that required tasks are executed during instance launch without an explicit connection block.Example: Using User Data
The following Terraform configuration uses the User Data feature to install and configure NGINX during instance launch:While using provisioners like remote-exec or User Data can be helpful, it is recommended to limit post-provisioning tasks. Over-relying on them can lead to configuration drift and harder maintenance.