Created
November 22, 2024 00:39
-
-
Save Madrigal/7ba080dd181d94289f369634535b0215 to your computer and use it in GitHub Desktop.
EC2 describeInstances
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"fmt" | |
"log" | |
"github.com/aws/aws-sdk-go-v2/config" | |
"github.com/aws/aws-sdk-go-v2/service/ec2" | |
) | |
func main() { | |
// Load the AWS configuration | |
cfg, err := config.LoadDefaultConfig(context.TODO(), config.WithRegion("us-west-2")) | |
if err != nil { | |
log.Fatalf("Failed to load configuration, %v", err) | |
} | |
// Create an EC2 client | |
client := ec2.NewFromConfig(cfg) | |
// Call DescribeInstances to list all EC2 instances | |
output, err := client.DescribeInstances(context.TODO(), &ec2.DescribeInstancesInput{}) | |
if err != nil { | |
log.Fatalf("Failed to describe instances, %v", err) | |
} | |
if len(output.Reservations) == 0 { | |
fmt.Println("No instances found") | |
} | |
// Iterate through the reservations and instances | |
for _, reservation := range output.Reservations { | |
for _, instance := range reservation.Instances { | |
instanceID := instance.InstanceId | |
instanceState := instance.State.Name | |
fmt.Printf("Instance ID: %v, State: %s\n", instanceID, instanceState) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment