Terraform için Azure Uzak Backend Oluşturma
Basit test scriptleri veya geliştirme ortamları için bir yerel state dosyası uygun olacaktır. Ancak, bir ekip içinde çalışıyorsak, altyapımızı bir CI/CD aracından dağıtıyorsak veya birden çok katman kullanarak bir Terraform geliştiriyorsak, hatalardan kaçınmak veya mevcut altyapıya zarar vermemek için state dosyasını uzak bir backend’de depolamamız ve dosyayı kilitlememiz gerekir. .
Dosyalarımızı güvende tutmak ve birden çok kullanıcı arasında paylaşmak için Azure Storage, Google Cloud Storage, Amazon S3 ve HashiCorp Terraform Cloud & Terraform Enterprise gibi uzak backendleri kullanabiliriz. Bu makalede, Azure CLI, PowerShell ve Terraform kullanarak Terraform için bir Uzak backend oluşturmak üzere Microsoft Azure Storage kullanma prosedürüne adım adım göz atacağız.
Service Principal ve Client Secret Oluşturma
SPN olarak da bilinen bir Service Principal kullanmak, DevOps veya CI/CD ortamları için en iyi yöntemdir ve uzak bir backend kurmanın ve daha sonra Azure DevOps gibi CI/CD’ye geçmenin en popüler yollarından biridir.
Öncelikle, Azure’da kimlik doğrulaması yapmamız gerekiyor. Azure CLI kullanarak kimlik doğrulaması yapmak için şunu yazıyoruz:
az login
İşlem tarayıcıyı başlatacak ve kimlik doğrulama tamamlandıktan sonra hazır olacaktır.
Azure aboneliklerinin listesini almak için aşağıdaki komutu çalıştırabilirsiniz:
az account list --output table
Aşağıdaki komutu kullanarak istediğiniz aboneliği seçebiliriz (hem abonelik kimliği hem de abonelik adı kabul edilir):
az account set --subscription <Azure-SubscriptionId>
Ardından, aşağıdaki komutu kullanarak service principal hesabını oluşturun:
az ad sp create-for-rbac --role="Contributor"
--scopes="/subscriptions/SUBSCRIPTION_ID"
Bir seçenek olarak, açıklayıcı bir ad eklemek için -name parametresini ekleyebiliriz.
az ad sp create-for-rbac --role="Contributor"
--scopes="/subscriptions/SUBSCRIPTION_ID" --name="Azure-DevOps"
Bu değerler şu Terraform değişkenlerine eşlenecektir:
- appId (Azure) → client_id (Terraform)
- password (Azure) → client_secret (Terraform)
- tenant (Azure) → tenant_id (Terraform)
Uzak Backend, Azure Depolama kullanacak şekilde yapılandırma (Azure CLI)
Bash veya Azure Cloud Shell’de Azure Storage hesabı oluşturmak için aşağıdaki Azure CLI betiğini kullanabilirsiniz:
RESOURCE_GROUP_NAME=msazureturkey-tstate-rg
STORAGE_ACCOUNT_NAME=msazureturkeytfstate$RANDOM
CONTAINER_NAME=tfstate
az group create --name $RESOURCE_GROUP_NAME --location "West Europe"
az storage account create --resource-group $RESOURCE_GROUP_NAME --name $STORAGE_ACCOUNT_NAME --sku Standard_LRS --encryption-services blob
ACCOUNT_KEY=$(az storage account keys list --resource-group $RESOURCE_GROUP_NAME --account-name $STORAGE_ACCOUNT_NAME --query [0].value -o tsv)
az storage container create --name $CONTAINER_NAME --account-name $STORAGE_ACCOUNT_NAME --account-key $ACCOUNT_KEY
echo "storage_account_name: $STORAGE_ACCOUNT_NAME"
echo "container_name: $CONTAINER_NAME"
echo "access_key: $ACCOUNT_KEY"
Uzak Backend, Azure Depolama kullanacak şekilde yapılandırma (Azure PowerShell)
Azure Storage hesabı oluşturmak için aşağıdaki Azure PowerShell betiğini kullanabilirsiniz:
# Variables
$azureSubscriptionId = "9c242362-6776-47d9-9db9-2aab2449703"
$resourceGroup = "msazureturkey-tstate-rg"
$location = "westeurope"
$random = -join ((0..9) | Get-Random -Count 5 | % {$_})
$accountName = "msazureturkeytfstate" + $random
$containerName = "tfstate"
# Set Default Subscription
Select-AzSubscription -SubscriptionId $azureSubscriptionId
New-AzResourceGroup -Name $resourceGroup -Location $location -Force
$storageAccount = New-AzStorageAccount `
-ResourceGroupName $resourceGroup `
-Name $accountName `
-Location $location `
-SkuName Standard_RAGRS `
-Kind StorageV2
$storageKey = (Get-AzStorageAccountKey `
-ResourceGroupName $resourceGroup `
-Name $accountName).Value[0]
$ctx = $storageAccount.Context
$container = New-AzStorageContainer `
-Name $containerName `
-Context $ctx -Permission blob# Results
Write-Host
Write-Host ("Storage Account Name: " + $accountName)
Write-Host ("Container Name: " + $container.Name)
Write-Host ("Access Key: " + $storageKey)
Uzak Backend Azure Depolamayı Terraform ile kullanacak şekilde yapılandırma
Azure Storage’da depolama hesabı oluşturmak için Terraform’u da kullanabiliriz.
az-remote-backend-variables.tf adlı bir dosya oluşturmaya ve kodu eklemeye başlayacağız:
# company
variable "company" {
type = string
description = "This variable defines the name of the company"
}
# environment
variable "environment" {
type = string
description = "This variable defines the environment to be built"
}
# azure region
variable "location" {
type = string
description = "Azure region where the resource group will be created"
default = "north europe"
}
Ardından, depolama hesabını yapılandıracak az-remote-backend-main.tf dosyasını oluşturuyoruz:
# Generate a random storage name
resource "random_string" "tf-name" {
length = 8
upper = false
number = true
lower = true
special = false
}
# Create a Resource Group for the Terraform State File
resource "azurerm_resource_group" "state-rg" {
name = "${lower(var.company)}-tfstate-rg"
location = var.location lifecycle {
prevent_destroy = true
}
tags = {
environment = var.environment
}
}
# Create a Storage Account for the Terraform State File
resource "azurerm_storage_account" "state-sta" {
depends_on = [azurerm_resource_group.state-rg]
name = "${lower(var.company)}tf${random_string.tf-name.result}"
resource_group_name = azurerm_resource_group.state-rg.name
location = azurerm_resource_group.state-rg.location
account_kind = "StorageV2"
account_tier = "Standard"
access_tier = "Hot"
account_replication_type = "ZRS"
enable_https_traffic_only = true
lifecycle {
prevent_destroy = true
}
tags = {
environment = var.environment
}
}
# Create a Storage Container for the Core State File
resource "azurerm_storage_container" "core-container" {
depends_on = [azurerm_storage_account.state-sta]
name = "core-tfstate"
storage_account_name = azurerm_storage_account.state-sta.name
}
Son olarak, çıktıyı gösterecek az-remote-backend-output.tf dosyasını oluşturuyoruz:
output "terraform_state_resource_group_name" {
value = azurerm_resource_group.state-rg.name
}
output "terraform_state_storage_account" {
value = azurerm_storage_account.state-sta.name
}
output "terraform_state_storage_container_core" {
value = azurerm_storage_container.core-container.name
}
Uzak Backend State Dosyalarını kullanmak için SPN kullanarak Azure’da Kimlik Doğrulama
SPN ile uzak bir backend’de paylaşılan state dosyalarını kullanmak istiyorsak, Terraform’u aşağıdaki prosedürü kullanarak yapılandırabiliriz:
Kimlik bilgileriyle bir yapılandırma dosyası oluşturacağız. Bu örnek için azurecreds.conf dosyasını çağırdım. Bu dosyanın içeriği:
ARM_SUBSCRIPTION_ID=" "
ARM_CLIENT_ID = " "
ARM_CLIENT_SECRET=" "
ARM_TENANT_ID=" "
Ardından Provider-main.tf dosyasını oluşturup Terraform ve Azure sağlayıcılarını yönetmek için kodu ekliyoruz:
# Define Terraform provider
terraform {
required_version = ">= 0.12"
backend "azurerm" {
resource_group_name = "msazureturkey-tfstate-rg"
storage_account_name = "msazureturkeytfstate"
container_name = "core-tfstate"
key = "core.msazureturkey.tfstate"
}
}
# Configure the Azure provider
provider "azurerm" {
environment = "public"
}
Son olarak, bu komutu kullanarak Terraform konfigürasyonunu başlatıyoruz:
terraform init -backend-config=azurecreds.conf
Ardından, terraform’u çalıştırabiliriz:
terraform apply -auto-approve