To work with terraform code, you must know the usage of these five commands – Declare, Init, Plan, apply, and destroy. You can test terraform code locally by using these commands.
Declare allows declaring resources. You can run this in any directory – where no other details are present. It is the first step.
$ terraform init
- Terraform isn’t aware of your workspace, let alone that it’s supposed to create or manage anything, because it hasn’t been initialized.
- Terraform configuration must always be initialized at least once, but you may have to initialize it again if you add new providers or modules.
- Don’t fret about when to run
init, because Terraform will always remind you. Moreover,
initis an idempotent command, which means you can call it as many times as you want in a row with no side effects.
- After initialization, Terraform creates a hidden .terraform directory for installing plugins and modules.
$ terraform plan
- Terraform intends to do this by running
plan. You should always run
terraform planinforms you about what Terraform intends to do and acts as a linter, letting you know about any syntax or dependency errors.
- It’s a read-only action that does not alter the state of deployed infrastructure, and like
init, it’s idempotent.
$ terraform apply
The apply command compares the output against the generated execution plan.
$ terraform destroy -auto-approve
During destroy, first it generates an execution plan as if there were no resources in the configuration files by performing a Read() on each resource and marking all existing resources for deletion.
The optional flag
-auto-approve, which automatically approves the result of the execution plan.