

AWS SDK for Go V1 has reached end-of-support. We recommend that you migrate to [AWS SDK for Go V2](https://docs.aws.amazon.com/sdk-for-go/v2/developer-guide/). For additional details and information on how to migrate, please refer to this [announcement](https://aws.amazon.com/blogs//developer/announcing-end-of-support-for-aws-sdk-for-go-v1-on-july-31-2025/).

# AWS CloudTrail Examples Using the AWS SDK for Go
AWS CloudTrail Examples

CloudTrail is an AWS service that helps you enable governance, compliance, and operational and risk auditing of your AWS account. Actions taken by a user, role, or an AWS service are recorded as events in CloudTrail. Events include actions taken in the AWS Management Console, AWS Command Line Interface, and AWS SDKs and APIs.

The examples assume you have already set up and configured the SDK (that is, you’ve imported all required packages and set your credentials and region). For more information, see [Getting Started with the AWS SDK for Go](setting-up.md) and [Configuring the AWS SDK for Go](configuring-sdk.md).

You can download complete versions of these example files from the [aws-doc-sdk-examples](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/go/example_code/cloudtrail) repository on GitHub.

**Topics**
+ [

# Listing the CloudTrail Trails
](cloudtrail-example-describe-trails.md)
+ [

# Creating a CloudTrail Trail
](cloudtrail-example-create-trail.md)
+ [

# Listing CloudTrail Trail Events
](cloudtrail-example-lookup-events.md)
+ [

# Deleting a CloudTrail Trail
](cloudtrail-example-delete-trail.md)

# Listing the CloudTrail Trails


This example uses the [DescribeTrails](https://docs.aws.amazon.com/sdk-for-go/api/service/cloudtrail/#CloudTrail.DescribeTrails) operation to list the names of the CloudTrail trails and the bucket in which CloudTrail stores information in the `us-west-2` region.

Choose `Copy` to save the code locally.

Create the file *describe\$1trails.go*. Add the following statements to import the Go and AWS SDK for Go packages used in the example.

```
import (
    "fmt"

    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/cloudtrail"
)
```

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.

```
sess := session.Must(session.NewSessionWithOptions(session.Options{
    SharedConfigState: session.SharedConfigEnable,
}))

// Create CloudTrail client
svc := cloudtrail.New(sess)
```

Call **DescribeTrails**. If an error occurs, print the error and exit. If no error occurs, loop through the trails, printing the name of each trail and the bucket.

```
resp, err := svc.DescribeTrails(&cloudtrail.DescribeTrailsInput{TrailNameList: nil})
if err != nil {
    fmt.Println("Got error calling CreateTrail:")
    fmt.Println(err.Error())
    return
}

fmt.Println("Found", len(resp.TrailList), "trail(s)")
fmt.Println("")

for _, trail := range resp.TrailList {
    fmt.Println("Trail name:  " + *trail.Name)
    fmt.Println("Bucket name: " + *trail.S3BucketName)
    fmt.Println("")
}
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/cloudtrail/describe_trails.go) on GitHub.

# Creating a CloudTrail Trail


This example uses the [CreateTrail](https://docs.aws.amazon.com/sdk-for-go/api/service/cloudtrail/#CloudTrail.CreateTrail) operation to create a CloudTrail trail in the `us-west-2` region. It requires two inputs, the name of the trail and the name of the bucket in which CloudTrail stores information. If the bucket does not have the proper policy, include the **-p** flag to attach the correct policy to the bucket.

Choose `Copy` to save the code locally.

Create the file *create\$1trail.go*. Add the following statements to import the Go and AWS SDK for Go packages used in the example.

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/cloudtrail"
    "github.com/aws/aws-sdk-go/service/s3"
    "github.com/aws/aws-sdk-go/service/sts"

    "encoding/json"
    "flag"
    "fmt"
)
```

Get the names of the trail and bucket, and whether to attach the policy to the bucket. If either the trail name or bucket name is missing, display an error message and exit.

```
trailNamePtr := flag.String("n", "", "The name of the trail")
bucketNamePtr := flag.String("b", "", "the name of the bucket to which the trails are uploaded")
addPolicyPtr := flag.Bool("p", false, "Whether to add the CloudTrail policy to the bucket")

flag.Parse()

if *trailNamePtr == "" || *bucketNamePtr == "" {
    fmt.Println("You must supply a trail name and bucket name.")
    return
}
```

Initialize the session that the SDK uses to load credentials from the shared credentials file `.aws/credentials` in your home folder.

```
sess := session.Must(session.NewSessionWithOptions(session.Options{
    SharedConfigState: session.SharedConfigEnable,
}))
```

If the **-p** flag was specfied, add a policy to the bucket.

```
if *addPolicyPtr {
    svc := sts.New(sess)
    input := &sts.GetCallerIdentityInput{}

    result, err := svc.GetCallerIdentity(input)
    if err != nil {
        fmt.Println("Got error snarfing caller identity:")
        fmt.Println(err.Error())
        return
    }

    accountID := aws.StringValue(result.Account)

    s3Policy := map[string]interface{}{
        "Version": "2012-10-17",		 	 	 
        "Statement": []map[string]interface{}{
            {
                "Sid":    "AWSCloudTrailAclCheck20150319",
                "Effect": "Allow",
                "Principal": map[string]interface{}{
                    "Service": "cloudtrail.amazonaws.com",
                },
                "Action":   "s3:GetBucketAcl",
                "Resource": "arn:aws:s3:::" + *bucketNamePtr,
            },
            {
                "Sid":    "AWSCloudTrailWrite20150319",
                "Effect": "Allow",
                "Principal": map[string]interface{}{
                    "Service": "cloudtrail.amazonaws.com",
                },
                "Action":   "s3:PutObject",
                "Resource": "arn:aws:s3:::" + *bucketNamePtr + "/AWSLogs/" + accountID + "/*",
                "Condition": map[string]interface{}{
                    "StringEquals": map[string]interface{}{
                        "s3:x-amz-acl": "bucket-owner-full-control",
                    },
                },
            },
        },
    }

    policy, err := json.Marshal(s3Policy)
    if err != nil {
        fmt.Println("Error marshalling request")
        return
    }

    // Create S3 service
    s3Svc := s3.New(sess)

    // Now set the policy on the bucket
    _, err = s3Svc.PutBucketPolicy(&s3.PutBucketPolicyInput{
        Bucket: aws.String(*bucketNamePtr),
        Policy: aws.String(string(policy)),
    })
    if err != nil {
        fmt.Print("Got error adding bucket policy:")
        fmt.Print(err.Error())
        return
    }

    fmt.Printf("Successfully set bucket %q's policy\n", *bucketNamePtr)
}
```

Create the CloudTrail client, the input for **CreateTrail**, and call **CreateTrail**. If an error occurs, print the error and exit. If no error occurs, print a success message.

```
svc := cloudtrail.New(sess)

input := &cloudtrail.CreateTrailInput{
    Name:         aws.String(*trailNamePtr),
    S3BucketName: aws.String(*bucketNamePtr),
}

_, err := svc.CreateTrail(input)
if err != nil {
    fmt.Println("Got error calling CreateTrail:")
    fmt.Println(err.Error())
    return
}

fmt.Println("Created the trail", *trailNamePtr, "for bucket", *bucketNamePtr)
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/cloudtrail/create_trail.go) on GitHub.

# Listing CloudTrail Trail Events


This example uses the [LookupEvents](https://docs.aws.amazon.com/sdk-for-go/api/service/cloudtrail/#CloudTrail.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\$1events.go*. Add the following statements to import the Go and AWS SDK for Go packages used in the example.

```
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"
    "time"
)
```

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

```
trailNamePtr := flag.String("n", "", "The name of the trail")

flag.Parse()

if *trailNamePtr == "" {
    fmt.Println("You must supply a trail name")
    return
}
```

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.

```
sess := session.Must(session.NewSessionWithOptions(session.Options{
    SharedConfigState: session.SharedConfigEnable,
}))
```

Create the CloudTrail client, and 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.

```
svc := cloudtrail.New(sess)

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())
    return
}

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("Resources:")

    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](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/cloudtrail/lookup_events.go) on GitHub.

