Terraform is a tool for creating, changing, and deleting infrastructure as code. It is a tool for creating and managing infrastructure resources on cloud providers.
The first step in using Terraform is to create a basic project structure.
The entry point of the project should be a main.tf file.
Basic main.tf file (see main.tf):
terraform {
required_providers {
docker = {
source = "kreuzwerker/docker"
version = "3.0.2"
}
}
}
provider "docker" {
# uri to the docker deamon
host = "unix:///$HOME/.docker/run/docker.sock"
}Also, we have to define the provider, in our case docker.
see docker.tf
// This is the same as doing:
// docker pull hashicorp/vault:1.12.6
resource "docker_image" "vault" {
name = "hashicorp/vault:1.12.6"
}
// This is the same as doing:
// docker run -p 8200:8200 --name "terraform-basics-vault" hashicorp/vault:1.12.6
resource "docker_container" "vault" {
name = "terraform-basics-vault"
image = docker_image.vault.image_id
ports {
internal = 8200
external = 8200
}
}To initialize Terraform, you need to run the terraform init command.
This command will download the necessary plugins and dependencies for your Terraform configuration.
To run Terraform plan, you need to run the terraform plan command.
This command will generate a execution plan, which lets you preview the changes that Terraform will make to your infrastructure.
The terraform apply command will create or update your infrastructure based on the changes in your Terraform configuration (e.g. the main.tf file).
After this command, the infrastructure will be created and we can see by running docker ps that the container (with vault server) is running.
Now we can test the vault server by running curl http://localhost:8200/v1/sys/health.
We can update vault server to a new version from name = "hashicorp/vault:1.12.6" to name = "hashicorp/vault:1.17.1" by updating the main.tf file.
To apply the changes, we can run the terraform apply command.
Terraform will destroy the old container and create a new one with the new version.
To check the changes, we can run docker ps and see that the container (with vault server) is running with the new version.
Now we can test the vault server by running curl http://localhost:8200/v1/sys/health.
You should see the new version.
{
"initialized": true,
"sealed": false,
"standby": false,
"performance_standby": false,
"replication_performance_mode": "disabled",
"replication_dr_mode": "disabled",
"server_time_utc": 1733427473,
"version": "1.17.1",
"enterprise": false,
"cluster_name": "vault-cluster-c79068ef",
"cluster_id": "487d3eb4-20cb-8ea6-019d-56429c7d45c4",
"echo_duration_ms": 0,
"clock_skew_ms": 0,
"replication_primary_canary_age_ms": 0
}To destroy the project, we can run the terraform destroy command.
Terraform will destroy the container and all the resources that were created by the Terraform project.
To check the changes, we can run docker ps and see that the container (with vault server) is not running.