How Terraform works, drawn — the terraform command on our workstation, the AWS provider it downloads, the EC2 API calls that create and destroy an instance, and the state file that ties the code to what Terraform made, while an instance made by hand stays outside it.
Terraform turns code that describes cloud resources into the resources themselves.
- Terraform is a program on our workstation, run as a command in the terminal.
- The code,
main.tf, says what we want: here one EC2 instance, EC2-B. - The AWS provider program, downloaded from the Terraform Registry, turns Terraform's plan into calls to AWS's API.
- The state,
terraform.tfstate, records what Terraform made, so it can find it again.
Reading the drawing
- Our workstation, the dashed frame on the left, holds everything Terraform needs:
- the terminal, where we type the commands;
- Terraform: the core program, the AWS provider program once it runs, and the last plan;
- the project's directory:
main.tf beside terraform.tfstate.
- The Terraform Registry, top right: where
terraform init downloads the AWS provider program from, as a zip
built for our workstation's system. - AWS, right: the EC2 API and the account's instances.
- EC2-A was made by hand in the console; EC2-B is made by Terraform.
- The events, far right: each step's explanation.
The state
The state is how Terraform knows which real resources are its own.
- It maps each name in the code (
aws_instance.b) to a real resource's id (i-0b7e4c2f9a1d36e85). plan and destroy start from it: they look up only the ids it lists.- A resource missing from it, like EC2-A, is invisible to Terraform: it is neither changed nor destroyed.
- It starts as a local file on our workstation. A later scene moves it to an S3 bucket, with a
backend "s3"
block and terraform init -migrate-state, so a team can work from the same state.