OpenTofu: A Beginners Guide to a Terraform Fork Including Migration From Terraform
OpenTofu Basics
Demo Resource Dependencies
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
- Understanding Resource Dependencies
- Generating a TLS Private Key
- Writing the Key to a Local File
- Cleanup
- Explicit Dependency with depends_on
- Links and References
Understanding Resource Dependencies
OpenTofu resources can depend on each other in two ways:
Dependency Type | Definition | Syntax Example |
---|---|---|
Explicit | Resource A waits for Resource B without accessing its attributes directly. | depends_on = [local_file.krill] |
Implicit | Resource A references Resource B’s attribute in its arguments. | content = tls_private_key.pvtkey.private_key_pem |
First, we set an explicit dependency using the depends_on
argument when Resource A does not reference Resource B’s attributes:
Next, an implicit dependency is created by referencing one resource’s attributes inside another:
Generating a TLS Private Key
Navigate to your project’s key-generator
directory and create key.tf
:
resource "tls_private_key" "pvtkey" {
algorithm = "RSA"
rsa_bits = 4096
}
Initialize, plan, and apply the configuration:
opentofu init
opentofu plan
opentofu apply
# Type "yes" to confirm
Inspect the generated key:
opentofu show tls_private_key.pvtkey
Warning
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:
resource "tls_private_key" "pvtkey" {
algorithm = "RSA"
rsa_bits = 4096
}
resource "local_file" "key_details" {
filename = "/root/key.txt"
content = tls_private_key.pvtkey.private_key_pem
}
Re-run OpenTofu:
opentofu init
opentofu plan
opentofu apply
# Confirm with "yes"
Verify that /root/key.txt
contains your PEM-encoded private key.
Cleanup
When you’re done, destroy both resources:
opentofu destroy
# Confirm with "yes"
Explicit Dependency with depends_on
Create a new directory (e.g., /root/explicit-dependency
) and add main.tf
:
resource "local_file" "krill" {
filename = "/root/krill.txt"
content = "krill"
}
resource "local_file" "whale" {
filename = "/root/whale.txt"
content = "whale"
depends_on = [local_file.krill]
}
Here, whale
will only be created after krill
, illustrating an explicit dependency without attribute references.
Apply this configuration:
opentofu init
opentofu plan
opentofu apply
# Enter "yes" to proceed
Links and References
Watch Video
Watch video content
Practice Lab
Practice lab