Deploys lambdas to AWS
961726
def deploy(self, *lambdas):
        """"""

        if not self.role:
            logger.error('Missing AWS Role')
            raise ArgumentsError('Role required')

        logger.debug('Deploying lambda {}'.format(self.lambda_name))
        zfh = self.package()

        if self.lambda_name in self.get_function_names():
            logger.info('Updating {} lambda'.format(self.lambda_name))

            response = self.client.update_function_code(
                FunctionName=self.lambda_name,
                ZipFile=zfh.getvalue(),
                Publish=True
            )
        else:
            logger.info('Adding new {} lambda'.format(self.lambda_name))

            response = self.client.create_function(
                FunctionName=self.lambda_name,
                Runtime=yaep.env(
                    'LAMBDA_RUNTIME',
                    'python2.7'
                ),
                Role=self.role,
                Handler=yaep.env(
                    'LAMBDA_HANDLER',
                    'lambda_function.lambda_handler'
                ),
                Code={
                    'ZipFile': zfh.getvalue(),
                },
                Description=yaep.env(
                    'LAMBDA_DESCRIPTION',
                    'Lambda code for {}'.format(self.lambda_name)
                ),
                Timeout=yaep.env(
                    'LAMBDA_TIMEOUT',
                    3,
                    convert_booleans=False,
                    type_class=int
                ),
                MemorySize=yaep.env(
                    'LAMBDA_MEMORY_SIZE',
                    128,
                    convert_booleans=False,
                    type_class=int
                ),
                Publish=True
            )

        status_code = response.get(
            'ResponseMetadata', {}
        ).get('HTTPStatusCode')

        if status_code in [200, 201]:
            logger.info('Successfully deployed {} version {}'.format(
                self.lambda_name,
                response.get('Version', 'Unkown')
            ))
        else:
            logger.error('Error deploying {}: {}'.format(
                self.lambda_name,
                response
            ))
311308
def _generate_lambda_handler(config, output='.slam/handler.py'):
    """"""
    # Determine what the start up code is. The default is to just run the
    # function, but it can be overriden by a plugin such as wsgi for a more
    # elaborated way to run the function.
    run_function = _run_lambda_function
    for name, plugin in plugins.items():
        if name in config and hasattr(plugin, 'run_lambda_function'):
            run_function = plugin.run_lambda_function
    run_code = ''.join(inspect.getsourcelines(run_function)[0][1:])

    # generate handler.py
    with open(os.path.join(os.path.dirname(__file__),
                           'templates/handler.py.template')) as f:
        template = f.read()
    template = render_template(template, module=config['function']['module'],
                               app=config['function']['app'],
                               run_lambda_function=run_code,
                               config_json=json.dumps(config,
                                                      separators=(',', ':')))
    with open(output, 'wt') as f:
        f.write(template + '\n')
1050035
def generate_lambda_functions():
    """"""
    logger.debug("[#] Setting up the Lambda functions")
    aws_lambda = boto3.client('lambda', region_name=PRIMARY_REGION)
    functions = aws_lambda.list_functions().get('Functions')
    existing_funcs = [x['FunctionName'] for x in functions]

    iam = boto3.resource('iam')
    account_id = iam.CurrentUser().arn.split(':')[4]

    responses = list()
    for label in LAMBDA_FUNCTIONS:
        if label in existing_funcs:
            logger.debug("[*] Lambda function %s already exists" % (label))
            continue
        dir_path = os.path.dirname(os.path.realpath(__file__))
        dir_path = dir_path.replace('/cli', '/aws')

        kwargs = {
            'Runtime': 'python2.7',
            'Role': 'arn:aws:iam::{0}:role/{1}'.format(account_id, BLOCKADE_ROLE),
            'Timeout': 3,
            'MemorySize': 128,
            'Publish': True,
            'Code': {
                'ZipFile': open("{0}/lambda-zips/{1}.zip".format(dir_path, label), 'rb').read()
            }
        }
        kwargs.update(LAMBDA_SCHEMA[label])
        logger.debug("[#] Setting up the %s Lambda function" % (label))
        response = aws_lambda.create_function(**kwargs)
        responses.append(response)
        logger.debug("[#] Successfully setup Lambda function %s" % (label))
    logger.info("[#] Successfully setup Lambda functions")

    return responses
