# 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/Struttura Directory
.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 con 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: Test di infrastruttura
# 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
# Migliori Pratiche
- **Uso Stack References**: Share output tra stack con `StackReference`_ per creare infrastrutture modulari. Esempio: `ref = pulumi.StackReference("org/project/stack")` poi accedere `ref.get_output("vpcId")`_
- **Configurazione delle informazioni**: memorizzare i valori specifici dell'ambiente nei file di configurazione dello stack piuttosto che nella codifica. Utilizzare `pulumi config set` per tutti i valori variabili e `--secret` flag per i dati sensibili
- ** Protezione delle risorse di esecuzione**: Proteggere le risorse critiche dalla cancellazione accidentale con l'opzione `protect=True`. Usa `pulumi.ResourceOptions(protect=True)` per database, risorse statali
- **Version Control Everything**: Commit `Pulumi.yaml`, stack config files, and code to git. Aggiungi `.pulumi/`_ directory a `.gitignore` per escludere stato e plugin
- **Utilizza le risorse dei componenti**: Crea componenti di infrastruttura riutilizzabili estendendo `pulumi.ComponentResource`. Pacchetto schemi comuni (configurazione VPC, cluster EKS) come componenti
- **Automa con CI/CD**: Integrare Pulumi in tubazioni utilizzando `pulumi preview` per le PR e `pulumi up --yes` per le distribuzioni. Utilizzare `PULUMI_ACCESS_TOKEN` variabili di ambiente per l'autenticazione
- **Tag All Resources**: Applicare una strategia di tagging coerente usando il parametro `tags`. Includere l'ambiente, il progetto, il proprietario, il centro costi per il monitoraggio dei costi e l'organizzazione
- **Abilitare la politica come codice**: rafforzare gli standard organizzativi con i pacchetti politici. Configurazioni delle risorse, convenzioni di nomina e requisiti di sicurezza prima dell'implementazione
- **Regolare State Backups**: esportazione stack state periodicamente con `pulumi stack export`. Memorizzare i backup in storage controllato o sicuro in versione separato dal backend primario
- **Usa dipendenze esplicite**: Quando le dipendenze implicite non vengono rilevate, utilizzare `depends_on` o `pulumi.Output.all()`_ per garantire un corretto ordinamento delle risorse
## Risoluzione dei problemi
_Tabella_166_
## Quick Reference: Resource URNs
Risorse URNs identificare in modo univoco le risorse in formato: `urn:pulumi: