goamazon-ec2aws-sdk-go

AWS Golang SDK v2 - How to add function to Go AWS script


Trying to seperate out each part of the script into functions to use the output later on. Cannot get this part to work when trying to pass in instances to the printVolumesInfo function.

[]InstanceBlockDeviceMapping is part of the Instance struct but I am unsure what to use as an input for the function.

`

package main

import (
    "context"
    "fmt"

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

var client *ec2.Client


func init() {
    cfg, err := config.LoadDefaultConfig(context.TODO())
    if err != nil {
        panic("configuration error, " + err.Error())
    }
    client = ec2.NewFromConfig(cfg)

}

func printVolumesInfo(volumes []ec2.InstanceBlockDeviceMapping) {
    for _, b := range volumes {
        fmt.Println("   " + *b.DeviceName)
        fmt.Println("   " + *b.Ebs.VolumeId)
    }
}

func main() {
    parms := &ec2.DescribeInstancesInput{}
    result, err := client.DescribeInstances(context.TODO(), parms)

    if err != nil {
        fmt.Println("Error calling ec2: ", err)
        return
    }

    for _, r := range result.Reservations {
        fmt.Println("Reservation ID: " + *r.ReservationId)
        fmt.Println("Instance IDs:")
        for _, i := range r.Instances {
            fmt.Println("   " + *i.InstanceId)
            printVolumesInfo(i.InstanceBlockDeviceMapping)
        }
    }
}

`

Error received: ./main.go:74:37: undefined: ec2.InstanceBlockDeviceMapping

Tried to use different parameters including []InstanceBlockDeviceMapping and BlockDeviceMapping. Also, used ec2 and client for the values as well.


Solution

  • Check the documentation: https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/ec2/types#Instance

    The field is called BlockDeviceMappings. And the type InstanceBlockDeviceMapping is in the package github.com/aws/aws-sdk-go-v2/service/ec2/types, not in the ec2 package.

    1. Add github.com/aws/aws-sdk-go-v2/service/ec2/types` to your imports
    2. Change argument type of function printVolumes to volumes []ec2.InstanceBlockDeviceMapping
    3. Call the function as printVolumesInfo(i.BlockDeviceMappings)