505507
def create_awslambda(self):
        """"""
        utils.banner("Creating Lambda Function")
        awslambdaobj = awslambda.LambdaFunction(
            app=self.app, env=self.env, region=self.region, prop_path=self.json_path)
        awslambdaobj.create_lambda_function()

        utils.banner("Creating Lambda Event")
        lambdaeventobj = awslambda.LambdaEvent(app=self.app, env=self.env, region=self.region, prop_path=self.json_path)
        lambdaeventobj.create_lambda_events()
289697
function buildCloudwatchEvent(options, functionType) {
  validateCloudWatchEvent(functionType, options.eventSources);

  let eventName = options.name + utils.capitalizeFirst(functionType);
  let event = {
    Resources: {}
  };

  event.Resources[eventName + 'Permission'] = {
    Type: 'AWS::Lambda::Permission',
    Properties: {
      FunctionName: cf.getAtt(options.name, 'Arn'),
      Action: 'lambda:InvokeFunction',
      Principal: 'events.amazonaws.com',
      SourceArn: cf.getAtt(eventName + 'Rule', 'Arn')
    }
  };

  event.Resources[eventName + 'Rule'] = {
    Type: 'AWS::Events::Rule',
    Properties: {
      RoleArn: cf.if('HasDispatchSnsArn', cf.getAtt('LambdaCfnDispatchRole', 'Arn'), cf.getAtt('LambdaCfnRole', 'Arn')),
      State: 'ENABLED',
      Targets: [
        {
          Arn: cf.getAtt(options.name, 'Arn'),
          Id: options.name
        }
      ]
    }
  };

  if (functionType === 'cloudwatchEvent') {
    event.Resources[eventName + 'Rule'].Properties.EventPattern = options.eventSources.cloudwatchEvent.eventPattern;
  } else {
    event.Resources[eventName + 'Rule'].Properties.ScheduleExpression = options.eventSources.schedule.expression;
  }

  return event;
}
826914
async function connect() {
  
  let esConfig
  let client

  // use local client
  if (!process.env.ES_HOST) {
    client = new elasticsearch.Client({host: 'localhost:9200'})
  } else {
    await new Promise((resolve, reject) => AWS.config.getCredentials((err) => {
      if (err) return reject(err)
      resolve()
    }))

    esConfig = {
      host: process.env.ES_HOST,
      connectionClass: httpAwsEs,
      amazonES: {
        region: process.env.AWS_DEFAULT_REGION || 'us-east-1',
        credentials: AWS.config.credentials
      },
      // Note that this doesn't abort the query.
      requestTimeout: 120000  // milliseconds
    }
    client = new elasticsearch.Client(esConfig)
  }

  await new Promise((resolve, reject) => client.ping({requestTimeout: 1000}, (err) => {
    if (err) {
      console.log('unable to connect to elasticsearch')
      reject('unable to connect to elasticsearch')
    } else {
      resolve()
    }
  }))
  return client
}
319152
function generateAdminRouter(conf) {
  var awsKey = conf.aws.key;
  var awsSecret = conf.aws.secret;

  var api = apiFactory(log);
  var p = q.defer();

  // Register backup handlers:

  backup.registerHandler('s3', backupHandlers.genS3BackupHandler(
        awsKey,
        awsSecret
  ));

  MongoClient.connect(conf.database.url, function(err, db) {
    if(err) {
      p.reject(err);
      return;
    }

    var backupCollection = db.collection(BACKUP_COLLECTION_NAME);
    var liveBackups = {};

    //Lists all persisted backups
    api.register('backup', 'list', 'GET', function() {
        var results = backupCollection.find({});
        return q.nbind(results.toArray, results)();
    });

    api.register('backup', 'stat', 'GET', [ 'id' ], function(id) {
      if(liveBackups[id]) {
        return q(liveBackups[id]);
      }

      return q.nbind(backupCollection.findOne, backupCollection)({ backupId: id })
        .then(function(r) {
          if(!r) {
            return q({ 'error': true, msg: 'backup with id ' + id + ' not found'});
          }

          return q({ 'status': 'saved' });
        });
    });

    //Request object must be of the form
    //  {
    //    collections: [<String>],
    //    type: <String>,
    //    opts: <Object>
    //  }
    api.register('backup', 'start', 'POST', function(args) {
      var id = uuid.v1();
      // TODO: add a call to mongo's admin.serverStatus function to get the time on server.
      var backupTimestamp = new Date();
      liveBackups[id] = { 'status': 'in-progress' };
      backup.create(conf.backups.target, args.collections, args.type, args.opts)
        .then(function(backupRecord) {
          backupRecord.name = args.name;
          backupRecord.timestamp = backupTimestamp.toISOString();
          backupRecord.backupId = id;
          backupCollection.insert(backupRecord, function(e) {
            if(e) {
              liveBackups[id] = { 'status': 'failed' };
              log.error(e);
            }
            delete liveBackups[id];
          });
        })
        .then(null, log.error.bind(log));
      return q({id: id});
    });


    //FIXME use tickets to manage restore ops (similar to backups)

    api.register('backup', 'restore', 'POST', function(args) {
      var id = args.id;
      return q.nbind(backupCollection.findOne, backupCollection)({ backupId: id })
        .then(function(r) {
          if(!r) {
            return q({ error: true, msg: 'backup with id ' + id + ' not found ' });
          }
          return backup.restore(r, conf.backups.target);
        });
    });

    p.resolve(api.getApp());
  });

  return p.promise;
}
1250513
def new_deploy(py_ver: PyVer, release_target: ReleaseTarget):
    """"""
    cache_file = f'app_{py_ver.name}.tar'
    template = yaml.safe_load(f"""
    machine:
      image: circleci/classic:201710-02
    steps:
      - attach_workspace:
          at: {cache_dir}
      - checkout
      - run:
          name: Install prerequisites
          command: sudo pip install awscli
      - run:
          name: Load docker image layer cache
          command: docker load -i {cache_dir}/{cache_file}
      - run:
          name: Start a named container
          command: docker run --name=SDK {py_ver.tag}
      - run:
          name: Extract the documentation
          command: 'docker cp SDK:/build/built_docs ./built_docs'
      - run:
          name: Upload the documentation
          command: >-
            aws s3 sync --delete --cache-control
            max-age=3600 built_docs s3://mbed-cloud-sdk-python
      - run:
          name: Tag and release
          command: >-
            docker run --env-file=scripts/templates/envvars.env
            -e TWINE_REPOSITORY={release_target.twine_repo}
            {py_ver.tag}
            sh -c "source .venv/bin/activate && python scripts/tag_and_release.py --mode={release_target.mode}"
      - run:
          name: Start the release party!
          command: >-
            docker run --env-file=scripts/templates/envvars.env
            {py_ver.tag}
            sh -c "source .venv/bin/activate && python scripts/notify.py"
    """)
    return deploy_name(py_ver, release_target), template
