Okay, here's a simple Go API using the Gin framework that accepts a POST payload to provision an OpenStack machine (compute instance) using Pulumi's Automation API.
This example assumes:
- Pulumi CLI is installed: Ensure
pulumi is in your system's PATH.
- Go is installed: Ensure you have a compatible Go version.
- OpenStack Credentials: Your OpenStack environment variables (
OS_USERNAME, OS_PASSWORD, OS_TENANT_NAME, OS_DOMAIN_NAME, OS_AUTH_URL, OS_REGION_NAME etc.) are correctly set in the environment where the Go application runs. Pulumi's OpenStack provider automatically picks these up.
- OpenStack Resources Exist: The
imageName, flavorName, networkName, and sshKeyName specified in the payload must exist and be accessible in your OpenStack project.
1. Project Setup
Create a new directory for your project, navigate into it, and initialize Go modules:
mkdir pulumi-openstack-api
cd pulumi-openstack-api
go mod init pulumi-openstack-api
2. Install Dependencies
You'll need the Gin web framework and the Pulumi SDKs (core and OpenStack provider):
go get github.com/gin-gonic/gin
go get github.com/pulumi/pulumi/sdk/v3/go/pulumi
go get github.com/pulumi/pulumi/sdk/v3/go/auto
go get github.com/pulumi/pulumi/sdk/v3/go/auto/optupath
go get github.com/pulumi/pulumi-openstack/sdk/v4/go/openstack # Use v4 for the provider
3. Create the Go Application (main.go)
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"github.com/gin-gonic/gin"
openstack "github.com/pulumi/pulumi-openstack/sdk/v4/go/openstack"
"github.com/pulumi/pulumi/sdk/v3/go/auto"
"github.com/pulumi/pulumi/sdk/v3/go/auto/optupath"
"github.com/pulumi/pulumi/sdk/v3/go/pulumi"
)
// CreateInstanceRequest defines the expected payload for creating an instance.
type CreateInstanceRequest struct {
Name string `json:"name" binding:"required"`
ImageName string `json:"imageName" binding:"required"` // e.g., "Ubuntu 22.04 LTS" or image ID
FlavorName string `json:"flavorName" binding:"required"` // e.g., "m1.small" or flavor ID
NetworkName string `json:"networkName" binding:"required"` // e.g., "private-network" or network ID
SSHKeyName string `json:"sshKeyName" binding:"required"` // The name of an existing SSH key in OpenStack
Region string `json:"region,omitempty"` // OpenStack region, defaults to env var OS_REGION_NAME or provider default
UserData string `json:"userData,omitempty"` // Optional cloud-init user data script
SecurityGroups []string `json:"securityGroups,omitempty"` // Optional list of security group names
}
// CreateInstanceResponse defines the structure of the API response.
type CreateInstanceResponse struct {
Message string `json:"message"`
InstanceID string `json:"instanceID,omitempty"`
InstanceName string `json:"instanceName,omitempty"`
PublicIP string `json:"publicIP,omitempty"` // Assuming AccessIPv4 is desired
Logs string `json:"logs,omitempty"`
Error string `json:"error,omitempty"`
}
// Constants for Pulumi project and stack
const (
pulumiProjectName = "simple-openstack-api-project"
pulumiStackName = "dev" // Or make this dynamic based on request/tenant
)
func main() {
// Initialize Gin router
router := gin.Default()
// Define the POST endpoint for creating instances
router.POST("/create-instance", createInstanceHandler)
// Start the server
port := os.Getenv("PORT")
if port == "" {
port = "8080" // Default port
}
log.Printf("Starting server on port %s...", port)
if err := router.Run(":" + port); err != nil {
log.Fatalf("Failed to start server: %v", err)
}
}
// createInstanceHandler handles the incoming requests to create an OpenStack instance.
func createInstanceHandler(c *gin.Context) {
var req CreateInstanceRequest
// Bind the JSON request payload to the CreateInstanceRequest struct
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request payload: " + err.Error()})
return
}
// Define the inline Pulumi program function.
// This function will be executed by the Pulumi engine.
deployFunc := func(ctx *pulumi.Context) error {
// Define the OpenStack instance resource using Pulumi Go SDK.
// Use the data from the incoming request payload.
// Create the OpenStack Instance resource.
// The first argument "my-openstack-instance" is the logical name within the Pulumi program.
instanceArgs := &openstack.ComputeInstanceArgs{
Name: pulumi.String(req.Name), // Actual OpenStack resource name
ImageName: pulumi.String(req.ImageName),
FlavorName: pulumi.String(req.FlavorName),
Networks: openstack.ComputeInstanceNetworkArray{
&openstack.ComputeInstanceNetworkArgs{
Name: pulumi.String(req.NetworkName), // Reference network by name
},
},
SshKeyName: pulumi.String(req.SSHKeyName), // Reference SSH key by name
}
// Add optional parameters if provided in the request
if req.UserData != "" {
instanceArgs.UserData = pulumi.String(req.UserData)
}
if len(req.SecurityGroups) > 0 {
// SecurityGroups argument expects a slice of SecurityGroupArgs
var sgArgs openstack.ComputeInstanceSecurityGroupArray
for _, sgName := range req.SecurityGroups {
sgArgs = append(sgArgs, &openstack.ComputeInstanceSecurityGroupArgs{Name: pulumi.String(sgName)})
}
instanceArgs.SecurityGroups = sgArgs
}
instance, err := openstack.NewComputeInstance(ctx, "my-openstack-instance", instanceArgs)
if err != nil {
// Return error immediately if resource definition fails
return fmt.Errorf("failed to define OpenStack instance resource: %w", err)
}
// Export outputs that will be returned by the Pulumi operation.
ctx.Export("instanceID", instance.ID())
ctx.Export("instanceName", instance.Name)
// AccessIPv4 is typically the public IP if assigned by DHCP or Floating IP association logic is handled elsewhere/later.
// For simplicity, we export AccessIPv4 here. You might need to manage Floating IPs separately.
ctx.Export("instancePublicIP", instance.AccessIPv4)
ctx.Export("instanceStatus", instance.Status) // Note: Status might not be populated until after the first apply.
return nil // Success
}
// --- Pulumi Automation API Execution ---
// 1. Setup Pulumi Workspace
// We'll use the current directory as the Pulumi Home for simplicity.
// In production, manage $PULUMI_HOME appropriately.
// auto.OptPulumiHome(".") tells Pulumi to look for its config/state in the current directory.
workspaceOptions := []auto.Option{
optupath.SetPulumiHome("."), // Use current directory for Pulumi state/config
auto.UseProjectBackend(true), // Ensure backend is configured (e.g., Pulumi Cloud or local)
}
// Check if a specific region was provided, otherwise rely on environment variables.
if req.Region != "" {
workspaceOptions = append(workspaceOptions, auto.WithCloudProviderCredentials(map[string][]byte{
"openstack:region": []byte(req.Region),
}))
}
// Create or select the Pulumi stack using the inline source function.
// This function handles project creation if it doesn't exist.
s, err := auto.UpsertStackInlineSource(context.Background(), pulumiStackName, pulumiProjectName, deployFunc, workspaceOptions...)
if err != nil {
log.Printf("ERROR: Failed to create/select Pulumi stack: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to initialize Pulumi stack: " + err.Error()})
return
}
// 2. Configure the Stack (Region if not set via Option)
// If region wasn't passed via Option, ensure it's set here if needed.
// This overwrites any default region if req.Region was empty but OS_REGION_NAME is set.
if req.Region != "" {
err = s.SetConfig(context.Background(), "openstack:region", auto.ConfigValue{Value: req.Region})
if err != nil {
log.Printf("ERROR: Failed to set OpenStack region config: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to set OpenStack region config: " + err.Error()})
return
}
}
// 3. Install Necessary Provider Plugins
// Specify the provider name and version. Check the Pulumi Registry for the latest OpenStack provider version.
// As of writing, v4.7.0 is a recent version.
providerVersion := "v4.7.0"
err = s.InstallPlugin(context.Background(), "openstack", providerVersion)
if err != nil {
log.Printf("ERROR: Failed to install OpenStack plugin (%s): %v", providerVersion, err)
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("Failed to install OpenStack provider plugin %s: %v", providerVersion, err)})
return
}
// 4. Perform the Pulumi Update (deployment)
// Capture stdout logs for the response.
var logStream bytes.Buffer
updateResult, err := s.Up(context.Background(), auto.LogStream(&logStream))
if err != nil {
log.Printf("ERROR: Pulumi deployment failed: %v", err)
// Return the error and logs from the failed update.
c.JSON(http.StatusInternalServerError, gin.H{
"error": "Pulumi deployment failed: " + err.Error(),
"logs": logStream.String(),
})
return
}
// 5. Process Results and Prepare Response
// Extract exported outputs from the update result.
instanceID, _ := updateResult.Outputs["instanceID"].Value.(string)
instanceName, _ := updateResult.Outputs["instanceName"].Value.(string)
publicIP, _ := updateResult.Outputs["instancePublicIP"].Value.(string)
response := CreateInstanceResponse{
Message: "OpenStack instance created successfully",
InstanceID: instanceID,
InstanceName: instanceName,
PublicIP: publicIP,
Logs: logStream.String(),
}
c.JSON(http.StatusOK, response)
}
4. Set OpenStack Environment Variables
Before running the Go application, ensure your OpenStack credentials are set in your terminal environment. Replace placeholders with your actual credentials.
export OS_USERNAME="your_username"
export OS_PASSWORD="your_password"
export OS_TENANT_NAME="your_project_name" # Or OS_PROJECT_NAME depending on your OpenStack setup
export OS_DOMAIN_NAME="your_domain_name"
export OS_AUTH_URL="http://your-keystone-url:5000/v3"
# export OS_REGION_NAME="regionOne" # Optional, can be specified in payload or rely on provider default
(Note: The exact environment variables might vary slightly depending on your OpenStack distribution and configuration.)
5. Run the Go API
go run main.go
The API server will start, typically on http://localhost:8080.
6. Send a POST Request
You can use curl or any API client (like Postman) to send a request to create an instance.
Example curl command:
curl -X POST http://localhost:8080/create-instance \
-H "Content-Type: application/json" \
-d '{
"name": "my-api-instance",
"imageName": "Ubuntu 22.04 LTS",
"flavorName": "m1.small",
"networkName": "private",
"sshKeyName": "my-ssh-key",
"region": "RegionOne",
"securityGroups": ["default", "allow-ssh"]
}'
Explanation:
CreateInstanceRequest Struct: Defines the expected JSON input for the API. binding:"required" ensures these fields must be present.
CreateInstanceResponse Struct: Defines the JSON output, including success messages, instance details, and any logs or errors.
main() Function: Initializes the Gin web server and sets up the /create-instance POST route.
createInstanceHandler() Function:
- Parses the incoming JSON request.
- Defines
deployFunc: This is the core Pulumi program written in Go. It uses the openstack provider package to declare an openstack.ComputeInstance. It dynamically uses the values from the req struct.
- Pulumi Workspace Setup: Creates a Pulumi workspace.
optupath.SetPulumiHome(".") is used for simplicity, making the Pulumi state files appear in the current directory. In production, you'd want to manage $PULUMI_HOME more carefully.
auto.UpsertStackInlineSource: This is the key Automation API function. It takes the stack name, project name, and the deployFunc (the inline Go program). It ensures the stack and project exist and returns a *auto.Stack object.
s.SetConfig: Configures the Pulumi stack, specifically setting the openstack:region.
s.InstallPlugin: Ensures the openstack provider plugin is available for the stack.
s.Up: Executes the Pulumi program against the configured stack. It attempts to create/update the resources defined in deployFunc. auto.LogStream captures the output.
- Result Processing: Extracts the exported values (
instanceID, instanceName, instancePublicIP) from the updateResult and constructs the API response.
This setup provides a basic but functional API to programmatically create OpenStack instances using Pulumi.