Terraform

Terraform

__HTML_TAG_67_ Todos los comandos_HTML_TAG_68___ __HTML_TAG_71_ Comandos completos de Terraform y flujos de trabajo de Infraestructura como Código (IaC), incluyendo la gestión de recursos, operaciones estatales y despliegues multicloud. ## Instalación > Configuración |Command|Description| |---------|-------------| |__INLINE_CODE_16__|Show Terraform version| |__INLINE_CODE_17__|Show help information| |__INLINE_CODE_18__|Show help for specific command| ## Core Workflow ### Operaciones básicas |Command|Description| |---------|-------------| |__INLINE_CODE_19__|Initialize working directory| |__INLINE_CODE_20__|Create execution plan| |__INLINE_CODE_21__|Apply changes| |__INLINE_CODE_22__|Destroy infrastructure| |__INLINE_CODE_23__|Validate configuration| |__INLINE_CODE_24__|Format configuration files| ## Advanced Planning |Command|Description| |---------|-------------| |__INLINE_CODE_25__|Save plan to file| |__INLINE_CODE_26__|Apply saved plan| |__INLINE_CODE_27__|Plan specific resource| |__INLINE_CODE_28__|Plan with variables| |__INLINE_CODE_29__|Plan with variable file| _ ## State Management ## State Operations |Command|Description| |---------|-------------| |__INLINE_CODE_30__|List resources in state| |__INLINE_CODE_31__|Show resource details| |__INLINE_CODE_32__|Move resource in state| |__INLINE_CODE_33__|Remove resource from state| |__INLINE_CODE_34__|Download remote state| |__INLINE_CODE_35__|Upload state to remote| _ ## State Backup and Recovery |Command|Description| |---------|-------------| |__INLINE_CODE_36__|Create state backup| |__INLINE_CODE_37__|Force unlock state| |__INLINE_CODE_38__|Update state with real resources| ## Workspaces |Command|Description| |---------|-------------| |__INLINE_CODE_39__|List workspaces| |__INLINE_CODE_40__|Create new workspace| |__INLINE_CODE_41__|Switch to workspace| |__INLINE_CODE_42__|Delete workspace| |__INLINE_CODE_43__|Show current workspace| ## Importación y salida ## Import Resources |Command|Description| |---------|-------------| |__INLINE_CODE_44__|Import existing resource| |__INLINE_CODE_45__|Import AWS instance| _ ### Outputs |Command|Description| |---------|-------------| |__INLINE_CODE_46__|Show all outputs| |__INLINE_CODE_47__|Show specific output| |__INLINE_CODE_48__|Show outputs in JSON| _ ## Ejemplos de configuración ## Basic AWS EC2 Instance
provider "aws" \\\\{
  region = "us-west-2"
\\\\}

resource "aws_instance" "example" \\\\{
  ami           = "ami-0c55b159cbfafe1d0"
  instance_type = "t2.micro"

  tags = \\\\{
    Name = "example-instance"
  \\\\}
\\\\}

output "instance_ip" \\\\{
  value = aws_instance.example.public_ip
\\\\}
## Variables
variable "instance_type" \\\\{
  description = "EC2 instance type"
  type        = string
  default     = "t2.micro"
\\\\}

variable "environment" \\\\{
  description = "Environment name"
  type        = string
\\\\}
### Fuentes de datos
data "aws_ami" "ubuntu" \\\\{
  most_recent = true
  owners      = ["099720109477"] # Canonical

  filter \\\\{
    name   = "name"
    values = ["ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*"]
  \\\\}
\\\\}
### Módulos
module "vpc" \\\\{
  source = "terraform-aws-modules/vpc/aws"

  name = "my-vpc"
  cidr = "10.0.0.0/16"

  azs             = ["us-west-2a", "us-west-2b"]
  private_subnets = ["10.0.1.0/24", "10.0.2.0/24"]
  public_subnets  = ["10.0.101.0/24", "10.0.102.0/24"]

