Skip to main content
This lesson demonstrates how to manage resource dependencies in OpenTofu, covering both explicit and implicit approaches using depends_on and attribute references.

Table of Contents

  1. Understanding Resource Dependencies
  2. Generating a TLS Private Key
  3. Writing the Key to a Local File
  4. Cleanup
  5. Explicit Dependency with depends_on
  6. Links and References

Understanding Resource Dependencies

OpenTofu resources can depend on each other in two ways: First, we set an explicit dependency using the depends_on argument when Resource A does not reference Resource B’s attributes:
The image shows a Visual Studio Code editor with a welcome message for KodeKloud OpenTofu Lab on the right, and a multiple-choice question about dependencies on the left.
Next, an implicit dependency is created by referencing one resource’s attributes inside another:
The image shows a KodeKloud OpenTofu Lab interface with a Visual Studio Code editor on the right, displaying a welcome message and terminal, and a quiz question on the left about implicit dependency.

Generating a TLS Private Key

Navigate to your project’s key-generator directory and create key.tf:
Initialize, plan, and apply the configuration:
Inspect the generated key:
Storing private keys in plain text can pose a security risk. Never commit sensitive key material to version control.

Writing the Key to a Local File

Update key.tf to include a local_file resource:
Re-run OpenTofu:
Verify that /root/key.txt contains your PEM-encoded private key.

Cleanup

When you’re done, destroy both resources:

Explicit Dependency with depends_on

Create a new directory (e.g., /root/explicit-dependency) and add main.tf:
Here, whale will only be created after krill, illustrating an explicit dependency without attribute references. Apply this configuration:

Watch Video

Practice Lab