All Products
Search
Document Center

Use SDK for Go

Last Updated: Aug 16, 2021

This topic describes how to use Elastic Container Instance SDK for Go and provides an example.

Install the SDK

You can obtain Elastic Container Instance SDK for Go from GitHub.

Sample code

const.go

package eci
type ContainerGroupStatus string
const (
        Scheduling     = ContainerGroupStatus("Scheduling")
        Pending        = ContainerGroupStatus("Pending")
        Running        = ContainerGroupStatus("Running")
        Succeeded      = ContainerGroupStatus("Succeeded")
        Failed         = ContainerGroupStatus("Failed")
        Restarting     = ContainerGroupStatus("Restarting")
        Updating       = ContainerGroupStatus("Updating")
        ScheduleFailed = ContainerGroupStatus("ScheduleFailed")
)
type ContainerStatus string
const (
        waiting    = ContainerStatus("Waiting")
        running    = ContainerStatus("Running")
        terminated = ContainerStatus("Terminated")
)

config.conf

[eci_conf]
# The AccessKey pair of the test account.
access_key = xxx
secret_key = xxx
#region
region_id=cn-hangzhou
# The information of the resources in each region, which is in the JSON format.
region_info={"cn-hangzhou": {"securityGroupId": "sg-bp118knl07ymorgzfhyw","vSwitchId": "vsw-bp1jrgfqqy54kg5hcf8bc","zoneId": "cn-hangzhou-h"},"cn-shanghai": {"securityGroupId": "sg-uf62jug0dt92nfy630cs","vSwitchId": "vsw-uf6cb39ub5urw82bv3w70","zoneId": "cn-shanghai-g"},"cn-beijing": {"securityGroupId": "sg-2ze6uv80a8s4yk04dmyu","vSwitchId": "vsw-2zegtxf8q29d8tt1xtcjk","zoneId": "cn-beijing-h"},"cn-shenzhen":{"securityGroupId": "sg-wz96x4kv4edy97q6jjzn","vSwitchId": "vsw-wz9rn33jwilodp24klo0q","zoneId": "cn-shenzhen-a"},"cn-hongkong":{"securityGroupId": "sg-j6cjajpf7f4ybda7h19w","vSwitchId": "vsw-j6c9c9fit5owbbc0ids6c","zoneId": "cn-hongkong-b"},"us-west-1":{"securityGroupId": "sg-u19hbpj9x","vSwitchId": "vsw-rj9h5vvzhb4fjkuzuyi8j","zoneId": "us-west-1a"},"us-east-1":{"securityGroupId": "sg-0xih51sfoldxzxfsbja5","vSwitchId": "vsw-0xisefewxoqe4f849jbnl","zoneId": "us-east-1b"},"ap-southeast-1":{"securityGroupId": "sg-t4n23ppw7fm5to7cnib9","vSwitchId": "vsw-t4nr1xt8zupxg00unnmg9","zoneId": "ap-southeast-1b"},"cn-zhangjiakou": {"securityGroupId": "sg-8vb96lku1dgq71ckh98g","vSwitchId": "vsw-8vbtnz5878r3bcio7cpyx", "nfs":"9cbb94a474-oav34.cn-zhangjiakou.nas.aliyuncs.com", "zoneId": "cn-zhangjiakou-a"}}

The following sample code shows the region_info parameter settings in an easy-to-read format. These settings are for reference only.

