Saltar a contenido
_

Pulumi Cheatsheet

Instalación

Platform Command
Linux (curl) INLINE_CODE_10
macOS (Homebrew) INLINE_CODE_11
Windows (Chocolatey) INLINE_CODE_12
Windows (PowerShell) INLINE_CODE_13
Docker INLINE_CODE_14
Python SDK INLINE_CODE_15
Node.js SDK INLINE_CODE_16
Verify Installation INLINE_CODE_17

Language Runtime Requirements

__TABLE_153_

Comandos básicos

Project Management

Command Description
INLINE_CODE_22 Create new project interactively
INLINE_CODE_23 Create project from specific template
INLINE_CODE_24 List all available templates
INLINE_CODE_25 Create project with name, skip prompts
INLINE_CODE_26 Create from custom template URL

Stack Operations

Command Description
INLINE_CODE_27 List all stacks in current project
INLINE_CODE_28 Create new stack named "dev"
INLINE_CODE_29 Switch to "dev" stack
INLINE_CODE_30 Show current stack information
INLINE_CODE_31 Display all stack outputs
INLINE_CODE_32 Get specific output value
INLINE_CODE_33 Export outputs as JSON
INLINE_CODE_34 Delete "dev" stack
INLINE_CODE_35 Rename current stack
INLINE_CODE_36 List resources with URNs

Configuración

Command Description
INLINE_CODE_37 List all configuration values
INLINE_CODE_38 Set configuration value
INLINE_CODE_39 Set encrypted secret value
INLINE_CODE_40 Get configuration value
INLINE_CODE_41 Remove configuration value
INLINE_CODE_42 Set config from file
INLINE_CODE_43 Copy config between stacks

Deployment

Command Description
INLINE_CODE_44 Preview changes without applying (dry run)
INLINE_CODE_45 Show detailed resource differences
INLINE_CODE_46 Deploy infrastructure changes
INLINE_CODE_47 Deploy without confirmation prompt
INLINE_CODE_48 Deploy with 10 parallel operations
INLINE_CODE_49 Destroy all resources in stack
INLINE_CODE_50 Destroy without confirmation
INLINE_CODE_51 Sync state with actual cloud resources
INLINE_CODE_52 Refresh without confirmation
INLINE_CODE_53 Cancel in-progress update

Authentication

Command Description
INLINE_CODE_54 Login to Pulumi Service (SaaS)
INLINE_CODE_55 Login with access token
INLINE_CODE_56 Use S3 as state backend
INLINE_CODE_57 Use Azure Blob as state backend
INLINE_CODE_58 Use local filesystem backend
INLINE_CODE_59 Logout from current backend
INLINE_CODE_60 Show current logged-in user

Advanced Usage

Resource Targeting

Command Description
INLINE_CODE_61 Deploy only specific resource
INLINE_CODE_62 Destroy specific resource
INLINE_CODE_63 Preview resource and its dependents
INLINE_CODE_64 Force replacement of resource

State Management

__TABLE_160_

Policy as Code

Command Description
INLINE_CODE_71 Create new policy pack
INLINE_CODE_72 Publish policy pack to organization
INLINE_CODE_73 Enable policy pack for organization
INLINE_CODE_74 Disable policy pack
INLINE_CODE_75 List all policy packs
INLINE_CODE_76 Run deployment with local policy pack
INLINE_CODE_77 Preview with policy enforcement

Logging and Debugging

Command Description
INLINE_CODE_78 View logs from all resources
INLINE_CODE_79 Stream logs in real-time
INLINE_CODE_80 Filter logs by resource name
INLINE_CODE_81 Show logs from last 2 hours
INLINE_CODE_82 Deploy with verbose debug logging
INLINE_CODE_83 Hide sensitive output values

Secrets Management

__TABLE_163_

Organization Management

Command Description
INLINE_CODE_88 List all organizations
INLINE_CODE_89 Show default organization
INLINE_CODE_90 Set default organization
INLINE_CODE_91 Create new organization

Plugin Management

Command Description
INLINE_CODE_92 List installed plugins
INLINE_CODE_93 Install specific plugin version
INLINE_CODE_94 Remove plugin version

Configuración

Pulumi.yaml (Configuración de proyecto)

name: my-infrastructure
runtime: python
description: Production AWS infrastructure
backend:
  url: s3://my-pulumi-state-bucket

Pulumi.dev.yaml (Stack Configuration)

config:
  aws:region: us-west-2
  myproject:instanceType: t3.micro
  myproject:dbPassword:
    secure: AAABAHVzLXdlc3QtMg==  # Encrypted value
  myproject:environment: development
  myproject:enableMonitoring: "true"

