Home > Enterprise >  AWS SDK in Go. Parsing data
AWS SDK in Go. Parsing data

Time:08-12

I'm using aws-sdk for go. I want to describe EC2 instance based on instance-type filter. Here's my code:

    ec2Svc := ec2.New(sess, &aws.Config{Credentials: creds})
    params := &ec2.DescribeInstanceTypesInput{
        Filters: []*ec2.Filter{
            {
                Name:   aws.String("instance-type"),
                Values: []*string{aws.String("t2*")},
            },
        },
    }

    result, err := ec2Svc.DescribeInstanceTypes(params)
    if err != nil {
        fmt.Println("Error", err)
    } else {
        fmt.Println(result.String())
    }

This works fine. The type of result variable is *ec2.DescribeInstanceTypeOutput. Here's how result looks like:

{
  InstanceTypes: [{
      AutoRecoverySupported: true,
      BareMetal: false,
      BurstablePerformanceSupported: true,
      CurrentGeneration: true,
      DedicatedHostsSupported: false,
      EbsInfo: {
        EbsOptimizedSupport: "unsupported",
        EncryptionSupport: "supported",
        NvmeSupport: "unsupported"
      },
      FreeTierEligible: false,
      InstanceStorageSupported: false,
      InstanceType: "t2.2xlarge",
      MemoryInfo: {
        SizeInMiB: 32768
      },
      NetworkInfo: {
        DefaultNetworkCardIndex: 0,
        MaximumNetworkCards: 1,
        MaximumNetworkInterfaces: 3,
        NetworkCards: [{
            MaximumNetworkInterfaces: 3,
          }],
        NetworkPerformance: "Moderate"
      },
      PlacementGroupInfo: {
        SupportedStrategies: ["partition","spread"]
      },
      ProcessorInfo: {
        SupportedArchitectures: ["x86_64"],
      },
      SupportedBootModes: ["legacy-bios"],
      SupportedVirtualizationTypes: ["hvm"],
      VCpuInfo: {
        DefaultCores: 8,
      }
    }],
  NextToken: "asadasdasd"
}

As you can see this json is quite long and I've removed some content from it to make more readable. I want to get one information from it - MemoryInfo.SizeInMiB but I don't know how to. I've tried using json.Marshal and json.Unmarshal but I get error because of *ec2.DescribeInstanceTypeOutput type.

Is the only way to get this value is to create some long structure and then using it somehow?

CodePudding user response:

You don't have to create a new structure, this is already provided by the SDK. The return type of DescribeInstanceTypes is a pointer to a DescribeInstanceTypesOutput object.

You can access MemoryInfo.SizeInMiB in the following way:

func main() {

    // Build a session
    sess := session.Must(session.NewSessionWithOptions(session.Options{
        SharedConfigState: session.SharedConfigEnable,
    }))

    ec2Svc := ec2.New(sess)
    params := &ec2.DescribeInstanceTypesInput{
        Filters: []*ec2.Filter{
            {
                Name:   aws.String("instance-type"),
                Values: []*string{aws.String("t2*")},
            },
        },
    }

    // Retrieve the instance types in a loop using NextToken. The filtering of instances will happen locally
    for {
        result, err := ec2Svc.DescribeInstanceTypes(params)
        if err != nil {
            fmt.Println("Error", err)
            break
        } else {
            
            // InstanceTypes is slice, so we have to iterate over it
            for _, instance := range result.InstanceTypes {
                // Grab the memory size of the instance
                fmt.Printf("%s - %d MiB\n", *instance.InstanceType, *instance.MemoryInfo.SizeInMiB)
            }

            // Check if they are any instances left
            if result.NextToken != nil {
                params.NextToken = result.NextToken
            } else {
                break
            }
        }
    }
}

This should output something similar to this:

t2.2xlarge - 32768 MiB
t2.large - 8192 MiB
t2.micro - 1024 MiB
t2.medium - 4096 MiB
t2.xlarge - 16384 MiB
t2.small - 2048 MiB
t2.nano - 512 MiB
  • Related