.
├── main.tf # ресурсы/модули
├── variables.tf # входные переменные
├── outputs.tf # выходные значения
├── versions.tf # required_version + required_providers
├── locals.tf # локальные вычисления (опционально)
└── env/
├── dev.tfvars
└── prod.tfvars terraform fmt -recursive
terraform validate # 1. Провайдер (Плагин для API AWS)
provider "aws" {
region = "us-east-1"
}
# 2. Находим свежий AMI Ubuntu автоматически (хардкод AMI сломается при смене региона)
data "aws_ami" "ubuntu" {
most_recent = true
owners = ["099720109477"] # Canonical
filter {
name = "name"
values = ["ubuntu/images/hvm-ssd/ubuntu-*-amd64-server-*"]
}
}
# 3. Ресурс (То, что мы создаём)
resource "aws_instance" "app_server" {
ami = data.aws_ami.ubuntu.id # Всегда актуальный образ
instance_type = "t2.micro" # 1 CPU, 1 GB RAM
tags = {
Name = "Production-App"
Environment = "Prod"
}
}
# 3. Output (Что вернуть после создания)
output "instance_ip" {
value = aws_instance.app_server.public_ip
description = "Публичный IP созданного сервера"
} variable "instance_count" {
description = "Сколько серверов создать"
type = number
default = 2
}
resource "aws_instance" "web" {
count = var.instance_count # Цикл
ami = data.aws_ami.ubuntu.id
instance_type = "t2.micro"
} terraform plan -var-file=env/dev.tfvars
terraform apply -var-file=env/prod.tfvars terraform state list
terraform state show aws_instance.app_server - name: Configure Web Server
hosts: webservers # Группа из inventory файла
become: true # sudo
tasks:
- name: Install Nginx
apt:
name: nginx
state: present
update_cache: yes
- name: Start Nginx
service:
name: nginx
state: started
enabled: yes - name: Configure Web Server
hosts: webservers
become: true
tasks:
- name: Install Nginx
apt:
name: nginx
state: present
update_cache: yes
- name: Put nginx config
copy:
src: nginx.conf
dest: /etc/nginx/nginx.conf
notify: restart nginx
handlers:
- name: restart nginx
service:
name: nginx
state: restarted locals {
common_tags = {
Project = "demo"
Environment = "dev"
}
}
resource "aws_instance" "app_server" {
# ...
tags = local.common_tags
} terraform plan terraform import aws_instance.app_server i-0123456789abcdef0 moved {
from = aws_instance.web
to = aws_instance.app_server
} terraform {
required_providers {
docker = {
source = "kreuzwerker/docker"
version = "~> 3.0.1"
}
}
}
provider "docker" {}
resource "docker_image" "nginx" {
name = "nginx:stable-alpine"
keep_locally = false
}
resource "docker_container" "nginx" {
image = docker_image.nginx.image_id
name = "tutorial"
ports {
internal = 80
external = 8000
}
}