Terraform O`rnatish va Sozlash
Terraform ni o'rnatish
Linux (Ubuntu/Debian) da o'rnatish
Usul 1: HashiCorp repository orqali (Tavsiya etiladi)
# 1. System paketlarini yangilash
sudo apt-get update && sudo apt-get install -y gnupg software-properties-common
# 2. HashiCorp GPG kalitini qo'shish
wget -O- https://apt.releases.hashicorp.com/gpg | \
gpg --dearmor | \
sudo tee /usr/share/keyrings/hashicorp-archive-keyring.gpg
# 3. GPG kalitini tekshirish
gpg --no-default-keyring \
--keyring /usr/share/keyrings/hashicorp-archive-keyring.gpg \
--fingerprint
# 4. HashiCorp repository qo'shish
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
# 5. Paketlar ro'yxatini yangilash
sudo apt update
# 6. Terraform o'rnatish
sudo apt-get install terraform
# 7. Versiyani tekshirish
terraform -version
Usul 2: Binary faylni yuklab olish
# 1. Terraform binary yuklab olish
TERRAFORM_VERSION="1.6.5"
wget https://releases.hashicorp.com/terraform/${TERRAFORM_VERSION}/terraform_${TERRAFORM_VERSION}_linux_amd64.zip
# 2. Unzip qilish
unzip terraform_${TERRAFORM_VERSION}_linux_amd64.zip
# 3. Binary ni PATH ga ko'chirish
sudo mv terraform /usr/local/bin/
# 4. Ruxsatlarni berish
sudo chmod +x /usr/local/bin/terraform
# 5. Versiyani tekshirish
terraform -version
# 6. Autocomplete o'rnatish
terraform -install-autocomplete
CentOS/RHEL da o'rnatish
# 1. yum-config-manager o'rnatish
sudo yum install -y yum-utils
# 2. HashiCorp repository qo'shish
sudo yum-config-manager --add-repo https://rpm.releases.hashicorp.com/RHEL/hashicorp.repo
# 3. Terraform o'rnatish
sudo yum -y install terraform
# 4. Versiyani tekshirish
terraform -version
macOS da o'rnatish
Usul 1: Homebrew orqali (Tavsiya etiladi)
# 1. Homebrew tap qo'shish
brew tap hashicorp/tap
# 2. Terraform o'rnatish
brew install hashicorp/tap/terraform
# 3. Versiyani tekshirish
terraform -version
# 4. Yangilash
brew upgrade hashicorp/tap/terraform
Usul 2: Binary yuklab olish
# 1. Terraform binary yuklab olish
TERRAFORM_VERSION="1.6.5"
wget https://releases.hashicorp.com/terraform/${TERRAFORM_VERSION}/terraform_${TERRAFORM_VERSION}_darwin_amd64.zip
# 2. Unzip qilish
unzip terraform_${TERRAFORM_VERSION}_darwin_amd64.zip
# 3. Binary ni PATH ga ko'chirish
sudo mv terraform /usr/local/bin/
# 4. Versiyani tekshirish
terraform -version
Windows da o'rnatish
Usul 1: Chocolatey orqali
# PowerShell Administrator sifatida
# 1. Chocolatey bor ekanligini tekshirish
choco --version
# 2. Terraform o'rnatish
choco install terraform
# 3. Versiyani tekshirish
terraform -version
# 4. Yangilash
choco upgrade terraform
Usul 2: Scoop orqali
# 1. Scoop o'rnatilganligini tekshirish
scoop --version
# 2. Terraform o'rnatish
scoop install terraform
# 3. Versiyani tekshirish
terraform -version
Usul 3: Manual o'rnatish
# 1. terraform.io dan ZIP faylni yuklab oling
# https://www.terraform.io/downloads
# 2. ZIP faylni extract qiling, masalan: C:\terraform
# 3. PATH ga qo'shing:
# Windows + R → sysdm.cpl → Advanced → Environment Variables
# Path o'zgaruvchisiga C:\terraform qo'shing
# 4. Yangi terminal ochib tekshiring
terraform -version
Docker container da ishlatish
# 1. Terraform Docker image ni yuklab olish
docker pull hashicorp/terraform:latest
# 2. Container ichida Terraform ishlatish
docker run -it --rm \
-v $(pwd):/workspace \
-w /workspace \
hashicorp/terraform:latest init
# 3. Alias yaratish (.bashrc yoki .zshrc ga)
alias terraform='docker run -it --rm -v $(pwd):/workspace -w /workspace hashicorp/terraform:latest'
# 4. Ishlatish
terraform version
Terraform versiyasini boshqarish
tfenv - Terraform Version Manager
# 1. tfenv o'rnatish (Linux/macOS)
git clone https://github.com/tfutils/tfenv.git ~/.tfenv
echo 'export PATH="$HOME/.tfenv/bin:$PATH"' >> ~/.bashrc
source ~/.bashrc
# 2. Mavjud versiyalarni ko'rish
tfenv list-remote
# 3. Ma'lum versiyani o'rnatish
tfenv install 1.6.5
# 4. Versiyani ishlatish
tfenv use 1.6.5
# 5. O'rnatilgan versiyalarni ko'rish
tfenv list
# 6. Eng oxirgi versiyani o'rnatish
tfenv install latest
# 7. Loyiha uchun .terraform-version fayli yaratish
echo "1.6.5" > .terraform-version
tfenv install
Versiyani tekshirish
# Terraform versiyasi
terraform version
# Batafsil ma'lumot
terraform version -json
# Output:
# Terraform v1.6.5
# on linux_amd64
Terraform asosiy buyruqlari
terraform --help
# Barcha buyruqlarni ko'rish
terraform --help
# Muayyan buyruq haqida ma'lumot
terraform init --help
terraform plan --help
terraform apply --help
Asosiy buyruqlar ro'yxati
# Ishga tushirish
terraform init # Loyihani initialize qilish
terraform validate # Konfiguratsiyani tekshirish
terraform fmt # Kodni formatlash
# Rejalashtirish va qo'llash
terraform plan # O'zgarishlarni ko'rish
terraform apply # O'zgarishlarni qo'llash
terraform destroy # Infratuzilmani yo'q qilish
# State boshqaruvi
terraform state list # State dagi resurslarni ko'rish
terraform state show # Resurs haqida ma'lumot
terraform state rm # Resursni state dan o'chirish
# Workspace
terraform workspace list # Workspace'larni ko'rish
terraform workspace new # Yangi workspace
terraform workspace select # Workspace tanlash
# Boshqa foydali buyruqlar
terraform output # Output qiymatlarini ko'rish
terraform show # State yoki plan'ni ko'rish
terraform graph # Dependency graph yaratish
terraform console # Interactive console
Birinchi Terraform loyihasi
Loyiha tuzilmasini yaratish
# 1. Yangi katalog yaratish
mkdir my-first-terraform
cd my-first-terraform
# 2. Fayl tuzilmasi
touch main.tf
touch variables.tf
touch outputs.tf
touch terraform.tfvars
touch .gitignore
.gitignore fayli
# .gitignore
# Local .terraform directories
**/.terraform/*
# .tfstate files
*.tfstate
*.tfstate.*
# Crash log files
crash.log
crash.*.log
# Exclude all .tfvars files
*.tfvars
*.tfvars.json
# Ignore override files
override.tf
override.tf.json
*_override.tf
*_override.tf.json
# Ignore CLI configuration files
.terraformrc
terraform.rc
# Ignore lock files (optional)
# .terraform.lock.hcl
Oddiy misol - AWS EC2 Instance
main.tf
# Terraform versiyasi va provider
terraform {
required_version = ">= 1.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
# AWS Provider sozlamalari
provider "aws" {
region = var.aws_region
}
# Data source - AMI topish
data "aws_ami" "ubuntu" {
most_recent = true
owners = ["099720109477"] # Canonical
filter {
name = "name"
values = ["ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*"]
}
filter {
name = "virtualization-type"
values = ["hvm"]
}
}
# EC2 Instance
resource "aws_instance" "web" {
ami = data.aws_ami.ubuntu.id
instance_type = var.instance_type
tags = {
Name = var.instance_name
Environment = var.environment
ManagedBy = "Terraform"
}
}
variables.tf
variable "aws_region" {
description = "AWS region"
type = string
default = "us-east-1"
}
variable "instance_type" {
description = "EC2 instance type"
type = string
default = "t2.micro"
}
variable "instance_name" {
description = "EC2 instance name"
type = string
default = "MyFirstTerraformInstance"
}
variable "environment" {
description = "Environment name"
type = string
default = "dev"
}
outputs.tf
output "instance_id" {
description = "EC2 instance ID"
value = aws_instance.web.id
}
output "instance_public_ip" {
description = "Public IP address"
value = aws_instance.web.public_ip
}
output "instance_private_ip" {
description = "Private IP address"
value = aws_instance.web.private_ip
}
output "ami_id" {
description = "AMI ID used"
value = data.aws_ami.ubuntu.id
}
terraform.tfvars (optional)
aws_region = "us-east-1"
instance_type = "t2.micro"
instance_name = "WebServer"
environment = "development"
Loyihani ishga tushirish
# 1. Provider va modullarni yuklab olish
terraform init
# Output:
# Initializing the backend...
# Initializing provider plugins...
# - Finding hashicorp/aws versions matching "~> 5.0"...
# - Installing hashicorp/aws v5.25.0...
# Terraform has been successfully initialized!
# 2. Konfiguratsiyani tekshirish
terraform validate
# Output:
# Success! The configuration is valid.
# 3. Kodni formatlash
terraform fmt
# 4. O'zgarishlarni ko'rish
terraform plan
# Output:
# Terraform will perform the following actions:
# # aws_instance.web will be created
# + resource "aws_instance" "web" {
# + ami = "ami-0c55b159cbfafe1f0"
# + instance_type = "t2.micro"
# ...
# Plan: 1 to add, 0 to change, 0 to destroy.
# 5. Plan'ni faylga saqlash
terraform plan -out=tfplan
# 6. O'zgarishlarni qo'llash
terraform apply
# Yoki saqlangan plan'dan
terraform apply tfplan
# Yoki tasdiqlashsiz
terraform apply -auto-approve
# 7. Output'larni ko'rish
terraform output
# Muayyan output
terraform output instance_public_ip
# 8. State'ni ko'rish
terraform show
# 9. Infratuzilmani yo'q qilish
terraform destroy
# Tasdiqlashsiz
terraform destroy -auto-approve
AWS credentials sozlash
Usul 1: AWS CLI orqali
# 1. AWS CLI o'rnatish
# Linux
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install
# macOS
brew install awscli
# 2. AWS credentials sozlash
aws configure
# Input:
# AWS Access Key ID [None]: AKIAIOSFODNN7EXAMPLE
# AWS Secret Access Key [None]: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
# Default region name [None]: us-east-1
# Default output format [None]: json
# 3. Profile yaratish
aws configure --profile production
# 4. Terraform da profile ishlatish
provider "aws" {
region = "us-east-1"
profile = "production"
}
Usul 2: Environment variables
# Linux/macOS
export AWS_ACCESS_KEY_ID="your-access-key"
export AWS_SECRET_ACCESS_KEY="your-secret-key"
export AWS_DEFAULT_REGION="us-east-1"
# Windows PowerShell
$env:AWS_ACCESS_KEY_ID="your-access-key"
$env:AWS_SECRET_ACCESS_KEY="your-secret-key"
$env:AWS_DEFAULT_REGION="us-east-1"
# .bashrc yoki .zshrc ga qo'shish
echo 'export AWS_ACCESS_KEY_ID="your-access-key"' >> ~/.bashrc
echo 'export AWS_SECRET_ACCESS_KEY="your-secret-key"' >> ~/.bashrc
echo 'export AWS_DEFAULT_REGION="us-east-1"' >> ~/.bashrc
source ~/.bashrc
Usul 3: Shared credentials file
~/.aws/credentials:
[default]
aws_access_key_id = AKIAIOSFODNN7EXAMPLE
aws_secret_access_key = wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
[production]
aws_access_key_id = AKIAI44QH8DHBEXAMPLE
aws_secret_access_key = je7MtGbClwBF/2Zp9Utk/h3yCo8nvbEXAMPLEKEY
~/.aws/config:
[default]
region = us-east-1
output = json
[profile production]
region = us-west-2
output = json
Usul 4: IAM Role (EC2 instance uchun)
# Terraform EC2 instance'da ishlayotganda
provider "aws" {
region = "us-east-1"
# IAM role avtomatik ishlatiladi
}
# Yoki assume role
provider "aws" {
region = "us-east-1"
assume_role {
role_arn = "arn:aws:iam::123456789012:role/TerraformRole"
session_name = "terraform-session"
}
}
Terraform atrof-muhit o'zgaruvchilari
# AWS credentials
export AWS_ACCESS_KEY_ID="your-key"
export AWS_SECRET_ACCESS_KEY="your-secret"
export AWS_DEFAULT_REGION="us-east-1"
# Terraform log level
export TF_LOG=TRACE # Eng batafsil
export TF_LOG=DEBUG # Debug ma'lumotlari
export TF_LOG=INFO # Asosiy ma'lumotlar
export TF_LOG=WARN # Ogohlantirishlar
export TF_LOG=ERROR # Faqat xatolar
# Log faylga yozish
export TF_LOG_PATH="terraform.log"
# Terraform input o'chirish (CI/CD uchun)
export TF_INPUT=false
# Terraform CLI config file
export TF_CLI_CONFIG_FILE="$HOME/.terraformrc"
# Data directory
export TF_DATA_DIR=".terraform"
# Plugin cache directory
export TF_PLUGIN_CACHE_DIR="$HOME/.terraform.d/plugin-cache"
mkdir -p $TF_PLUGIN_CACHE_DIR
# Workspace
export TF_WORKSPACE="development"
# Variable'larni set qilish
export TF_VAR_instance_type="t2.small"
export TF_VAR_environment="production"
Terraform konfiguratsiya fayli
~/.terraformrc (Linux/macOS) yoki %APPDATA%/terraform.rc (Windows)
# Plugin cache katalogi
plugin_cache_dir = "$HOME/.terraform.d/plugin-cache"
# Credentials - Terraform Cloud/Enterprise
credentials "app.terraform.io" {
token = "xxxxxx.atlasv1.zzzzzzzzzzzzz"
}
# Provider installation
provider_installation {
filesystem_mirror {
path = "/usr/share/terraform/providers"
include = ["registry.terraform.io/*/*"]
}
direct {
exclude = ["registry.terraform.io/*/*"]
}
}
# Disable checkpoint (telemetry)
disable_checkpoint = true
disable_checkpoint_signature = true
# Logging
# log_path = "/var/log/terraform.log"
VS Code uchun Terraform sozlamalari
Extension'lar o'rnatish
- HashiCorp Terraform - Official extension
- Terraform - Anton Kulikov
- Terraform Autocomplete - Richard Sentino
settings.json sozlamalari
{
// Terraform extension sozlamalari
"terraform.languageServer.enable": true,
"terraform.experimentalFeatures.validateOnSave": true,
"terraform.experimentalFeatures.prefillRequiredFields": true,
// Format on save
"[terraform]": {
"editor.formatOnSave": true,
"editor.defaultFormatter": "hashicorp.terraform"
},
// Linting
"terraform.validation.enableEnhancedValidation": true,
// Syntax highlighting
"files.associations": {
"*.tf": "terraform",
"*.tfvars": "terraform",
"*.hcl": "terraform"
}
}
Keyboard shortcuts
// keybindings.json
[
{
"key": "ctrl+shift+f",
"command": "terraform.fmt",
"when": "editorTextFocus && editorLangId == terraform"
},
{
"key": "ctrl+shift+v",
"command": "terraform.validate",
"when": "editorTextFocus && editorLangId == terraform"
}
]
Terraform loyiha tuzilmasi (Best practices)
Oddiy loyiha
my-project/
├── main.tf # Asosiy konfiguratsiya
├── variables.tf # Input variables
├── outputs.tf # Outputs
├── terraform.tfvars # Variable values
├── .gitignore # Git ignore qoidalari
└── README.md # Dokumentatsiya
O'rta darajadagi loyiha
my-project/
├── main.tf
├── variables.tf
├── outputs.tf
├── versions.tf # Terraform va provider versiyalari
├── terraform.tfvars
├── modules/ # Local modules
│ ├── vpc/
│ │ ├── main.tf
│ │ ├── variables.tf
│ │ └── outputs.tf
│ └── ec2/
│ ├── main.tf
│ ├── variables.tf
│ └── outputs.tf
├── .gitignore
└── README.md
Katta loyiha (Environments)
my-project/
├── modules/ # Reusable modules
│ ├── vpc/
│ ├── ec2/
│ ├── rds/
│ └── alb/
├── environments/
│ ├── dev/
│ │ ├── main.tf
│ │ ├── variables.tf
│ │ ├── outputs.tf
│ │ ├── terraform.tfvars
│ │ └── backend.tf
│ ├── staging/
│ │ ├── main.tf
│ │ ├── variables.tf
│ │ ├── outputs.tf
│ │ ├── terraform.tfvars
│ │ └── backend.tf
│ └── prod/
│ ├── main.tf
│ ├── variables.tf
│ ├── outputs.tf
│ ├── terraform.tfvars
│ └── backend.tf
├── scripts/ # Helper scripts
│ ├── plan.sh
│ ├── apply.sh
│ └── destroy.sh
├── .gitignore
├── README.md
└── Makefile # Automation
Maslahatlar va yaxshi amaliyotlar
1. Versiyani doim belgilang
terraform {
required_version = ">= 1.0, < 2.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
2. State'ni remote joyda saqlang
terraform {
backend "s3" {
bucket = "my-terraform-state"
key = "prod/terraform.tfstate"
region = "us-east-1"
encrypt = true
dynamodb_table = "terraform-locks"
}
}
3. .gitignore ni to'g'ri sozlang
**/.terraform/*
*.tfstate
*.tfstate.*
*.tfvars
4. Pre-commit hooks ishlatish
# .git/hooks/pre-commit
#!/bin/bash
terraform fmt -check
terraform validate
5. Makefile yaratish
# Makefile
.PHONY: init plan apply destroy
init:
terraform init
validate:
terraform validate
terraform fmt -check
plan:
terraform plan
apply:
terraform apply
destroy:
terraform destroy
clean:
rm -rf .terraform
rm -rf .terraform.lock.hcl
rm -f terraform.tfstate*
Xulosa
Siz endi Terraform'ni: ✅ Turli platformalarda o'rnatishni ✅ Credentials sozlashni ✅ Birinchi loyihani yaratishni ✅ Asosiy buyruqlarni ishlatishni ✅ IDE'ni sozlashni
Bilasiz! Keyingi mavzuda HCL tilini chuqurroq o'rganamiz.