• CLI

sdk
  1. Help Center
  2. CLI
  3. Developer Guide
  4. SDK
  5. Go
  6. ECS Go SDK User Guide

ECS Go SDK User Guide

Service Client

To interact with OpenStack APIs, transfer the identity credentials to the provider. After that, if you want to retrieve any information about the compute service, you need to make a call to NewComputeV2 to create a compute service client and then use required SDKs.

client, err := openstack.NewComputeV2(provider, gophercloud.EndpointOpts{
 Region: "RegionName",
})

Servers

A server is a VM instance or physical device managed by the computing system.

Create a server.

import (  
"github.com/gophercloud/gophercloud/openstack/compute/v2/servers"
"github.com/gophercloud/gophercloud/openstack/compute/v2/extensions/keypairs"
"github.com/gophercloud/gophercloud/openstack/compute/v2/extensions/startstop"
"github.com/gophercloud/gophercloud/openstack/compute/v2/extensions/attachinterfaces"
"github.com/gophercloud/gophercloud/openstack/compute/v2/extensions/bootfromvolume"  ) 
func TestServersCreatePublicKey(t *testing.T) {
CreateOpts:= servers.CreateOpts{
    Name:         "server_name",
    FlavorRef:    "flavor_id",
    ImageRef:     "image_id",
    Networks:[]servers.Network{
                  servers.Network{UUID:"network_id"},
           },
    AvailabilityZone: "AvailabilityZone",

}
server, err = servers.Create(client, keypairs.CreateOptsExt{
           CreateOptsBuilder: CreateOpts,
           KeyName:             "keypair_name",
}).Extract()
}

Update a server.

func TestServersUpdate(t *testing.T) {
    updateOpts := servers.UpdateOpts{
           Name:   "alternateName",
    }
    updated, err := servers.Update(client, "server_id", updateOpts).Extract()
}

List servers.

func TestServerListAll(t *testing.T){
    listOpts := servers.ListOpts{
           TenantID:      "tenant_id",
           ChangesSince: "2017-11-28T07:52:17Z",
           Flavor:         "flavor_id",
           Status:         "ACTIVE",
           Limit:          2,
    }
    // Retrieve a pager (i.e. a paginated collection)
    allPages, err := servers.List(client, listOpts).AllPages()

    // Define an anonymous function to be executed on each page's iteration
    allServers, err := servers.ExtractServers(allPages)

    for _, server := range allServers {
    // " server " will be a servers.Server
                                }
}

Get details about a specific server.

func TestServerGet(t *testing.T){
    server, err := servers.Get(client, "server_id").Extract()
}

Delete a server.

//Delete requests that a server previously provisioned be removed from your account.

func TestServerDelete(t *testing.T){
    err = servers.Delete(client, "server_id").ExtractErr()
}

Rebuild a server.

Rebuilding reprovisions a server based on the configuration options provided by the RebuildOpts structure.

func TestServersActionRebuild(t *testing.T) {
    rebuildOpts := servers.RebuildOpts{
           Name:      "RebuildName",
           Metadata: map[string]string{
                  "rebuild": "yes",
           },
           ImageID:   "image_id",
    }
    rebuilt, err := servers.Rebuild(client, "server_id", rebuildOpts).Extract()
  }

Resize a server.

func TestServersActionResizeConfirm(t *testing.T) {
    opts := &servers.ResizeOpts{
           FlavorRef: "flavorresize_id",
    }
     res := servers.Resize(client, "server_id", opts)
}

Confirm a resize operation.

You can use ConfirmResize to confirm the previous reset operation on the server.

func TestServersActionResizeConfirm(t *testing.T) {
    res := servers.ConfirmResize(client, "server_id")
}

Revert a resize operation.

You can use RevertResize to cancel the previous reset operation on the server.

func TestServersActionResizeRevert(t *testing.T) {
     res := servers.RevertResize(client, "server_id")
}

Start a server.

You can use Start to start a server.

func TestServerActionStartStop(t *testing.T){
    err = startstop.Start(client , "server_id").ExtractErr()
}

Stop a server.

You can use Stop to stop a server.

func TestServerActionStartStop(t *testing.T){
    err = startstop.Stop(client , "server_id").ExtractErr()
}

Reboot a server.

You can either soft or hard restart a VM. Soft restart indicates that the OS runs its own restart process. Hard restart indicates that the power supply of the physical server is cut off or the VM instance is stopped in the hypervisor.

