### Run SDK Example Source: https://github.com/vmware/go-vcloud-director/blob/main/README.md Steps to set up and run a basic example demonstrating the go-vcloud-director SDK in action. This involves initializing a Go module, fetching the SDK, building an example executable, and running it with necessary arguments. ```bash mkdir ~/govcd_example go mod init govcd_example go get github.com/vmware/go-vcloud-director/v3@main go build -o example ./example user_name "password" org_name vcd_IP vdc_name ``` -------------------------------- ### Basic Test Function Organization in Go Source: https://github.com/vmware/go-vcloud-director/blob/main/TESTING.md Demonstrates the standard four-step process for organizing a test function: setup, execute operation, assert results, and cleanup. This example focuses on finding a catalog item and retrieving a vApp template. ```go package govcd import ( "fmt" checks "gopkg.in/check.v1" ) func (vcd *TestVCD) Test_GetVAppTemplate(check *checks.C) { fmt.Printf("Running: %s\n", check.TestName()) // #0 Check that the data needed for this test is in the configuration if vcd.config.VCD.Catalog.Name == "" { check.Skip("Catalog name not provided. Test can't proceed") } // #1: preliminary data cat, err := vcd.org.FindCatalog(vcd.config.VCD.Catalog.Name) if err != nil { check.Skip("Catalog not found. Test can't proceed") } // #2: Run the operation being tested catitem, err := cat.FindCatalogItem(vcd.config.VCD.Catalog.Catalogitem) check.Assert(err, checks.IsNil) vapptemplate, err := catitem.GetVAppTemplate() // #3: Tests the object contents check.Assert(err, checks.IsNil) check.Assert(vapptemplate.VAppTemplate.Name, checks.Equals, vcd.config.VCD.Catalog.Catalogitem) if vcd.config.VCD.Catalog.Description != "" { check.Assert(vapptemplate.VAppTemplate.Description, checks.Equals, vcd.config.VCD.Catalog.CatalogItemDescription) } // #4 is not needed here, as the test did not modify anything } ``` -------------------------------- ### Build and Run SAML Auth Example Source: https://github.com/vmware/go-vcloud-director/blob/main/samples/saml_auth_adfs/README.md Build the Go application and run it with the required command-line parameters for SAML authentication against vCD using ADFS. ```bash go build -o auth ./auth --username test@test-forest.net --password my-password --org my-org --endpoint https://_YOUR_HOSTNAME_/api ``` -------------------------------- ### Example Test Command with Multiple Tags Source: https://github.com/vmware/go-vcloud-director/blob/main/TESTING.md Demonstrates how to run tests with multiple tags by passing them as a space-separated string to the '-tags' flag. This example shows running 'query' and 'extnetwork' tests. ```bash go test -tags "query extnetwork" -check.vv -timeout=45m . ``` -------------------------------- ### Build and Install go-vcloud-director Source: https://github.com/vmware/go-vcloud-director/blob/main/README.md Instructions for cloning the repository and building the go-vcloud-director package using Go modules. Ensure GO111MODULE is set to 'on' if working within GOPATH. ```bash cd ~/Documents/mycode git clone https://github.com/vmware/go-vcloud-director.git cd go-vcloud-director/govcd go build ``` -------------------------------- ### Outer Type Wrap Method Example Source: https://github.com/vmware/go-vcloud-director/blob/main/CODING_GUIDELINES.md Provides an example signature for the required 'wrap' method that an 'outer' type must implement to satisfy generic interface constraints. ```go func (o OuterEntity) wrap(inner *InnerEntity) *OuterEntity { o.OuterEntity = inner return &o } ``` -------------------------------- ### Retrieve Tenant Context in AdminOrg Source: https://github.com/vmware/go-vcloud-director/blob/main/CODING_GUIDELINES.md Example of how to retrieve the tenant context from an AdminOrg object and use it to make an API call. It demonstrates the pattern of getting context and passing it to a helper function for API requests. ```go func (adminOrg *AdminOrg) GetAllRoles(queryParameters url.Values) ([]*Role, error) { tenantContext, err := adminOrg.getTenantContext() if err != nil { return nil, err } return getAllRoles(adminOrg.client, queryParameters, getTenantContextHeader(tenantContext)) } ``` -------------------------------- ### Makefile Test Command with Custom Tags Source: https://github.com/vmware/go-vcloud-director/blob/main/TESTING.md Example of how to include custom build tags in the `make test` command for running specific tests. ```bash test: fmtcheck @echo "==> Running Tests" cd govcd && \ go test -tags "MyNewTag" -timeout=10m -check.vv . && \ go test -tags "functional" -timeout=60m -check.vv . ``` -------------------------------- ### vCD Query Engine Filter Criteria Example Source: https://github.com/vmware/go-vcloud-director/blob/main/CODING_GUIDELINES.md Example demonstrating how to construct a FilterDef for the vCD query engine. This includes name, date, latest, and metadata filters. ```go criteria := &govcd.FilterDef{ Filters: { "name": "^Centos", "date": "> 2020-02-02", "latest": "true", }, Metadata: { { Key: "dept", Type: "STRING", Value: "ST\\w+", IsSystem: false, }, }, UseMetadataApiFilter: false, } ``` -------------------------------- ### Build Tag and Package Declaration Source: https://github.com/vmware/go-vcloud-director/blob/main/TESTING.md Test files must start with a build tag, followed by a blank line and the package declaration. The `functional` tag is used for tests requiring a live vCD instance. ```go // +build functional featurename ALL package govcd ``` -------------------------------- ### vCD System Metadata Example Source: https://github.com/vmware/go-vcloud-director/blob/main/CODING_GUIDELINES.md Illustrates SYSTEM metadata values, such as annotations added by vCD to a vApp template when saved to a catalog. Useful for understanding vCD's internal object representation. ```json "metadata" = { "vapp.origin.id" = "deadbeef-2913-4ed7-b943-79a91620fd52" // vApp ID "vapp.origin.name" = "my_vapp_name" "vapp.origin.type" = "com.vmware.vcloud.entity.vapp" } ``` -------------------------------- ### Create and Get OpenAPI Org VDC Network Source: https://context7.com/vmware/go-vcloud-director/llms.txt Demonstrates creating a routed Org VDC network and then retrieving it by name. Ensure the VDC and Edge Gateway objects are properly initialized. ```go vdc, _ := org.GetVDCByName("my-vdc", false) egw, _ := vdc.GetNsxtEdgeGatewayByName("my-edge-gw") // Create a routed network networkConfig := &types.OpenApiOrgVdcNetwork{ Name: "routed-net", Description: "Routed network connected to edge gateway", OwnerRef: &types.OpenApiReference{ID: vdc.Vdc.ID}, NetworkType: types.OrgVdcNetworkTypeRouted, Subnets: types.OrgVdcNetworkSubnets{ Values: []types.OrgVdcNetworkSubnetValues{ { Gateway: "192.168.100.1", PrefixLength: 24, IPRanges: types.OrgVdcNetworkSubnetIPRanges{ Values: []types.OrgVdcNetworkSubnetIPRangeValues{ {StartAddress: "192.168.100.10", EndAddress: "192.168.100.200"}, }, }, }, }, }, Connection: &types.Connection{ RouterRef: types.OpenApiReference{ID: egw.EdgeGateway.ID}, ConnectionType: "INTERNAL", }, } newNet, err := vdc.CreateOpenApiOrgVdcNetwork(networkConfig) if err != nil { panic(err) } fmt.Println("Network created:", newNet.OpenApiOrgVdcNetwork.ID) // Retrieve existing network net, _ := vdc.GetOpenApiOrgVdcNetworkByName("routed-net") fmt.Println("Network HREF:", net.OpenApiOrgVdcNetwork.ID) ``` -------------------------------- ### Update VM Network Configuration Source: https://context7.com/vmware/go-vcloud-director/llms.txt Manages NIC assignments on a VM, supporting DHCP, pool, manual, and none allocation modes. This example reconfigures the first NIC to manual IP and adds a second NIC with DHCP. ```go vm, _ := vapp.GetVMByName("my-vm", true) netSection, err := vm.GetNetworkConnectionSection() if err != nil { panic(err) } // Reconfigure first NIC to manual IP netSection.NetworkConnection[0].IPAddressAllocationMode = types.IPAllocationModeManual netSection.NetworkConnection[0].IPAddress = "192.168.1.50" netSection.NetworkConnection[0].IsConnected = true if err := vm.UpdateNetworkConnectionSection(netSection); err != nil { panic(err) } fmt.Println("NIC updated to 192.168.1.50") // Add a second NIC orgNetwork, _ := vdc.GetOrgVdcNetworkByName("mgmt-network", false) netSection.NetworkConnection = append(netSection.NetworkConnection, &types.NetworkConnection{ Network: orgNetwork.OrgVDCNetwork.Name, NetworkConnectionIndex: 1, IsConnected: true, IPAddressAllocationMode: types.IPAllocationModeDHCP, }) _ = vm.UpdateNetworkConnectionSection(netSection) ``` -------------------------------- ### Get and Update NSX-T Firewall Rules Source: https://context7.com/vmware/go-vcloud-director/llms.txt Retrieves the current NSX-T firewall rules and then replaces all user-defined rules atomically. Ensure the Edge Gateway object is properly initialized. ```go egw, _ := adminOrg.GetNsxtEdgeGatewayByName("my-edge-gw") // Read current rules fw, err := egw.GetNsxtFirewall() if err != nil { panic(err) } fmt.Println("Existing user rules:", len(fw.NsxtFirewallRuleContainer.UserDefinedRules)) // Set new rules (replaces all user-defined rules) newRules := &types.NsxtFirewallRuleContainer{ UserDefinedRules: []*types.NsxtFirewallRule{ { Name: "allow-http", Action: "ALLOW", Enabled: true, Direction: "IN_OUT", IpProtocol: "IPV4_IPV6", ApplicationPortProfiles: []*types.OpenApiRef{ {Name: "HTTP", ID: "urn:vcloud:applicationPortProfile:..."}, }, }, { Name: "deny-all", Action: "DROP", Enabled: true, Direction: "IN_OUT", IpProtocol: "IPV4_IPV6", }, }, } updatedFw, err := egw.UpdateNsxtFirewall(newRules) if err != nil { panic(err) } fmt.Println("Applied", len(updatedFw.NsxtFirewallRuleContainer.UserDefinedRules), "firewall rules") ``` -------------------------------- ### Authenticate VCD Client with SAML ADFS Source: https://github.com/vmware/go-vcloud-director/blob/main/README.md Provides an example of authenticating a VCD client using SAML with ADFS as the Identity Provider. This method requires specifying SAML ADFS options and formatting the username appropriately for ADFS. ```go vcdCli := govcd.NewVCDClient(*vcdURL, true, govcd.WithSamlAdfs(true, customAdfsRptId)) err = vcdCli.Authenticate(username, password, org) ``` -------------------------------- ### Create a New Topic Branch Source: https://github.com/vmware/go-vcloud-director/blob/main/CONTRIBUTING.md Start a new topic branch from the current HEAD position on main to commit your feature changes. This isolates your work and makes it easier to manage pull requests. ```shell git checkout -b foo-api-fix-22 main ``` -------------------------------- ### Initialize VCD Client with Options Source: https://context7.com/vmware/go-vcloud-director/llms.txt Demonstrates creating a VCD client using functional options for configuration such as retry timeouts, HTTP timeouts, and user agent. Includes authentication with username/password and disconnection. ```go package main import ( "fmt" "net/url" "github.com/vmware/go-vcloud-director/v3/govcd" ) func main() { vcdURL, err := url.ParseRequestURI("https://vcd.example.com/api") if err != nil { panic(err) } // Create client with options client := govcd.NewVCDClient(*vcdURL, true, // insecure TLS govcd.WithMaxRetryTimeout(120), govcd.WithHttpTimeout(600), govcd.WithHttpUserAgent("my-app/1.0"), ) // Authenticate with username/password if err := client.Authenticate("admin", "password", "System"); err != nil { panic(fmt.Sprintf("auth failed: %s", err)) } defer client.Disconnect() fmt.Println("Connected to VCD successfully") } ``` -------------------------------- ### Create a vApp from scratch or from a template Source: https://context7.com/vmware/go-vcloud-director/llms.txt Demonstrates creating an empty vApp or instantiating a vApp from an existing template. Ensure the VDC, catalog, and template exist. ```go vdc, _ := org.GetVDCByName("my-vdc", false) // Create empty vApp vapp, err := vdc.CreateRawVApp("my-vapp", "My test vApp") if err != nil { panic(err) } fmt.Println("Created vApp:", vapp.VApp.Name, "HREF:", vapp.VApp.HREF) // -- OR: instantiate from template -- catalog, _ := org.GetCatalogByName("my-catalog", false) vappTemplate, _ := catalog.GetVAppTemplateByName("ubuntu-22.04") storageProfile, _ := vdc.FindStorageProfileReference("*") newVapp, err := vdc.CreateVappFromTemplate(vappTemplate, &storageProfile, "from-template-vapp") if err != nil { panic(err) } if err := newVapp.BlockWhileStatus("UNRESOLVED", 120); err != nil { panic(err) } fmt.Println("vApp from template:", newVapp.VApp.Name) ``` -------------------------------- ### Client Initialization Source: https://context7.com/vmware/go-vcloud-director/llms.txt Demonstrates how to create a new VCD client instance using functional options for configuration and authenticate with username and password. ```APIDOC ## Client Initialization `NewVCDClient` creates a VCD client with a functional-options pattern for configuration. Supported options include `WithMaxRetryTimeout`, `WithAPIVersion`, `WithHttpTimeout`, `WithSamlAdfs`, `WithHttpUserAgent`, and `WithHttpHeader`. ### Method Signature ```go func NewVCDClient(apiEndpoint url.URL, insecure bool, options ...ClientOption) *VCDClient ``` ### Parameters - **apiEndpoint** (url.URL) - The base URL for the VCD API. - **insecure** (bool) - Whether to allow insecure TLS connections. - **options** (...ClientOption) - Functional options for client configuration. ### Example Usage ```go package main import ( "fmt" "net/url" "github.com/vmware/go-vcloud-director/v3/govcd" ) func main() { vcdURL, err := url.ParseRequestURI("https://vcd.example.com/api") if err != nil { panic(err) } // Create client with options client := govcd.NewVCDClient(*vcdURL, true, // insecure TLS govcd.WithMaxRetryTimeout(120), govcd.WithHttpTimeout(600), govcd.WithHttpUserAgent("my-app/1.0"), ) // Authenticate with username/password if err := client.Authenticate("admin", "password", "System"); err != nil { panic(fmt.Sprintf("auth failed: %s", err)) } defer client.Disconnect() fmt.Println("Connected to VCD successfully") } ``` ``` -------------------------------- ### Filter Logs by Function Name Source: https://github.com/vmware/go-vcloud-director/blob/main/util/LOGGING.md To log only messages from specific function names, use `util.SetApiLogFunctions()`. For example, to log only from `FindVAppByName` and `GetAdminOrgByName`. ```go util.SetApiLogFunctions("FindVAppByName,GetAdminOrgByName") ``` -------------------------------- ### Skip Specific Tags in Logs Source: https://github.com/vmware/go-vcloud-director/blob/main/util/LOGGING.md To exclude large log outputs for specific tags, use `util.SetSkipTags()`. For example, to skip `SupportedVersions` and `ovf:License`. ```go util.SetSkipTags("SupportedVersions,ovf:License") ``` -------------------------------- ### Create Entity with Simplified Input Structure Source: https://github.com/vmware/go-vcloud-director/blob/main/CODING_GUIDELINES.md Demonstrates how to handle entity creation when there are too many parameters. A simplified input structure is defined and passed to the asynchronous creation method. This approach is preferred when the structure closely matches a Terraform resource. ```go type EntityInput struct { field1 string field2 string field3 bool field4 bool field5 int field6 string field7 []string } ``` ```go (parent *Parent) CreateEntityAsync(simple EntityInput) (Task, error) ``` -------------------------------- ### Outer Type Function Signature Example Source: https://github.com/vmware/go-vcloud-director/blob/main/CODING_GUIDELINES.md Demonstrates the function signature for an operation involving an 'outer' type, typically returning a pointer to a custom entity struct. ```go func (vcdClient *VCDClient) CreateIpSpace(ipSpaceConfig *types.IpSpace) (*IpSpace, error) { ``` -------------------------------- ### Initialize and Authenticate VCD Client Source: https://github.com/vmware/go-vcloud-director/blob/main/README.md This Go code demonstrates how to initialize a VMware Cloud Director client and authenticate using user credentials. It includes error handling for URL parsing and authentication. ```go package main import ( "fmt" "net/url" "os" "github.com/vmware/go-vcloud-director/v3/govcd" ) type Config struct { User string Password string Org string Href string VDC string Insecure bool } func (c *Config) Client() (*govcd.VCDClient, error) { u, err := url.ParseRequestURI(c.Href) if err != nil { return nil, fmt.Errorf("unable to pass url: %s", err) } vcdclient := govcd.NewVCDClient(*u, c.Insecure) err = vcdclient.Authenticate(c.User, c.Password, c.Org) if err != nil { return nil, fmt.Errorf("unable to authenticate: %s", err) } return vcdclient, nil } func main() { if len(os.Args) < 6 { fmt.Println("Syntax: example user password org VCD_IP VDC ") os.Exit(1) } config := Config{ User: os.Args[1], Password: os.Args[2], Org: os.Args[3], Href: fmt.Sprintf("https://%s/api", os.Args[4]), VDC: os.Args[5], Insecure: true, } client, err := config.Client() // We now have a client if err != nil { fmt.Println(err) os.Exit(1) } org, err := client.GetOrgByName(config.Org) if err != nil { fmt.Println(err) os.Exit(1) } vdc, err := org.GetVDCByName(config.VDC, false) if err != nil { fmt.Println(err) os.Exit(1) } fmt.Printf("Org URL: %s\n", org.Org.HREF) fmt.Printf("VDC URL: %s\n", vdc.Vdc.HREF) } ``` -------------------------------- ### Inner Type Function Signature Example Source: https://github.com/vmware/go-vcloud-director/blob/main/CODING_GUIDELINES.md Illustrates the function signature for an operation involving an 'inner' type, typically returning a pointer to a types package struct. ```go func (adminVdc *AdminVdc) UpdateVdcNetworkProfile(vdcNetworkProfileConfig *types.VdcNetworkProfile) (*types.VdcNetworkProfile, error) { ``` -------------------------------- ### Create Entity with Few Parameters Source: https://github.com/vmware/go-vcloud-director/blob/main/CODING_GUIDELINES.md Illustrates an approach for creating entities when the number of required parameters is small (less than 4). Parameters are passed directly as arguments to the asynchronous creation method. ```go (parent *Parent) CreateEntityAsync(field1, field2 string, field3 bool) (Task, error) ``` -------------------------------- ### Log to Screen Source: https://github.com/vmware/go-vcloud-director/blob/main/util/LOGGING.md To direct log output to the console, use `util.Logger.SetOutput()` with either `os.Stdout` or `os.Stderr`. ```go util.Logger.SetOutput(os.Stdout) ``` ```go util.Logger.SetOutput(os.Stderr) ``` -------------------------------- ### Create a new catalog and upload an OVA Source: https://context7.com/vmware/go-vcloud-director/llms.txt Creates a new catalog and then uploads an OVA file to it. Ensure the file path is correct and the catalog name is unique. ```go adminOrg, _ := client.GetAdminOrgByName("my-org") adminCatalog, err := adminOrg.CreateCatalog("my-catalog", "Catalog for VM templates") if err != nil { panic(err) } fmt.Println("Catalog ID:", adminCatalog.AdminCatalog.ID) // Upload an OVA to the catalog task, err := adminCatalog.UploadOvfByFilePath( "/path/to/template.ova", "my-template", "Ubuntu 22.04 template", 1024, // piece size (KB) nil, // progress callback ) if err != nil { panic(err) } if err := task.WaitTaskCompletion(); err != nil { panic(err) } fmt.Println("OVA uploaded successfully") ``` -------------------------------- ### Get and Create NSX-T Edge Gateway Source: https://context7.com/vmware/go-vcloud-director/llms.txt Retrieves an existing NSX-T Edge Gateway by name or creates a new one with specified uplinks. Requires AdminOrg context. ```go adminOrg, _ := client.GetAdminOrgByName("my-org") // Retrieve existing edge gateway egw, err := adminOrg.GetNsxtEdgeGatewayByName("my-edge-gw") if err != nil { panic(err) } fmt.Println("Edge GW ID:", egw.EdgeGateway.ID) fmt.Println("Edge GW Status:", egw.EdgeGateway.Status) // Create a new edge gateway vdc, _ := adminOrg.GetVDCByName("my-vdc", false) extNet, _ := client.GetExternalNetworkV2ByName("external-net") newEgwConfig := &types.OpenAPIEdgeGateway{ Name: "new-edge-gw", Description: "Edge gateway for my-vdc", OwnerRef: &types.OpenApiReference{ID: vdc.Vdc.ID}, EdgeGatewayUplinks: []types.OpenAPIEdgeGatewayUplinks{ { UplinkID: extNet.ExternalNetwork.ID, UplinkName: extNet.ExternalNetwork.Name, }, }, } newEgw, err := adminOrg.CreateNsxtEdgeGateway(newEgwConfig) if err != nil { panic(err) } fmt.Println("Created Edge GW:", newEgw.EdgeGateway.Name) ``` -------------------------------- ### Run Tests with Go Source: https://github.com/vmware/go-vcloud-director/blob/main/TESTING.md Execute tests using the 'go test' command with the 'functional' tag. Use '-check.vv' for more detailed output. ```bash cd govcd go test -tags "functional" -check.v . ``` ```bash cd govcd go test -check.f Test_SetOvf -check.vv . ``` -------------------------------- ### Outer Type Structure Example Source: https://github.com/vmware/go-vcloud-director/blob/main/CODING_GUIDELINES.md Defines the structure of an 'outer' type, which wraps an 'inner' type and includes a client reference and additional data fields for VCD entity operations. ```go type DistributedFirewall struct { DistributedFirewallRuleContainer *types.DistributedFirewallRules client *Client VdcGroup *VdcGroup } ``` -------------------------------- ### Run Tests with Makefile Source: https://github.com/vmware/go-vcloud-director/blob/main/TESTING.md Utilize the makefile for convenient test execution. Specific commands are available for different test suites. ```bash make test ``` ```bash make testcatalog ``` ```bash make testnetwork ``` ```bash make testvapp ``` ```bash make testconcurrent ``` -------------------------------- ### Enable Logging Source: https://github.com/vmware/go-vcloud-director/blob/main/util/LOGGING.md To enable logging, set `util.EnableLogging` to true and call `util.SetLog()`. By default, logging is disabled and `Printf` statements are discarded. ```go util.EnableLogging = true util.SetLog() ``` -------------------------------- ### Configure SAML Authentication with ADFS Source: https://github.com/vmware/go-vcloud-director/blob/main/TESTING.md Demonstrates how to configure SAML authentication with Active Directory Federation Services (ADFS) as an Identity Provider (IdP) using the NewVCDClient function. ```go client, err := NewVCDClient(vcdEndpoint, true, WithSamlAdfs()) if err != nil { log.Fatalf("Error creating VCD client: %v", err) } ``` -------------------------------- ### Select API Version for Testing Source: https://github.com/vmware/go-vcloud-director/blob/main/TESTING.md Use the GOVCD_API_VERSION environment variable to specify the API version for testing purposes only. Note that this may lead to unexpected failures as the SDK is tested against specific API versions. ```bash export GOVCD_API_VERSION=30.0 ``` -------------------------------- ### Configure SAML ADFS Integration Source: https://github.com/vmware/go-vcloud-director/blob/main/samples/saml_auth_adfs/README.md Use the `WithSamlAdfs` configuration option when initializing the vCD client. Ensure the ADFS WS-TRUST endpoint is enabled on the ADFS server. ```go govcd.NewVCDClient(client, WithSamlAdfs(useSaml bool, customAdfsRptId string)) ``` -------------------------------- ### Authenticate VCD Client with User Credentials Source: https://github.com/vmware/go-vcloud-director/blob/main/README.md Demonstrates authenticating a VCD client using either a System Administration user or an Organization user with their respective passwords. ```go err := vcdClient.Authenticate(User, Password, Org) // or resp, err := vcdClient.GetAuthResponse(User, Password, Org) ``` -------------------------------- ### Manage NSX-T NAT Rules Source: https://context7.com/vmware/go-vcloud-director/llms.txt Lists all existing NAT rules and demonstrates creating a new DNAT rule. Ensure the Edge Gateway object is properly initialized. ```go egw, _ := adminOrg.GetNsxtEdgeGatewayByName("my-edge-gw") // List all NAT rules natRules, err := egw.GetAllNatRules(nil) if err != nil { panic(err) } for _, rule := range natRules { fmt.Printf(" NAT: %s Type: %s External: %s -> Internal: %s\n", rule.NsxtNatRule.Name, rule.NsxtNatRule.RuleType, rule.NsxtNatRule.ExternalAddresses, rule.NsxtNatRule.InternalAddresses) } // Create a DNAT rule (inbound: external IP port 443 -> internal VM port 443) newRule := &types.NsxtNatRule{ Name: "dnat-web", RuleType: "DNAT", Enabled: true, ExternalAddresses: "203.0.113.10", InternalAddresses: "192.168.1.100", DnatExternalPort: "443", ApplicationPortProfile: &types.OpenApiRef{ Name: "HTTPS", ID: "urn:vcloud:applicationPortProfile:...", }, } created, err := egw.CreateNatRule(newRule) if err != nil { panic(err) } fmt.Println("Created NAT rule ID:", created.NsxtNatRule.ID) ``` -------------------------------- ### Create a new VDC Source: https://context7.com/vmware/go-vcloud-director/llms.txt Creates a new VDC under an admin organization. Ensure you have the necessary provider VDC and storage profile references. ```go adminOrg, _ := client.GetAdminOrgByName("my-org") providerVdc, _ := client.GetProviderVdcByName("provider-vdc") storageProfile, _ := client.QueryProviderVdcStorageProfileByName("*", providerVdc.ProviderVdc.HREF) vdcConfig := &types.VdcConfiguration{ Name: "new-vdc", AllocationModel: "AllocationVApp", ComputeCapacity: []*types.CapacityWithUsage{ { CPU: &types.CapacityWithUsage{Units: "MHz", Allocated: 1024, Limit: 2048}, Memory: &types.CapacityWithUsage{Units: "MB", Allocated: 1024, Limit: 2048}, }, }, VdcStorageProfile: []*types.VdcStorageProfileConfiguration{ { Enabled: true, Units: "MB", Limit: 10240, Default: true, ProviderVdcStorageProfile: &types.Reference{HREF: storageProfile.HREF}, }, }, NetworkPoolReference: &types.Reference{HREF: "https://vcd.example.com/api/networkPool/"}, ProviderVdcReference: &types.Reference{HREF: providerVdc.ProviderVdc.HREF}, } newVdc, err := adminOrg.CreateVdc(vdcConfig) if err != nil { panic(err) } fmt.Println("Created VDC:", newVdc.Vdc.Name) ``` -------------------------------- ### Skip Initial vApp Creation Source: https://github.com/vmware/go-vcloud-director/blob/main/TESTING.md Use the GOVCD_SKIP_VAPP_CREATION environment variable set to '1' or the '-vcd-skip-vapp-creation' flag to prevent the creation of the initial vApp. Tests depending on vApp availability will be skipped. ```bash export GOVCD_SKIP_VAPP_CREATION=1 ``` -------------------------------- ### Registering New Feature Tags Source: https://github.com/vmware/go-vcloud-director/blob/main/TESTING.md If a new feature tag is introduced, an `init` function must be implemented to register it with the testing framework. ```go func init() { testingTags["newtag"] = "filename_test.go" } ``` -------------------------------- ### CreateRawVApp / CreateVappFromTemplate Source: https://context7.com/vmware/go-vcloud-director/llms.txt Creates a new vApp either from scratch (CreateRawVApp) or by instantiating a vApp template (CreateVappFromTemplate). ```APIDOC ## Vdc.CreateRawVApp / Vdc.CreateVappFromTemplate Creates a new vApp either from scratch (`CreateRawVApp`) or by instantiating a vApp template (`CreateVappFromTemplate`). ```go vdc, _ := org.GetVDCByName("my-vdc", false) // Create empty vApp vapp, err := vdc.CreateRawVApp("my-vapp", "My test vApp") if err != nil { panic(err) } fmt.Println("Created vApp:", vapp.VApp.Name, "HREF:", vapp.VApp.HREF) // --- // OR: instantiate from template --- catalog, _ := org.GetCatalogByName("my-catalog", false) vappTemplate, _ := catalog.GetVAppTemplateByName("ubuntu-22.04") storageProfile, _ := vdc.FindStorageProfileReference("*") newVapp, err := vdc.CreateVappFromTemplate(vappTemplate, &storageProfile, "from-template-vapp") if err != nil { panic(err) } if err := newVapp.BlockWhileStatus("UNRESOLVED", 120); err != nil { panic(err) } fmt.Println("vApp from template:", newVapp.VApp.Name) ``` ``` -------------------------------- ### Create Entity Methods Source: https://github.com/vmware/go-vcloud-director/blob/main/CODING_GUIDELINES.md Provides standard methods for creating entities asynchronously and synchronously. The synchronous method internally uses the asynchronous one and waits for task completion. ```go (parent *Parent) CreateEntityAsync(input *types.Entity) (Task, error) ``` ```go (parent *Parent) CreateEntity(input *types.Entity) (*Entity, error) ``` -------------------------------- ### Authenticate VCD Client with Authorization Token Source: https://github.com/vmware/go-vcloud-director/blob/main/README.md Shows how to authenticate a VCD client by setting an authorization token. The token can be extracted using the provided `scripts/get_token.sh` script. ```go err := vcdClient.SetToken(Org, govcd.AuthorizationHeader, Token) ``` -------------------------------- ### Manage API Tokens for Service Accounts Source: https://context7.com/vmware/go-vcloud-director/llms.txt Creates and manages API tokens for service accounts, enabling token-file-based authentication. Use `CreateToken` to generate a new token and `SaveTokenToFile` for persistence. ```go // Create a new API token (requires authenticated admin session) token, err := client.CreateToken("my-org", "my-service-account-token") if err != nil { panic(err) } fmt.Println("Token ID:", token.Token.ID) initialRefresh, err := token.GetInitialRefreshToken() if err != nil { panic(err) } fmt.Println("Initial refresh token:", initialRefresh) // Save token to file for future use (the token file is self-refreshing) if err := token.SaveTokenToFile("/path/to/token.json"); err != nil { panic(err) } // Subsequent connections using the saved token file newClient := govcd.NewVCDClient(*vcdURL, true) if err := newClient.SetServiceAccountApiToken("my-org", "/path/to/token.json"); err != nil { panic(err) } ``` -------------------------------- ### List Available Test Tags Source: https://github.com/vmware/go-vcloud-director/blob/main/TESTING.md Run 'go test -v .' without any tags to see a list of available test tags and their descriptions. This helps in understanding which components are covered by each tag. ```bash $ go test -v . ``` -------------------------------- ### Set Custom Logger Source: https://github.com/vmware/go-vcloud-director/blob/main/util/LOGGING.md If the built-in configuration options are insufficient, you can provide a custom logger implementation using `util.SetCustomLogger()`. ```go util.SetCustomLogger(mylogger) ``` -------------------------------- ### Add a VM to a vApp Source: https://context7.com/vmware/go-vcloud-director/llms.txt Adds a new VM to an existing vApp, either from a vApp template or using raw parameters. Requires a vApp, template, and network configuration. ```go vapp, _ := vdc.GetVAppByName("my-vapp", true) catalog, _ := org.GetCatalogByName("my-catalog", false) vappTemplate, _ := catalog.GetVAppTemplateByName("ubuntu-22.04") orgNetwork, _ := vdc.GetOrgVdcNetworkByName("my-network", false) networkSection := &types.NetworkConnectionSection{ PrimaryNetworkConnectionIndex: 0, NetworkConnection: []*types.NetworkConnection{ { Network: orgNetwork.OrgVDCNetwork.Name, NetworkConnectionIndex: 0, IsConnected: true, IPAddressAllocationMode: types.IPAllocationModePool, }, }, } task, err := vapp.AddNewVM("my-vm", *vappTemplate, networkSection, true) if err != nil { panic(err) } if err := task.WaitTaskCompletion(); err != nil { panic(err) } vm, err := vapp.GetVMByName("my-vm", true) if err != nil { panic(err) } fmt.Println("VM created:", vm.VM.Name, "Status:", vm.VM.Status) ``` -------------------------------- ### Enable API Call Logging Source: https://github.com/vmware/go-vcloud-director/blob/main/samples/saml_auth_adfs/README.md Set the `GOVCD_LOG` environment variable to `1` to enable detailed logging of API calls, which can assist in troubleshooting SAML authentication issues. ```bash export GOVCD_LOG=1 ``` -------------------------------- ### Authenticate VCD Client with Service Account Token Source: https://github.com/vmware/go-vcloud-director/blob/main/README.md Illustrates authenticating a VCD client using a service account token from a JSON file. The token file must have read and write permissions. ```go err := vcdClient.SetServiceAccountApiToken(Org, "tokenfile.json") ``` -------------------------------- ### Show API Response on Standard Output Source: https://github.com/vmware/go-vcloud-director/blob/main/TESTING.md Set the GOVCD_SHOW_RESP environment variable or use the '-vcd-show-response' flag to display the API response on standard output. This aids in understanding the data returned by the API. ```bash export GOVCD_SHOW_RESP=1 ``` -------------------------------- ### Execute API Request and Parse Response Source: https://github.com/vmware/go-vcloud-director/blob/main/CODING_GUIDELINES.md Use this helper function to create, execute, and parse API responses. It handles request creation, execution, response checking, and unmarshalling the output into a provided structure. ```go func (client *Client) ExecuteRequest(pathURL, requestType, contentType, errorMessage string, payload, out interface{}) (*http.Response, error) ``` -------------------------------- ### Retrieve Media Item using Query Engine Source: https://github.com/vmware/go-vcloud-director/blob/main/CODING_GUIDELINES.md Use this to retrieve a media item based on specific criteria like date, latest status, and metadata. The `explanation` returned by `SearchByFilter` can be used for detailed error messages. ```go criteria := &govcd.FilterDef{ Filters: map[string]string{ "date":"> 2020-02-02", "latest": "true", }, Metadata: []govcd.MetadataDef{ { Key: "abc", Type: "STRING", Value: "\\S+", IsSystem: false, }, }, UseMetadataApiFilter: false, } queryType := govcd.QtMedia if vcdClient.Client.IsSysAdmin { queryType = govcd.QtAdminMedia } queryItems, explanation, err := vcdClient.Client.SearchByFilter(queryType, criteria) if err != nil { return err } if len(queryItems) == 0 { return fmt.Errorf("no media found with given criteria (%s)", explanation) } if len(queryItems) > 1 { // deal with several items var itemNames = make([]string, len(queryItems)) for i, item := range queryItems { itemNames[i] = item.GetName() } return fmt.Errorf("more than one media item found by given criteria: %v", itemNames) } // retrieve the full entity for the item found media, err = catalog.GetMediaByHref(queryItems[0].GetHref()) ``` -------------------------------- ### Run Tests with SAML Authentication using User/Password Source: https://github.com/vmware/go-vcloud-director/blob/main/TESTING.md This approach enables SAML authentication for all tests by providing SAML credentials via regular user and password variables, along with 'true' for 'useSamlAdfs'. The Relaying Party Trust ID can be optionally overridden. ```bash export VCD_USER="your_saml_user" export VCD_PASSWORD="your_saml_password" export VCD_USE_SAML_ADFS=true # Optionally override Relaying Party Trust ID # export VCD_CUSTOM_ADFS_RPT_ID="your_custom_id" go test -tags functional -timeout 0 . ``` -------------------------------- ### Show API Request on Standard Output Source: https://github.com/vmware/go-vcloud-director/blob/main/TESTING.md Set the GOVCD_SHOW_REQ environment variable or use the '-vcd-show-request' flag to display the API request on standard output. This is helpful for debugging API interactions. ```bash export GOVCD_SHOW_REQ=1 ``` -------------------------------- ### Test Function with Cleanup and Check Assertions Source: https://github.com/vmware/go-vcloud-director/blob/main/TESTING.md Illustrates a test function that includes cleanup logic and uses `check.Check` for assertions that do not terminate the test immediately. This is useful when subsequent steps, like cleanup, must be reached even if an assertion fails. ```go func (vcd *TestVCD) Test_ComposeVApp(check *checks.C) { fmt.Printf("Running: %s\n", check.TestName()) // Populate the input data // [ ... ] // See the full function in govcd/vcd_test.go // Run the main operation task, err := vcd.vdc.ComposeVApp(networks, vapptemplate, storageprofileref, temp_vapp_name, temp_vapp_description) // These tests can fail: we need to make sure that the new entity was created check.Assert(err, checks.IsNil) check.Assert(task.Task.OperationName, checks.Equals, composeVappName) // Get VApp vapp, err := vcd.vdc.FindVAppByName(temp_vapp_name) check.Assert(err, checks.IsNil) // After a successful creation, the entity is added to the cleanup list. // If something fails after this point, the entity will be removed AddToCleanupList(composeVappName, "vapp", "", "Test_ComposeVApp") // Once the operation is successful, we won't trigger a failure // until after the vApp deletion // Instead of "Assert" we run "Check". If one of the following // checks fails, it won't terminate the test, and we can reach the cleanup point. check.Check(vapp.VApp.Name, checks.Equals, temp_vapp_name) check.Check(vapp.VApp.Description, checks.Equals, temp_vapp_description) // [ ... ] // More checks follow // Here's the cleanup point // Deleting VApp task, err = vapp.Delete() task.WaitTaskCompletion() // Here we can fail again. check.Assert(err, checks.IsNil) no_such_vapp, err := vcd.vdc.FindVAppByName(temp_vapp_name) check.Assert(err, checks.NotNil) check.Assert(no_such_vapp.VApp, checks.IsNil) // If this deletion fails, a further attempt will be made // by the cleanup function at the end of all tests } ``` -------------------------------- ### Makefile Test Command with Script Source: https://github.com/vmware/go-vcloud-director/blob/main/TESTING.md Alternative method for complex test execution using a dedicated script within the `make test` command. ```bash test: fmtcheck @echo "==> Running Tests" ./scripts/my_complicated_test.sh cd govcd && go test -tags "functional" -timeout=60m -check.vv . ``` -------------------------------- ### Create, Attach, and Detach Independent Disk Source: https://context7.com/vmware/go-vcloud-director/llms.txt Creates an independent named disk in a VDC, attaches it to a VM, and then detaches it. Requires VM and VDC to exist. ```go vdc, _ := org.GetVDCByName("my-vdc", false) diskParams := &types.DiskCreateParams{ Disk: &types.Disk{ Name: "data-disk", SizeMb: 10240, // 10 GB }, } task, err := vdc.CreateDisk(diskParams) if err != nil { panic(err) } if err := task.WaitTaskCompletion(); err != nil { panic(err) } disk, err := vdc.GetDiskByName("data-disk", true) if err != nil { panic(err) } fmt.Println("Disk ID:", disk.Disk.ID) // Attach to VM vm, _ := vapp.GetVMByName("my-vm", true) attachTask, err := vm.AttachDisk(&types.DiskAttachOrDetachParams{ Disk: &types.Reference{HREF: disk.Disk.HREF}, }) if err != nil { panic(err) } _ = attachTask.WaitTaskCompletion() // Detach detachTask, _ := vm.DetachDisk(&types.DiskAttachOrDetachParams{ Disk: &types.Reference{HREF: disk.Disk.HREF}, }) _ = detachTask.WaitTaskCompletion() ``` -------------------------------- ### Manage NSX-T IPsec VPN Tunnels Source: https://context7.com/vmware/go-vcloud-director/llms.txt Lists existing IPsec VPN tunnels and demonstrates creating a new site-to-site VPN tunnel. Ensure the Edge Gateway object is properly initialized. ```go egw, _ := adminOrg.GetNsxtEdgeGatewayByName("my-edge-gw") // List existing tunnels tunnels, err := egw.GetAllIpSecVpnTunnels(nil) if err != nil { panic(err) } for _, t := range tunnels { fmt.Printf(" Tunnel: %s Status: %s\n", t.NsxtIpSecVpn.DisplayName, t.NsxtIpSecVpn.Status) } // Create new IPsec tunnel tunnelConfig := &types.NsxtIpSecVpnTunnel{ DisplayName: "site-to-site-vpn", Description: "Connection to branch office", Enabled: true, LocalEndpointIp: "203.0.113.10", RemoteEndpointIp: "198.51.100.5", LocalSubnets: []string{"192.168.1.0/24"}, RemoteSubnets: []string{"10.10.0.0/24"}, PreSharedKey: "super-secret-psk", SecurityType: "DEFAULT", } newTunnel, err := egw.CreateIpSecVpnTunnel(tunnelConfig) if err != nil { panic(err) } fmt.Println("Created VPN Tunnel:", newTunnel.NsxtIpSecVpn.DisplayName) ``` -------------------------------- ### Define Org Structure with Tenant Context Source: https://github.com/vmware/go-vcloud-director/blob/main/CODING_GUIDELINES.md Represents an organization entity within the SDK, including a pointer to the client and tenant context. This structure facilitates access to organization-specific data and operations. ```go type Org struct { Org *types.Org client *Client TenantContext *TenantContext } ``` -------------------------------- ### VM Power Operations Source: https://context7.com/vmware/go-vcloud-director/llms.txt VMs expose PowerOn, PowerOff, Suspend, Reset, Undeploy, and PowerOnAndForceCustomization for lifecycle management. All return a Task except PowerOnAndForceCustomization which waits synchronously. ```APIDOC ## VM Power Operations VMs expose `PowerOn`, `PowerOff`, `Suspend`, `Reset`, `Undeploy`, and `PowerOnAndForceCustomization` for lifecycle management. All return a `Task` except `PowerOnAndForceCustomization` which waits synchronously. ```go vm, _ := vapp.GetVMByName("my-vm", true) // Power on task, err := vm.PowerOn() if err != nil { panic(err) } if err := task.WaitTaskCompletion(); err != nil { panic(fmt.Sprintf("power on failed: %s", err)) } status, _ := vm.GetStatus() fmt.Println("VM status:", status) // "POWERED_ON" // Power off task, err = vm.PowerOff() if err != nil { panic(err) } _ = task.WaitTaskCompletion() // Force customization on next boot (VM must be undeployed first) undeployTask, _ := vm.Undeploy() _ = undeployTask.WaitTaskCompletion() if err := vm.PowerOnAndForceCustomization(); err != nil { panic(err) } ``` ``` -------------------------------- ### Specify Authorization Token for API Access Source: https://github.com/vmware/go-vcloud-director/blob/main/TESTING.md Use the VCD_TOKEN environment variable to provide an authorization token for API access, instead of using username and password. Retrieve a token using the provided script. ```bash export VCD_TOKEN=$(./scripts/get_token.sh) ``` -------------------------------- ### Implement Entity Search Methods Source: https://github.com/vmware/go-vcloud-director/blob/main/CODING_GUIDELINES.md Standard methods for searching entities within a parent object. These include searching by Href (optional), Name, ID, or a combined Name or ID. ```go // OPTIONAL (parent *Parent) GetEntityByHref(href string) (*Entity, error) ``` ```go // ALWAYS (parent *Parent) GetEntityByName(name string) (*Entity, error) ``` ```go (parent *Parent) GetEntityById(id string) (*Entity, error) ``` ```go (parent *Parent) GetEntityByNameOrId(identifier string) (*Entity, error) ``` -------------------------------- ### Define Organization Interface for Tenant Context Source: https://github.com/vmware/go-vcloud-director/blob/main/CODING_GUIDELINES.md Defines an interface for organizations to abstract tenant context retrieval. This allows different organization types (Org, AdminOrg) to be treated uniformly. ```go type organization interface { orgId() string orgName() string tenantContext() (*TenantContext, error) fullObject() interface{} } ```