# Deleting a CloudTrail Trail


This example uses the [DeleteTrail](https://docs.aws.amazon.com/sdk-for-go/api/service/cloudtrail/#CloudTrail.DeleteTrail) operation to delete a CloudTrail trail in the `us-west-2` region. It requires one input, the name of the trail.

Choose `Copy` to save the code locally.

Create the file *delete\$1trail.go*. Add the following statements to import the Go and AWS SDK for Go packages used in the example.

```
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"
)
```

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

```
trailNamePtr := flag.String("n", "", "The name of the trail to delete")

flag.Parse()

if *trailNamePtr == "" {
    fmt.Println("You must supply a trail name")
    return
}
```

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

```
sess := session.Must(session.NewSessionWithOptions(session.Options{
    SharedConfigState: session.SharedConfigEnable,
}))
```

Create a CloudTrail client and call **DeleteTrail** with the trail name. If an error occurs, print the error and exit. If no error occurs, print a success message.

```
svc := cloudtrail.New(sess)

_, err := svc.DeleteTrail(&cloudtrail.DeleteTrailInput{Name: aws.String(*trailNamePtr)})
if err != nil {
    fmt.Println("Got error calling CreateTrail:")
    fmt.Println(err.Error())
    return
}

fmt.Println("Successfully deleted trail", *trailNamePtr)
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/cloudtrail/delete_trail.go) on GitHub.