Menu
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.

Copy
import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/cloudtrail" "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.

Copy
// 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.

Copy
// 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.

Copy
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 { if showEvents { 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.