DEV Community

Alex Spinov
Alex Spinov

Posted on

Pulumi Has a Free API: Here's How to Use It for Infrastructure as Code

Pulumi lets you define cloud infrastructure using real programming languages — Python, TypeScript, Go, C#. But beyond the CLI, Pulumi offers a powerful REST API for managing stacks, deployments, and resources programmatically.

Why Use the Pulumi API?

  • Automate stack management across environments
  • Build internal developer portals with self-service infrastructure
  • Monitor deployment history and resource drift
  • Integrate IaC into custom CI/CD pipelines

Getting Started

Get your access token from app.pulumi.com > Settings > Access Tokens:

export PULUMI_ACCESS_TOKEN="pul-xxxxxxxxxxxxxxxxxxxx"

# List all stacks
curl -s -H "Authorization: token $PULUMI_ACCESS_TOKEN" \
  "https://api.pulumi.com/api/user/stacks" | jq '.stacks[] | {name: .stackName, project: .projectName, lastUpdate: .lastUpdate}'
Enter fullscreen mode Exit fullscreen mode

Get Stack Resources

# Get all resources in a stack
curl -s -H "Authorization: token $PULUMI_ACCESS_TOKEN" \
  "https://api.pulumi.com/api/stacks/your-org/your-project/dev/export" \
  | jq '.deployment.resources[] | {type: .type, id: .id}'
Enter fullscreen mode Exit fullscreen mode

Python Automation API

Pulumi's Automation API is a game-changer — run Pulumi programs from within your application:

import pulumi
from pulumi import automation as auto
import pulumi_aws as aws

def pulumi_program():
    bucket = aws.s3.Bucket("my-bucket",
        website=aws.s3.BucketWebsiteArgs(
            index_document="index.html"
        )
    )
    pulumi.export("bucket_url", bucket.website_endpoint)

# Create or select a stack
stack = auto.create_or_select_stack(
    stack_name="dev",
    project_name="my-infra",
    program=pulumi_program
)

# Set AWS region
stack.set_config("aws:region", auto.ConfigValue(value="us-east-1"))

# Deploy
result = stack.up(on_output=print)
print(f"Bucket URL: {result.outputs['bucket_url'].value}")
Enter fullscreen mode Exit fullscreen mode

Self-Service Infrastructure Portal

from flask import Flask, request, jsonify
from pulumi import automation as auto
import pulumi_aws as aws

app = Flask(__name__)

def create_environment(env_name):
    def pulumi_program():
        vpc = aws.ec2.Vpc(f"{env_name}-vpc", cidr_block="10.0.0.0/16")
        bucket = aws.s3.Bucket(f"{env_name}-data")
        pulumi.export("vpc_id", vpc.id)
        pulumi.export("bucket", bucket.bucket)
    return pulumi_program

@app.route("/api/environments", methods=["POST"])
def create_env():
    env_name = request.json["name"]
    stack = auto.create_or_select_stack(
        stack_name=env_name,
        project_name="environments",
        program=create_environment(env_name)
    )
    stack.set_config("aws:region", auto.ConfigValue(value="us-east-1"))
    result = stack.up()
    return jsonify({"status": "created", "outputs": {k: v.value for k, v in result.outputs.items()}})

@app.route("/api/environments/<name>", methods=["DELETE"])
def destroy_env(name):
    stack = auto.select_stack(
        stack_name=name,
        project_name="environments",
        program=create_environment(name)
    )
    stack.destroy()
    stack.workspace.remove_stack(name)
    return jsonify({"status": "destroyed"})
Enter fullscreen mode Exit fullscreen mode

Track Deployment History

# Get deployment history
curl -s -H "Authorization: token $PULUMI_ACCESS_TOKEN" \
  "https://api.pulumi.com/api/stacks/your-org/your-project/dev/updates" \
  | jq '.updates[:5][] | {version: .version, result: .result, startTime: .startTime, resourceChanges: .resourceChanges}'
Enter fullscreen mode Exit fullscreen mode

Drift Detection

from pulumi import automation as auto

def check_drift(org, project, stack_name):
    stack = auto.select_stack(
        stack_name=stack_name,
        project_name=project,
        program=lambda: None
    )

    preview = stack.preview()
    changes = preview.change_summary

    if changes.get("update", 0) > 0 or changes.get("delete", 0) > 0:
        print(f"DRIFT DETECTED in {stack_name}!")
        print(f"  Updates needed: {changes.get('update', 0)}")
        print(f"  Deletes needed: {changes.get('delete', 0)}")
        return True
    else:
        print(f"{stack_name}: No drift detected")
        return False
Enter fullscreen mode Exit fullscreen mode

Real-World Use Case

A platform team at a SaaS company used Pulumi's Automation API to build a self-service portal. Developers could spin up complete staging environments in 3 minutes via Slack commands — VPC, database, load balancer, all configured. What took 2 days of DevOps tickets now takes one Slack message.

What You Can Build

  • Self-service portal for dev environments
  • Automated compliance checking across all stacks
  • Cost tracker monitoring infrastructure spend per team
  • Drift detector running daily to catch manual changes
  • Multi-cloud orchestrator managing AWS + GCP + Azure from one API

Need custom infrastructure automation? I build IaC solutions and DevOps tools.

Email me: spinov001@gmail.com
Check out my developer tools: https://apify.com/spinov001

Top comments (0)