1304871
def main():
  
  setup_logging(logging.INFO)

  # Parse arguments
  parser = argparse.ArgumentParser(
    description="A utility to interact with AWS using Cloudera Manager.")
  parser.add_argument('-H', '--hostname', action='store', dest='hostname',
                      required=True,
                      help='The hostname of the Cloudera Manager server.')
  parser.add_argument('-p', action='store', dest='port', type=int,
                      help='The port of the Cloudera Manager server. Defaults '
                           'to 7180 (http) or 7183 (https).')
  parser.add_argument('-u', '--username', action='store', dest='username',
                      help='Login name.')
  parser.add_argument('--password', action='store', dest='password',
                      help='Login password.')
  parser.add_argument('--api-version', action='store', dest='api_version',
                      type=int,
                      default=MINIMUM_SUPPORTED_API_VERSION,
                      help='API version to be used. Defaults to {0}.'.format(
                        MINIMUM_SUPPORTED_API_VERSION))
  parser.add_argument('--tls', action='store_const', dest='use_tls',
                      const=True, default=False,
                      help='Whether to use tls (https).')
  parser.add_argument('-c', '--show-categories', action='store_true',
                      default=False, dest='show_categories',
                      help='Prints a list of supported external account '
                           'category names. For example, "AWS" is a supported '
                           'external account category name.')
  parser.add_argument('-t', '--show-types', action='store',
                      dest='category_name',
                      help='Prints a list of supported external account type '
                           'names for the given CATEGORY_NAME. For example, '
                           '"AWS_ACCESS_KEY_AUTH" is a supported external '
                           'account type name for external account category '
                           '"AWS".')
  parser.add_argument('-n', '--show-credentials', action='store',
                      dest='type_name',
                      help='Prints a list of available credential names for '
                           'the given TYPE_NAME.')
  parser.add_argument('--prune', action='store', dest='credential_name',
                      help='Runs S3Guard prune command on external account '
                           'associated with the given CREDENTIAL_NAME.')
  parser.add_argument('--version', action='version', version='%(prog)s 1.0')
  args = parser.parse_args()

  # Use the default port if required.
  if not args.port:
    if args.use_tls:
      args.port = DEFAULT_HTTPS_PORT
    else:
      args.port = DEFAULT_HTTP_PORT

  validate_api_compatibility(args)
  get_login_credentials(args)
  initialize_api(args)

  # Perform the AWS operation based on the input arguments.
  if args.show_categories:
    list_supported_categories()
  elif args.category_name:
    list_supported_types(args.category_name)
  elif args.type_name:
    list_credentials_by_name(args.type_name)
  elif args.credential_name:
    call_s3guard_prune(args.credential_name)
  else:
    print ("ERROR: No arguments given to perform any AWS operation.")
    parser.print_help()
    sys.exit(1)