func TestServersActionReboot(t *testing.T) {
    rebootOpts := &servers.RebootOpts{
           Type: servers.HardReboot,
    }
    res := servers.Reboot(client, "server_id", rebootOpts)
}

Reset metadata.

You can use ResetMetadata to create multiple key-value pairs for a specified server ID. This operation will clear all existing metadata and create the provided metadata.

func TestServersSetMetadata(t *testing.T) {
metadata, err := servers.ResetMetadata(client, "server_id", servers.MetadataOpts{
           "Metadata":  "testing",
    }).Extract()
}

Update metadata.

You can use UpdateMetadata to update or create metadata provided by MetadataOpts for a specified server ID.

func TestServersUpdateMetadata(t *testing.T) {
metadata, err := servers.UpdateMetadata(client, "server_id", servers.MetadataOpts{
           "Metadata":  "testing",
    }).Extract()
}

List metadata.

You can use Metadata to request the metadata of a specified server ID.

func TestServerListMetadata(t *testing.T){
    metadata, err = servers.Metadata(client, "server_id").Extract()
}

Get details about specific metadatum.

You can use Metadatum to request the key-value pair of a specified key of a specified server ID.

func TestServerGetMetadata(t *testing.T){
    metadata, err := servers.Metadatum(client, "server_id", "key").Extract()   
}

Delete metadatum.

You can use DeleteMetadatum to delete the key-value pair of a specified key of a specified server ID.

func TestServerDeleteMetadata(t *testing.T){
    err = servers.DeleteMetadatum(client, "server_id", "key").ExtractErr()
}

List server NICs.

You can use List to request the Nova API to list the server NICs.

func TestServerListAttachInterfaces(t *testing.T){

    // Retrieve a pager (i.e. a paginated collection)
    allPages, err := attachinterfaces.List(client, "server_id").AllPages()

// Define an anonymous function to be executed on each page's iteration
    attachInterfaces, err := attachinterfaces.ExtractInterfaces(allPages)

    for _, attachInterfaces := range attachInterfaces {
           // " attachInterfaces " will be a attachinterfaces.Interface
    }
}

Boot from an image.

func TestBootFromExistingImage(t *testing.T) {

    blockDevices := []bootfromvolume.BlockDevice{
           bootfromvolume.BlockDevice{
                  SourceType:"image",
                  DestinationType:"volume",
                  DeleteOnTermination:true,
                  BootIndex:0,
                  VolumeSize:50,
                  UUID:"image_id",
           },
    }
    serverCreateOpts := servers.CreateOpts{
           Name:         "name",
           FlavorRef:    "flavor_id",
           Networks:[]servers.Network{
                         servers.Network{UUID:"network_id"},
                  },
           AvailabilityZone: "AvailabilityZone",
           
    }
    server, err = bootfromvolume.Create(client, bootfromvolume.CreateOptsExt{
           CreateOptsBuilder: serverCreateOpts,
           BlockDevice:         blockDevices,
    }).Extract()
}

Boot from a volume.

func TestBootFromExistingImage(t *testing.T) {

    blockDevices := []bootfromvolume.BlockDevice{
           bootfromvolume.BlockDevice{
                  SourceType:"volume",
                  DestinationType:"volume",
                  DeleteOnTermination:true,
                  BootIndex:0,
                  VolumeSize:50,
                  UUID:"volume_id",

           },
    }
    serverCreateOpts := servers.CreateOpts{
           Name:      name,
           FlavorRef: "flavor_id",
           Networks:[]servers.Network{
                         servers.Network{UUID:"network_id"},
                  },
           AvailabilityZone: "AvailabilityZone",

    }
    server, err = bootfromvolume.Create(client, bootfromvolume.CreateOptsExt{
           CreateOptsBuilder: serverCreateOpts,
           BlockDevice:         blockDevices,
    }).Extract()
}

Flavors

A flavor refers to the hardware configuration of a server. Each Flavor specifies the unique disk space, memory capacity, and CPUs.

List flavors.

import (
    "github.com/gophercloud/gophercloud/openstack/compute/v2/flavors"
)

func TestFlavorsList(t *testing.T) {

     listOpts := MyListFlavorOpts{
           MinDisk: 20,
           MinRAM: 4096,
           AccessType: PublicAccess,
           SortKey: "vcpus",
           SortDir: "desc",
     }
     // Retrieve a pager (i.e. a paginated collection)
     allPages, err := flavors.ListDetail(client, listOpts).AllPages()

     // Define an anonymous function to be executed on each page's iteration
     allFlavors, err := flavors.ExtractFlavors(allPages)

     for _, flavor := range allFlavors {
           // "flavor" will be a flavors.Flavor
     }
}