{
    "cn-hangzhou": {
        "securityGroupId": "sg-bp118knl07ymorgzfhyw",
        "vSwitchId": "vsw-bp1jrgfqqy54kg5hcf8bc",
        "zoneId": "cn-hangzhou-h"
    },
    "cn-shanghai": {
        "securityGroupId": "sg-uf62jug0dt92nfy630cs",
        "vSwitchId": "vsw-uf6cb39ub5urw82bv3w70",
        "zoneId": "cn-shanghai-g"
    },
    "cn-beijing": {
        "securityGroupId": "sg-2ze6uv80a8s4yk04dmyu",
        "vSwitchId": "vsw-2zegtxf8q29d8tt1xtcjk",
        "zoneId": "cn-beijing-h"
    },
    "cn-shenzhen": {
        "securityGroupId": "sg-wz96x4kv4edy97q6jjzn",
        "vSwitchId": "vsw-wz9rn33jwilodp24klo0q",
        "zoneId": "cn-shenzhen-a"
    },
    "cn-hongkong": {
        "securityGroupId": "sg-j6cjajpf7f4ybda7h19w",
        "vSwitchId": "vsw-j6c9c9fit5owbbc0ids6c",
        "zoneId": "cn-hongkong-b"
    },
    "us-west-1": {
        "securityGroupId": "sg-u19hbpj9x",
        "vSwitchId": "vsw-rj9h5vvzhb4fjkuzuyi8j",
        "zoneId": "us-west-1a"
    },
    "ap-southeast-1": {
        "securityGroupId": "sg-t4n23ppw7fm5to7cnib9",
        "vSwitchId": "vsw-t4nr1xt8zupxg00unnmg9",
        "zoneId": "ap-southeast-1b"
    },
    "cn-zhangjiakou": {
        "securityGroupId": "sg-8vb96lku1dgq71ckh98g",
        "vSwitchId": "vsw-8vbtnz5878r3bcio7cpyx",
        "zoneId": "cn-zhangjiakou-a"
    }
}

eci.go

package eci
import (
        "encoding/json"
        "fmt"
        "github.com/Unknwon/goconfig"
        "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
        "github.com/aliyun/alibaba-cloud-sdk-go/services/eci"
        "math"
        "os"
        "reflect"
        "strconv"
        "time"
)
var accessKey string
var secretKey string
var regionId string
var zoneId string
var securityGroupId string
var vSwitchId string
var client *eci.Client
/**
Obtain the configurations.
 */