434840
def deploy(
    config,
    name,
    bucket,
    timeout,
    memory,
    description,
    subnet_ids,
    security_group_ids
):
    
    # options should override config if it is there
    myname = name or config.name
    mybucket = bucket or config.bucket
    mytimeout = timeout or config.timeout
    mymemory = memory or config.memory
    mydescription = description or config.description
    mysubnet_ids = subnet_ids or config.subnet_ids
    mysecurity_group_ids = security_group_ids or config.security_group_ids

    vpc_config = {}
    if mysubnet_ids and mysecurity_group_ids:
        vpc_config = {
            'SubnetIds': mysubnet_ids.split(','),
            'SecurityGroupIds': mysecurity_group_ids.split(',')
        }

    click.echo('Deploying {} to {}'.format(myname, mybucket))
    lambder.deploy_function(
        myname,
        mybucket,
        mytimeout,
        mymemory,
        mydescription,
        vpc_config
    )
312091
def update_lambda_configuration(    self,
                                        lambda_arn,
                                        function_name,
                                        handler,
                                        description='Zappa Deployment',
                                        timeout=30,
                                        memory_size=512,
                                        publish=True,
                                        vpc_config=None,
                                        runtime='python2.7',
                                        aws_environment_variables=None,
                                        aws_kms_key_arn=None
                                    ):
        
        print("Updating Lambda function configuration..")

        if not vpc_config:
            vpc_config = {}
        if not self.credentials_arn:
            self.get_credentials_arn()
        if not aws_kms_key_arn:
            aws_kms_key_arn = ''
        if not aws_environment_variables:
            aws_environment_variables = {}

        # Check if there are any remote aws lambda env vars so they don't get trashed.
        # https://github.com/Miserlou/Zappa/issues/987,  Related: https://github.com/Miserlou/Zappa/issues/765
        lambda_aws_config = self.lambda_client.get_function_configuration(FunctionName=function_name)
        if "Environment" in lambda_aws_config:
            lambda_aws_environment_variables = lambda_aws_config["Environment"].get("Variables", {})
            # Append keys that are remote but not in settings file
            for key, value in lambda_aws_environment_variables.items():
                if key not in aws_environment_variables:
                    aws_environment_variables[key] = value

        response = self.lambda_client.update_function_configuration(
            FunctionName=function_name,
            Runtime=runtime,
            Role=self.credentials_arn,
            Handler=handler,
            Description=description,
            Timeout=timeout,
            MemorySize=memory_size,
            VpcConfig=vpc_config,
            Environment={'Variables': aws_environment_variables},
            KMSKeyArn=aws_kms_key_arn,
            TracingConfig={
                'Mode': 'Active' if self.xray_tracing else 'PassThrough'
            }
        )

        resource_arn = response['FunctionArn']

        if self.tags:
            self.lambda_client.tag_resource(Resource=resource_arn, Tags=self.tags)

        return resource_arn
