AdSense

網頁

2023/9/5

Golang 取得AWS產品價格資訊

Go以AWS提供的SDK aws-sdk-go-v2來取得AWS服務的產品價格資訊。



事前要求

參考「AWS 建立IAM管理使用者及credentials」設定供應用程式存取AWS需要的credentials。

參考「Golang 取得AWS Pricing ServiceCode」取得要查詢產品的服務代碼(ServiceCode)。


取得產品資訊

呼叫pricing.Client.GetProducts傳入參數pricing.GetProductsInput取得服務的產品列表。

pricing.GetProductsInput參數欄位,

  • ServiceCode - 輸入查詢產品的服務代碼。例如EC2的服務代碼為AmazonEC2
  • MaxResults - 最大輸出結果筆數。
  • Filters - 輸入types.Filter陣列,用來篩選符合條件的結果。Field為要篩選的欄位名稱;Value為刪選欄位的值。例如範例只篩選輸出結果中欄位sku值為7UV2VKCDN6WVVP54的結果。

main.go

package main

import (
    "context"
    "fmt"

    "github.com/aws/aws-sdk-go-v2/aws"
    "github.com/aws/aws-sdk-go-v2/config"
    "github.com/aws/aws-sdk-go-v2/service/pricing"
    "github.com/aws/aws-sdk-go-v2/service/pricing/types"
)

func main() {
    ctx := context.TODO()
    client := NewPricingClient(ctx)

    serviceCode := "AmazonEC2"
    out, err := client.GetProducts(ctx, &pricing.GetProductsInput{
        ServiceCode: &serviceCode,
        MaxResults:  aws.Int32(2),
        Filters: []types.Filter{
            {
                Field: aws.String("sku"),
                Type:  "TERM_MATCH",
                Value: aws.String("7UV2VKCDN6WVVP54"),
            },
        },
    })
    if err != nil {
        panic(err)
    }

    for _, price := range out.PriceList {
        fmt.Println(price)
    }
}

func NewPricingClient(ctx context.Context) *pricing.Client {
    cfg, err := config.LoadDefaultConfig(
        ctx,
        config.WithRegion("ap-south-1"),
    )
    if err != nil {
        panic(err)
    }

    return pricing.NewFromConfig(cfg) // Create an Pricing service client
}

github



測試

執行Go應用程式輸出以下結果,為JSON字串表示的產品資訊(因為使用欄位sku篩選,所以只會有一筆)。

{"product":{"productFamily":"Compute Instance","attributes":{"enhancedNetworkingSupported":"No","intelTurboAvailable":"Yes","memory":"0.5 GiB","vcpu":"1","classicnetworkingsupport":"false","capacitystatus":"AllocatedCapacityReservation","locationType":"AWS Region","storage":"EBS only","instanceFamily":"General purpose","operatingSystem":"Linux","intelAvx2Available":"No","regionCode":"ap-northeast-1","physicalProcessor":"Intel Xeon Family","clockSpeed":"Up to 3.3 GHz","ecu":"Variable","networkPerformance":"Low","servicename":"Amazon Elastic Compute Cloud","instancesku":"F7XCNBBYFKX42QF3","gpuMemory":"NA","vpcnetworkingsupport":"true","instanceType":"t2.nano","tenancy":"Shared","usagetype":"APN1-Reservation:t2.nano","normalizationSizeFactor":"0.25","intelAvxAvailable":"Yes","processorFeatures":"Intel AVX; Intel Turbo","servicecode":"AmazonEC2","licenseModel":"No License required","currentGeneration":"Yes","preInstalledSw":"NA","location":"Asia Pacific (Tokyo)","processorArchitecture":"32-bit or 64-bit","marketoption":"OnDemand","operation":"RunInstances","availabilityzone":"NA"},"sku":"7UV2VKCDN6WVVP54"},"serviceCode":"AmazonEC2","terms":{"OnDemand":{"7UV2VKCDN6WVVP54.JRTCKXETXF":{"priceDimensions":{"7UV2VKCDN6WVVP54.JRTCKXETXF.6YS6EN2CT7":{"unit":"Hrs","endRange":"Inf","description":"$0.00 per Reservation Linux t2.nano Instance Hour","appliesTo":[],"rateCode":"7UV2VKCDN6WVVP54.JRTCKXETXF.6YS6EN2CT7","beginRange":"0","pricePerUnit":{"USD":"0.0000000000"}}},"sku":"7UV2VKCDN6WVVP54","effectiveDate":"2023-08-01T00:00:00Z","offerTermCode":"JRTCKXETXF","termAttributes":{}}}},"version":"20230901144327","publicationDate":"2023-09-01T14:43:27Z"}

將輸出的JSON排版如下:

{
  "product": {
    "productFamily": "Compute Instance",
    "attributes": {
      "enhancedNetworkingSupported": "No",
      "intelTurboAvailable": "Yes",
      "memory": "0.5 GiB",
      "vcpu": "1",
      "classicnetworkingsupport": "false",
      "capacitystatus": "AllocatedCapacityReservation",
      "locationType": "AWS Region",
      "storage": "EBS only",
      "instanceFamily": "General purpose",
      "operatingSystem": "Linux",
      "intelAvx2Available": "No",
      "regionCode": "ap-northeast-1",
      "physicalProcessor": "Intel Xeon Family",
      "clockSpeed": "Up to 3.3 GHz",
      "ecu": "Variable",
      "networkPerformance": "Low",
      "servicename": "Amazon Elastic Compute Cloud",
      "instancesku": "F7XCNBBYFKX42QF3",
      "gpuMemory": "NA",
      "vpcnetworkingsupport": "true",
      "instanceType": "t2.nano",
      "tenancy": "Shared",
      "usagetype": "APN1-Reservation:t2.nano",
      "normalizationSizeFactor": "0.25",
      "intelAvxAvailable": "Yes",
      "processorFeatures": "Intel AVX; Intel Turbo",
      "servicecode": "AmazonEC2",
      "licenseModel": "No License required",
      "currentGeneration": "Yes",
      "preInstalledSw": "NA",
      "location": "Asia Pacific (Tokyo)",
      "processorArchitecture": "32-bit or 64-bit",
      "marketoption": "OnDemand",
      "operation": "RunInstances",
      "availabilityzone": "NA"
    },
    "sku": "7UV2VKCDN6WVVP54"
  },
  "serviceCode": "AmazonEC2",
  "terms": {
    "OnDemand": {
      "7UV2VKCDN6WVVP54.JRTCKXETXF": {
        "priceDimensions": {
          "7UV2VKCDN6WVVP54.JRTCKXETXF.6YS6EN2CT7": {
            "unit": "Hrs",
            "endRange": "Inf",
            "description": "$0.00 per Reservation Linux t2.nano Instance Hour",
            "appliesTo": [],
            "rateCode": "7UV2VKCDN6WVVP54.JRTCKXETXF.6YS6EN2CT7",
            "beginRange": "0",
            "pricePerUnit": {
              "USD": "0.0000000000"
            }
          }
        },
        "sku": "7UV2VKCDN6WVVP54",
        "effectiveDate": "2023-08-01T00:00:00Z",
        "offerTermCode": "JRTCKXETXF",
        "termAttributes": {}
      }
    }
  },
  "version": "20230901144327",
  "publicationDate": "2023-09-01T14:43:27Z"
}

沒有留言:

AdSense