class EC2CreateSnapshot implements ShouldQueue
{
use Queueable;
/**
* Create a new job instance.
*/
public function __construct(private User $user, protected int $accountID, protected string $instanceID, protected string $snapshotDescription)
{
//
}
/**
* Execute the job.
*/
public function handle(): void
{
$region = Config::get('cfp.aws_region');
$creds = new Credentials(
Config::get('cfp.aws_access_key'),
Config::get('cfp.aws_secret_key'),
);
$stsClient = new StsClient([
'credentials' => $creds,
'region' => $region,
]);
$roleARN = "arn:aws:iam::{$this->accountID}:role/CyberForce-Admin";
$assumedRole = $stsClient->assumeRole([
'RoleArn' => $roleARN,
'RoleSessionName' => 'controller-EC2RestoreSnapshot',
]);
$assumedEc2Client = new Ec2Client([
'credentials' => [
'key' => $assumedRole['Credentials']['AccessKeyId'],
'secret' => $assumedRole['Credentials']['SecretAccessKey'],
'token' => $assumedRole['Credentials']['SessionToken'],
],
'region' => $region,
]);
$snapshots = $assumedEc2Client->describeSnapshots([
'OwnerIds' => ['self'],
'Filters' => [
[
'Name' => 'tag:InstanceID',
'Values' => [
$this->instanceID,
],
],
],
]);
$instanceVolumes = $assumedEc2Client->describeVolumes([
'Filters' => [
[
'Name' => 'attachment.instance-id',
'Values' => [
$this->instanceID,
],
],
],
]);
$volumeID = $instanceVolumes['Volumes'][0]['VolumeId'];
$createSnapshotResult = $assumedEc2Client->createSnapshot([
'Description' => $this->snapshotDescription,
'VolumeId' => $volumeID,
'TagSpecifications' => [
[
'ResourceType' => 'snapshot',
'Tags' => [
[
'Key' => 'InstanceID',
'Value' => $this->instanceID,
],
],
],
],
]);
EC2CheckCreateSnapshotStatus::dispatch($this->user, $this->accountID, $this->instanceID, $createSnapshotResult->get('SnapshotId'), $this->snapshotDescription, $snapshots);
}
}