main.tf.
Prerequisites
- OpenTofu CLI installed (see OpenTofu Installation).
- A working directory with an existing
main.tfand an initialized backend.
Defining Multiple Resources
Extend yourmain.tf by adding a random_pet resource alongside the existing local_file:
Whenever you introduce a new Provider (e.g., the
random provider here), you must reinitialize your configuration so OpenTofu can download or reuse the required plugin.Initializing Providers
Run:Review changes in your
.terraform.lock.hcl after tofu init. Commit updates only if they match your intended dependency versions.Planning and Applying Changes
First, generate and inspect the execution plan:| Command | Purpose | Example |
|---|---|---|
| tofu init | Initialize backend & providers | tofu init |
| tofu plan | Preview changes without applying | tofu plan -out=tfplan |
| tofu apply | Apply changes to reach desired state | tofu apply tfplan |
Example Execution Output
random_pet resource simply generates a random name, exposed as its id attribute—no real infrastructure is provisioned.
Chaining Resources Across Providers
You can reference one resource’s attribute in another, even if they come from different Providers. For example, generate a random string to tag an AWS EC2 instance:tofu apply, OpenTofu will:
- Create the random string.
- Launch an EC2 instance tagged with
web-<generated-suffix>.
.tf file.