  enable_nat_gateway = true
  enable_vpn_gateway = true
\\\\}
## Configuración remota del Estado ### S3 Backend
terraform \\\\{
  backend "s3" \\\\{
    bucket = "my-terraform-state"
    key    = "state/terraform.tfstate"
    region = "us-west-2"
  \\\\}
\\\\}
## Azure Backend
terraform \\\\{
  backend "azurerm" \\\\{
    resource_group_name  = "tfstate"
    storage_account_name = "tfstate"
    container_name       = "tfstate"
    key                  = "prod.terraform.tfstate"
  \\\\}
\\\\}
### Google Cloud Backend
terraform \\\\{
  backend "gcs" \\\\{
    bucket = "tf-state-bucket"
    prefix = "terraform/state"
  \\\\}
\\\\}
## Configuración del proveedor ### AWS Provider
provider "aws" \\\\{
  region  = "us-west-2"
  profile = "default"

  default_tags \\\\{
    tags = \\\\{
      Environment = "production"
      Project     = "my-project"
    \\\\}
  \\\\}
\\\\}
## Azure Provider
provider "azurerm" \\\\{
  features \\\\{\\\\}

  subscription_id = "00000000-0000-0000-0000-000000000000"
  tenant_id       = "00000000-0000-0000-0000-000000000000"
\\\\}
### Google Cloud Provider
provider "google" \\\\{
  project = "my-project-id"
  region  = "us-central1"
  zone    = "us-central1-c"
\\\\}
## Características avanzadas ### Recursos condicionales
resource "aws_instance" "example" \\\\{
  count = var.create_instance ? 1 : 0

  ami           = data.aws_ami.ubuntu.id
  instance_type = var.instance_type
\\\\}
## Para cada uno
resource "aws_instance" "example" \\\\{
  for_each = toset(var.instance_names)

  ami           = data.aws_ami.ubuntu.id
  instance_type = var.instance_type

  tags = \\\\{
    Name = each.key
  \\\\}
\\\\}
### Dynamic Blocks
resource "aws_security_group" "example" \\\\{
  name = "example"

  dynamic "ingress" \\\\{
    for_each = var.ingress_rules
    content \\\\{
      from_port   = ingress.value.from_port
      to_port     = ingress.value.to_port
      protocol    = ingress.value.protocol
      cidr_blocks = ingress.value.cidr_blocks
    \\\\}
  \\\\}
\\\\}
Testing and Validation ## Terraform Validate |Command|Description| |---------|-------------| |__INLINE_CODE_49__|Validate syntax| |__INLINE_CODE_50__|Validate with JSON output| ### Terraform Plan Analysis |Command|Description| |---------|-------------| |__INLINE_CODE_51__|Plan with detailed exit codes| |__INLINE_CODE_52__|Show current state| |__INLINE_CODE_53__|Show state in JSON| ### Herramientas de terceros |Command|Description| |---------|-------------| |__INLINE_CODE_54__|Terraform linter| |__INLINE_CODE_55__|Generate documentation| |__INLINE_CODE_56__|Security scanning| |__INLINE_CODE_57__|Security analysis| ## Debugging and Troubleshooting ### Logging |Command|Description| |---------|-------------| |__INLINE_CODE_58__|Enable debug logging| |__INLINE_CODE_59__|Enable trace logging| |__INLINE_CODE_60__|Log to file| ### Problemas comunes |Command|Description| |---------|-------------| |__INLINE_CODE_61__|Sync state with reality| |__INLINE_CODE_62__|Mark resource for recreation| |__INLINE_CODE_63__|Remove taint from resource| _ ## Buenas prácticas ### File Organization
project/
├── main.tf              # Main configuration
├── variables.tf         # Variable definitions
├── outputs.tf          # Output definitions
├── versions.tf         # Provider versions
├── terraform.tfvars   # Variable values
└── modules/
    └── vpc/
        ├── main.tf
        ├── variables.tf
        └── outputs.tf
### Version Constraints
terraform \\\\{
  required_version = ">= 1.0"

  required_providers \\\\{
    aws = \\\\{
      source  = "hashicorp/aws"
      version = "~> 5.0"
    \\\\}
  \\\\}
\\\\}
### Resource Naming
resource "aws_instance" "web_server" \\\\{
  # Use descriptive names
  ami           = data.aws_ami.ubuntu.id
  instance_type = var.instance_type

  tags = \\\\{
    Name        = "$\\\\{var.project_name\\\\}-web-$\\\\{var.environment\\\\}"
    Environment = var.environment
    Project     = var.project_name
  \\\\}
\\\\}
## Seguridad Buenas Prácticas 1. ** Seguridad del Estado**: Usar el estado remoto con cifrado 2. **Secrets Management**: Use tiendas secretas externas 3. ** Control de acceso**: Implementar políticas de IAM adecuadas 4. **Code Review**: Review all infrastructure changes 5. **Scanning**: Use herramientas de análisis de seguridad ### Performance Optimization 1. **Parallelism**: Use `-parallelism` flag for large deployments 2. **Targeting**: Use `-target` para recursos específicos 3. ** Dividir estados**: dividir estados grandes en pequeños 4. **Module Design**: Diseño de módulos reutilizables