Environment Variables

# Backend configuration
export PULUMI_BACKEND_URL=s3://my-bucket
export PULUMI_CONFIG_PASSPHRASE=mysecretkey

# AWS credentials
export AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE
export AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY

# Pulumi Service
export PULUMI_ACCESS_TOKEN=pul-abc123def456

# Debugging
export PULUMI_DEBUG_COMMANDS=true
export PULUMI_DEBUG_PROMISE_LEAKS=true

.pulumi/ Directory Structure

.pulumi/
├── stacks/
│   ├── dev.json          # Stack-specific state
│   └── production.json
├── backups/              # Automatic state backups
└── plugins/              # Downloaded provider plugins

Common Use Cases

Use Case 1: Create AWS S3 Bucket with Python

# Initialize new project
pulumi new aws-python --name my-s3-project --yes

# Configure AWS region
pulumi config set aws:region us-east-1

# Edit __main__.py to add S3 bucket
cat > __main__.py << 'EOF'
import pulumi
import pulumi_aws as aws

bucket = aws.s3.Bucket('my-bucket',
    acl='private',
    versioning=aws.s3.BucketVersioningArgs(enabled=True),
    tags={'Environment': 'dev', 'Project': 'demo'}
)

pulumi.export('bucket_name', bucket.id)
pulumi.export('bucket_arn', bucket.arn)
EOF

# Preview and deploy
pulumi preview
pulumi up --yes

# Get bucket name
pulumi stack output bucket_name

Use Case 2: Multi-Stack Deployment (Dev/Staging/Prod)

# Create project
pulumi new aws-typescript --yes

# Create and configure dev stack
pulumi stack init dev
pulumi config set aws:region us-west-2
pulumi config set instanceType t3.micro
pulumi config set environment dev

# Create and configure staging stack
pulumi stack init staging
pulumi config set aws:region us-west-2
pulumi config set instanceType t3.small
pulumi config set environment staging

# Create and configure production stack
pulumi stack init production
pulumi config set aws:region us-east-1
pulumi config set instanceType t3.large
pulumi config set environment production

# Deploy to each environment
pulumi stack select dev && pulumi up --yes
pulumi stack select staging && pulumi up --yes
pulumi stack select production && pulumi up --yes

Use Case 3: Kubernetes Deployment with TypeScript

# Create Kubernetes project
pulumi new kubernetes-typescript --yes

# Configure kubeconfig
pulumi config set kubernetes:kubeconfig ~/.kube/config

# Create deployment (index.ts)
cat > index.ts << 'EOF'
import * as k8s from "@pulumi/kubernetes";

const appLabels = { app: "nginx" };
const deployment = new k8s.apps.v1.Deployment("nginx", {
    spec: {
        selector: { matchLabels: appLabels },
        replicas: 3,
        template: {
            metadata: { labels: appLabels },
            spec: { containers: [{ name: "nginx", image: "nginx:1.21" }] }
        }
    }
});

const service = new k8s.core.v1.Service("nginx", {
    spec: {
        type: "LoadBalancer",
        selector: appLabels,
        ports: [{ port: 80, targetPort: 80 }]
    }
});

export const serviceName = service.metadata.name;
export const serviceIP = service.status.loadBalancer.ingress[0].ip;
EOF

# Install dependencies and deploy
npm install
pulumi up --yes

Use Case 4: Infrastructure Testing

# Create project with testing
pulumi new aws-python --yes

# Install testing dependencies
pip install pytest pytest-mock

# Create test file (test_infrastructure.py)
cat > test_infrastructure.py << 'EOF'
import pulumi
import pytest

class MyMocks(pulumi.runtime.Mocks):
    def new_resource(self, args: pulumi.runtime.MockResourceArgs):
        return [args.name + '_id', args.inputs]
    def call(self, args: pulumi.runtime.MockCallArgs):
        return {}

pulumi.runtime.set_mocks(MyMocks())

# Import your infrastructure code
import __main__

@pulumi.runtime.test
def test_bucket_created():
    def check_bucket(args):
        assert args is not None
    return __main__.bucket.arn.apply(check_bucket)
EOF

# Run tests
pytest test_infrastructure.py

Use Case 5: State Migration Between Backends

# Export current state
pulumi stack export --file state-backup.json

# Login to new backend
pulumi login s3://new-state-bucket

# Create stack in new backend
pulumi stack init production

# Import state
pulumi stack import --file state-backup.json

# Verify migration
pulumi preview  # Should show no changes

# Update backend URL in Pulumi.yaml
cat > Pulumi.yaml << 'EOF'
name: my-project
runtime: python
backend:
  url: s3://new-state-bucket
