· 7 years ago · Nov 16, 2018, 10:46 PM
1#! /usr/bin/perl -w
2
3# Really simple script to copy a file to an S3 bucket.
4# Credentials are read from ~/.s3credentials, which should
5# consist of two lines: the access key id and the secret key.
6
7use strict;
8use FileHandle;
9use Net::Amazon::S3;
10
11scalar(@ARGV) == 2 || Usage();
12
13my $local_file = shift @ARGV;
14my $bucket_name = shift @ARGV;
15
16my ($access_key, $secret_key) = ReadCredentials();
17
18my $s3 = Net::Amazon::S3->new({
19 aws_access_key_id => $access_key,
20 aws_secret_access_key => $secret_key,
21 retry => 1,
22});
23
24my $bucket = $s3->bucket($bucket_name);
25print "Transferring file $local_file to bucket $bucket_name...";
26STDOUT->flush();
27$bucket->add_key_filename($local_file, $local_file, { content_type => 'application/octet-stream' })
28 || die "Couldn't copy file to bucket: " . $s3->errstr . "\n";
29print "Done!\n";
30exit 0;
31
32sub Usage {
33 print STDERR <<"USAGE";
34Usage: s3backup.pl <local file> <bucket>
35USAGE
36 exit 1;
37}
38
39sub ReadCredentials {
40 my $home = $ENV{'HOME'};
41 my $credentials_fh = new FileHandle("<$home/.s3credentials")
42 || die "Couldn't open $home/.s3credentials: $!\n";
43
44 my $access_key = <$credentials_fh>;
45 chomp $access_key;
46 my $secret_key = <$credentials_fh>;
47 chomp $secret_key;
48
49 die "Could not read access key\n" if (!defined $access_key);
50 die "Could not read secret key\n" if (!defined $secret_key);
51
52 return ($access_key, $secret_key);
53}
54
55# vim:set ts=2: