Most of the time you do something like:
if err != nil {
fmt.Println("Error calling ec2: ",err)
return
}
For larger projects you would change the simple fmt.Println statement for a logging statement. For now it’s ok
In results you now get a full blown ec2.DescribeInstancesOutput, which is quite complex.
Here are the first lines of the json:
{
"Reservations": [
{
"Groups": [],
"Instances": [
{
"AmiLaunchIndex": 0,
"ImageId": "ami-0cd855c8009cb26ef",
"InstanceId": "i-047f905e0ad093147",
"InstanceType": "t2.nano",
"LaunchTime": "2021-09-09T12:17:53+00:00",
"Monitoring": {
"State": "disabled"
},
"Placement": {
"AvailabilityZone": "eu-central-1c",
"GroupName": "",
"Tenancy": "default"
},
"PrivateDnsName": "ip-172-31-11-17.eu-central-1.compute.internal",
"PrivateIpAddress": "172.31.11.17",
...
The EC2 APi itself returns XML. The AWS GO SDK transforms that to json.
Because the json object is transformed to the struct, you get full auto-completion support:
The AWS api Describe commands return arrays. You easily loop through these arrays with range.
As ec2 instances loops over Reservations and Instances you get all data with:
for i, reservation := range result.Reservations {
for k, instance := range reservation.Instances {
fmt.Println("Instance number: ",i,"-",k , "Id: ", instance.InstanceId)
}
}
This corresponds to the json arrays:
{
"Reservations": [
{
"Groups": [],
"Instances": [
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/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 main() {
parms := &ec2.DescribeInstancesInput{
MaxResults: aws.Int32(10),
}
result, err := client.DescribeInstances(context.TODO(),parms)
if err != nil {
fmt.Println("Error calling ec2: ",err)
return
}
count := len(result.Reservations)
fmt.Println("Instances: ",count)
for i, reservation := range result.Reservations {
for k, instance := range reservation.Instances {
fmt.Println("Instance number: ",i,"-",k , "Id: ", instance.InstanceId)
}
}
}
go run main.go
In my AWS account two instances are running:
go run main.go
Output:
Instances: 2
Instance number: 0 - 0 Id: 0xc000021310
Instance number: 1 - 0 Id: 0xc0000216a0
See the full source on github.