Understanding Exported Attributes
Earlier, we created an AWS key pair resource that required a user-supplied public key. After its creation, Terraform exported several attributes, which you can inspect using the Terraform show command. Below is the configuration used to create the AWS key pair resource:Remember: Utilizing exported attributes allows you to build dependencies between resources, enabling dynamic infrastructure provisioning.
Referencing Resource Attributes
Exported resource attributes are often used as inputs for configuring other resources. Consider a scenario where you need to configure an EC2 instance using the AWS key pair resource. You can reference the key pair’s attributes in your EC2 instance configuration as follows:aws_key_pair.alpha.key_name refers to the key_name attribute of the key pair resource named “alpha”. By running terraform apply, both the key pair and the EC2 instance are provisioned in the correct order. Terraform automatically ensures that the key pair is created before the EC2 instance, thanks to the inherent resource dependency.
The sample console output from running terraform apply is shown below:
Terraform automatically manages the creation order by analyzing resource dependencies. During deletion, resources are removed in reverse order, ensuring a safe teardown.
Managing Explicit Dependencies
Sometimes, two resources might not implicitly depend on each other—for instance, two EC2 instances that do not reference one another. In such cases, you can enforce a creation order using thedepends_on meta-argument.
Imagine you have two EC2 instances: one for your database server and another for your web server. To ensure that Terraform creates the database instance before the web instance, modify the configuration as follows:
depends_on argument, Terraform provisions the database instance first. When removing resources, it deletes the web instance before the database instance, preserving the dependency order.
Be cautious with explicit dependencies. Overusing
depends_on can lead to unnecessarily complex dependency graphs, which might complicate the execution plan.