-
Notifications
You must be signed in to change notification settings - Fork 86
Expand file tree
/
Copy pathCreateBucket.php
More file actions
107 lines (80 loc) · 2.6 KB
/
CreateBucket.php
File metadata and controls
107 lines (80 loc) · 2.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
<?php
declare(strict_types=1);
/**
* @author Aaron Francis <aarondfrancis@gmail.com|https://twitter.com/aarondfrancis>
*/
namespace Hammerstone\Sidecar\Commands\Actions;
use Aws\S3\S3Client;
use Exception;
use Illuminate\Support\Str;
use Throwable;
class CreateBucket extends BaseAction
{
protected S3Client $client;
protected string $bucket;
public function invoke(): string
{
$this->client = $this->command->client(S3Client::class);
$this->bucket = config('sidecar.aws_bucket') ?? $this->defaultBucketName();
$this->ensureBucketIsPrefixed();
$this->progress("Using bucket name `$this->bucket`");
$this->progress('Checking to see if the bucket exists...');
if ($this->bucketExists()) {
$this->progress('Bucket already exists');
return $this->bucket;
}
$this->progress('Bucket doesn\'t exist.');
// Sometimes it takes a second for the AWS credentials to populate, so we will try a couple times.
retry(3, function () {
$this->progress('Trying to create bucket...');
$this->createBucket();
}, 4000);
$this->progress('Bucket created');
return $this->bucket;
}
protected function defaultBucketName()
{
$now = now()->timestamp;
return "sidecar-{$this->region}-{$now}";
}
protected function ensureBucketIsPrefixed()
{
if (Str::startsWith($this->bucket, 'sidecar-')) {
return;
}
$this->bucket = Str::start($this->bucket, 'sidecar-');
$question = implode("\n", [
'Your bucket name must begin with "sidecar-".',
" Using the name `$this->bucket`. Is that ok?"
]);
if (!$this->command->confirm($question, $default = true)) {
throw new Exception('Unable to determine valid bucket name.');
}
}
protected function bucketExists()
{
try {
$this->client->headBucket([
'Bucket' => $this->bucket,
]);
return true;
} catch (Throwable $e) {
return false;
}
}
protected function createBucket()
{
try {
$this->client->createBucket([
'ACL' => 'private',
'Bucket' => $this->bucket,
'CreateBucketConfiguration' => [
'LocationConstraint' => $this->region,
],
]);
} catch (Throwable $e) {
$this->command->error('Unable to create deployment artifact bucket.');
throw $e;
}
}
}