Now, let’s go ahead and clean up both resource groups to avoid unnecessary charges.

As we’re already within the test workspace, let’s run the following command to destroy resources within the test workspace:
$ terraform destroy –auto-approve

Now, let’s switch to the dev workspace using the following command:
$ terraform workspace select dev
Switched to workspace “dev”.

As we’re within the dev workspace, use the following command to destroy all resources within the dev workspace:
$ terraform destroy –auto-approve

In a while, we should see that both resource groups are gone. Now, let’s look at some of the advanced concepts of Terraform in the next section.

Terraform output, state, console, and graphs

While we understand that Terraform uses state files to manage resources, let’s look at some advanced commands to help us appreciate and make more sense of the Terraform state concept.

To access the resources for this section, cd into the following:
$ cd ~/modern-devops/ch8/terraform-workspaces/

Now, let’s go ahead and look at our first command – terraform output.

terraform output

So far, we’ve looked at variables but haven’t yet discussed outputs. Terraform outputs are return values of a Terraform configuration that allow users to export configuration to users or any modules that might use the current module.

Let’s go with the last example and add an output variable that exports the private IP of the network interface attached to the VM in the outputs.tf file:
output “vm_ip_addr” {
value = azurerm_network_interface.main.private_ip_address
}

Now, let’s go ahead and apply the configuration:
$ terraform apply –auto-approve

Outputs:
vm_ip_addr = “10.0.2.4”

After Terraform has applied the configuration, it shows the outputs at the end of the console result.

You can run the following to inspect the output anytime later:
$ terraform output
vm_ip_addr = “10.0.2.4”

Outputs are stored in the state file like everything else, so let’s look at how we can manage Terraform state using the CLI.

Managing Terraform state

Terraform stores the configuration it manages in state files and therefore provides a command for advanced state management. The terraform state command helps you manage the state of the current configuration. While the state file is plaintext and you can manually modify it, using the terraform state command is recommended.

But before we get into details, we must understand why we want to do that. Things might not always go according to plan, so the state file may have corrupt data. You also might want to see specific attributes of a particular resource after you’ve applied it. The state file might need to be investigated for the root cause analysis of a specific infrastructure provisioning problem. Let’s have a look at the most common use cases.

Leave a Reply

Your email address will not be published. Required fields are marked *