英文:
AWS Golang SDK v2 - How to add function to Go AWS script
问题
尝试将脚本的每个部分分离为函数,以便稍后使用输出。但是,在尝试将实例传递给printVolumesInfo函数时,无法使此部分工作。
[]InstanceBlockDeviceMapping是Instance结构的一部分,但我不确定在函数中应该使用什么作为输入。
错误信息:
./main.go:74:37: undefined: ec2.InstanceBlockDeviceMapping
尝试使用不同的参数,包括[]InstanceBlockDeviceMapping和BlockDeviceMapping。还尝试使用ec2和client作为值。
英文:
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.
答案1
得分: 1
请查看文档:https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/ec2/types#Instance
该字段名为BlockDeviceMappings
。类型InstanceBlockDeviceMapping
位于包github.com/aws/aws-sdk-go-v2/service/ec2/types
中,而不是ec2
包。
- 将
github.com/aws/aws-sdk-go-v2/service/ec2/types
添加到你的导入项中。 - 将函数
printVolumes
的参数类型更改为volumes []ec2.InstanceBlockDeviceMapping
。 - 调用函数时使用
printVolumesInfo(i.BlockDeviceMappings)
。
英文:
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.
- Add github.com/aws/aws-sdk-go-v2/service/ec2/types` to your imports
- Change argument type of function
printVolumes
tovolumes []ec2.InstanceBlockDeviceMapping
- Call the function as
printVolumesInfo(i.BlockDeviceMappings)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论