文档首页> > 开发指南> Go> ECS Go SDK用户指导

ECS Go SDK用户指导

更新时间: 2018-11-26 14:29

Service Client

为了能够与OpenStack API进行交互,首先必须将身份验证凭据传递给Provider,此后,如果要检索Compute服务的任何信息,则需要调用NewComputeV2方法来创建一个Compute服务客户端,然后即可使用相关的SDK。

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

Servers 服务器

服务器是指由计算系统管理的虚拟机实例或物理设备。

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 for 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 重建服务器

重建是指根据RebuildOpts结构提供的配置选项重新发放服务器。

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 确认规格重置操作

通过ConfirmResize可确认该服务器上的前一项重置操作。

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

Revert a resize operation 退回重置操作

通过RevertResize可取消该服务器上的前一项重置操作。

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

Start a server 启动服务器

Start操作负责启动ECS服务器。

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

Stop a server 关闭服务器

Stop操作负责关闭服务器。

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

Reboot a server 重启服务器

重启虚拟机有两种方法:软重启和硬重启。软重启是指操作系统运行其自身的重启进程,而硬重启是指切断物理机的电源或者从hypervisor层终止虚拟机实例。

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

Reset Metadata 重置元数据

通过ResetMetadata可为指定服务器ID创建多个新的键值对。此操作将清除所有现存元数据并创建所提供的元数据。

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

Update Metadata 更新元数据

通过UpdateMetadata可为指定服务器ID更新或创建MetadataOpts提供的元数据。

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

List Metadata 查询元数据列表

通过Metadata可请求指定服务器ID的元数据。

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

Get details for a specific metadatum 获取指定元数据详情

通过Metadatum可请求指定服务器ID的指定键的键值对。

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

Delete a metadatum 删除指定元数据

通过DeleteMetadatum可删除指定服务器ID的指定键的键值对。

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

List attach interfaces 查询服务器网卡列表

List可请求nova API列出服务器的网卡信息。

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 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 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()
}

Flavor

Flavor是指服务器的硬件配置。每个Flavor规定唯一的磁盘空间、内存容量及CPU资源。

List flavors 查询Flavor列表

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 for a specific flavor 获取指定Flavor详情

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

Image 镜像

镜像是虚拟机的操作系统,是一系列用于创建及重建服务器的文件。运营商默认提供预置操作系统镜像,但用户也可以从云服务器中创建自定义镜像。

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 for a specific image 获取指定镜像详情

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

Delete a image 删除镜像

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

Key Pairs 密钥对

Create a keypair 创建密钥对

Create可请求在服务器上创建新密钥对。

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 返回密钥对列表。

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 for a specific keypair 获取指定密钥对详情

Get 返回指定密钥对的详细信息。

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

Delete a keypair 删除密钥对

Delete请求从服务器中删除储存的一个密钥对。

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

Volumeattach

Attach a volume 挂载卷

Create请求在服务器上挂载新卷。

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 attachvolumes 查询挂载卷列表

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 for a specific attach 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()
}

文档是否有解决您的问题?

提交成功!

非常感谢您的反馈,我们会继续努力做到更好!

反馈提交失败,请稍后再试!

在文档使用中是否遇到以下问题







请至少选择或填写一项反馈信息

字符长度不能超过100

反馈内容不能为空!

提交反馈 取消

如您有其它疑问,您也可以通过华为云社区问答频道来与我们联系探讨

跳转到云社区
点我,12·12惊喜等着你哦~