1323670
def deploy(self, source_zip=None):
        

        if not source_zip:
            # Make sure we're in a venv.
            self.check_venv()

            # Execute the prebuild script
            if self.prebuild_script:
                self.execute_prebuild_script()

            # Make sure this isn't already deployed.
            deployed_versions = self.zappa.get_lambda_function_versions(self.lambda_name)
            if len(deployed_versions) > 0:
                raise ClickException("This application is " + click.style("already deployed", fg="red") +
                                     " - did you mean to call " + click.style("update", bold=True) + "?")

            # Make sure the necessary IAM execution roles are available
            if self.manage_roles:
                try:
                    self.zappa.create_iam_roles()
                except botocore.client.ClientError:
                    raise ClickException(
                        click.style("Failed", fg="red") + " to " + click.style("manage IAM roles", bold=True) + "!\n" +
                        "You may " + click.style("lack the necessary AWS permissions", bold=True) +
                        " to automatically manage a Zappa execution role.\n" +
                        "To fix this, see here: " +
                        click.style("https://github.com/Miserlou/Zappa#custom-aws-iam-roles-and-policies-for-deployment", bold=True)
                        + '\n')

            # Create the Lambda Zip
            self.create_package()
            self.callback('zip')

            # Upload it to S3
            success = self.zappa.upload_to_s3(
                    self.zip_path, self.s3_bucket_name, disable_progress=self.disable_progress)
            if not success: # pragma: no cover
                raise ClickException("Unable to upload to S3. Quitting.")

            # If using a slim handler, upload it to S3 and tell lambda to use this slim handler zip
            if self.stage_config.get('slim_handler', False):
                # https://github.com/Miserlou/Zappa/issues/510
                success = self.zappa.upload_to_s3(self.handler_path, self.s3_bucket_name, disable_progress=self.disable_progress)
                if not success:  # pragma: no cover
                    raise ClickException("Unable to upload handler to S3. Quitting.")

                # Copy the project zip to the current project zip
                current_project_name = '{0!s}_{1!s}_current_project.tar.gz'.format(self.api_stage, self.project_name)
                success = self.zappa.copy_on_s3(src_file_name=self.zip_path, dst_file_name=current_project_name,
                                                bucket_name=self.s3_bucket_name)
                if not success:  # pragma: no cover
                    raise ClickException("Unable to copy the zip to be the current project. Quitting.")

                handler_file = self.handler_path
            else:
                handler_file = self.zip_path

        # Fixes https://github.com/Miserlou/Zappa/issues/613
        try:
            self.lambda_arn = self.zappa.get_lambda_function(
                function_name=self.lambda_name)
        except botocore.client.ClientError:
            # Register the Lambda function with that zip as the source
            # You'll also need to define the path to your lambda_handler code.
            kwargs = dict(
                handler=self.lambda_handler,
                description=self.lambda_description,
                vpc_config=self.vpc_config,
                dead_letter_config=self.dead_letter_config,
                timeout=self.timeout_seconds,
                memory_size=self.memory_size,
                runtime=self.runtime,
                aws_environment_variables=self.aws_environment_variables,
                aws_kms_key_arn=self.aws_kms_key_arn,
                use_alb=self.use_alb
            )
            if source_zip and source_zip.startswith('s3://'):
                bucket, key_name = parse_s3_url(source_zip)
                kwargs['function_name'] = self.lambda_name
                kwargs['bucket'] = bucket
                kwargs['s3_key'] = key_name
            elif source_zip and not source_zip.startswith('s3://'):
                with open(source_zip, mode='rb') as fh:
                    byte_stream = fh.read()
                kwargs['function_name'] = self.lambda_name
                kwargs['local_zip'] = byte_stream
            else:
                kwargs['function_name'] = self.lambda_name
                kwargs['bucket'] = self.s3_bucket_name
                kwargs['s3_key'] = handler_file

            self.lambda_arn = self.zappa.create_lambda_function(**kwargs)

        # Schedule events for this deployment
        self.schedule()

        endpoint_url = ''
        deployment_string = click.style("Deployment complete", fg="green", bold=True) + "!"

        if self.use_alb:
            kwargs = dict(
                lambda_arn=self.lambda_arn,
                lambda_name=self.lambda_name,
                alb_vpc_config=self.alb_vpc_config,
                timeout=self.timeout_seconds
            )
            self.zappa.deploy_lambda_alb(**kwargs)

        if self.use_apigateway:

            # Create and configure the API Gateway
            template = self.zappa.create_stack_template(
                                                        lambda_arn=self.lambda_arn,
                                                        lambda_name=self.lambda_name,
                                                        api_key_required=self.api_key_required,
                                                        iam_authorization=self.iam_authorization,
                                                        authorizer=self.authorizer,
                                                        cors_options=self.cors,
                                                        description=self.apigateway_description,
                                                        endpoint_configuration=self.endpoint_configuration
                                                    )

            self.zappa.update_stack(
                                    self.lambda_name,
                                    self.s3_bucket_name,
                                    wait=True,
                                    disable_progress=self.disable_progress
                                )

            api_id = self.zappa.get_api_id(self.lambda_name)

            # Add binary support
            if self.binary_support:
                self.zappa.add_binary_support(api_id=api_id, cors=self.cors)

            # Add payload compression
            if self.stage_config.get('payload_compression', True):
                self.zappa.add_api_compression(
                    api_id=api_id,
                    min_compression_size=self.stage_config.get('payload_minimum_compression_size', 0))

            # Deploy the API!
            endpoint_url = self.deploy_api_gateway(api_id)
            deployment_string = deployment_string + ": {}".format(endpoint_url)

            # Create/link API key
            if self.api_key_required:
                if self.api_key is None:
                    self.zappa.create_api_key(api_id=api_id, stage_name=self.api_stage)
                else:
                    self.zappa.add_api_stage_to_api_key(api_key=self.api_key, api_id=api_id, stage_name=self.api_stage)

            if self.stage_config.get('touch', True):
                self.touch_endpoint(endpoint_url)

        # Finally, delete the local copy our zip package
        if not source_zip:
            if self.stage_config.get('delete_local_zip', True):
                self.remove_local_zip()

        # Remove the project zip from S3.
        if not source_zip:
            self.remove_uploaded_zip()

        self.callback('post')

        click.echo(deployment_string)