Get details about specific flavor.

func TestFlavorsGet(t *testing.T) {
     flavor, err := flavors.Get(client, "flavor_id").Extract()
}

Images

An image is the OS of a VM and it is a series of files used to create or rebuild servers. By default, the carrier provides preset OS images, but you can also create customized images from the ECSs.

List images.

import (
    "github.com/gophercloud/gophercloud/openstack/compute/v2/images"
)
func TestImagesListALL(t *testing.T) {
    listOpts := images.ListOpts{
           Status: "active",
    }
    // Retrieve a pager (i.e. a paginated collection)
    allPages, err := images.ListDetail(client, listOpts).AllPages()

    // Define an anonymous function to be executed on each page's iteration
    allImages, err := images.ExtractImages(allPages)

    for _, image := range allImages {
           // "image" will be a images.Image
    }
}

Get details about a specific image.

func TestImagesGet(t *testing.T) {
    image, err := images.Get(client, "image_id").Extract()
}

Delete an image.

func TestImagesDelete(t *testing.T) {
    err := images.Delete(client, "image_id").ExtractErr()
}

Keypairs

Create a keypair.

You can use Create to create a new keypair on the server.

import (  
"github.com/gophercloud/gophercloud/openstack/networking/v2/extensions/keypairs" 
"github.com/gophercloud/gophercloud/openstack/compute/v2/servers"
"crypto/rsa"
"golang.org/x/crypto/ssh"  ) 

func TestKeypairsImportPublicKey(t *testing.T) {

    privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
    publicKey := privateKey.PublicKey
    pub, err := ssh.NewPublicKey(&publicKey)
    pubBytes := ssh.MarshalAuthorizedKey(pub)
    publicKey:= string(pubBytes)

    createOpts := keypairs.CreateOpts{
           Name:      keyPairName,
           PublicKey: publicKey,
    }
    keyPair, err := keypairs.Create(client, createOpts).Extract()
}

List keypairs.

List returns the keypair list.

func TestKeypairsList(t *testing.T) {
    // Retrieve all pagers (i.e. a paginated collection)
    allPages, err := keypairs.List(client).AllPages()
    
    // Define an anonymous function to be executed on each page's iteration
    allKeys, err := keypairs.ExtractKeyPairs(allPages)

    for _, keypair := range allKeys {
    // " keypair " will be a keypairs.KeyPair
    }
}

Get details about a specific keypair.

Get returns details about a specified keypair.

func TestKeypairsGet(t *testing.T){
    keyPairGet,err:= keypairs.Get(client,"keypair_name").Extract()
}

Delete a keypair.

You can use Delete to delete a stored keypair from the server.

func TestKeypairsDelete(t *testing.T){
    err = keypairs.Delete(client, "keypair_name").ExtractErr()
}

Volume Attachment

Attach a volume.

You can use Create to attach a new volume to the server.

import (  
"github.com/gophercloud/gophercloud/openstack/blockstorage/v2/volumes"
"github.com/gophercloud/gophercloud/openstack/compute/v2/extensions/volumeattach"  ) 

func TestVolumeAttachAttachment(t *testing.T) {
    volumeAttachOptions := volumeattach.CreateOpts{
           Device: "/dev/sdb",
           VolumeID: "volume_id",
    }
volumeAttachment, err := volumeattach.Create(client, "server_id", volumeAttachOptions).Extract()
}

List attached volumes.

func TestVolumesListAttach(t *testing.T) {
    // Retrieve a pager (i.e. a paginated collection)
allPages, err := volumeattach.List(client, "server_id").AllPages()

     // Define an anonymous function to be executed on each page's iteration
    allVolumes, err := volumeattach.ExtractVolumeAttachments(allPages)

    for _, volume := range allVolumes {
    // " volume " will be a volumes.Volume
    }
}

Get details about a specific attached volume.

func TestVolumesShowAttach(t *testing.T) {
     volumeGet, err := volumeattach.Get(client,"server_id","attachment_id").Extract()

 }

Detach a volume.

func TestVolumesDetach(t *testing.T) {
    err := volumeattach.Delete(client, "server_id", "attachmentvolume_id").ExtractErr()
}