Search code examples
amazon-web-servicesamazon-ec2aws-lambdaamazon-ecs

List all AWS ECS (EC2 Container) servers across all the accounts


Is there any way to get list of all the ECS servers running/stopped in multiple accounts within single AWS subscription. I can curl into localhost to fetch the meta data

curl http://localhost:51678/v1/metadata

but I have to run it for every single server, to fetch the info. and then list out the servers who responded with containers services.

Is there any better way to do this ? any lambda function or anything.

Any help is appreciated.

Thanks.


Solution

  • You can implement a Lambda Function to do that if you want.

    That would be something like(if you choose nodejs):

    const AWS      = require('aws-sdk');
    const bluebird = require('bluebird');
    
    const EC2_TOPIC_ARN   = process.env.EC2_TOPIC_ARN;
    const DEFAULT_FILTERS = {};
    
    AWS.config.setPromisesDependency(bluebird);
    
    var ec2 = new AWS.EC2();
    var sns = new AWS.SNS();
    
    /**
    * Describes EC2 instances
    * 
    * @param {Object} filters 
    */
    var getEC2Instances = (filters) => {
       var params = {
           DryRun : false,
           Filters: [filters]
       };
    
       return ec2.describeInstances(params).promise();
    }
    
    /**
    * Publishes a message to the sns topic
    * 
    * @param {Object} message
    */
    var broadcast = (message) => {
        var params = {
            TargetArn: EC2_TOPIC_ARN,
            Message  : JSON.stringify(message),
            Subject  : 'EC2 Describe Event'
        };
    
        return sns.publish(params).promise();
    }
    
    exports.handler = (event, context, callback) => {
       var body    = JSON.parse(event.body);
       var filters = body.filters || DEFAULT_FILTERS;
    
       getEC2Instances(filters)
           .then(
               (result) => {
                   console.log(result);
    
                   broadcast(result)
                       .then((status) => console.log(status))
                       .catch((error) => console.error(error));
    
                   callback(null, { statusCode: 200, body: JSON.stringify(result) });
               }
           ).catch(
               (error) => {
                   console.error(error);
                   callback(null, { statusCode: 500, body: JSON.stringify({message: 'Ops'}) });                
               }
          );
    }
    

    For more details, take a look at the AWS-SDK Documentation