### Set up Authentication for STACKIT SDK for Go Source: https://context7.com/stackitcloud/stackit-sdk-go/llms.txt Demonstrates various authentication methods for the STACKIT SDK for Go, including default auto-discovery, key-based authentication with an explicit path, token-based authentication, and unauthenticated clients for public endpoints. It utilizes the `dns` service as an example. ```go package main import ( "context" "fmt" "os" "github.com/stackitcloud/stackit-sdk-go/core/config" "github.com/stackitcloud/stackit-sdk-go/services/dns" ) func main() { // Default authentication - auto-discovers credentials client, err := dns.NewAPIClient() if err != nil { fmt.Fprintf(os.Stderr, "Creating API client: %v\n", err) os.Exit(1) } // Key flow authentication with explicit path clientWithKey, err := dns.NewAPIClient( config.WithServiceAccountKeyPath("/path/to/service_account_key.json"), ) if err != nil { fmt.Fprintf(os.Stderr, "Creating API client: %v\n", err) os.Exit(1) } // Token flow authentication clientWithToken, err := dns.NewAPIClient( config.WithToken("your-service-account-token"), ) if err != nil { fmt.Fprintf(os.Stderr, "Creating API client: %v\n", err) os.Exit(1) } // Unauthenticated client (for public endpoints) clientNoAuth, err := dns.NewAPIClient(config.WithoutAuthentication()) if err != nil { fmt.Fprintf(os.Stderr, "Creating API client: %v\n", err) os.Exit(1) } _ = client _ = clientWithKey _ = clientWithToken _ = clientNoAuth } ``` -------------------------------- ### IaaS Server Management API Source: https://context7.com/stackitcloud/stackit-sdk-go/llms.txt This API allows for the creation, configuration, and management of virtual servers, including their associated networks and boot volumes. It also supports operations such as starting, stopping, resizing, and deleting servers. ```APIDOC ## List Servers ### Description Retrieves a list of all servers within a specified project and region. ### Method GET ### Endpoint `/iaas/api/v1/projects/{projectId}/regions/{region}/servers` ### Parameters #### Path Parameters - **projectId** (string) - Required - The unique identifier for the project. - **region** (string) - Required - The region where the servers are located. #### Query Parameters None ### Request Example None ### Response #### Success Response (200) - **items** (array) - A list of server objects. - **id** (string) - The unique identifier for the server. - **name** (string) - The name of the server. - **availabilityZone** (string) - The availability zone of the server. - **machineType** (string) - The machine type of the server. - **bootVolume** (object) - Details about the boot volume. - **size** (integer) - The size of the boot volume in GB. - **source** (object) - Information about the boot volume source. - **id** (string) - The ID of the image or volume. - **type** (string) - The type of the source ('image' or 'volume'). - **networking** (object) - Networking configuration for the server. - **networkId** (string) - The ID of the network. #### Response Example ```json { "items": [ { "id": "server-uuid-1", "name": "my-server-1", "availabilityZone": "eu01-1", "machineType": "g1.1", "bootVolume": { "size": 64, "source": { "id": "image-uuid", "type": "image" } }, "networking": { "networkId": "network-uuid-1" } } ] } ``` ## Create Network ### Description Creates a new network within a specified project and region. ### Method POST ### Endpoint `/iaas/api/v1/projects/{projectId}/regions/{region}/networks` ### Parameters #### Path Parameters - **projectId** (string) - Required - The unique identifier for the project. - **region** (string) - Required - The region where the network will be created. #### Query Parameters None #### Request Body - **name** (string) - Required - The name of the network. - **ipv4** (object) - IPv4 configuration for the network. - **createNetworkIPv4WithPrefixLength** (object) - IPv4 configuration with prefix length. - **prefixLength** (integer) - Required - The prefix length for the IPv4 subnet. ### Request Example ```json { "name": "my-network", "ipv4": { "createNetworkIPv4WithPrefixLength": { "prefixLength": 24 } } } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the created network. - **name** (string) - The name of the network. - **ipv4** (object) - IPv4 configuration of the network. - **cidr** (string) - The CIDR block of the network. #### Response Example ```json { "id": "network-uuid", "name": "my-network", "ipv4": { "cidr": "10.0.0.0/24" } } ``` ## Create Server ### Description Creates a new virtual server with specified configuration, including machine type, boot volume, and networking. ### Method POST ### Endpoint `/iaas/api/v1/projects/{projectId}/regions/{region}/servers` ### Parameters #### Path Parameters - **projectId** (string) - Required - The unique identifier for the project. - **region** (string) - Required - The region where the server will be created. #### Query Parameters None #### Request Body - **name** (string) - Required - The name of the server. - **availabilityZone** (string) - Required - The availability zone for the server. - **machineType** (string) - Required - The machine type for the server (e.g., 'g1.1'). - **bootVolume** (object) - Required - Configuration for the server's boot volume. - **size** (integer) - Required - The size of the boot volume in GB. - **source** (object) - Required - Information about the boot volume source. - **id** (string) - Required - The ID of the image or volume. - **type** (string) - Required - The type of the source ('image' or 'volume'). - **networking** (object) - Networking configuration for the server. - **createServerNetworking** (object) - Networking details. - **networkId** (string) - Required - The ID of the network to attach the server to. ### Request Example ```json { "name": "my-server", "availabilityZone": "eu01-1", "machineType": "g1.1", "bootVolume": { "size": 64, "source": { "id": "image-uuid", "type": "image" } }, "networking": { "createServerNetworking": { "networkId": "network-uuid" } } } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the created server. - **name** (string) - The name of the server. - **status** (string) - The current status of the server (e.g., 'CREATE_IN_PROGRESS', 'ACTIVE'). #### Response Example ```json { "id": "server-uuid", "name": "my-server", "status": "CREATE_IN_PROGRESS" } ``` ## Stop Server ### Description Stops a running virtual server. ### Method POST ### Endpoint `/iaas/api/v1/projects/{projectId}/regions/{region}/servers/{serverId}/stop` ### Parameters #### Path Parameters - **projectId** (string) - Required - The unique identifier for the project. - **region** (string) - Required - The region where the server is located. - **serverId** (string) - Required - The unique identifier for the server to stop. #### Query Parameters None ### Request Example None ### Response #### Success Response (200) - **id** (string) - The unique identifier for the server. - **status** (string) - The status of the server after the stop operation (e.g., 'STOPPING', 'STOPPED'). #### Response Example ```json { "id": "server-uuid", "status": "STOPPED" } ``` ## Start Server ### Description Starts a stopped virtual server. ### Method POST ### Endpoint `/iaas/api/v1/projects/{projectId}/regions/{region}/servers/{serverId}/start` ### Parameters #### Path Parameters - **projectId** (string) - Required - The unique identifier for the project. - **region** (string) - Required - The region where the server is located. - **serverId** (string) - Required - The unique identifier for the server to start. #### Query Parameters None ### Request Example None ### Response #### Success Response (200) - **id** (string) - The unique identifier for the server. - **status** (string) - The status of the server after the start operation (e.g., 'STARTING', 'ACTIVE'). #### Response Example ```json { "id": "server-uuid", "status": "ACTIVE" } ``` ## Resize Server ### Description Resizes a virtual server to a different machine type. ### Method POST ### Endpoint `/iaas/api/v1/projects/{projectId}/regions/{region}/servers/{serverId}/resize` ### Parameters #### Path Parameters - **projectId** (string) - Required - The unique identifier for the project. - **region** (string) - Required - The region where the server is located. - **serverId** (string) - Required - The unique identifier for the server to resize. #### Query Parameters None #### Request Body - **machineType** (string) - Required - The new machine type for the server (e.g., 'c1.2'). ### Request Example ```json { "machineType": "c1.2" } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the server. - **machineType** (string) - The new machine type of the server. - **status** (string) - The status of the server after the resize operation (e.g., 'RESIZING', 'ACTIVE'). #### Response Example ```json { "id": "server-uuid", "machineType": "c1.2", "status": "ACTIVE" } ``` ## Delete Server ### Description Deletes a virtual server. ### Method DELETE ### Endpoint `/iaas/api/v1/projects/{projectId}/regions/{region}/servers/{serverId}` ### Parameters #### Path Parameters - **projectId** (string) - Required - The unique identifier for the project. - **region** (string) - Required - The region where the server is located. - **serverId** (string) - Required - The unique identifier for the server to delete. #### Query Parameters None ### Request Example None ### Response #### Success Response (204) No Content. Indicates the server was successfully deleted. #### Response Example None ``` -------------------------------- ### Manage IaaS Servers and Networks with Stackit SDK Go Source: https://context7.com/stackitcloud/stackit-sdk-go/llms.txt This Go program utilizes the Stackit SDK to perform various IaaS server and network management operations. It covers creating networks and servers, waiting for their creation, and then proceeding to stop, start, resize, and delete the server. Dependencies include the Stackit SDK for Go. The input includes project ID, image ID, and region. The output consists of status messages and IDs of the created/managed resources. ```go package main import ( "context" "fmt" "os" "github.com/stackitcloud/stackit-sdk-go/core/utils" "github.com/stackitcloud/stackit-sdk-go/services/iaas" "github.com/stackitcloud/stackit-sdk-go/services/iaas/wait" ) func main() { ctx := context.Background() projectId := "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" imageId := "image-uuid" region := "eu01" iaasClient, err := iaas.NewAPIClient() if err != nil { fmt.Fprintf(os.Stderr, "Creating API client: %v\n", err) os.Exit(1) } // List existing servers serversResp, err := iaasClient.ListServers(ctx, projectId, region).Execute() if err != nil { fmt.Fprintf(os.Stderr, "Error listing servers: %v\n", err) } else { fmt.Printf("Number of servers: %v\n", len(*serversResp.Items)) } // Create a network first networkPayload := iaas.CreateNetworkPayload{ Name: utils.Ptr("my-network"), Ipv4: &iaas.CreateNetworkIPv4{ CreateNetworkIPv4WithPrefixLength: &iaas.CreateNetworkIPv4WithPrefixLength{ PrefixLength: utils.Ptr(int64(24)), }, }, } network, err := iaasClient.CreateNetwork(ctx, projectId, region). CreateNetworkPayload(networkPayload). Execute() if err != nil { fmt.Fprintf(os.Stderr, "Error creating network: %v\n", err) os.Exit(1) } // Wait for network creation network, err = wait.CreateNetworkWaitHandler(ctx, iaasClient, projectId, region, *network.Id). WaitWithContext(ctx) if err != nil { fmt.Fprintf(os.Stderr, "Error waiting for network: %v\n", err) os.Exit(1) } fmt.Printf("Network created: %s\n", *network.Id) // Create a server serverPayload := iaas.CreateServerPayload{ Name: utils.Ptr("my-server"), AvailabilityZone: utils.Ptr("eu01-1"), MachineType: utils.Ptr("g1.1"), BootVolume: &iaas.ServerBootVolume{ Size: utils.Ptr(int64(64)), Source: &iaas.BootVolumeSource{ Id: utils.Ptr(imageId), Type: utils.Ptr("image"), }, }, Networking: &iaas.CreateServerPayloadAllOfNetworking{ CreateServerNetworking: &iaas.CreateServerNetworking{ NetworkId: network.Id, }, }, } server, err := iaasClient.CreateServer(ctx, projectId, region). CreateServerPayload(serverPayload). Execute() if err != nil { fmt.Fprintf(os.Stderr, "Error creating server: %v\n", err) os.Exit(1) } fmt.Printf("Triggered server creation: %s\n", *server.Id) // Wait for server creation server, err = wait.CreateServerWaitHandler(ctx, iaasClient, projectId, region, *server.Id). WaitWithContext(ctx) if err != nil { fmt.Fprintf(os.Stderr, "Error waiting for server: %v\n", err) os.Exit(1) } fmt.Printf("Server created: %s\n", *server.Id) // Stop the server err = iaasClient.StopServer(ctx, projectId, region, *server.Id).Execute() if err != nil { fmt.Fprintf(os.Stderr, "Error stopping server: %v\n", err) } server, _ = wait.StopServerWaitHandler(ctx, iaasClient, projectId, region, *server.Id).WaitWithContext(ctx) fmt.Printf("Server stopped: %s\n", *server.Id) // Start the server err = iaasClient.StartServer(ctx, projectId, region, *server.Id).Execute() if err != nil { fmt.Fprintf(os.Stderr, "Error starting server: %v\n", err) } server, _ = wait.StartServerWaitHandler(ctx, iaasClient, projectId, region, *server.Id).WaitWithContext(ctx) fmt.Printf("Server started: %s\n", *server.Id) // Resize the server resizePayload := iaas.ResizeServerPayload{ MachineType: utils.Ptr("c1.2"), } err = iaasClient.ResizeServer(ctx, projectId, region, *server.Id). ResizeServerPayload(resizePayload). Execute() if err != nil { fmt.Fprintf(os.Stderr, "Error resizing server: %v\n", err) } server, _ = wait.ResizeServerWaitHandler(ctx, iaasClient, projectId, region, *server.Id).WaitWithContext(ctx) fmt.Printf("Server resized: %s\n", *server.Id) // Delete the server err = iaasClient.DeleteServer(ctx, projectId, region, *server.Id).Execute() if err != nil { fmt.Fprintf(os.Stderr, "Error deleting server: %v\n", err) } _, _ = wait.DeleteServerWaitHandler(ctx, iaasClient, projectId, region, *server.Id).WaitWithContext(ctx) fmt.Println("Server deleted") } ``` -------------------------------- ### Load Balancer Management API Source: https://context7.com/stackitcloud/stackit-sdk-go/llms.txt This section covers the management of Stackit Load Balancers. You can list existing load balancers, create new ones with specified configurations, and potentially update or delete them (though update/delete are not shown in the provided Go example). ```APIDOC ## Load Balancer Management API ### Description Provides endpoints for managing Stackit Load Balancers, including listing and creating load balancers with detailed configurations for networks, listeners, and target pools. ### Method GET, POST ### Endpoints - `/loadbalancer/v1/{projectId}/{region}/loadbalancers` (List Load Balancers) - `/loadbalancer/v1/{projectId}/{region}/loadbalancers` (Create Load Balancer) ### Parameters #### List Load Balancers (GET) ##### Query Parameters - `projectId` (string) - Required - The ID of the project. - `region` (string) - Required - The region of the load balancer. #### Create Load Balancer (POST) ##### Path Parameters - `projectId` (string) - Required - The ID of the project. - `region` (string) - Required - The region of the load balancer. ##### Headers - `X-Request-ID` (string) - Optional - A unique identifier for the request. ##### Request Body - `name` (string) - Required - The name of the load balancer. - `options` (object) - Optional - Load balancer options. - `privateNetworkOnly` (boolean) - Optional - Specifies if the load balancer is only accessible within a private network. - `networks` (array) - Required - A list of networks to associate with the load balancer. - `networkId` (string) - Required - The ID of the network. - `role` (string) - Required - The role of the network (e.g., `LISTENERS_AND_TARGETS`). - `listeners` (array) - Optional - A list of listeners for the load balancer. - `displayName` (string) - Optional - A display name for the listener. - `port` (integer) - Required - The port the listener listens on. - `protocol` (string) - Required - The protocol for the listener (e.g., `TCP`). - `targetPool` (string) - Required - The name of the target pool to route traffic to. - `targetPools` (array) - Optional - A list of target pools for the load balancer. - `name` (string) - Required - The name of the target pool. - `targetPort` (integer) - Required - The port on the targets to send traffic to. - `targets` (array) - Required - A list of targets in the pool. - `displayName` (string) - Optional - A display name for the target. - `ip` (string) - Required - The IP address of the target. ### Request Example (Create Load Balancer) ```json { "name": "my-loadbalancer", "options": { "privateNetworkOnly": true }, "networks": [ { "networkId": "network-uuid", "role": "LISTENERS_AND_TARGETS" } ], "listeners": [ { "displayName": "http-listener", "port": 80, "protocol": "TCP", "targetPool": "web-pool" } ], "targetPools": [ { "name": "web-pool", "targetPort": 8080, "targets": [ { "displayName": "web-server-1", "ip": "10.0.0.10" }, { "displayName": "web-server-2", "ip": "10.0.0.11" } ] } ] } ``` ### Response #### Success Response (200) ##### List Load Balancers Response - `loadBalancers` (array) - A list of load balancers. - (Object structure similar to the create payload, representing a load balancer) ##### Create Load Balancer Response - `name` (string) - The name of the created load balancer. - (Other fields representing the created load balancer configuration) #### Response Example (Create Load Balancer) ```json { "name": "my-loadbalancer" } ``` ``` -------------------------------- ### Manage SKE Clusters and Credentials with Go Source: https://context7.com/stackitcloud/stackit-sdk-go/llms.txt This Go code snippet demonstrates the full lifecycle management of STACKIT Kubernetes Engine (SKE) clusters. It includes listing clusters, creating a new cluster with specific node pool configurations, waiting for its creation, and performing credential rotation (start, wait, complete). Dependencies include the stackit-sdk-go library. It takes project ID, region, and cluster name as inputs and outputs cluster information and status updates. ```go package main import ( "context" "fmt" "os" "github.com/stackitcloud/stackit-sdk-go/core/utils" "github.com/stackitcloud/stackit-sdk-go/services/ske" "github.com/stackitcloud/stackit-sdk-go/services/ske/wait" ) func main() { ctx := context.Background() projectId := "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" region := "eu01" clusterName := "my-cluster" skeClient, err := ske.NewAPIClient() if err != nil { fmt.Fprintf(os.Stderr, "Creating API client: %v\n", err) os.Exit(1) } // List existing clusters clustersResp, err := skeClient.ListClusters(ctx, projectId, region).Execute() if err != nil { fmt.Fprintf(os.Stderr, "Error listing clusters: %v\n", err) os.Exit(1) } fmt.Printf("Number of clusters: %v\n", len(*clustersResp.Items)) // Get available Kubernetes versions optionsResp, err := skeClient.ListProviderOptions(ctx, region).Execute() if err != nil { fmt.Fprintf(os.Stderr, "Error getting options: %v\n", err) os.Exit(1) } versions := *optionsResp.KubernetesVersions availableVersion := *versions[0].Version fmt.Printf("Using Kubernetes version: %s\n", availableVersion) // Create a cluster createClusterPayload := ske.CreateOrUpdateClusterPayload{ Kubernetes: &ske.Kubernetes{ Version: utils.Ptr(availableVersion), }, Nodepools: &[]ske.Nodepool{ { AvailabilityZones: utils.Ptr([]string{"eu01-3"}), Machine: &ske.Machine{ Image: &ske.Image{ Name: utils.Ptr("flatcar"), Version: utils.Ptr("3510.2.5"), }, Type: utils.Ptr("b1.2"), }, Maximum: utils.Ptr(int64(3)), Minimum: utils.Ptr(int64(2)), Name: utils.Ptr("worker-pool"), Volume: &ske.Volume{ Size: utils.Ptr(int64(50)), Type: utils.Ptr("storage_premium_perf0"), }, }, }, } createResp, err := skeClient.CreateOrUpdateCluster(ctx, projectId, region, clusterName). CreateOrUpdateClusterPayload(createClusterPayload). Execute() if err != nil { fmt.Fprintf(os.Stderr, "Error creating cluster: %v\n", err) os.Exit(1) } fmt.Printf("Triggered creation of cluster: %s\n", *createResp.Name) // Wait for cluster creation _, err = wait.CreateOrUpdateClusterWaitHandler(ctx, skeClient, projectId, region, clusterName). WaitWithContext(ctx) if err != nil { fmt.Fprintf(os.Stderr, "Error waiting for cluster: %v\n", err) os.Exit(1) } fmt.Println("Cluster created successfully") // Start credential rotation _, err = skeClient.StartCredentialsRotationExecute(ctx, projectId, region, clusterName) if err != nil { fmt.Fprintf(os.Stderr, "Error starting rotation: %v\n", err) } // Wait for rotation to be ready _, err = wait.StartCredentialsRotationWaitHandler(ctx, skeClient, projectId, region, clusterName). WaitWithContext(ctx) if err != nil { fmt.Fprintf(os.Stderr, "Error waiting for rotation: %v\n", err) } // Complete credential rotation _, err = skeClient.CompleteCredentialsRotationExecute(ctx, projectId, region, clusterName) if err != nil { fmt.Fprintf(os.Stderr, "Error completing rotation: %v\n", err) } fmt.Println("Credential rotation completed") } ``` -------------------------------- ### STACKIT DNS Service Client and Operations (Go) Source: https://github.com/stackitcloud/stackit-sdk-go/blob/main/README.md Demonstrates creating a STACKIT DNS service client and performing operations like getting DNS zones, creating DNS zones, and retrieving record sets. It requires a project ID and handles potential errors during API calls. The code uses the `context` package for request cancellation and timeouts. ```go package main import ( "context" "fmt" "os" "github.com/stackitcloud/stackit-sdk-go/services/dns" ) func main() { // Specify the project ID projectId := "PROJECT_ID" // Create a new API client, that uses default authentication and configuration dnsClient, err := dns.NewAPIClient() if err != nil { fmt.Fprintf(os.Stderr, "[DNS API] Creating API client: %v\n", err) os.Exit(1) } // Get the DNS Zones for your project var getZoneResp *dns.ZonesResponse getZoneResp, err = dnsClient.GetZones(context.Background(), projectId).Execute() // Get only active DNS Zones for your project by adding the filter "ActiveEq(true)" to the call. More filters are available and can be chained. // dnsRespGetZones, err := dnsClient.ZoneApi.GetZones(context.Background(), projectId).ActiveEq(true).Execute() if err != nil { fmt.Fprintf(os.Stderr, "[DNS API] Error when calling `ZoneApi.GetZones`: %v\n", err) } else { fmt.Printf("[DNS API] Number of zones: %v\n", len(getZoneResp.Zones)) } // Create a DNS Zone createZonePayload := dns.CreateZonePayload{ Name: "myZone", DnsName: "testZone.com", } var createZoneResp *dns.ZoneResponse createZoneResp, err = dnsClient.CreateZone(context.Background(), projectId).CreateZonePayload(createZonePayload).Execute() if err != nil { fmt.Fprintf(os.Stderr, "[DNS API] Error when calling `ZoneApi.CreateZone`: %v\n", err) } else { var createdZone dns.Zone = createZoneResp.Zone fmt.Printf("[DNS API] Created zone \"%s\" with DNS name \"%s\" and zone id \"%s\".\n", createdZone.Name, createdZone.DnsName, createdZone.Id) } // Get a record set of a DNS zone. var recordSetResp *dns.RecordSetResponse recordSetResp, err = dnsClient.GetRecordSet(context.Background(), projectId, "zoneId", "recordSetId").Execute() if err != nil { fmt.Fprintf(os.Stderr, "[DNS API] Error when calling `GetRecordSet`: %v\n", err) } else { fmt.Printf("[DNS API] Got record set with name \"%s\".\n", recordSetResp.Rrset.Name) } } ``` -------------------------------- ### Implement Custom HTTP Middleware with Go SDK Source: https://context7.com/stackitcloud/stackit-sdk-go/llms.txt Demonstrates how to add custom middleware to the STACKIT Go SDK client to intercept and modify HTTP requests and responses. The example shows a logging middleware that prints request and response details. Uses `config.Middleware` for customization. ```go package main import ( "context" "fmt" "net/http" "os" "github.com/stackitcloud/stackit-sdk-go/core/config" "github.com/stackitcloud/stackit-sdk-go/services/dns" ) // LoggingMiddleware logs all requests and responses func LoggingMiddleware(label string) config.Middleware { return func(rt http.RoundTripper) http.RoundTripper { return &loggingRoundTripper{rt: rt, label: label} } } type loggingRoundTripper struct { rt http.RoundTripper label string } func (l *loggingRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { fmt.Printf("[%s] Request: %s %s\n", l.label, req.Method, req.URL.String()) resp, err := l.rt.RoundTrip(req) if err != nil { fmt.Printf("[%s] Error: %v\n", l.label, err) return nil, err } fmt.Printf("[%s] Response: %s\n", l.label, resp.Status) return resp, nil } func main() { projectId := "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" // Create client with middleware (executed in reverse order) dnsClient, err := dns.NewAPIClient( config.WithMiddleware(LoggingMiddleware("outer")), config.WithMiddleware(LoggingMiddleware("inner")), ) if err != nil { fmt.Fprintf(os.Stderr, "Creating API client: %v\n", err) os.Exit(1) } // Make a request - middleware will log it zonesResp, err := dnsClient.ListZones(context.Background(), projectId).Execute() if err != nil { fmt.Fprintf(os.Stderr, "Error listing zones: %v\n", err) os.Exit(1) } fmt.Printf("Number of zones: %v\n", len(*zonesResp.Zones)) } ``` -------------------------------- ### Service Account Key JSON Structure Source: https://github.com/stackitcloud/stackit-sdk-go/blob/main/README.md Example structure of a service account key JSON file obtained from the STACKIT Portal. This JSON contains essential fields like 'id', 'publicKey', and 'credentials' which include 'kid', 'iss', 'sub', 'aud', and optionally 'privateKey'. ```json { "id": "uuid", "publicKey": "public key", "credentials": { "kid": "string", "iss": "my-sa@sa.stackit.cloud", "sub": "uuid", "aud": "string", "privateKey": "private key (if STACKIT-generated)" } // ... other fields ... } ``` -------------------------------- ### PostgreSQL Flex Database Management API Source: https://context7.com/stackitcloud/stackit-sdk-go/llms.txt Create and manage PostgreSQL Flex database instances and users. ```APIDOC ## PostgreSQL Flex Database Management ### Description Create and manage PostgreSQL Flex database instances and users. ### Method GET, POST, DELETE ### Endpoint `/stackit/postgresflex/v1/{projectId}/{region}/instances` `/stackit/postgresflex/v1/{projectId}/{region}/instances/{instanceId}/users` ### Parameters #### Path Parameters - **projectId** (string) - Required - The ID of the project. - **region** (string) - Required - The region of the PostgreSQL Flex instance. - **instanceId** (string) - Required - The ID of the PostgreSQL Flex instance. #### Query Parameters None #### Request Body - **CreateUserPayload** (object) - Required - Payload for creating a user. - **Username** (string) - Required - The username for the new user. - **Roles** ([]string) - Optional - The roles to assign to the user. ### Request Example ```go // Example for listing instances pgClient.ListInstances(ctx, projectId, region).Execute() // Example for creating a user createUserPayload := postgresflex.CreateUserPayload{ Username: &[]string{"app-user"}[0], Roles: &[]string{"login", "createdb"}, } pgClient.CreateUser(ctx, projectId, region, instanceId).CreateUserPayload(createUserPayload).Execute() // Example for deleting an instance pgClient.DeleteInstance(ctx, projectId, region, instanceId).Execute() ``` ### Response #### Success Response (200) - **Items** ([]postgresflex.Instance) - A list of PostgreSQL Flex instances. #### Response Example ```json { "Items": [ { "Id": "instance-id-123", "Name": "my-postgres-instance" } ] } ``` ``` -------------------------------- ### Manage PostgreSQL Flex Databases with Go SDK Source: https://context7.com/stackitcloud/stackit-sdk-go/llms.txt Shows how to create, list, and delete PostgreSQL Flex database instances and users using the Stackit Go SDK. It requires project ID and region, and utilizes a waiter for deletion. ```go package main import ( "context" "fmt" "os" "github.com/stackitcloud/stackit-sdk-go/services/postgresflex" "github.com/stackitcloud/stackit-sdk-go/services/postgresflex/wait" ) func main() { ctx := context.Background() projectId := "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" region := "eu01" pgClient, err := postgresflex.NewAPIClient() if err != nil { fmt.Fprintf(os.Stderr, "Creating API client: %v\n", err) os.Exit(1) } // List PostgreSQL instances instancesResp, err := pgClient.ListInstances(ctx, projectId, region).Execute() if err != nil { fmt.Fprintf(os.Stderr, "Error listing instances: %v\n", err) os.Exit(1) } items := *instancesResp.Items fmt.Printf("Number of PostgreSQL instances: %v\n", len(items)) if len(items) == 0 { fmt.Println("No instances available") return } instanceId := *items[0].Id instanceName := *items[0].Name // Create a database user createUserPayload := postgresflex.CreateUserPayload{ Username: &[]string{"app-user"}[0], Roles: &[]string{"login", "createdb"}, } _, err = pgClient.CreateUser(ctx, projectId, region, instanceId). CreateUserPayload(createUserPayload). Execute() if err != nil { fmt.Fprintf(os.Stderr, "Error creating user: %v\n", err) } else { fmt.Printf("Created user for instance: %s\n", instanceName) } // Delete an instance with waiter err = pgClient.DeleteInstance(ctx, projectId, region, instanceId).Execute() if err != nil { fmt.Fprintf(os.Stderr, "Error deleting instance: %v\n", err) } _, err = wait.DeleteInstanceWaitHandler(ctx, pgClient, projectId, region, instanceId). WaitWithContext(ctx) if err != nil { fmt.Fprintf(os.Stderr, "Error waiting for deletion: %v\n", err) } else { fmt.Printf("Instance %s deleted\n", instanceId) } } ``` -------------------------------- ### Manage Object Storage Buckets with Go SDK Source: https://context7.com/stackitcloud/stackit-sdk-go/llms.txt Demonstrates how to create and list object storage buckets using the Stackit Go SDK. It requires project ID and region as input and interacts with the objectstorage service. ```go package main import ( "context" "fmt" "os" "github.com/stackitcloud/stackit-sdk-go/services/objectstorage" ) func main() { ctx := context.Background() projectId := "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" region := "eu01" osClient, err := objectstorage.NewAPIClient() if err != nil { fmt.Fprintf(os.Stderr, "Creating API client: %v\n", err) os.Exit(1) } // List existing buckets bucketsResp, err := osClient.ListBuckets(ctx, projectId, region).Execute() if err != nil { fmt.Fprintf(os.Stderr, "Error listing buckets: %v\n", err) os.Exit(1) } fmt.Printf("Number of buckets: %v\n", len(*bucketsResp.Buckets)) // Create a bucket createBucketResp, err := osClient.CreateBucket(ctx, projectId, region, "my-new-bucket").Execute() if err != nil { fmt.Fprintf(os.Stderr, "Error creating bucket: %v\n", err) os.Exit(1) } fmt.Printf("Created bucket: %s\n", *createBucketResp.Bucket) } ``` -------------------------------- ### Manage STACKIT Projects with Go SDK Source: https://context7.com/stackitcloud/stackit-sdk-go/llms.txt Demonstrates how to create and manage STACKIT projects within an organization using the Go SDK. It includes listing existing projects and creating new ones with specified members and roles. Requires the 'resourcemanager' service. ```go package main import ( "context" "fmt" "os" "github.com/stackitcloud/stackit-sdk-go/core/utils" "github.com/stackitcloud/stackit-sdk-go/services/resourcemanager" ) func main() { ctx := context.Background() organizationId := "org-uuid" rmClient, err := resourcemanager.NewAPIClient() if err != nil { fmt.Fprintf(os.Stderr, "Creating API client: %v\n", err) os.Exit(1) } // List projects in organization projectsResp, err := rmClient.ListProjects(ctx). ContainerParentId(organizationId). Execute() if err != nil { fmt.Fprintf(os.Stderr, "Error listing projects: %v\n", err) os.Exit(1) } fmt.Printf("Number of projects: %v\n", len(*projectsResp.Items)) // Create a new project createPayload := resourcemanager.CreateProjectPayload{ ContainerParentId: utils.Ptr(organizationId), Name: utils.Ptr("my-new-project"), Members: &[]resourcemanager.Member{ { Role: utils.Ptr("project.owner"), Subject: utils.Ptr("owner@example.com"), }, { Role: utils.Ptr("project.member"), Subject: utils.Ptr("developer@example.com"), }, }, } createResp, err := rmClient.CreateProject(ctx). CreateProjectPayload(createPayload). Execute() if err != nil { fmt.Fprintf(os.Stderr, "Error creating project: %v\n", err) os.Exit(1) } fmt.Printf("Created project: %s\n", *createResp.ProjectId) } ``` -------------------------------- ### Manage Stackit Load Balancers with Go SDK Source: https://context7.com/stackitcloud/stackit-sdk-go/llms.txt This Go code snippet demonstrates how to interact with the Stackit Load Balancer service. It shows how to initialize the SDK client, list existing load balancers, and create a new load balancer with specific network configurations, listeners, and target pools. It requires the 'stackit-sdk-go' library and project/region identifiers. ```go package main import ( "context" "fmt" "os" "github.com/stackitcloud/stackit-sdk-go/core/utils" "github.com/stackitcloud/stackit-sdk-go/services/loadbalancer" ) func main() { ctx := context.Background() projectId := "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" region := "eu01" lbClient, err := loadbalancer.NewAPIClient() if err != nil { fmt.Fprintf(os.Stderr, "Creating API client: %v\n", err) os.Exit(1) } // List load balancers listResp, err := lbClient.ListLoadBalancers(ctx, projectId, region).Execute() if err != nil { fmt.Fprintf(os.Stderr, "Error listing load balancers: %v\n", err) os.Exit(1) } if listResp.LoadBalancers != nil { fmt.Printf("Number of load balancers: %v\n", len(*listResp.LoadBalancers)) } // Create a load balancer createPayload := loadbalancer.CreateLoadBalancerPayload{ Name: utils.Ptr("my-loadbalancer"), Options: &loadbalancer.LoadBalancerOptions{ PrivateNetworkOnly: utils.Ptr(true), }, Networks: &[]loadbalancer.Network{ { NetworkId: utils.Ptr("network-uuid"), Role: utils.Ptr(loadbalancer.NETWORKROLE_LISTENERS_AND_TARGETS), }, }, Listeners: &[]loadbalancer.Listener{ { DisplayName: utils.Ptr("http-listener"), Port: utils.Ptr(int64(80)), Protocol: utils.Ptr(loadbalancer.LISTENERPROTOCOL_TCP), TargetPool: utils.Ptr("web-pool"), }, }, TargetPools: &[]loadbalancer.TargetPool{ { Name: utils.Ptr("web-pool"), TargetPort: utils.Ptr(int64(8080)), Targets: &[]loadbalancer.Target{ { DisplayName: utils.Ptr("web-server-1"), Ip: utils.Ptr("10.0.0.10"), }, { DisplayName: utils.Ptr("web-server-2"), Ip: utils.Ptr("10.0.0.11"), }, }, }, }, } createResp, err := lbClient.CreateLoadBalancer(ctx, projectId, region). CreateLoadBalancerPayload(createPayload). XRequestID("request-correlation-id"). Execute() if err != nil { fmt.Fprintf(os.Stderr, "Error creating load balancer: %v\n", err) os.Exit(1) } fmt.Printf("Created load balancer: %s\n", *createResp.Name) } ``` -------------------------------- ### Go Waiter Function for Deleting a Bar Resource Source: https://github.com/stackitcloud/stackit-sdk-go/blob/main/CONTRIBUTION.md This Go function, DeleteBarWaitHandler, demonstrates how to implement a waiter to confirm the successful deletion of a 'Bar' resource. It polls the ListBars API until the specified barId is no longer present in the response. This approach is useful when a direct 'Get' call after deletion might fail because the resource no longer exists. The function sets a timeout for the waiting period. ```go func DeleteBarWaitHandler(ctx context.Context, a APIClientInterface, barId, projectId string) *wait.AsyncActionHandler[foo.ListBarsResponse] { handler := wait.New(func() (waitFinished bool, response *foo.ListBarsResponse, err error) { s, err := a.ListBarsExecute(ctx, barId, projectId) if err != nil { return false, nil, err } for i := range s { if *s[i].Id == barId { return false, nil, nil } } return true, s, nil }) handler.SetTimeout(10 * time.Minute) return handler } ```