Урок 8-10: Переменные и внешние файлы
Часть 1: Работа с переменными (Variables)
Объявление переменных
Файл: variables.tf
variable "aws_region" {
description = "AWS region where resources will be created"
type = string
default = "us-west-2"
}
variable "instance_type" {
description = "EC2 instance type"
type = string
default = "t2.micro"
}
variable "environment" {
description = "Environment name"
type = string
validation {
condition = contains(["dev", "staging", "prod"], var.environment)
error_message = "Environment must be dev, staging, or prod."
}
}
variable "tags" {
description = "Common tags for all resources"
type = map(string)
default = {
Project = "MyApp"
Owner = "DevOps"
}
}
variable "cidr_blocks" {
description = "CIDR blocks for security group"
type = list(string)
default = ["0.0.0.0/0"]
}
Типы переменных
| Тип | Пример | Описание |
|---|---|---|
| string | "us-west-2" | Текстовая строка |
| number | 42 | Числовое значение |
| bool | true | Булево значение |
| list(string) | ["a", "b", "c"] | Список строк |
| map(string) | {name = "value"} | Словарь/объект |
| object | {id = "123", name = "test"} | Сложный объект |
| any | - | Любой тип |
Использование переменных в коде
provider "aws" {
region = var.aws_region
}
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = var.instance_type
tags = merge(
var.tags,
{
Name = "web-server"
Environment = var.environment
}
)
}
resource "aws_security_group" "web" {
name = "web-sg"
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = var.cidr_blocks
}
}
Часть 2: Автоматическое заполнение переменных (.tfvars)
Файл: terraform.tfvars
aws_region = "us-west-2"
instance_type = "t2.micro"
environment = "production"
tags = {
Project = "WebApp"
Owner = "DevOps"
CostCenter = "Engineering"
}
cidr_blocks = ["0.0.0.0/0"]
Различные файлы переменных для окружений
Файл: dev.tfvars
aws_region = "us-west-2"
instance_type = "t2.micro"
environment = "dev"
cidr_blocks = ["10.0.0.0/8"]
Файл: prod.tfvars
aws_region = "us-east-1"
instance_type = "t2.large"
environment = "prod"
cidr_blocks = ["10.0.0.0/8", "172.16.0.0/12"]
Использование различных файлов переменных
# Для разработки
terraform apply -var-file="dev.tfvars"
# Для production
terraform apply -var-file="prod.tfvars"
# Переопределить конкретную переменную
terraform apply -var-file="prod.tfvars" -var="instance_type=t2.xlarge"
Часть 3: Локальные переменные (Locals)
Объявление локальных переменных
Файл: main.tf или locals.tf
locals {
common_tags = {
Project = "MyApp"
Owner = "DevOps"
ManagedBy = "Terraform"
CreatedAt = timestamp()
}
instance_name = "${var.environment}-web-server"
# Условные переменные
instance_type = var.environment == "prod" ? "t2.large" : "t2.micro"
# Вычисленные значения
region_prefix = substr(var.aws_region, 0, 2)
}
Использование локальных переменных
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = local.instance_type
tags = merge(
local.common_tags,
{
Name = local.instance_name
}
)
}
Часть 4: Работа с внешними файлами
File - Статический внешний файл
Файл: user-data.sh
#!/bin/bash
set -e
echo "Updating system packages..."
apt-get update
apt-get install -y curl wget
echo "Installing nginx..."
apt-get install -y nginx
echo "Starting nginx..."
systemctl start nginx
systemctl enable nginx
echo "Setup completed!"
Использование в Terraform:
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
user_data = file("${path.module}/user-data.sh")
tags = {
Name = "web-server"
}
}
Templatefile - Динамический внешний файл
Файл: user-data.tpl
#!/bin/bash
set -e
echo "Environment: ${environment}"
echo "Region: ${region}"
echo "Installing packages: ${packages}"
apt-get update
apt-get install -y ${packages}
echo "Setup completed for ${environment}!"
Использование в Terraform:
locals {
user_data_vars = {
environment = var.environment
region = var.aws_region
packages = "nginx curl wget"
}
}
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
user_data = templatefile("${path.module}/user-data.tpl", local.user_data_vars)
tags = {
Name = "web-server"
}
}
Jsonencode и Yamlencode
Генерация JSON конфигурации:
locals {
config = {
version = "1.0"
app = {
name = "myapp"
port = 8080
debug = var.environment != "prod"
}
database = {
host = "db.example.com"
port = 5432
username = var.db_user
}
}
}
resource "aws_secretsmanager_secret_version" "config" {
secret_id = aws_secretsmanager_secret.app_config.id
secret_string = jsonencode(local.config)
}
Часть 5: Переменные окружения
Использование переменных окружения
# Экспортировать переменные
export TF_VAR_aws_region="eu-west-1"
export TF_VAR_environment="production"
export TF_VAR_instance_type="t2.large"
# Terraform автоматически прочитает эти переменные
terraform plan
Приоритет значений переменных
Из высокого к низкому приоритету:
1. Флаг -var в命令 строке: terraform apply -var="region=eu-west-1"
2. Переменные окружения: TF_VAR_region="eu-west-1"
3. Файл terraform.tfvars
4. Файл *.auto.tfvars
5. Значение по умолчанию в variables.tf
Полный пример: Веб-сервер с переменными
Структура проекта
terraform-web-server/
├── provider.tf
├── variables.tf
├── locals.tf
├── main.tf
├── outputs.tf
├── terraform.tfvars
├── dev.tfvars
├── prod.tfvars
├── user-data.sh
└── user-data.tpl
Файл: variables.tf
variable "aws_region" {
type = string
default = "us-west-2"
}
variable "environment" {
type = string
validation {
condition = contains(["dev", "prod"], var.environment)
error_message = "Environment must be dev or prod."
}
}
variable "instance_count" {
type = number
default = 1
}
Файл: locals.tf
locals {
instance_type = var.environment == "prod" ? "t2.large" : "t2.micro"
common_tags = {
Environment = var.environment
ManagedBy = "Terraform"
}
}
Файл: main.tf
resource "aws_instance" "web" {
count = var.instance_count
ami = "ami-0c55b159cbfafe1f0"
instance_type = local.instance_type
user_data = templatefile("${path.module}/user-data.tpl", {
environment = var.environment
region = var.aws_region
packages = "nginx"
})
tags = merge(
local.common_tags,
{
Name = "${var.environment}-web-${count.index + 1}"
}
)
}
Использование
# Для разработки
terraform apply -var-file="dev.tfvars"
# Для production
terraform apply -var-file="prod.tfvars" -var="instance_count=3"
# С переменными окружения
export TF_VAR_environment="prod"
terraform plan