### Go Module File Example for vSphere Automation SDK Source: https://github.com/vmware/vsphere-automation-sdk-go/blob/master/README.md This is an example of a go.mod file generated after initializing a Go Module for a project using the vSphere Automation SDK. It specifies the module name and the Go version required. ```go module sample go 1.17 ``` -------------------------------- ### Provisioning an SDDC in VMware Cloud with Task Tracking Source: https://context7.com/vmware/vsphere-automation-sdk-go/llms.txt Provides a Go code example for provisioning a Software-Defined Data Center (SDDC) in VMware Cloud, including asynchronous task tracking. It uses OAuth for authentication and configures SDDC parameters like name, hosts, region, and VPC CIDR. ```go package main import ( "fmt" "log" "time" "github.com/vmware/vsphere-automation-sdk-go/lib/cis" "github.com/vmware/vsphere-automation-sdk-go/lib/cis/task" "github.com/vmware/vsphere-automation-sdk-go/runtime/protocol/client" "github.com/vmware/vsphere-automation-sdk-go/runtime/security" "github.com/vmware/vsphere-automation-sdk-go/services/vmc/model" "github.com/vmware/vsphere-automation-sdk-go/services/vmc/orgs" ) func main() { // Setup connector with OAuth connector := client.NewConnector( "https://vmc.vmware.com/vmc/api", client.UsingRest(nil), client.WithSecurityContext(security.NewOauthSecurityContext("your-token"))) orgID := "your-org-id" // Configure SDDC numHosts := int64(3) region := "US_WEST_2" sddcName := "my-production-sddc" vpcCidr := "10.0.0.0/16" sddcConfig := model.AwsSddcConfig{ Name: &sddcName, NumHosts: &numHosts, Provider: model.SddcConfig_PROVIDER_AWS, Region: ®ion, VpcCidr: &vpcCidr, SddcType: model.AwsSddcConfig_SDDC_TYPE_1NODE, } // Create SDDC (returns task) sddcsClient := orgs.NewSddcsClient(connector) validateOnly := false taskResult, err := sddcsClient.Create(orgID, sddcConfig, &validateOnly) if err != nil { log.Fatalf("Failed to create SDDC: %v", err) } fmt.Printf("SDDC provisioning initiated. Task ID: %s\n", taskResult.Id) // Poll task until completion tasksClient := cis.NewTasksClient(connector) for { taskInfo, err := tasksClient.Get(taskResult.Id, nil) if err != nil { log.Fatalf("Failed to get task status: %v", err) } fmt.Printf("Task Status: %s - Progress: %d%%\n", taskInfo.Status, *taskInfo.Progress) if taskInfo.Status == task.Status_SUCCEEDED { fmt.Println("SDDC provisioning completed successfully!") // Result contains the created SDDC object break } if taskInfo.Status == task.Status_FAILED { log.Fatalf("SDDC provisioning failed: %v", taskInfo.Error_) } time.Sleep(30 * time.Second) // Poll every 30 seconds } } ``` -------------------------------- ### List and Get SDDCs with Filtering in Go Source: https://context7.com/vmware/vsphere-automation-sdk-go/llms.txt This Go code snippet demonstrates how to list all Software-Defined Data Centers (SDDCs) within an organization, including options to include deleted SDDCs. It also shows how to apply advanced filters to retrieve specific SDDCs based on status, region, and creation date. Furthermore, it retrieves detailed information for a specific SDDC using its ID. Requires the vsphere-automation-sdk-go library and a valid OAuth token. ```go package main import ( "fmt" "log" "github.com/vmware/vsphere-automation-sdk-go/runtime/protocol/client" "github.com/vmware/vsphere-automation-sdk-go/runtime/security" "github.com/vmware/vsphere-automation-sdk-go/services/vmc/orgs" ) func main() { connector := client.NewConnector( "https://vmc.vmware.com/vmc/api", client.UsingRest(nil), client.WithSecurityContext(security.NewOauthSecurityContext("your-token"))) orgID := "your-org-id" sddcsClient := orgs.NewSddcsClient(connector) // List all SDDCs including deleted ones includeDeleted := true // Filter for active SDDCs in US regions created after specific date filter := "(sddc.status eq 'READY') and (region startswith 'US') and (created gt 2024-01-01)" sddcs, err := sddcsClient.List(orgID, &includeDeleted, &filter) if err != nil { log.Fatalf("Failed to list SDDCs: %v", err) } fmt.Printf("Found %d SDDCs:\n\n", len(sddcs)) for _, sddc := range sddcs { fmt.Printf("Name: %s\n", *sddc.Name) fmt.Printf(" ID: %s\n", sddc.Id) fmt.Printf(" Status: %s\n", sddc.SddcState) fmt.Printf(" Region: %s\n", *sddc.ResourceConfig.Region) fmt.Printf(" Hosts: %d\n", len(sddc.ResourceConfig.EsxHosts)) fmt.Printf(" vCenter: %s\n", *sddc.ResourceConfig.VcUrl) fmt.Printf(" NSX Manager: %s\n", *sddc.ResourceConfig.NsxMgrUrl) fmt.Println() } // Get detailed information about a specific SDDC if len(sddcs) > 0 { sddcID := sddcs[0].Id sddc, err := sddcsClient.Get(orgID, sddcID) if err != nil { log.Fatalf("Failed to get SDDC details: %v", err) } fmt.Printf("Detailed info for %s:\n", *sddc.Name) fmt.Printf(" Provider: %s\n", sddc.Provider) fmt.Printf(" Account ID: %s\n", *sddc.ResourceConfig.AccountLinkSddcConfig.CustomerSubnetIds) } } ``` -------------------------------- ### Manage NSX-T Infrastructure Configuration with Go Source: https://context7.com/vmware/vsphere-automation-sdk-go/llms.txt This Go code snippet demonstrates how to connect to an NSX-T Manager using the vSphere Automation SDK. It shows how to retrieve the current infrastructure configuration, create a new security domain, update the infrastructure with this new domain using a hierarchical patch, and then verify the changes by fetching the updated configuration. Dependencies include the vsphere-automation-sdk-go library. It takes NSX-T Manager connection details and security credentials as input and outputs infrastructure details and domain creation status. ```go package main import ( "fmt" "log" "github.com/vmware/vsphere-automation-sdk-go/runtime/protocol/client" "github.com/vmware/vsphere-automation-sdk-go/runtime/security" nsx_policy "github.com/vmware/vsphere-automation-sdk-go/services/nsxt" "github.com/vmware/vsphere-automation-sdk-go/services/nsxt/model" ) func main() { // Connect to NSX-T Manager with REST protocol connector := client.NewConnector( "https://nsx-manager.example.com", client.UsingRest(nil), client.WithSecurityContext( security.NewUserPasswordSecurityContext("admin", "password123")))) infraClient := nsx_policy.NewInfraClient(connector) // Get current infrastructure configuration infra, err := infraClient.Get(nil, nil, nil) if err != nil { log.Fatalf("Failed to get infrastructure: %v", err) } fmt.Printf("Infrastructure ID: %s\n", *infra.Id) fmt.Printf("Resource Type: %s\n", *infra.ResourceType) // Create a new domain for security policies domainID := "production-domain" domainName := "Production Domain" domain := model.Domain{ Id: &domainID, DisplayName: &domainName, Description: strPtr("Domain for production workloads"), } // Update infrastructure with new domain (hierarchical patch) infra.Domains = []model.Domain{domain} err = infraClient.Patch(infra, nil) if err != nil { log.Fatalf("Failed to patch infrastructure: %v", err) } fmt.Printf("Successfully created domain: %s\n", domainName) // Get updated infrastructure with filter filter := "Domain" updatedInfra, err := infraClient.Get(nil, &filter, nil) if err != nil { log.Fatalf("Failed to get updated infrastructure: %v", err) } fmt.Printf("Total domains: %d\n", len(updatedInfra.Domains)) for _, d := range updatedInfra.Domains { fmt.Printf(" - %s (ID: %s)\n", *d.DisplayName, *d.Id) } } func strPtr(s string) *string { return &s } ``` -------------------------------- ### Manage Session with Token Exchange (Go) Source: https://context7.com/vmware/vsphere-automation-sdk-go/llms.txt Demonstrates creating a session using initial credentials, exchanging them for a session token, and then using that token for subsequent API calls. It involves creating a connector, using the session client to create and manage the session, and updating the connector's security context. Sessions must be explicitly deleted when no longer needed. ```go package main import ( "fmt" "log" "github.com/vmware/vsphere-automation-sdk-go/lib/cis" "github.com/vmware/vsphere-automation-sdk-go/runtime/protocol/client" "github.com/vmware/vsphere-automation-sdk-go/runtime/security" ) func main() { // Step 1: Create connector with initial authentication (username/password) connector := client.NewConnector( "https://vcenter.example.com/api", client.WithSecurityContext( security.NewUserPasswordSecurityContext("administrator@vsphere.local", "password123"))) // Step 2: Create session client and exchange credentials for session token sessionClient := cis.NewSessionClient(connector) sessionID, err := sessionClient.Create() if err != nil { log.Fatalf("Failed to create session: %v", err) } fmt.Printf("Session created: %s\n", sessionID) // Step 3: Update connector to use session token for subsequent requests connector.SetSecurityContext(security.NewSessionSecurityContext(sessionID)) // Step 4: Get session information sessionInfo, err := sessionClient.Get() if err != nil { log.Fatalf("Failed to get session info: %v", err) } fmt.Printf("Session User: %s\n", sessionInfo.User) fmt.Printf("Created: %s\n", sessionInfo.CreatedTime) fmt.Printf("Last Accessed: %s\n", sessionInfo.LastAccessedTime) // Perform operations with the session... // Step 5: Clean up - delete session when done err = sessionClient.Delete() if err != nil { log.Fatalf("Failed to delete session: %v", err) } fmt.Println("Session deleted successfully") } ``` -------------------------------- ### Create NSX-T Security Policy and Rules (Go) Source: https://context7.com/vmware/vsphere-automation-sdk-go/llms.txt This Go code snippet demonstrates how to create a distributed firewall security policy and add a rule to it using the NSX-T Policy APIs. It requires the vsphere-automation-sdk-go library. Inputs include NSX-T manager address, credentials, policy details, and rule specifics. Outputs are the created policy and rule, with error handling. ```go package main import ( "fmt" "log" "github.com/vmware/vsphere-automation-sdk-go/runtime/protocol/client" "github.com/vmware/vsphere-automation-sdk-go/runtime/security" "github.com/vmware/vsphere-automation-sdk-go/services/nsxt/infra/domains" "github.com/vmware/vsphere-automation-sdk-go/services/nsxt/model" ) func main() { connector := client.NewConnector( "https://nsx-manager.example.com", client.UsingRest(nil), client.WithSecurityContext( security.NewUserPasswordSecurityContext("admin", "password123")))) domainID := "default" policyID := "web-tier-policy" ruleID := "allow-https" // Create security policy client securityPoliciesClient := domains.NewSecurityPoliciesClient(connector) // Define security policy policyName := "Web Tier Security Policy" category := model.SecurityPolicy_CATEGORY_APPLICATION securityPolicy := model.SecurityPolicy{ Id: &policyID, DisplayName: &policyName, Category: &category, Scope: []string{"/infra/domains/default/groups/web-servers"}, } // Create rules client rulesClient := domains.security_policies.NewRulesClient(connector) // Define firewall rule to allow HTTPS ruleName := "Allow HTTPS Inbound" action := model.Rule_ACTION_ALLOW direction := model.Rule_DIRECTION_IN disabled := false logged := true rule := model.Rule{ Id: &ruleID, DisplayName: &ruleName, Action: &action, Direction: &direction, Disabled: &disabled, Logged: &logged, SourceGroups: []string{"ANY"}, DestinationGroups: []string{"/infra/domains/default/groups/web-servers"}, Services: []string{"/infra/services/HTTPS"}, Scope: []string{"/infra/domains/default/groups/web-servers"}, } // Create the security policy createdPolicy, err := securityPoliciesClient.Patch(domainID, policyID, securityPolicy) if err != nil { log.Fatalf("Failed to create security policy: %v", err) } fmt.Printf("Created security policy: %s\n", *createdPolicy.DisplayName) // Add the rule to the policy err = rulesClient.Patch(domainID, policyID, ruleID, rule) if err != nil { log.Fatalf("Failed to create rule: %v", err) } fmt.Printf("Created firewall rule: %s\n", *rule.DisplayName) // Retrieve and display the complete policy policy, err := securityPoliciesClient.Get(domainID, policyID) if err != nil { log.Fatalf("Failed to get policy: %v", err) } fmt.Printf("\nPolicy Details:\n") fmt.Printf(" Name: %s\n", *policy.DisplayName) fmt.Printf(" Category: %s\n", *policy.Category) fmt.Printf(" Sequence: %d\n", *policy.SequenceNumber) fmt.Printf(" Path: %s\n", *policy.Path) } ``` -------------------------------- ### Initialize Go Module for vSphere Automation SDK Source: https://github.com/vmware/vsphere-automation-sdk-go/blob/master/README.md This code snippet demonstrates how to initialize a Go Module for a new project that will use the vSphere Automation SDK. It creates a go.mod file in the current directory, specifying the Go version and module name. ```shell go mod init sample ``` -------------------------------- ### IDE Auto-completion for vSphere Automation SDK Imports in Go Source: https://github.com/vmware/vsphere-automation-sdk-go/blob/master/README.md This Go code snippet demonstrates how to use underscore aliasing for importing vSphere Automation SDK modules, which is recommended for IDEs to enable features like auto-completion. After setting up imports, running 'go test' or 'go build' fetches dependencies. ```go package main import ( _ "github.com/vmware/vsphere-automation-sdk-go/services/vmc" ) ``` -------------------------------- ### Create vSphere Connector with Username/Password Auth (Go) Source: https://context7.com/vmware/vsphere-automation-sdk-go/llms.txt Initializes a vSphere API connector using basic username and password authentication. It requires the SDK's client and security packages. The connector is ready for service client usage and is thread-safe. ```go package main import ( "fmt" "log" "github.com/vmware/vsphere-automation-sdk-go/runtime/protocol/client" "github.com/vmware/vsphere-automation-sdk-go/runtime/security" ) func main() { // Create connector with basic authentication connector := client.NewConnector( "https://vcenter.example.com/api", client.WithSecurityContext( security.NewUserPasswordSecurityContext("administrator@vsphere.local", "password123"))) // Connector is now ready for use with any service client fmt.Println("Connector created successfully") fmt.Println("Address:", connector.Address()) // The connector is thread-safe and can be reused across multiple goroutines // for concurrent API calls } ``` -------------------------------- ### Import VMC and NSX-T Services in Go Source: https://github.com/vmware/vsphere-automation-sdk-go/blob/master/README.md This Go code excerpt shows how to import the vSphere Automation SDK modules for VMC and NSX-T services. It includes necessary imports for basic functionality and demonstrates aliasing for IDE support. ```go package main import ( "fmt" "os" vmc "github.com/vmware/vsphere-automation-sdk-go/services/vmc" . . . ) ``` -------------------------------- ### SAML Holder-of-Key Authentication with Request Signing Source: https://context7.com/vmware/vsphere-automation-sdk-go/llms.txt Illustrates advanced authentication using SAML Holder-of-Key (HoK) tokens with request signing for enhanced security. This method requires a SAML HoK token, a corresponding RSA private key, and specifies the signature algorithm. ```go package main import ( "fmt" "log" "github.com/vmware/vsphere-automation-sdk-go/runtime/protocol/client" "github.com/vmware/vsphere-automation-sdk-go/runtime/security" ) func main() { // SAML HoK token from Secure Token Service (STS) samlHokToken := `...` // RSA private key in PEM format (matching the certificate in SAML token) privateKeyPEM := `-----BEGIN RSA PRIVATE KEY----- MIIEpAIBAAKCAQEA... -----END RSA PRIVATE KEY-----` // Create connector with SAML HoK authentication // The SDK will automatically sign each request with the private key connector := client.NewConnector( "https://vcenter.example.com/api", client.WithSecurityContext( security.NewSAMLSecurityContext( samlHokToken, privateKeyPEM, security.RS256))) // Signature algorithm (RS256, RS384, or RS512) // Connector is ready - all requests will be signed automatically fmt.Println("SAML HoK connector created successfully") // The SDK handles request signing transparently for all API calls } ``` -------------------------------- ### List and Filter vSphere Tasks Source: https://context7.com/vmware/vsphere-automation-sdk-go/llms.txt Retrieves a list of vSphere tasks based on specified filters. It demonstrates how to filter by task status (e.g., running, pending) and retrieve detailed information for each task. Supports filtering by service and specifying returned data. Maximum of 1000 tasks are returned. ```go package main import ( "fmt" "log" "github.com/vmware/vsphere-automation-sdk-go/lib/cis" "github.com/vmware/vsphere-automation-sdk-go/lib/cis/task" "github.com/vmware/vsphere-automation-sdk-go/runtime/protocol/client" "github.com/vmware/vsphere-automation-sdk-go/runtime/security" ) func main() { connector := client.NewConnector( "https://vcenter.example.com/api", client.WithSecurityContext( security.NewSessionSecurityContext("your-session-id"))) // Replace with your session ID tasksClient := cis.NewTasksClient(connector) // Create filter for running tasks runningStatus := []task.Status{task.Status_RUNNING, task.Status_PENDING} filterSpec := &cis.TasksFilterSpec{ Tasks: nil, // nil = all tasks Status: runningStatus, Services: nil, // Filter by service if needed } // Optionally specify what data to retrieve resultSpec := &cis.TasksGetSpec{ ReturnAll: nil, // Get all available data ExcludeResult: nil, } // List tasks (max 1000 returned) tasks, err := tasksClient.List(filterSpec, resultSpec) if err != nil { log.Fatalf("Failed to list tasks: %v", err) } fmt.Printf("Found %d active tasks:\n\n", len(tasks)) for taskID, taskInfo := range tasks { fmt.Printf("Task ID: %s\n", taskID) fmt.Printf(" Status: %s\n", taskInfo.Status) fmt.Printf(" Description: %s\n", taskInfo.Description.DefaultMessage) fmt.Printf(" Progress: %d%%\n", *taskInfo.Progress) fmt.Printf(" Service: %s\n", taskInfo.Service) fmt.Printf(" Operation: %s\n", taskInfo.Operation) fmt.Printf(" Started: %s\n", taskInfo.StartTime.String()) if taskInfo.User != nil { fmt.Printf(" User: %s\n", *taskInfo.User) } fmt.Println() } } ``` -------------------------------- ### Handle vAPI Standard Errors in Go Source: https://context7.com/vmware/vsphere-automation-sdk-go/llms.txt Demonstrates how to catch and handle various vAPI standard error types (e.g., Unauthenticated, Unauthorized, NotFound) using type assertions in Go. This ensures graceful failure and informative feedback for API interactions. ```go package main import ( "errors" "fmt" "log" "github.com/vmware/vsphere-automation-sdk-go/lib/cis" "github.com/vmware/vsphere-automation-sdk-go/lib/vapi/std/errors" "github.com/vmware/vsphere-automation-sdk-go/runtime/protocol/client" "github.com/vmware/vsphere-automation-sdk-go/runtime/security" ) func main() { connector := client.NewConnector( "https://vcenter.example.com/api", client.WithSecurityContext( security.NewUserPasswordSecurityContext("admin", "wrong-password"))) // Example with wrong password sessionClient := cis.NewSessionClient(connector) // Attempt to create session (will fail with wrong password) sessionID, err := sessionClient.Create() if err != nil { handleError(err) return } fmt.Printf("Session created: %s\n", sessionID) } func handleError(err error) { // Check for specific error types using type assertions var unauthenticated *errors.Unauthenticated if errors.As(err, &unauthenticated) { log.Printf("Authentication failed: %v", unauthenticated.Messages) log.Printf("Please check your credentials") return } var unauthorized *errors.Unauthorized if errors.As(err, &unauthorized) { log.Printf("Authorization failed: %v", unauthorized.Messages) log.Printf("User lacks required privileges") return } var notFound *errors.NotFound if errors.As(err, ¬Found) { log.Printf("Resource not found: %v", notFound.Messages) return } var serviceUnavailable *errors.ServiceUnavailable if errors.As(err, &serviceUnavailable) { log.Printf("Service unavailable: %v", serviceUnavailable.Messages) log.Printf("Please retry after some time") return } var invalidArgument *errors.InvalidArgument if errors.As(err, &invalidArgument) { log.Printf("Invalid argument: %v", invalidArgument.Messages) return } var timedOut *errors.TimedOut if errors.As(err, &timedOut) { log.Printf("Operation timed out: %v", timedOut.Messages) return } var resourceBusy *errors.ResourceBusy if errors.As(err, &resourceBusy) { log.Printf("Resource busy: %v", resourceBusy.Messages) log.Printf("Please retry later") return } var alreadyExists *errors.AlreadyExists if errors.As(err, &alreadyExists) { log.Printf("Resource already exists: %v", alreadyExists.Messages) return } // Generic error handling log.Printf("Unexpected error: %v", err) } ``` -------------------------------- ### Perform Concurrent vSphere API Calls in Go Source: https://context7.com/vmware/vsphere-automation-sdk-go/llms.txt Illustrates how to utilize a single, thread-safe connector instance to make concurrent API calls across multiple goroutines. This pattern enhances performance by parallelizing operations, such as fetching organization details and listing SDDCs. ```go package main import ( "fmt" "sync" "github.com/vmware/vsphere-automation-sdk-go/runtime/protocol/client" "github.com/vmware/vsphere-automation-sdk-go/runtime/security" "github.com/vmware/vsphere-automation-sdk-go/services/vmc" "github.com/vmware/vsphere-automation-sdk-go/services/vmc/orgs" ) func main() { // Single connector instance (thread-safe) connector := client.NewConnector( "https://vmc.vmware.com/vmc/api", client.UsingRest(nil), client.WithSecurityContext( security.NewOauthSecurityContext("your-token"))) // Replace with your token // List of organization IDs to process orgIDs := []string{"org-1", "org-2", "org-3", "org-4", "org-5"} // Example IDs var wg sync.WaitGroup results := make(chan string, len(orgIDs)) // Launch concurrent goroutines using the same connector for _, orgID := range orgIDs { wg.Add(1) go func(id string) { defer wg.Done() // Each goroutine uses the same connector safely orgsClient := vmc.NewOrgsClient(connector) sddcsClient := orgs.NewSddcsClient(connector) // Get organization details org, err := orgsClient.Get(id) if err != nil { results <- fmt.Sprintf("Org %s: Error - %v", id, err) return } // List SDDCs for this organization sddcs, err := sddcsClient.List(id, nil, nil) if err != nil { results <- fmt.Sprintf("Org %s: Error listing SDDCs - %v", id, err) return } results <- fmt.Sprintf("Org %s (%s): %d SDDCs", id, *org.DisplayName, len(sddcs)) }(orgID) } // Close results channel when all goroutines complete go func() { wg.Wait() close(results) }() // Collect and display results fmt.Println("Processing organizations concurrently...") for result := range results { fmt.Println(result) } } ``` -------------------------------- ### Listing and Filtering Tasks Source: https://context7.com/vmware/vsphere-automation-sdk-go/llms.txt Query multiple vSphere tasks with filter specifications. This endpoint is useful for monitoring the status of ongoing operations and can be filtered by status, service, etc. ```APIDOC ## GET /api/tasks ### Description Retrieves a list of vSphere tasks, with options to filter by status and other criteria. ### Method GET ### Endpoint /api/tasks ### Parameters #### Query Parameters - **status** (array[string]) - Optional - Filters tasks by their status (e.g., RUNNING, PENDING, SUCCESS, FAILED). - **services** (array[string]) - Optional - Filters tasks by the service they belong to. - **max_results** (integer) - Optional - The maximum number of tasks to return. ### Request Example ```json { "example": "GET /api/tasks?status=RUNNING&status=PENDING&max_results=100" } ``` ### Response #### Success Response (200 OK) - **tasks** (object) - A map where keys are task IDs and values are task information objects. - **task_id** (string) - The unique identifier for the task. - **status** (string) - The current status of the task (e.g., RUNNING, PENDING, SUCCESS, FAILED). - **description** (object) - A localized description of the task. - **default_message** (string) - The default message for the task description. - **progress** (integer) - The completion percentage of the task. - **service** (string) - The vSphere service associated with the task. - **operation** (string) - The specific operation the task is performing. - **start_time** (string) - The timestamp when the task started. - **user** (string) - The user who initiated the task (optional). #### Response Example ```json { "example": { "task-1": { "status": "RUNNING", "description": {"default_message": "Deploying virtual machine"}, "progress": 50, "service": "vcenter.vm", "operation": "com.vmware.vcenter.vm.deployment.deploy", "start_time": "2023-10-27T10:00:00Z", "user": "administrator@vsphere.local" }, "task-2": { "status": "PENDING", "description": {"default_message": "Creating snapshot"}, "progress": 0, "service": "vcenter.snapshot", "operation": "com.vmware.vcenter.vm.snapshot.create", "start_time": "2023-10-27T10:05:00Z" } } } ``` #### Error Response (400 Bad Request) - **error** (object) - Details about the error if the request parameters are invalid. ``` -------------------------------- ### OAuth Token Authentication for VMC using REST Source: https://context7.com/vmware/vsphere-automation-sdk-go/llms.txt Demonstrates how to authenticate to VMware Cloud services using OAuth access tokens with the REST protocol. It requires a valid OAuth access token and establishes a client to list authorized organizations. ```go package main import ( "fmt" "log" "github.com/vmware/vsphere-automation-sdk-go/runtime/protocol/client" "github.com/vmware/vsphere-automation-sdk-go/runtime/security" "github.com/vmware/vsphere-automation-sdk-go/services/vmc" ) func main() { // OAuth token obtained from VMware Cloud Console accessToken := "your-refresh-token-here" // Create connector with OAuth authentication and REST protocol connector := client.NewConnector( "https://vmc.vmware.com/vmc/api", client.UsingRest(nil), // Switch from JSON-RPC to REST protocol client.WithSecurityContext( security.NewOauthSecurityContext(accessToken))) // Create organizations client orgsClient := vmc.NewOrgsClient(connector) // List all authorized organizations orgs, err := orgsClient.List() if err != nil { log.Fatalf("Failed to list organizations: %v", err) } fmt.Printf("Found %d organizations:\n", len(orgs)) for _, org := range orgs { fmt.Printf(" - %s (ID: %s)\n", *org.DisplayName, org.Id) fmt.Printf(" Created: %s\n", org.Created.String()) } } ``` -------------------------------- ### Configure Custom REST Protocol Options (Go) Source: https://context7.com/vmware/vsphere-automation-sdk-go/llms.txt This Go code snippet shows how to configure a custom HTTP client with specific timeouts and TLS settings for use with the vSphere Automation SDK's REST protocol. It utilizes the standard Go `net/http` package and the SDK's `client.NewConnector` function with `client.WithHttpClient`. This allows fine-grained control over API communication parameters. ```go package main import ( "crypto/tls" "fmt" "net/http" "time" "github.com/vmware/vsphere-automation-sdk-go/runtime/protocol/client" "github.com/vmware/vsphere-automation-sdk-go/runtime/security" ) func main() { // Create custom HTTP client with specific timeouts and TLS config httpClient := &http.Client{ Timeout: 60 * time.Second, Transport: &http.Transport{ TLSClientConfig: &tls.Config{ InsecureSkipVerify: false, // Set to true only for testing MinVersion: tls.VersionTLS12, }, MaxIdleConns: 100, MaxIdleConnsPerHost: 10, IdleConnTimeout: 90 * time.Second, }, } // Create connector with custom HTTP client and REST protocol connector := client.NewConnector( "https://vmc.vmware.com/vmc/api", client.UsingRest(nil), // Use REST protocol client.WithHttpClient(httpClient), // Custom HTTP client client.WithSecurityContext( security.NewOauthSecurityContext("your-token"))) fmt.Println("Connector created with custom HTTP client") fmt.Printf("Address: %s\n", connector.Address()) // The connector now uses the custom HTTP client for all REST API calls // This is useful for: // - Custom timeout configurations // - Proxy settings // - TLS certificate handling // - Connection pooling tuning // - Request/response logging } ``` -------------------------------- ### Delete SDDC with Configuration Retention in Go Source: https://context7.com/vmware/vsphere-automation-sdk-go/llms.txt This Go code snippet demonstrates how to delete a Software-Defined Data Center (SDDC) using the vSphere Automation SDK for Go. It includes an option to retain the SDDC's configuration as a template for future use and allows for monitoring the deletion task's progress. The `force` parameter can be set to `true` to attempt deletion even if provisioning is in progress. Requires the vsphere-automation-sdk-go library and a valid OAuth token. ```go package main import ( "fmt" "log" "time" "github.com/vmware/vsphere-automation-sdk-go/lib/cis" "github.com/vmware/vsphere-automation-sdk-go/lib/cis/task" "github.com/vmware/vsphere-automation-sdk-go/runtime/protocol/client" "github.com/vmware/vsphere-automation-sdk-go/runtime/security" "github.com/vmware/vsphere-automation-sdk-go/services/vmc/orgs" ) func main() { connector := client.NewConnector( "https://vmc.vmware.com/vmc/api", client.UsingRest(nil), client.WithSecurityContext(security.NewOauthSecurityContext("your-token"))) orgID := "your-org-id" sddcID := "sddc-to-delete" // Configure deletion options retainConfig := true // Save SDDC configuration as template templateName := "production-sddc-template" force := false // Don't force delete if provisioning is in progress sddcsClient := orgs.NewSddcsClient(connector) // Initiate SDDC deletion taskResult, err := sddcsClient.Delete(orgID, sddcID, &retainConfig, &templateName, &force) if err != nil { log.Fatalf("Failed to delete SDDC: %v", err) } fmt.Printf("SDDC deletion initiated. Task ID: %s\n", taskResult.Id) // Monitor deletion progress tasksClient := cis.NewTasksClient(connector) for { taskInfo, err := tasksClient.Get(taskResult.Id, nil) if err != nil { log.Fatalf("Failed to get task status: %v", err) } fmt.Printf("Deletion Progress: %d%% - Status: %s\n", *taskInfo.Progress, taskInfo.Status) if taskInfo.Status == task.Status_SUCCEEDED { fmt.Println("SDDC deleted successfully!") fmt.Printf("Configuration saved as template: %s\n", templateName) break } if taskInfo.Status == task.Status_FAILED { log.Fatalf("SDDC deletion failed: %v", taskInfo.Error_) } time.Sleep(30 * time.Second) } } ``` -------------------------------- ### Cancel Long-Running vSphere Tasks Source: https://context7.com/vmware/vsphere-automation-sdk-go/llms.txt Demonstrates best-effort cancellation of a vSphere task. It first retrieves the task's status and cancelability, then initiates cancellation if the task is running and cancelable. Requires a valid session ID and task ID. ```go package main import ( "fmt" "log" "github.com/vmware/vsphere-automation-sdk-go/lib/cis" "github.com/vmware/vsphere-automation-sdk-go/lib/cis/task" "github.com/vmware/vsphere-automation-sdk-go/runtime/protocol/client" "github.com/vmware/vsphere-automation-sdk-go/runtime/security" ) func main() { connector := client.NewConnector( "https://vcenter.example.com/api", client.WithSecurityContext( security.NewSessionSecurityContext("your-session-id"))) // Replace with your session ID tasksClient := cis.NewTasksClient(connector) taskID := "task-id-to-cancel" // Replace with the ID of the task to cancel // Get current task status taskInfo, err := tasksClient.Get(taskID, nil) if err != nil { log.Fatalf("Failed to get task: %v", err) } fmt.Printf("Task Status: %s\n", taskInfo.Status) fmt.Printf("Description: %s\n", taskInfo.Description.DefaultMessage) fmt.Printf("Cancelable: %t\n", *taskInfo.Cancelable) // Only attempt cancellation if task is still running and cancelable if taskInfo.Status == task.Status_RUNNING && *taskInfo.Cancelable { err = tasksClient.Cancel(taskID) if err != nil { log.Fatalf("Failed to cancel task: %v", err) } fmt.Println("Cancellation requested (best effort)") // Verify cancellation taskInfo, _ = tasksClient.Get(taskID, nil) fmt.Printf("New Status: %s\n", taskInfo.Status) } else { fmt.Println("Task cannot be canceled (already completed or not cancelable)") } } ``` -------------------------------- ### Canceling Long-Running Tasks Source: https://context7.com/vmware/vsphere-automation-sdk-go/llms.txt This endpoint allows for the best-effort cancellation of in-progress vSphere operations. It first retrieves the task status to determine if it is running and cancelable, then attempts to cancel it. ```APIDOC ## POST /api/tasks/{task_id}/cancel ### Description Attempts to cancel a long-running vSphere task. ### Method POST ### Endpoint /api/tasks/{task_id}/cancel ### Parameters #### Path Parameters - **task_id** (string) - Required - The ID of the task to cancel. ### Request Example ```json { "example": "POST /api/tasks/task-id-to-cancel/cancel" } ``` ### Response #### Success Response (204 No Content) Indicates that the cancellation request was successfully sent. #### Error Response (400 Bad Request) - **error** (object) - Details about the error if the task cannot be canceled or does not exist. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.