690009
function buildLambdaSecurityGroup({ name = 'LambdaExecutionSecurityGroup' } = {}) {
  return {
    [name]: {
      Type: 'AWS::EC2::SecurityGroup',
      Properties: {
        GroupDescription: 'Lambda Execution Group',
        VpcId: {
          Ref: 'VPC',
        },
        Tags: [
          {
            Key: 'Name',
            Value: {
              'Fn::Join': [
                '-',
                [
                  {
                    Ref: 'AWS::StackName',
                  },
                  'lambda-exec',
                ],
              ],
            },
          },
        ],
      },
    },
  };
}
752164
def deploy_templates(bucket_name)
      begin
        Dir.mkdir(config_dir, 0755) if dir_exists? == false

        TEMPLATE_FILES.each do |template_file|
          FileUtils.cp(File.join(File.dirname(__FILE__), TEMPLATES_DIR, template_file),
                       File.join(config_dir, template_file))
        end

        save_config('jobs', { 'BUCKET_NAME' => bucket_name })
        save_aws_config

      rescue StandardError => e
        raise FileAccessError, e.message
      end
    end
93186
def handle(self, argv=None):
        

        desc = ('Zappa - Deploy Python applications to AWS Lambda'
                ' and API Gateway.\n')
        parser = argparse.ArgumentParser(description=desc)
        parser.add_argument(
            '-v', '--version', action='version',
            version=pkg_resources.get_distribution("zappa").version,
            help='Print the zappa version'
        )
        parser.add_argument(
            '--color', default='auto', choices=['auto','never','always']
        )

        env_parser = argparse.ArgumentParser(add_help=False)
        me_group = env_parser.add_mutually_exclusive_group()
        all_help = ('Execute this command for all of our defined '
                    'Zappa stages.')
        me_group.add_argument('--all', action='store_true', help=all_help)
        me_group.add_argument('stage_env', nargs='?')

        group = env_parser.add_argument_group()
        group.add_argument(
            '-a', '--app_function', help='The WSGI application function.'
        )
        group.add_argument(
            '-s', '--settings_file', help='The path to a Zappa settings file.'
        )
        group.add_argument(
            '-q', '--quiet', action='store_true', help='Silence all output.'
        )
        # https://github.com/Miserlou/Zappa/issues/407
        # Moved when 'template' command added.
        # Fuck Terraform.
        group.add_argument(
            '-j', '--json', action='store_true', help='Make the output of this command be machine readable.'
        )
        # https://github.com/Miserlou/Zappa/issues/891
        group.add_argument(
            '--disable_progress', action='store_true', help='Disable progress bars.'
        )

        ##
        # Certify
        ##
        subparsers = parser.add_subparsers(title='subcommands', dest='command')
        cert_parser = subparsers.add_parser(
            'certify', parents=[env_parser],
            help='Create and install SSL certificate'
        )
        cert_parser.add_argument(
            '--manual', action='store_true',
            help=("Gets new Let's Encrypt certificates, but prints them to console."
                "Does not update API Gateway domains.")
        )
        cert_parser.add_argument(
            '-y', '--yes', action='store_true', help='Auto confirm yes.'
        )

        ##
        # Deploy
        ##
        deploy_parser = subparsers.add_parser(
            'deploy', parents=[env_parser], help='Deploy application.'
        )
        deploy_parser.add_argument(
            '-z', '--zip', help='Deploy Lambda with specific local or S3 hosted zip package'
        )

        ##
        # Init
        ##
        init_parser = subparsers.add_parser('init', help='Initialize Zappa app.')

        ##
        # Package
        ##
        package_parser = subparsers.add_parser(
            'package', parents=[env_parser], help='Build the application zip package locally.'
        )
        package_parser.add_argument(
            '-o', '--output', help='Name of file to output the package to.'
        )

        ##
        # Template
        ##
        template_parser = subparsers.add_parser(
            'template', parents=[env_parser], help='Create a CloudFormation template for this API Gateway.'
        )
        template_parser.add_argument(
            '-l', '--lambda-arn', required=True, help='ARN of the Lambda function to template to.'
        )
        template_parser.add_argument(
            '-r', '--role-arn', required=True, help='ARN of the Role to template with.'
        )
        template_parser.add_argument(
            '-o', '--output', help='Name of file to output the template to.'
        )

        ##
        # Invocation
        ##
        invoke_parser = subparsers.add_parser(
            'invoke', parents=[env_parser],
            help='Invoke remote function.'
        )
        invoke_parser.add_argument(
            '--raw', action='store_true',
            help=('When invoking remotely, invoke this python as a string,'
                  ' not as a modular path.')
        )
        invoke_parser.add_argument(
            '--no-color', action='store_true',
            help=("Don't color the output")
        )
        invoke_parser.add_argument('command_rest')

        ##
        # Manage
        ##
        manage_parser = subparsers.add_parser(
            'manage',
            help='Invoke remote Django manage.py commands.'
        )
        rest_help = ("Command in the form of <env> <command>. <env> is not "
                     "required if --all is specified")
        manage_parser.add_argument('--all', action='store_true', help=all_help)
        manage_parser.add_argument('command_rest', nargs='+', help=rest_help)
        manage_parser.add_argument(
            '--no-color', action='store_true',
            help=("Don't color the output")
        )
        # This is explicitly added here because this is the only subcommand that doesn't inherit from env_parser
        # https://github.com/Miserlou/Zappa/issues/1002
        manage_parser.add_argument(
            '-s', '--settings_file', help='The path to a Zappa settings file.'
        )

        ##
        # Rollback
        ##
        def positive_int(s):
            """ Ensure an arg is positive """
            i = int(s)
            if i < 0:
                msg = "This argument must be positive (got {})".format(s)
                raise argparse.ArgumentTypeError(msg)
            return i

        rollback_parser = subparsers.add_parser(
            'rollback', parents=[env_parser],
            help='Rollback deployed code to a previous version.'
        )
        rollback_parser.add_argument(
            '-n', '--num-rollback', type=positive_int, default=1,
            help='The number of versions to rollback.'
        )

        ##
        # Scheduling
        ##
        subparsers.add_parser(
            'schedule', parents=[env_parser],
            help='Schedule functions to occur at regular intervals.'
        )

        ##
        # Status
        ##
        status_parser = subparsers.add_parser(
            'status', parents=[env_parser],
            help='Show deployment status and event schedules.'
        )

        ##
        # Log Tailing
        ##
        tail_parser = subparsers.add_parser(
            'tail', parents=[env_parser], help='Tail deployment logs.'
        )
        tail_parser.add_argument(
            '--no-color', action='store_true',
            help="Don't color log tail output."
        )
        tail_parser.add_argument(
            '--http', action='store_true',
            help='Only show HTTP requests in tail output.'
        )
        tail_parser.add_argument(
            '--non-http', action='store_true',
            help='Only show non-HTTP requests in tail output.'
        )
        tail_parser.add_argument(
            '--since', type=str, default="100000s",
            help="Only show lines since a certain timeframe."
        )
        tail_parser.add_argument(
            '--filter', type=str, default="",
            help="Apply a filter pattern to the logs."
        )
        tail_parser.add_argument(
            '--force-color', action='store_true',
            help='Force coloring log tail output even if coloring support is not auto-detected. (example: piping)'
        )
        tail_parser.add_argument(
            '--disable-keep-open', action='store_true',
            help="Exit after printing the last available log, rather than keeping the log open."
        )

        ##
        # Undeploy
        ##
        undeploy_parser = subparsers.add_parser(
            'undeploy', parents=[env_parser], help='Undeploy application.'
        )
        undeploy_parser.add_argument(
            '--remove-logs', action='store_true',
            help=('Removes log groups of api gateway and lambda task'
                  ' during the undeployment.'),
        )
        undeploy_parser.add_argument(
            '-y', '--yes', action='store_true', help='Auto confirm yes.'
        )

        ##
        # Unschedule
        ##
        subparsers.add_parser('unschedule', parents=[env_parser],
                              help='Unschedule functions.')

        ##
        # Updating
        ##
        update_parser = subparsers.add_parser(
            'update', parents=[env_parser], help='Update deployed application.'
        )
        update_parser.add_argument(
            '-z', '--zip', help='Update Lambda with specific local or S3 hosted zip package'
        )
        update_parser.add_argument(
            '-n', '--no-upload', help="Update configuration where appropriate, but don't upload new code"
        )

        ##
        # Debug
        ##
        subparsers.add_parser(
            'shell', parents=[env_parser], help='A debug shell with a loaded Zappa object.'
        )

        argcomplete.autocomplete(parser)
        args = parser.parse_args(argv)
        self.vargs = vars(args)

        if args.color == 'never':
            disable_click_colors()
        elif args.color == 'always':
            #TODO: Support aggressive coloring like "--force-color" on all commands
            pass
        elif args.color == 'auto':
            pass

        # Parse the input
        # NOTE(rmoe): Special case for manage command
        # The manage command can't have both stage_env and command_rest
        # arguments. Since they are both positional arguments argparse can't
        # differentiate the two. This causes problems when used with --all.
        # (e.g. "manage --all showmigrations admin" argparse thinks --all has
        # been specified AND that stage_env='showmigrations')
        # By having command_rest collect everything but --all we can split it
        # apart here instead of relying on argparse.
        if not args.command:
            parser.print_help()
            return

        if args.command == 'manage' and not self.vargs.get('all'):
            self.stage_env = self.vargs['command_rest'].pop(0)
        else:
            self.stage_env = self.vargs.get('stage_env')

        if args.command == 'package':
            self.load_credentials = False

        self.command = args.command

        self.disable_progress = self.vargs.get('disable_progress')
        if self.vargs.get('quiet'):
            self.silence()

        # We don't have any settings yet, so make those first!
        # (Settings-based interactions will fail
        # before a project has been initialized.)
        if self.command == 'init':
            self.init()
            return

        # Make sure there isn't a new version available
        if not self.vargs.get('json'):
            self.check_for_update()

        # Load and Validate Settings File
        self.load_settings_file(self.vargs.get('settings_file'))

        # Should we execute this for all stages, or just one?
        all_stages = self.vargs.get('all')
        stages = []

        if all_stages: # All stages!
            stages = self.zappa_settings.keys()
        else: # Just one env.
            if not self.stage_env:
                # If there's only one stage defined in the settings,
                # use that as the default.
                if len(self.zappa_settings.keys()) == 1:
                    stages.append(list(self.zappa_settings.keys())[0])
                else:
                    parser.error("Please supply a stage to interact with.")
            else:
                stages.append(self.stage_env)

        for stage in stages:
            try:
                self.dispatch_command(self.command, stage)
            except ClickException as e:
                # Discussion on exit codes: https://github.com/Miserlou/Zappa/issues/407
                e.show()
                sys.exit(e.exit_code)
