Container creation with Terraform
1
Terraform Installation
## Update packages
sudo apt update && sudo apt upgrade -y
## Install dependencies
sudo apt install -y wget unzip gpg
## Add GPG key
wget -O- https://apt.releases.hashicorp.com/gpg | gpg --dearmor | sudo tee /usr/share/keyrings/hashicorp-archive-keyring.gpg
## Add Hashicorp repository
echo "deb [signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/hashicorp.list
sudo apt update
## Terraform install
sudo apt install terraform -y
## Installation confirmation
terraform -v2
3
Files content
provider.tf
terraform {
required_providers {
azurerm = {
source = "hashicorp/azurerm"
version = ">= 3.0.0"
}
}
}
provider "azurerm" {
features {}
client_id = var.azure_client_id
client_secret = var.azure_client_secret
tenant_id = var.azure_tenant_id
subscription_id = var.azure_subscription_id
}main.tf
data "azurerm_resource_group" "rg" {
name = "rg_mas-rrn"
}
resource "azurerm_container_group" "client1" {
name = "${var.dns_name_label}-website"
location = "westeurope"
resource_group_name = data.azurerm_resource_group.rg.name
os_type = "Linux"
dns_name_label = var.dns_name_label
image_registry_credential {
server = "index.docker.io"
username = var.dockerhub_username
password = var.dockerhub_password
}
container {
name = "company-hello-world"
image = "rht19/nginx-hello:latest"
cpu = "1"
memory = "1.5"
ports {
port = 80
protocol = "TCP"
}
}
ip_address_type = "Public"
tags = {
environment = "demo"
}
}variables.tf
variable "azure_client_id" {}
variable "azure_client_secret" {}
variable "azure_tenant_id" {}
variable "azure_subscription_id" {}
variable "dockerhub_username" {}
variable "dockerhub_password" {}
variable "dns_name_label" {}terraform.tfvars
azure_client_id = "xxx"
azure_client_secret = "xxx"
azure_tenant_id = "xxx"
azure_subscription_id = "xxx"
dockerhub_username = "xxx"
dockerhub_password = "xxx"
dns_name_label = "clientName"4
Terraform commands to launch creation
## Show what terraform understand with config files
terraform plan
## Apply infrastructure (--auto-approve replace "yes" later)
terraform apply -auto-approve
## Remove infrastructure
terraform destroy -auto-approve
## Show saved state (Terraform save state of an infrastructure in different files
terraform state list
## Remove saved state
terraform state rm <stateName>Last updated