func init() {
        var cfg *goconfig.ConfigFile
        config, err := goconfig.LoadConfigFile("./eci/config.conf") // Load the configuration file.
        if err != nil {
                fmt.Println("get config file error:", err.Error())
                os.Exit(-1)
        }
        cfg = config
        accessKey, _ = cfg.GetValue("eci_conf", "access_key")
        secretKey, _ = cfg.GetValue("eci_conf", "secret_key")
        regionId, _ = cfg.GetValue("eci_conf", "region_id")
        var regionInfo map[string](map[string](string));
        value, _ := cfg.GetValue("eci_conf", "region_info")
        json.Unmarshal([]byte(value), &regionInfo)
        zoneId = regionInfo[regionId]["zoneId"]
        securityGroupId = regionInfo[regionId]["securityGroupId"]
        vSwitchId = regionInfo[regionId]["vSwitchId"]
        fmt.Printf("init success[ access_key:%s, secret_key:%s, region_id:%s, zoneId:%s, vSwitchId:%s, securityGroupId:%s]\n",
                accessKey, secretKey, regionId, zoneId, vSwitchId, securityGroupId)
    // Initialize the client.
    client, err = eci.NewClientWithAccessKey(regionId, accessKey, secretKey)
        if err != nil {
                panic(err)
        }
}
/**
Create an elastic container instance.
*/
func createContainerGroup ()(string)  {
        // Create Container Group
        createContainerRequest := eci.CreateCreateContainerGroupRequest()
        // required
        createContainerRequest.RegionId = regionId;
        createContainerRequest.SecurityGroupId = securityGroupId
        createContainerRequest.VSwitchId = vSwitchId
        createContainerRequest.ContainerGroupName = "test-go-sdk"
        createContainerRequest.RestartPolicy = "Never"
        createContainerRequestVolume := make([]eci.CreateContainerGroupVolume, 1)
        volume1 := &eci.CreateContainerGroupNFSVolume{
                Path:"/",
                Server:"0a1bf4a604-jaq68.cn-hangzhou.nas.aliyuncs.com",
        }
        createContainerRequestVolume[0].Name = "volume1"
        createContainerRequestVolume[0].Type ="NFSVolume"
        createContainerRequestVolume[0].NFSVolume=*volume1
        createContainerRequest.Volume = &createContainerRequestVolume
        createContainerRequestContainer := make([]eci.CreateContainerGroupContainer, 1)
        createContainerRequestContainer[0].Image = "nginx"
        createContainerRequestContainer[0].Name = "nginx-liu"
        // option
        createContainerRequestContainer[0].Cpu = requests.NewFloat(0.25)
        createContainerRequestContainer[0].Memory = requests.NewFloat(0.5)
        createContainerRequestContainer[0].ImagePullPolicy = "IfNotPresent"
        createContainerRequest.Container = &createContainerRequestContainer
        // The default number of retry attempts of sdk-core is 3. Without the settings used to ensure idempotence, the underlying operation does not need to automatically retry to create resources.
        client.GetConfig().MaxRetryTime = 0
        createContainerGroupResponse, err := client.CreateContainerGroup(createContainerRequest)
        if err != nil {
                panic(err)
        }
        containerGroupId := createContainerGroupResponse.ContainerGroupId
        fmt.Println(containerGroupId)
        return containerGroupId
}
/**
Delete an elastic container instance.
*/
func deleteContainerGroup(containerGroupId string) {
        deleteContainerGroupRequest := eci.CreateDeleteContainerGroupRequest()
        deleteContainerGroupRequest.RegionId = regionId
        deleteContainerGroupRequest.ContainerGroupId = containerGroupId
    _, err := client.DeleteContainerGroup(deleteContainerGroupRequest)
        if err != nil {
                panic(err)
        }
        fmt.Println("DeleteContainerGroup ContainerGroupId :", containerGroupId)
}
/**
Query an elastic container instance.
*/
func describeContainerGroup(containerGroupId string) (eci.DescribeContainerGroupsContainerGroup0)  {
        // Describe Container Groups
        describeContainerGroupsRequest := eci.CreateDescribeContainerGroupsRequest()
        describeContainerGroupsRequest.RegionId = regionId
        containerGroupIds := append([]string{}, containerGroupId)
        containerGroupIdsString, err := json.Marshal(containerGroupIds)
        describeContainerGroupsRequest.ContainerGroupIds = string(containerGroupIdsString)
        describeContainerGroupsResponse, err := client.DescribeContainerGroups(describeContainerGroupsRequest)
        if err != nil {
                panic(err)
        }
        describeContainerGroupNumber := len(describeContainerGroupsResponse.ContainerGroups)
        if describeContainerGroupsResponse.TotalCount != 1 && describeContainerGroupNumber != 1 {
                fmt.Println("Invalid ContainerGroups count", describeContainerGroupsResponse.TotalCount, describeContainerGroupNumber)
                panic("Invalid ContainerGroups count")
        }
        fmt.Println("ContainerGroup status:", describeContainerGroupsResponse.ContainerGroups[0].Status, containerGroupId,)
        // container groups
        return describeContainerGroupsResponse.ContainerGroups[0]
}
func describeContainerGroupMetric(containerGroupId string)  {
        describeContainerGroupMetricRequest :=eci.CreateDescribeContainerGroupMetricRequest()
        describeContainerGroupMetricRequest.RegionId = regionId
        describeContainerGroupMetricRequest.ContainerGroupId=containerGroupId
        response, err := client.DescribeContainerGroupMetric(describeContainerGroupMetricRequest)
        if err != nil {
                panic(err)
        }
        data, _ :=json.Marshal(response)
        fmt.Printf("Metrics for %s:%s\n", containerGroupId, string(data))
}
func describeMultiContainerGroupMetric(containerGroupIds []string)  {
        describeContainerGroupMetricRequest
    :=eci.CreateDescribeMultiContainerGroupMetricRequest()
        describeContainerGroupMetricRequest.RegionId = regionId
        data,_ :=json.Marshal(containerGroupIds)
        describeContainerGroupMetricRequest.ContainerGroupIds=string(data)
        response, err := client.DescribeMultiContainerGroupMetric(describeContainerGroupMetricRequest)
        if err != nil {
                panic(err)
        }
        data, _ = json.Marshal(response)
        fmt.Printf("Metrics:%s\n", string(data))
}
func Test() {
        containerGroupIds := make(chan string)
        go func() {
                for i := 0; i < 1; i++ {
                        containerGroupId := createContainerGroup()
                        containerGroupIds <- containerGroupId
                }
        }()
        go func() {
                for containerGroupId := range containerGroupIds {
                        for i := 0; i < 10; i++ {
                                status := describeContainerGroup(containerGroupId).Status
                                if Running == ContainerGroupStatus(status) {
                                        break
                                } else {
                                        time.Sleep(5 * time.Second)
                                }
                        }
                        //deleteContainerGroupById(containerGroupId)
                }
        }()
        // Block the thread until the asynchronous operation is complete. Otherwise, the thread exits before the operation is complete. 
        var input string
        fmt.Println("waiting for input to finish:")
        fmt.Scanln(&input)
        fmt.Println("test done!")
}

main.go

func main() {
        eci.Test()
}