diff --git a/builtin/providers/aws/resource_aws_cloudtrail.go b/builtin/providers/aws/resource_aws_cloudtrail.go index eed420edf..82a9172c0 100644 --- a/builtin/providers/aws/resource_aws_cloudtrail.go +++ b/builtin/providers/aws/resource_aws_cloudtrail.go @@ -22,6 +22,11 @@ func resourceAwsCloudTrail() *schema.Resource { Required: true, ForceNew: true, }, + "enable_logging": &schema.Schema{ + Type: schema.TypeBool, + Optional: true, + Default: false, + }, "s3_bucket_name": &schema.Schema{ Type: schema.TypeString, Required: true, @@ -84,6 +89,11 @@ func resourceAwsCloudTrailCreate(d *schema.ResourceData, meta interface{}) error d.SetId(*t.Name) + // AWS CloudTrail sets newly-created trails to false. + if v, ok := d.GetOk("enable_logging"); ok && v.(bool) { + cloudTrailSetLogging(conn, v.(bool), d.Id()) + } + return resourceAwsCloudTrailRead(d, meta) } @@ -115,6 +125,12 @@ func resourceAwsCloudTrailRead(d *schema.ResourceData, meta interface{}) error { d.Set("include_global_service_events", trail.IncludeGlobalServiceEvents) d.Set("sns_topic_name", trail.SnsTopicName) + logstatus, err := cloudTrailGetLoggingStatus(conn, *trail.Name) + if err != nil { + return err + } + d.Set("enable_logging", logstatus) + return nil } @@ -149,6 +165,15 @@ func resourceAwsCloudTrailUpdate(d *schema.ResourceData, meta interface{}) error if err != nil { return err } + + if d.HasChange("enable_logging") { + log.Printf("[DEBUG] Updating logging on CloudTrail: %s", input) + err := cloudTrailSetLogging(conn, d.Get("enable_logging").(bool), *input.Name) + if err != nil { + return err + } + } + log.Printf("[DEBUG] CloudTrail updated: %s", t) return resourceAwsCloudTrailRead(d, meta) @@ -165,3 +190,42 @@ func resourceAwsCloudTrailDelete(d *schema.ResourceData, meta interface{}) error return err } + +func cloudTrailGetLoggingStatus(conn *cloudtrail.CloudTrail, id string) (bool, error) { + GetTrailStatusOpts := &cloudtrail.GetTrailStatusInput{ + Name: aws.String(id), + } + resp, err := conn.GetTrailStatus(GetTrailStatusOpts) + + return *resp.IsLogging, err +} + +func cloudTrailSetLogging(conn *cloudtrail.CloudTrail, enabled bool, id string) error { + if enabled { + log.Printf( + "[DEBUG] Starting logging on CloudTrail (%s)", + id) + StartLoggingOpts := &cloudtrail.StartLoggingInput{ + Name: aws.String(id), + } + if _, err := conn.StartLogging(StartLoggingOpts); err != nil { + return fmt.Errorf( + "Error starting logging on CloudTrail (%s): %s", + id, err) + } + } else { + log.Printf( + "[DEBUG] Stopping logging on CloudTrail (%s)", + id) + StopLoggingOpts := &cloudtrail.StopLoggingInput{ + Name: aws.String(id), + } + if _, err := conn.StopLogging(StopLoggingOpts); err != nil { + return fmt.Errorf( + "Error stopping logging on CloudTrail (%s): %s", + id, err) + } + } + + return nil +}