AWS SDK for Ruby
Developer Guide

Creating a CloudTrail Trail

This example uses the create_trail method 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_trail.rb. Add the following statements to use the CloudTrail, STS, and S3 gems of the AWS SDK for Ruby.

require 'aws-sdk-cloudtrail' # v2: require 'aws-sdk' require 'aws-sdk-s3' require 'aws-sdk-sts'

Create a function to add a policy to the bucket that gives CloudTrail permission to save data to the bucket.

def add_policy(bucket) # Get account ID using STS sts_client = Aws::STS::Client.new(region: 'us-west-2') resp = sts_client.get_caller_identity({}) account_id = resp.account # Attach policy to S3 bucket s3_client = Aws::S3::Client.new(region: 'us-west-2') begin policy = { 'Version' => '2012-10-17', 'Statement' => [ { 'Sid' => 'AWSCloudTrailAclCheck20150319', 'Effect' => 'Allow', 'Principal' => { 'Service' => 'cloudtrail.amazonaws.com', }, 'Action' => 's3:GetBucketAcl', 'Resource' => 'arn:aws:s3:::' + bucket, }, { 'Sid' => 'AWSCloudTrailWrite20150319', 'Effect' => 'Allow', 'Principal' => { 'Service' => 'cloudtrail.amazonaws.com', }, 'Action' => 's3:PutObject', 'Resource' => 'arn:aws:s3:::' + bucket + '/AWSLogs/' + account_id + '/*', 'Condition' => { 'StringEquals' => { 's3:x-amz-acl' => 'bucket-owner-full-control', }, }, }, ] }.to_json s3_client.put_bucket_policy( bucket: bucket, policy: policy ) puts 'Successfully added policy to bucket ' + bucket rescue StandardError => err puts 'Got error trying to add policy to bucket ' + bucket + ':' puts err exit 1 end end

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.

name = '' bucket = '' attach_policy = false i = 0 while i < ARGV.length case ARGV[i] when '-b' i += 1 bucket = ARGV[i] when '-p' attach_policy = true else name = ARGV[i] end i += 1 end if name == '' || bucket == '' puts 'You must supply a trail name and bucket name' puts USAGE exit 1 end

If the -p flag was specified, call add_policy to attach the policy to the bucket.

if attach_policy add_policy(bucket) end

Create the CloudTrail client and call create_trail to create the trail. If any errors occur, print the error and quit, otherwise print a success message.

client = Aws::CloudTrail::Client.new(region: 'us-west-2') begin resp = client.create_trail({ name: name, # required s3_bucket_name: bucket, # required }) puts 'Successfully created CloudTrail ' + name + ' in us-west-2' rescue StandardError => err puts 'Got error trying to create trail ' + name + ':' puts err exit 1 end

See the complete example on GitHub.