AWS SDK for Go
Developer Guide

Listing CloudTrail Trail Events

This example uses the LookupEvents operation to list the CloudTrail trail events in the us-west-2 region.

Choose Copy to save the code locally.

Create the file lookup_events.go. Add the following statements to import the Go and AWS SDK for Go packages used in the example.

import ( "" "" "" "flag" "fmt" "os" "time" )

Get the name of the trail, and whether to display the event. If the trail name is missing, display an error message and exit.

// Trail name required var trailName string flag.StringVar(&trailName, "n", "", "The name of the trail") // Option to show event var showEvent bool flag.BoolVar (&showEvent, "s", false, "Whether to show the event") flag.Parse() if trailName == "" { fmt.Println("You must supply a trail name") os.Exit(1) }

Initialize the session that the SDK uses to load credentials from the shared credentials file .aws/credentials in your home folder, and create a new service client.

// Initialize a session in us-west-2 that the SDK will use to load // credentials from the shared credentials file ~/.aws/credentials. sess, err := session.NewSession(&aws.Config{ Region: aws.String("us-west-2")}, ) // Create CloudTrail client svc := cloudtrail.New(sess)

Create the input for and call LookupEvents. If an error occurs, print the error and exit. If no error occurs, loop through the events, printing information about each event. If the -s flag was specified, print the CloudTrail event.

input := &cloudtrail.LookupEventsInput{EndTime: aws.Time(time.Now())} resp, err := svc.LookupEvents(input) if err != nil { fmt.Println("Got error calling CreateTrail:") fmt.Println(err.Error()) os.Exit(1) } fmt.Println("Found", len(resp.Events),"events before now") fmt.Println("") for _, event := range resp.Events { fmt.Println("Event:") fmt.Println(aws.StringValue(event.CloudTrailEvent)) fmt.Println("") fmt.Println("Name ", aws.StringValue(event.EventName)) fmt.Println("ID: ", aws.StringValue(event.EventId)) fmt.Println("Time: ", aws.TimeValue(event.EventTime)) fmt.Println("User: ", aws.StringValue(event.Username)) fmt.Println("Resourcs:") for _, resource := range event.Resources { fmt.Println(" Name:", aws.StringValue(resource.ResourceName)) fmt.Println(" Type:", aws.StringValue(resource.ResourceType)) } fmt.Println("") }

See the complete example on GitHub.