EOF

Buenas prácticas

  • Use Referencias de Stack: Compartir salidas entre pilas con StackReference para crear infraestructura modular. Ejemplo: ref = pulumi.StackReference("org/project/stack")_ entonces accede ref.get_output("vpcId")

  • Configuración de margen: Almacene valores específicos para el medio ambiente en archivos de configuración de pila en lugar de codificación dura. Use pulumi config set para todos los valores variables y --secret bandera para datos sensibles

Protección de recursos de implementación: Proteger los recursos críticos de la eliminación accidental con opción __INLINE_CODE_100_. Uso pulumi.ResourceOptions(protect=True) para bases de datos, recursos estatales

  • Version Control Todo: Commit Pulumi.yaml__, apilar archivos de configuración y código para git. Añadir .pulumi/_ directorio a .gitignore para excluir estado y plugins

  • Use Recursos de Componente: Crear componentes de infraestructura reutilizables al ampliar pulumi.ComponentResource_. Paquete de patrones comunes (configuración VPC, grupo EKS) como componentes

  • Automatizar con CI/CD: Integrar Pulumi en tuberías usando pulumi preview para PRs y pulumi up --yes para implementaciones. Uso PULUMI_ACCESS_TOKEN_ variable ambiente para autenticación

Tag All Resources: Aplicar una estrategia consistente de etiquetado usando el parámetro tags_. Incluir medio ambiente, proyecto, propietario, centro de costos para el seguimiento de costos y organización

Política de habilitación como código: Ejecuta las normas de organización con paquetes de políticas. Validar las configuraciones de recursos, nombrar convenciones y requisitos de seguridad antes del despliegue

  • Respaldos del Estado Regional: estado de la pila de exportación periódicamente con pulumi stack export_. Almacene copias de seguridad en el almacenamiento controlado por la versión o seguro separado del backend primario

  • Utilizar dependencias de gastos: Cuando no se detectan dependencias implícitas, utilice depends_on_ o pulumi.Output.all() para garantizar la correcta ordenación de los recursos

Troubleshooting

Issue Solution
Error: "no stack selected" Run INLINE_CODE_113 or INLINE_CODE_114 to create/select a stack
Error: "conflict: Another update is currently in progress" Run INLINE_CODE_115 to clear stuck update, or wait for other update to complete. Check INLINE_CODE_116 for details
Error: "failed to decrypt" Ensure INLINE_CODE_117 environment variable is set correctly. Run INLINE_CODE_118 to re-encrypt with current passphrase
Provider plugin not found Run INLINE_CODE_119 or delete INLINE_CODE_120 and run INLINE_CODE_121 to auto-download
State file corruption Restore from backup: INLINE_CODE_122. Always keep recent backups with INLINE_CODE_123
Resource already exists error Import existing resource: INLINE_CODE_124 or use INLINE_CODE_125 option in resource definition
Out of sync state Run INLINE_CODE_126 to sync state with actual cloud resources. Review changes before confirming
Secrets not decrypting Verify backend access and encryption key. For Pulumi Service, check INLINE_CODE_127. For self-managed, verify INLINE_CODE_128
Performance issues with large stacks Increase parallelism: INLINE_CODE_129. Split into multiple smaller stacks using stack references
"pulumi" command not found Add Pulumi to PATH: INLINE_CODE_130 (Linux/macOS) or reinstall with package manager
TypeScript compilation errors Run INLINE_CODE_131 to ensure dependencies are installed. Check INLINE_CODE_132 for correct configuration
Python import errors Activate virtual environment and run INLINE_CODE_133. Verify Python version is 3.7+

Quick Reference: Resource URNs

Recursos URNs identifica singularmente recursos en formato: urn:pulumi:<stack>::<project>::<type>::<name>

# Get URN from stack output
pulumi stack --show-urns

# Use URN for targeted operations
pulumi up --target urn:pulumi:dev::my-project::aws:s3/bucket:Bucket::my-bucket
pulumi state unprotect urn:pulumi:dev::my-project::aws:rds/instance:Instance::db

# Export specific resource details
pulumi stack export | jq '.deployment.resources[] | select(.urn | contains("my-bucket"))'

Quick Referencia: Proveedores comunes

Provider Installation Import Statement
AWS INLINE_CODE_135 INLINE_CODE_136 (Python)
Azure INLINE_CODE_137 INLINE_CODE_138
GCP INLINE_CODE_139 INLINE_CODE_140
Kubernetes INLINE_CODE_141 INLINE_CODE_142 (TS)
Docker Silencio __INLINE_CODE_143_ _ __INLINE_CODE_144_