| 1 | package Imager::CommandLine::MakeAMI { | ||
| 2 | use MooseX::App; | ||
| 3 | |||
| 4 | #parameter => | ||
| 5 | |||
| 6 | use DateTime; | ||
| 7 | use Term::ANSIColor; | ||
| 8 | use CloudDeploy::Utils; | ||
| 9 | use CloudDeploy::DeploymentCollection; | ||
| 10 | |||
| 11 | parameter deploy_class => (is => 'ro', isa => 'Str', required => 1); | ||
| 12 | option comments => (is => 'ro', isa => 'Str|Undef', documentation => "Comments to include with deployment"); | ||
| 13 | |||
| 14 | sub run { | ||
| 15 | my ($self) = @_; | ||
| 16 | |||
| 17 | my $module = load_class($self->deploy_class); | ||
| 18 | my $obj = $module->{class}->new(params => $module->{params_class}->new_with_options(argv => $self->extra_argv)); | ||
| 19 | |||
| 20 | if (not ($obj->isa('CCfnX::MakeAMIBase') or $obj->isa('CCfnX::MakeAMIBaseVPC'))){ | ||
| 21 | die "Can't make an AMI: Please check base classes are CCfnX::MakeAMIBase or CCfnX::MakeAMIBaseVPC" . $obj; | ||
| 22 | } | ||
| 23 | |||
| 24 | my $deployments = CloudDeploy::DeploymentCollection->new(account => $ENV{'CPSD_AWS_ACCOUNT'}); | ||
| 25 | my $lastday = DateTime->now()->subtract(days => 1); | ||
| 26 | my @list = $deployments->search_log_deployments({ | ||
| 27 | 'params.name' => $obj->params->name, | ||
| 28 | 'timestamp' => { '$gt' => $lastday->datetime() } | ||
| 29 | }, 1); | ||
| 30 | |||
| 31 | if (@list) { | ||
| 32 | print color('bold yellow'), | ||
| 33 | "WARNING: an AMI deployment with the same name was created in the last 24 hours!\n", | ||
| 34 | color('reset') | ||
| 35 | } | ||
| 36 | |||
| 37 | my $deployer = $obj->get_deployer({ | ||
| 38 | access_key => $ENV{AWS_ACCESS_KEY_ID}, | ||
| 39 | secret_key => $ENV{AWS_SECRET_ACCESS_KEY}, | ||
| 40 | account => $ENV{CPSD_AWS_ACCOUNT}, | ||
| 41 | comments => $self->comments, | ||
| 42 | },'CCfnX::CloudFormationDeployer', 'CCfnX::PersistentDeployment'); | ||
| 43 | |||
| 44 | if ($deployments->deployment_exists($obj->params->name)) { | ||
| 45 | my $stack; | ||
| 46 | eval { | ||
| 47 | $stack = $deployer->cfn->DescribeStacks(StackName => $deployer->name)->Stacks->[0]; | ||
| 48 | }; | ||
| 49 | |||
| 50 | unless (defined $stack and $obj->params->onlysnapshot) { | ||
| 51 | if (defined $stack) { | ||
| 52 | die "Stack already exists in AWS and option 'onlysnapshot' was not found.\n"; | ||
| 53 | } | ||
| 54 | else { | ||
| 55 | print "Found existing deployment with no matching AWS stack. Undeploying...\n"; | ||
| 56 | $deployer->undeploy; | ||
| 57 | } | ||
| 58 | } | ||
| 59 | } | ||
| 60 | |||
| 61 | $deployer = $obj->get_deployer({ | ||
| 62 | access_key => $ENV{AWS_ACCESS_KEY_ID}, | ||
| 63 | secret_key => $ENV{AWS_SECRET_ACCESS_KEY}, | ||
| 64 | account => $ENV{CPSD_AWS_ACCOUNT}, | ||
| 65 | comments => $self->comments, | ||
| 66 | },'CCfnX::CloudFormationDeployer', 'CCfnX::PersistentDeployment', 'CCfnX::MakeAMI'); | ||
| 67 | |||
| 68 | $deployer->deploy; | ||
| 69 | } | ||
| 70 | } | ||
| 71 | |||
| 72 | 1; |