|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Codinglabs\Yolo\Concerns; |
| 4 | + |
| 5 | +use Codinglabs\Yolo\Aws; |
| 6 | +use Codinglabs\Yolo\AwsResources; |
| 7 | + |
| 8 | +trait SyncsSslCertificates |
| 9 | +{ |
| 10 | + protected function requestCertificate(string $apex): void |
| 11 | + { |
| 12 | + $certificate = Aws::acm()->requestCertificate([ |
| 13 | + 'DomainName' => $apex, |
| 14 | + 'SubjectAlternativeNames' => ["*.{$apex}"], |
| 15 | + 'ValidationMethod' => 'DNS', |
| 16 | + ]); |
| 17 | + |
| 18 | + $this->validateCertificate($certificate['CertificateArn'], $apex); |
| 19 | + } |
| 20 | + |
| 21 | + protected function validateCertificate(string $certificateArn, string $apex): void |
| 22 | + { |
| 23 | + do { |
| 24 | + $certificate = Aws::acm()->describeCertificate([ |
| 25 | + 'CertificateArn' => $certificateArn, |
| 26 | + ])['Certificate']; |
| 27 | + |
| 28 | + // take a little snooze because the AWS result |
| 29 | + // is incomplete on the first request |
| 30 | + sleep(2); |
| 31 | + } while ( |
| 32 | + ! array_key_exists('DomainValidationOptions', $certificate) || |
| 33 | + ! collect($certificate['DomainValidationOptions']) |
| 34 | + ->every(fn (array $option) => array_key_exists('ResourceRecord', $option)) |
| 35 | + ); |
| 36 | + |
| 37 | + Aws::route53()->changeResourceRecordSets([ |
| 38 | + 'ChangeBatch' => [ |
| 39 | + 'Changes' => collect($certificate['DomainValidationOptions']) |
| 40 | + ->filter(fn (array $option) => $option['ValidationMethod'] === 'DNS' |
| 41 | + && ! str_starts_with($option['ValidationDomain'], '*')) |
| 42 | + ->map(function (array $option) { |
| 43 | + return [ |
| 44 | + 'Action' => 'UPSERT', |
| 45 | + 'ResourceRecordSet' => [ |
| 46 | + 'Name' => $option['ResourceRecord']['Name'], |
| 47 | + 'Type' => $option['ResourceRecord']['Type'], |
| 48 | + 'ResourceRecords' => [ |
| 49 | + [ |
| 50 | + 'Value' => $option['ResourceRecord']['Value'], |
| 51 | + ], |
| 52 | + ], |
| 53 | + 'TTL' => 300, |
| 54 | + ], |
| 55 | + ]; |
| 56 | + })->toArray(), |
| 57 | + 'Comment' => 'Created by yolo CLI', |
| 58 | + ], |
| 59 | + 'HostedZoneId' => AwsResources::hostedZone($apex)['Id'], |
| 60 | + ]); |
| 61 | + |
| 62 | + // wait for the certificate to be issued |
| 63 | + $certificate = AwsResources::certificate($apex); |
| 64 | + |
| 65 | + if ($certificate['Status'] !== 'ISSUED') { |
| 66 | + do { |
| 67 | + $certificate = AwsResources::certificate($apex); |
| 68 | + |
| 69 | + // take a little snooze until the certificate is issued |
| 70 | + sleep(2); |
| 71 | + } while ($certificate['Status'] !== 'ISSUED'); |
| 72 | + } |
| 73 | + } |
| 74 | +} |
0 commit comments