690995
def get_lambdas(awsclient, config, add_arn=False):
    
    if 'lambda' in config:
        client_lambda = awsclient.get_client('lambda')
        lambda_entries = config['lambda'].get('entries', [])
        lmbdas = []
        for lambda_entry in lambda_entries:
            lmbda = {
                'name': lambda_entry.get('name', None),
                'alias': lambda_entry.get('alias', None),
                'swagger_ref': lambda_entry.get('swaggerRef', None)
            }
            if add_arn:
                _sleep()
                response_lambda = client_lambda.get_function(
                    FunctionName=lmbda['name'])
                lmbda['arn'] = response_lambda['Configuration']['FunctionArn']
            lmbdas.append(lmbda)
        return lmbdas
    else:
        return []
159383
function loadLambda(lambdaPath, identifier) {
  return plugin.myrmex.fire('beforeLambdaLoad', lambdaPath, identifier)
  .spread((lambdaPath, identifier) => {
    // Because we use require() to get the config, it could either be a JSON file
    // or the content exported by a node module
    // But because require() caches the content it loads, we clone the result to avoid bugs
    // if the function is called twice.
    const lambdaConfig = _.cloneDeep(require(path.join(lambdaPath, 'config')));

    // If the identifier is not specified, it will be the name of the directory that contains the config
    lambdaConfig.identifier = lambdaConfig.identifier || identifier;

    // Lasy loading because the plugin has to be registered in a Myrmex instance before requiring ./lambda
    const Lambda = require('./lambda');
    const lambda = new Lambda(lambdaConfig, lambdaPath);

    // This event allows to inject code to alter the Lambda configuration
    return plugin.myrmex.fire('afterLambdaLoad', lambda);
  })
  .spread((lambda) => {
    return Promise.resolve(lambda);
  });
}