protected function execute(InputInterface $input, OutputInterface $output) { $iam = new \AwsInspector\Model\Iam\Repository(); $accountId = $iam->findCurrentUser()->getAccountId(); $output->writeln('Owner: ' . $accountId); $ec2Client = SdkFactory::getClient('EC2'); /* @var $ec2Client \Aws\Ec2\Ec2Client */ $res = $ec2Client->describeImages(['Owners' => [$accountId]]); $activeImageIds = array_flip($res->search('Images[].ImageId')); $res = $ec2Client->describeSnapshots(['OwnerIds' => [$accountId]]); $orphanSnapshots = []; foreach ($res->get('Snapshots') as $snapshotData) { $description = $snapshotData["Description"]; // Created by CreateImage(i-ee0c7564) for ami-9945d0ea from vol-e4b6ff16 // if (preg_match('/^Created by CreateImage\(i-.*\) for \(ami-.*\) from \(vol-.*\)$/', $description)) { if (preg_match('/^Created by CreateImage\\(i-.*\\) for (ami-.+) from vol-.+/', $description, $matches)) { $amiId = $matches[1]; if (isset($activeImageIds[$amiId])) { $output->writeln('Found active AMI: ' . $amiId); } else { $output->writeln('AMI not found: ' . $amiId); $orphanSnapshots[] = $snapshotData['SnapshotId']; } } } foreach ($orphanSnapshots as $snapshotId) { $output->writeln('Deleting ' . $snapshotId); $result = $ec2Client->deleteSnapshot(['SnapshotId' => $snapshotId]); } }
/** * @param $resourceStatusReason * @return array * @throws \Exception */ public function getDetailedLogFromResourceStatusReason($resourceStatusReason) { $logMessages = []; if (preg_match('/See the details in CloudWatch Log Stream: (.*)/', $resourceStatusReason, $matches)) { $logStream = $matches[1]; $logGroupName = Finder::findCloudWatchLogGroupByStream($logStream); if (empty($logGroupName)) { throw new \Exception('Could not find logGroupName for logStream: ' . $logStream); } $params = ['limit' => 20, 'logGroupName' => $logGroupName, 'logStreamName' => $logStream]; $cloudWatchLogClient = \AwsInspector\SdkFactory::getClient('CloudWatchLogs'); /* @var $cloudWatchLogClient \Aws\CloudWatchLogs\CloudWatchLogsClient */ $res = $cloudWatchLogClient->getLogEvents($params); $logMessages = array_merge(["==> Showing last 20 messages from {$logGroupName} -> {$logStream}"], $res->search('events[].message')); } elseif (preg_match('/WaitCondition received failed message:.*for uniqueId: (i-[0-9a-f]+)/', $resourceStatusReason, $matches)) { $instanceId = $matches[1]; $ec2Repo = new \AwsInspector\Model\Ec2\Repository(); $instance = $ec2Repo->findEc2InstanceBy('instance-id', $instanceId); if ($instance) { try { $res = $instance->exec('tail -50 /var/log/cloud-init-output.log'); $logMessages = array_merge(["==> Showing last 50 lines in /var/log/cloud-init-output.log"], $res['output']); } catch (FileNotFoundException $e) { $logMessages = ["Could not log in to instance '{$instanceId}' because the pem file could not be found"]; } } else { $logMessages = ["Could not find instance '{$instanceId}'"]; } } return $logMessages; }
protected function execute(InputInterface $input, OutputInterface $output) { $days = $input->getArgument('days'); $days = intval($days); if ($days == 0) { throw new \Exception('Invalid retention period'); } $groupPattern = $input->getArgument('group'); $cloudwatchLogsClient = \AwsInspector\SdkFactory::getClient('cloudwatchlogs'); /* @var $cloudwatchLogsClient \Aws\CloudWatchLogs\CloudWatchLogsClient */ $totalBytes = 0; $nextToken = null; do { $params = ['limit' => 50]; if ($nextToken) { $params['nextToken'] = $nextToken; } $result = $cloudwatchLogsClient->describeLogGroups($params); foreach ($result->get('logGroups') as $logGroup) { $name = $logGroup['logGroupName']; if (preg_match('/' . $groupPattern . '/', $name)) { $retention = isset($logGroup['retentionInDays']) ? $logGroup['retentionInDays'] : 'never'; if ($retention != $days) { $output->writeln('Updating ' . $logGroup['logGroupName']); $cloudwatchLogsClient->putRetentionPolicy(['logGroupName' => $name, 'retentionInDays' => $days]); } else { $output->writeln('Skipping ' . $logGroup['logGroupName']); } } else { $output->writeln('Does not match pattern: ' . $logGroup['logGroupName']); } } $nextToken = $result->get("nextToken"); } while ($nextToken); }
protected function execute(InputInterface $input, OutputInterface $output) { $groupPattern = $input->getArgument('group'); if (empty($groupPattern)) { $groupPattern = '.*'; } $cloudwatchLogsClient = \AwsInspector\SdkFactory::getClient('cloudwatchlogs'); /* @var $cloudwatchLogsClient \Aws\CloudWatchLogs\CloudWatchLogsClient */ $table = new Table($output); $table->setHeaders(['Name', 'Retention [days]', 'Size [MB]']); $totalBytes = 0; $nextToken = null; do { $params = ['limit' => 50]; if ($nextToken) { $params['nextToken'] = $nextToken; } $result = $cloudwatchLogsClient->describeLogGroups($params); foreach ($result->get('logGroups') as $logGroup) { $name = $logGroup['logGroupName']; if (preg_match('/' . $groupPattern . '/', $name)) { $table->addRow([$logGroup['logGroupName'], isset($logGroup['retentionInDays']) ? $logGroup['retentionInDays'] : 'Never', round($logGroup['storedBytes'] / (1024 * 1024))]); $totalBytes += $logGroup['storedBytes']; } } $nextToken = $result->get("nextToken"); } while ($nextToken); $table->render(); $output->writeln('Total size: ' . $this->formatBytes($totalBytes)); }
public function getTags() { if (is_null($this->tags)) { $elastiCacheClient = \AwsInspector\SdkFactory::getClient('ElastiCache'); /* @var $elastiCacheClient \Aws\ElastiCache\ElastiCacheClient */ $result = $elastiCacheClient->listTagsForResource(['ResourceName' => $this->getResourceName()]); $this->tags = $result->get('TagList'); } return $this->tags; }
public function getInstanceStates() { $elbClient = \AwsInspector\SdkFactory::getClient('ElasticLoadBalancing'); /* @var $elbClient \Aws\ElasticLoadBalancing\ElasticLoadBalancingClient */ $res = $elbClient->describeInstanceHealth(['LoadBalancerName' => $this->getLoadBalancerName()]); $instances = []; foreach ($res->search('InstanceStates[]') as $instanceState) { $instances[$instanceState['InstanceId']] = $instanceState; } return $instances; }
/** * @param array $filters * @return \AwsInspector\Model\Collection * @throws \Exception */ public function findEbsVolumes(array $filters = []) { $ec2Client = \AwsInspector\SdkFactory::getClient('ec2'); /* @var $ec2Client \Aws\Ec2\Ec2Client */ $result = $ec2Client->describeVolumes(['Filters' => $filters]); $rows = $result->search('Volumes[]'); $collection = new \AwsInspector\Model\Collection(); foreach ($rows as $row) { $collection->attach(new Volume($row)); } return $collection; }
/** * @param array $filters * @return \AwsInspector\Model\Collection * @throws \Exception */ public function findSecurityGroups(array $filters = []) { $ec2Client = \AwsInspector\SdkFactory::getClient('ec2'); /* @var $ec2Client \Aws\Ec2\Ec2Client */ $result = $ec2Client->describeSecurityGroups(['Filters' => $filters]); $rows = $result->search('SecurityGroups[]'); $collection = new \AwsInspector\Model\Collection(); foreach ($rows as $row) { $securityGroup = new SecurityGroup($row); if ($securityGroup !== false) { $collection->attach($securityGroup); } } return $collection; }
/** * @param array $filters * @return \AwsInspector\Model\Collection * @throws \Exception */ public function findEc2Instances(array $filters = []) { $ec2Client = \AwsInspector\SdkFactory::getClient('ec2'); /* @var $ec2Client \Aws\Ec2\Ec2Client */ $result = $ec2Client->describeInstances(['Filters' => $filters]); $rows = $result->search('Reservations[].Instances[]'); $collection = new \AwsInspector\Model\Collection(); foreach ($rows as $row) { $instance = Factory::create($row); if ($instance !== false) { $collection->attach($instance); } } return $collection; }
public function attachLoadBalancers(array $loadBalancers) { $loadBalancerNames = []; foreach ($loadBalancers as $loadBalancer) { if (is_string($loadBalancer)) { $loadBalancerNames[] = $loadBalancer; } elseif (is_object($loadBalancer) && $loadBalancer instanceof \AwsInspector\Model\Elb\Elb) { $loadBalancerNames[] = $loadBalancer->getLoadBalancerName(); } else { throw new \InvalidArgumentException('Argument must be an array of strings or \\AwsInspector\\Model\\Elb\\Elb objects'); } } $asgClient = \AwsInspector\SdkFactory::getClient('AutoScaling'); /* @var $asgClient \Aws\AutoScaling\AutoScalingClient */ $result = $asgClient->attachLoadBalancers(['AutoScalingGroupName' => $this->getAutoScalingGroupName(), 'LoadBalancerNames' => $loadBalancerNames]); return $result; }
/** * Repository constructor. * * @param $hostedZoneId */ public function __construct($hostedZoneId) { $r53Client = SdkFactory::getClient('Route53'); /* @var $r53Client \Aws\Route53\Route53Client */ $nextRecordName = null; do { $res = $r53Client->listResourceRecordSets(['HostedZoneId' => $hostedZoneId, 'StartRecordName' => $nextRecordName]); foreach ($res->search('ResourceRecordSets') as $recordSet) { $name = $recordSet['Name']; $type = $recordSet['Type']; unset($recordSet['Name']); unset($recordSet['Type']); $this->recordSets[$name][$type] = $recordSet; } $nextRecordName = $res->get('NextRecordName'); } while ($res->get('IsTruncated')); }
protected function execute(InputInterface $input, OutputInterface $output) { // TODO: refactor this to use \AwsInspector\Model\CloudWatchLogs\Repository $groupPattern = $input->getArgument('group'); $destinationArn = $input->getArgument('destinationArn'); $filterName = $input->getArgument('filterName'); /* @var $cloudwatchLogsClient \Aws\CloudWatchLogs\CloudWatchLogsClient */ $cloudwatchLogsClient = \AwsInspector\SdkFactory::getClient('cloudwatchlogs'); $lambdaClient = \AwsInspector\SdkFactory::getClient('lambda'); $nextToken = null; $logsWithLimitExceededException = []; do { $params = ['limit' => 50]; if ($nextToken) { $params['nextToken'] = $nextToken; } $result = $cloudwatchLogsClient->describeLogGroups($params); foreach ($result->get('logGroups') as $logGroup) { $name = $logGroup['logGroupName']; if (preg_match('/' . $groupPattern . '/', $name)) { try { $lambdaClient->addPermission(['Action' => 'lambda:*', 'FunctionName' => $destinationArn, 'Principal' => 'logs.eu-west-1.amazonaws.com', 'StatementId' => (string) md5($logGroup['logGroupName']), 'SourceArn' => $logGroup['arn']]); $cloudwatchLogsClient->putSubscriptionFilter(['destinationArn' => $destinationArn, 'filterName' => $filterName, 'filterPattern' => '', 'logGroupName' => $logGroup['logGroupName']]); } catch (\Aws\CloudWatchLogs\Exception\CloudWatchLogsException $e) { if ($e->getAwsErrorCode() == 'LimitExceededException') { $logsWithLimitExceededException[] = $logGroup; } } $output->writeln('Add lambda trigger for ' . $logGroup['logGroupName']); } } $nextToken = $result->get("nextToken"); } while ($nextToken); if (!empty($logsWithLimitExceededException)) { $output->writeln('The following log groups has already a different subscription:'); foreach ($logsWithLimitExceededException as $logGroup) { $output->writeln("\t" . $logGroup['logGroupName']); } } }
protected function execute(InputInterface $input, OutputInterface $output) { // TODO: refactor this to use \AwsInspector\Model\CloudWatchLogs\Repository $groupPattern = $input->getArgument('group'); $lambdaArn = $input->getArgument('lambdaArn'); $filterName = $input->getArgument('filterName'); /* @var $cloudwatchLogsClient \Aws\CloudWatchLogs\CloudWatchLogsClient */ $cloudwatchLogsClient = \AwsInspector\SdkFactory::getClient('cloudwatchlogs'); $lambdaClient = \AwsInspector\SdkFactory::getClient('lambda'); $nextToken = null; do { $params = ['limit' => 50]; if ($nextToken) { $params['nextToken'] = $nextToken; } $result = $cloudwatchLogsClient->describeLogGroups($params); foreach ($result->get('logGroups') as $logGroup) { $name = $logGroup['logGroupName']; if (preg_match('/' . $groupPattern . '/', $name)) { try { $subscriptionFilters = $cloudwatchLogsClient->describeSubscriptionFilters(['logGroupName' => $logGroup['logGroupName']]); if (empty($subscriptionFilters->get('subscriptionFilters'))) { continue; } $cloudwatchLogsClient->deleteSubscriptionFilter(['filterName' => $filterName, 'logGroupName' => $logGroup['logGroupName']]); $lambdaClient->removePermission(['FunctionName' => $lambdaArn, 'StatementId' => (string) md5($logGroup['logGroupName'])]); $output->writeln('Delete lambda trigger for ' . $logGroup['logGroupName']); } catch (\Aws\CloudWatchLogs\Exception\CloudWatchLogsException $e) { if ($e->getAwsErrorCode() != 'ResourceNotFoundException') { throw $e; } } } } $nextToken = $result->get("nextToken"); } while ($nextToken); }
public static function findCloudWatchLogGroupByStream($stream, $logGroupNamePrefix = null) { return null; // TODO: FIx this! // TODO: refactor this to use \AwsInspector\Model\CloudWatchLogs\Repository $cloudWatchLogClient = \AwsInspector\SdkFactory::getClient('CloudWatchLogs'); /* @var $cloudWatchLogClient \Aws\CloudWatchLogs\CloudWatchLogsClient */ $groupsNextToken = null; do { $params = []; if ($logGroupNamePrefix) { $params['logGroupNamePrefix'] = $logGroupNamePrefix; } if ($groupsNextToken) { $params['nextToken'] = $groupsNextToken; } $resGroups = $cloudWatchLogClient->describeLogGroups($params); foreach ($resGroups->search('logGroups[].logGroupName') as $logGroupName) { $streamsNextToken = null; do { $streamsParams = ['logGroupName' => $logGroupName, 'orderBy' => 'LastEventTime']; if ($streamsNextToken) { $streamsParams['nextToken'] = $streamsNextToken; } $resStreams = $cloudWatchLogClient->describeLogStreams($streamsParams); foreach ($resStreams->search('logStreams[].logStreamName') as $logStreamName) { if ($stream == $logStreamName) { return $logGroupName; } } $streamsNextToken = $resStreams->get("nextToken"); } while ($streamsNextToken); } $groupsNextToken = $resGroups->get("nextToken"); } while ($groupsNextToken); return null; }
public function __construct() { $this->rdsClient = \AwsInspector\SdkFactory::getClient('Rds'); }
public function __construct() { $this->elastiCacheClient = \AwsInspector\SdkFactory::getClient('ElastiCache'); }
public function __construct() { $this->asgClient = \AwsInspector\SdkFactory::getClient('AutoScaling'); }
public function terminate() { $ec2Client = \AwsInspector\SdkFactory::getClient('ec2'); /* @var $ec2Client \Aws\Ec2\Ec2Client */ $ec2Client->terminateInstances(['InstanceIds' => [$this->getInstanceId()]]); }
public function getPublicIpForNatGateway($natGatewayId) { $cacheKey = 'Ec2Repository->getPublicIpForNatGateway:' . $natGatewayId; return StaticCache::get($cacheKey, function () use($natGatewayId) { // Find the Elastic IP address attached to this NAT Gateway $ec2Client = \AwsInspector\SdkFactory::getClient('ec2'); /* @var $ec2Client \Aws\Ec2\Ec2Client */ $results = $ec2Client->describeNatGateways(['NatGatewayIds' => [$natGatewayId]]); $natGateway = $results->search('NatGateways'); return $natGateway[0]['NatGatewayAddresses'][0]['PublicIp']; }); }
public function __construct() { $this->iamClient = \AwsInspector\SdkFactory::getClient('Iam', 'default', ['region' => 'us-east-1']); }
public function __construct() { $this->elbClient = \AwsInspector\SdkFactory::getClient('ElasticLoadBalancing'); }
public function __construct() { $this->iamClient = \AwsInspector\SdkFactory::getClient('Iam'); }