The `zappa deploy` functionality for ALB infrastructure.
165806
def deploy_lambda_alb(  self,
                            lambda_arn,
                            lambda_name,
                            alb_vpc_config,
                            timeout
                         ):
        
        if not alb_vpc_config:
            raise EnvironmentError('When creating an ALB, alb_vpc_config must be filled out in zappa_settings.')
        if 'SubnetIds' not in alb_vpc_config:
            raise EnvironmentError('When creating an ALB, you must supply two subnets in different availability zones.')
        if 'SecurityGroupIds' not in alb_vpc_config:
            alb_vpc_config["SecurityGroupIds"] = []
        if not alb_vpc_config.get('CertificateArn'):
            raise EnvironmentError('When creating an ALB, you must supply a CertificateArn for the HTTPS listener.')
        print("Deploying ALB infrastructure...")

        # Create load balancer
        # https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/elbv2.html#ElasticLoadBalancingv2.Client.create_load_balancer
        kwargs = dict(
            Name=lambda_name,
            Subnets=alb_vpc_config["SubnetIds"],
            SecurityGroups=alb_vpc_config["SecurityGroupIds"],
            # TODO: Scheme can also be "internal" we need to add a new option for this.
            Scheme="internet-facing",
            # TODO: Tags might be a useful means of stock-keeping zappa-generated assets.
            #Tags=[],
            Type="application",
            # TODO: can be ipv4 or dualstack (for ipv4 and ipv6) ipv4 is required for internal Scheme.
            IpAddressType="ipv4"
        )
        response = self.elbv2_client.create_load_balancer(**kwargs)
        if not(response["LoadBalancers"]) or len(response["LoadBalancers"]) != 1:
            raise EnvironmentError("Failure to create application load balancer. Response was in unexpected format. Response was: {}".format(repr(response)))
        if response["LoadBalancers"][0]['State']['Code'] == 'failed':
            raise EnvironmentError("Failure to create application load balancer. Response reported a failed state: {}".format(response["LoadBalancers"][0]['State']['Reason']))
        load_balancer_arn = response["LoadBalancers"][0]["LoadBalancerArn"]
        load_balancer_dns = response["LoadBalancers"][0]["DNSName"]
        load_balancer_vpc = response["LoadBalancers"][0]["VpcId"]
        waiter = self.elbv2_client.get_waiter('load_balancer_available')

        # Match the lambda timeout on the load balancer.
        self.elbv2_client.modify_load_balancer_attributes(
            LoadBalancerArn=load_balancer_arn,
            Attributes=[{
                'Key': 'idle_timeout.timeout_seconds',
                'Value': str(timeout)
            }]
        )

        # Create/associate target group.
        # https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/elbv2.html#ElasticLoadBalancingv2.Client.create_target_group
        kwargs = dict(
            Name=lambda_name,
            TargetType="lambda",
            # TODO: Add options for health checks
        )

        response = self.elbv2_client.create_target_group(**kwargs)
        if not(response["TargetGroups"]) or len(response["TargetGroups"]) != 1:
            raise EnvironmentError("Failure to create application load balancer target group. Response was in unexpected format. Response was: {}".format(repr(response)))
        target_group_arn = response["TargetGroups"][0]["TargetGroupArn"]

        # Enable multi-value headers by default.
        response = self.elbv2_client.modify_target_group_attributes(
            TargetGroupArn=target_group_arn,
            Attributes=[
                {
                    'Key': 'lambda.multi_value_headers.enabled',
                    'Value': 'true'
                },
            ]
        )

        # Allow execute permissions from target group to lambda.
        # https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/lambda.html#Lambda.Client.add_permission
        kwargs = dict(
            Action="lambda:InvokeFunction",
            FunctionName="{}:{}".format(lambda_arn, ALB_LAMBDA_ALIAS),
            Principal="elasticloadbalancing.amazonaws.com",
            SourceArn=target_group_arn,
            StatementId=lambda_name
        )
        response = self.lambda_client.add_permission(**kwargs)

        # Register target group to lambda association.
        # https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/elbv2.html#ElasticLoadBalancingv2.Client.register_targets
        kwargs = dict(
            TargetGroupArn=target_group_arn,
            Targets=[{"Id": "{}:{}".format(lambda_arn, ALB_LAMBDA_ALIAS)}]
        )
        response = self.elbv2_client.register_targets(**kwargs)

        # Bind listener to load balancer with default rule to target group.
        # https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/elbv2.html#ElasticLoadBalancingv2.Client.create_listener
        kwargs = dict(
            # TODO: Listeners support custom ssl certificates (Certificates). For now we leave this default.
            Certificates=[{"CertificateArn": alb_vpc_config['CertificateArn']}],
            DefaultActions=[{
                "Type": "forward",
                "TargetGroupArn": target_group_arn,
            }],
            LoadBalancerArn=load_balancer_arn,
            Protocol="HTTPS",
            # TODO: Add option for custom ports
            Port=443,
            # TODO: Listeners support custom ssl security policy (SslPolicy). For now we leave this default.
        )
        response = self.elbv2_client.create_listener(**kwargs)
        print("ALB created with DNS: {}".format(load_balancer_dns))
        print("Note it may take several minutes for load balancer to become available.")
1247527
def prepare_infrastructure():
    """"""
    runner = ForemastRunner()

    runner.write_configs()
    runner.create_app()

    archaius = runner.configs[runner.env]['app']['archaius_enabled']
    eureka = runner.configs[runner.env]['app']['eureka_enabled']
    deploy_type = runner.configs['pipeline']['type']

    if deploy_type not in ['s3', 'datapipeline']:
        runner.create_iam()
        # TODO: Refactor Archaius to be fully featured
        if archaius:
            runner.create_archaius()
        runner.create_secgroups()

    if eureka:
        LOG.info("Eureka Enabled, skipping ELB and DNS setup")
    elif deploy_type == "lambda":
        LOG.info("Lambda Enabled, skipping ELB and DNS setup")
        runner.create_awslambda()
    elif deploy_type == "s3":
        runner.create_s3app()
    elif deploy_type == 'datapipeline':
        runner.create_datapipeline()
    else:
        LOG.info("No Eureka, running ELB and DNS setup")
        runner.create_elb()
        runner.create_dns()

    runner.slack_notify()
    runner.cleanup()
363866
def publish(version, stage, config_file):
    """"""
    config = _load_config(config_file)
    cfn = boto3.client('cloudformation')

    if version is None:
        version = config['devstage']
    elif version not in config['stage_environments'].keys() and \
            not version.isdigit():
        raise ValueError('Invalid version. Use a stage name or a numeric '
                         'version number.')
    if version == stage:
        raise ValueError('Cannot deploy a stage into itself.')

    # obtain previous deployment
    try:
        previous_deployment = cfn.describe_stacks(
            StackName=config['name'])['Stacks'][0]
    except botocore.exceptions.ClientError:
        raise RuntimeError('This project has not been deployed yet.')

    # preserve package from previous deployment
    bucket = _get_from_stack(previous_deployment, 'Parameter',
                             'LambdaS3Bucket')
    lambda_package = _get_from_stack(previous_deployment, 'Parameter',
                                     'LambdaS3Key')

    # prepare cloudformation template
    template_body = get_cfn_template(config)
    parameters = [
        {'ParameterKey': 'LambdaS3Bucket', 'ParameterValue': bucket},
        {'ParameterKey': 'LambdaS3Key', 'ParameterValue': lambda_package},
    ]
    stages = list(config['stage_environments'].keys())
    stages.sort()
    for s in stages:
        param = s.title() + 'Version'
        if s != stage:
            v = _get_from_stack(previous_deployment, 'Parameter', param) \
                if previous_deployment else '$LATEST'
            v = v or '$LATEST'
        else:
            if version.isdigit():
                # explicit version number
                v = version
            else:
                # publish version from a stage
                v = _get_from_stack(previous_deployment, 'Parameter',
                                    version.title() + 'Version')
                if v == '$LATEST':
                    # publish a new version from $LATEST
                    lmb = boto3.client('lambda')
                    v = lmb.publish_version(FunctionName=_get_from_stack(
                        previous_deployment, 'Output', 'FunctionArn'))[
                            'Version']
        parameters.append({'ParameterKey': param, 'ParameterValue': v})

    # run the cloudformation template
    print('Publishing {}:{} to {}...'.format(config['name'], version, stage))
    cfn.update_stack(StackName=config['name'], TemplateBody=template_body,
                     Parameters=parameters,
                     Capabilities=['CAPABILITY_IAM'])
    waiter = cfn.get_waiter('stack_update_complete')

    # wait for cloudformation to do its thing
    try:
        waiter.wait(StackName=config['name'])
    except botocore.exceptions.ClientError:
        raise

    # we are done, show status info and exit
    _print_status(config)
596898
def deploy(self):
        '''
            
        '''
        if not os.path.exists(self.path):
            makedirs(self.path)

        link(self.vault_path, self.real_path)
698163
def deploy(self, fobj, md5=None, sha1=None, parameters={}):
        
        return self._accessor.deploy(self, fobj, md5, sha1, parameters)
1316995
def update(self, source_zip=None, no_upload=False):
        

        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()

            # Temporary version check
            try:
                updated_time = 1472581018
                function_response = self.zappa.lambda_client.get_function(FunctionName=self.lambda_name)
                conf = function_response['Configuration']
                last_updated = parser.parse(conf['LastModified'])
                last_updated_unix = time.mktime(last_updated.timetuple())
            except botocore.exceptions.BotoCoreError as e:
                click.echo(click.style(type(e).__name__, fg="red") + ": " + e.args[0])
                sys.exit(-1)
            except Exception as e:
                click.echo(click.style("Warning!", fg="red") + " Couldn't get function " + self.lambda_name +
                           " in " + self.zappa.aws_region + " - have you deployed yet?")
                sys.exit(-1)

            if last_updated_unix <= updated_time:
                click.echo(click.style("Warning!", fg="red") +
                           " You may have upgraded Zappa since deploying this application. You will need to " +
                           click.style("redeploy", bold=True) + " for this deployment to work properly!")

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

            # Create the Lambda Zip,
            if not no_upload:
                self.create_package()
                self.callback('zip')

            # Upload it to S3
            if not no_upload:
                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 project 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

        # 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(
            bucket=self.s3_bucket_name,
            function_name=self.lambda_name,
            num_revisions=self.num_retained_versions
        )
        if source_zip and source_zip.startswith('s3://'):
            bucket, key_name = parse_s3_url(source_zip)
            kwargs.update(dict(
                bucket=bucket,
                s3_key=key_name
            ))
            self.lambda_arn = self.zappa.update_lambda_function(**kwargs)
        elif source_zip and not source_zip.startswith('s3://'):
            with open(source_zip, mode='rb') as fh:
                byte_stream = fh.read()
            kwargs['local_zip'] = byte_stream
            self.lambda_arn = self.zappa.update_lambda_function(**kwargs)
        else:
            if not no_upload:
                kwargs['s3_key'] = handler_file
                self.lambda_arn = self.zappa.update_lambda_function(**kwargs)

        # Remove the uploaded zip from S3, because it is now registered..
        if not source_zip and not no_upload:
            self.remove_uploaded_zip()

        # Update the configuration, in case there are changes.
        self.lambda_arn = self.zappa.update_lambda_configuration(
                                                        lambda_arn=self.lambda_arn,
                                                        function_name=self.lambda_name,
                                                        handler=self.lambda_handler,
                                                        description=self.lambda_description,
                                                        vpc_config=self.vpc_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
                                                    )

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

        if self.use_apigateway:

            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,
                                    update_only=True,
                                    disable_progress=self.disable_progress)

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

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

            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))
            else:
                self.zappa.remove_api_compression(api_id=api_id)

            # It looks a bit like we might actually be using this just to get the URL,
            # but we're also updating a few of the APIGW settings.
            endpoint_url = self.deploy_api_gateway(api_id)

            if self.stage_config.get('domain', None):
                endpoint_url = self.stage_config.get('domain')

        else:
            endpoint_url = None

        self.schedule()

        # Update any cognito pool with the lambda arn
        # do this after schedule as schedule clears the lambda policy and we need to add one
        self.update_cognito_triggers()

        self.callback('post')

        if endpoint_url and 'https://' not in endpoint_url:
            endpoint_url = 'https://' + endpoint_url

        if self.base_path:
            endpoint_url += '/' + self.base_path

        deployed_string = "Your updated Zappa deployment is " + click.style("live", fg='green', bold=True) + "!"
        if self.use_apigateway:
            deployed_string = deployed_string + ": " + click.style("{}".format(endpoint_url), bold=True)

            api_url = None
            if endpoint_url and 'amazonaws.com' not in endpoint_url:
                api_url = self.zappa.get_api_url(
                    self.lambda_name,
                    self.api_stage)

                if endpoint_url != api_url:
                    deployed_string = deployed_string + " (" + api_url + ")"

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

        click.echo(deployed_string)
158761
def deploy(verbose, app):
    """"""
    # Load psiTurk configuration.
    config = PsiturkConfig()
    config.load_config()

    # Set the mode.
    config.set("Experiment Configuration", "mode", "deploy")
    config.set("Server Parameters", "logfile", "-")

    # Ensure that psiTurk is not in sandbox mode.
    config.set("Shell Parameters", "launch_in_sandbox_mode", "false")

    # Do shared setup.
    deploy_sandbox_shared_setup(verbose=verbose, app=app)
1251969
def deploy!(archive, env)
            archive.upload(Beanstalk.api)
            
            if env.status.empty?
                puts "Creating stack '#{@stack}' for #{archive.app_name}-#{archive.version}..."
                env.create!(archive, @stack, @cnames, @config)
                env.wait_until_status_is_not "Launching"
            else
                puts "Deploying #{archive.version} to #{env.name}..."
                env.deploy!(archive, @config)
                env.wait_until_status_is_not "Updating"
            end
            
            env.wait_until_healthy
            puts "Done. Visit http://#{env.url} in your browser."
            DeploymentInfo.new env, archive
        end
1110603
def apply_zappa_settings(zappa_obj, zappa_settings, environment):
    ''''''

    settings_all = json.load(zappa_settings)
    settings = settings_all[environment]

    # load defaults for missing options
    for key,value in DEFAULT_SETTINGS.items():
        settings[key] = settings.get(key, value)

    if '~' in settings['settings_file']:
        settings['settings_file'] = settings['settings_file'].replace('~', os.path.expanduser('~'))
    if not os.path.isfile(settings['settings_file']):
        raise SettingsError("Please make sure your settings_file "
                            "is properly defined in {0}.".format(zappa_settings))

    for setting in CUSTOM_SETTINGS:
        if setting in settings:
            setattr(zappa_obj, setting, settings[setting])

    return settings
918503
def _deploy(self):
        """"""
        timeout = int(os.environ.get('AMULET_SETUP_TIMEOUT', 900))
        try:
            self.d.setup(timeout=timeout)
            self.d.sentry.wait(timeout=timeout)
        except amulet.helpers.TimeoutError:
            amulet.raise_status(
                amulet.FAIL,
                msg="Deployment timed out ({}s)".format(timeout)
            )
        except Exception:
            raise
5398
def _heat_deploy(self, stack, stack_name, template_path, parameters,
                     environments, timeout):
        """"""

        self.log.debug("Processing environment files")
        env_files, env = (
            template_utils.process_multiple_environments_and_files(
                environments))

        self.log.debug("Getting template contents")
        template_files, template = template_utils.get_template_contents(
            template_path)

        files = dict(list(template_files.items()) + list(env_files.items()))

        clients = self.app.client_manager
        orchestration_client = clients.rdomanager_oscplugin.orchestration()

        self.log.debug("Deploying stack: %s", stack_name)
        self.log.debug("Deploying template: %s", template)
        self.log.debug("Deploying parameters: %s", parameters)
        self.log.debug("Deploying environment: %s", env)
        self.log.debug("Deploying files: %s", files)

        stack_args = {
            'stack_name': stack_name,
            'template': template,
            'parameters': parameters,
            'environment': env,
            'files': files
        }

        if timeout:
            stack_args['timeout_mins'] = timeout

        if stack is None:
            self.log.info("Performing Heat stack create")
            orchestration_client.stacks.create(**stack_args)
        else:
            self.log.info("Performing Heat stack update")
            # Make sure existing parameters for stack are reused
            stack_args['existing'] = 'true'
            orchestration_client.stacks.update(stack.id, **stack_args)

        create_result = utils.wait_for_stack_ready(
            orchestration_client, stack_name)
        if not create_result:
            if stack is None:
                raise Exception("Heat Stack create failed.")
            else:
                raise Exception("Heat Stack update failed.")
964055
async function deploy() {
  try {
    await browserifyDBCP();
    await uglify();
    const ipfsHash = await deployToIPFS(`${ deploymentFolder}/${ browserifyName}`);
    await pinToIPFS(ipfsHash);
    const ipnsHash = await deployToIpns(ipfsHash);
    deleteDeploymentFolder();

    console.log(`\nFinished deployment`);
    console.log(`IPFS: ${ ipfsHash }`);
    console.log(`IPNS: ${ ipnsHash }`);
  } catch (ex) {
    console.error(ex);
  }
}
267186
private RollingUpdateOp rollingUpdateUndeploy(final ZooKeeperClient client,
                                                final RollingUpdateOpFactory opFactory,
                                                final DeploymentGroup deploymentGroup,
                                                final String host) {
    return rollingUpdateUndeploy(client, opFactory, deploymentGroup, host, true);
  }
1044551
public function deployWebapps()
    {

        // iterate over the deploy directories and deploy all archives
        /** @var \AppserverIo\Psr\ApplicationServer\Configuration\ContainerConfigurationInterface $containerNode */
        foreach ($this->getService()->getSystemConfiguration()->getContainers() as $containerNode) {
            // check if deploy dir exists
            if (is_dir($deployDir = $this->getService()->getBaseDirectory($containerNode->getHost()->getDeployBase()))) {
                // init file iterator on deployment directory
                $fileIterator = new \FilesystemIterator($deployDir);
                // Iterate through all phar files and extract them to tmp dir
                foreach (new \RegexIterator($fileIterator, '/^.*\\' . $this->getExtensionSuffix() . '$/') as $archive) {
                    $this->undeployArchive($containerNode, $archive);
                    $this->deployArchive($containerNode, $archive);
                }
            }

            // prepare the filename for the file with the last successful deployment timestamp
            $successFile = sprintf('%s/%s', $deployDir, ExtractorInterface::FILE_DEPLOYMENT_SUCCESSFULL);

            // create a flag file with date of the last successful deployment
            touch($successFile);
        }
    }
1328067
def main():
    

    template = Template()

    # Description
    template.add_description(
        'AWS CloudFormation Sample Template ElastiCache_Redis:'
        'Sample template showing how to create an Amazon'
        'ElastiCache Redis Cluster. **WARNING** This template'
        'creates an Amazon EC2 Instance and an Amazon ElastiCache'
        'Cluster. You will be billed for the AWS resources used'
        'if you create a stack from this template.')

    # Mappings
    template.add_mapping('AWSInstanceType2Arch', {
        't1.micro':     {'Arch': 'PV64'},
        't2.micro':     {'Arch': 'HVM64'},
        't2.small':     {'Arch': 'HVM64'},
        't2.medium':    {'Arch': 'HVM64'},
        'm1.small':     {'Arch': 'PV64'},
        'm1.medium':    {'Arch': 'PV64'},
        'm1.large':     {'Arch': 'PV64'},
        'm1.xlarge':    {'Arch': 'PV64'},
        'm2.xlarge':    {'Arch': 'PV64'},
        'm2.2xlarge':   {'Arch': 'PV64'},
        'm2.4xlarge':   {'Arch': 'PV64'},
        'm3.medium':    {'Arch': 'HVM64'},
        'm3.large':     {'Arch': 'HVM64'},
        'm3.xlarge':    {'Arch': 'HVM64'},
        'm3.2xlarge':   {'Arch': 'HVM64'},
        'c1.medium':    {'Arch': 'PV64'},
        'c1.xlarge':    {'Arch': 'PV64'},
        'c3.large':     {'Arch': 'HVM64'},
        'c3.xlarge':    {'Arch': 'HVM64'},
        'c3.2xlarge':   {'Arch': 'HVM64'},
        'c3.4xlarge':   {'Arch': 'HVM64'},
        'c3.8xlarge':   {'Arch': 'HVM64'},
        'c4.large':     {'Arch': 'HVM64'},
        'c4.xlarge':    {'Arch': 'HVM64'},
        'c4.2xlarge':   {'Arch': 'HVM64'},
        'c4.4xlarge':   {'Arch': 'HVM64'},
        'c4.8xlarge':   {'Arch': 'HVM64'},
        'g2.2xlarge':   {'Arch': 'HVMG2'},
        'r3.large':     {'Arch': 'HVM64'},
        'r3.xlarge':    {'Arch': 'HVM64'},
        'r3.2xlarge':   {'Arch': 'HVM64'},
        'r3.4xlarge':   {'Arch': 'HVM64'},
        'r3.8xlarge':   {'Arch': 'HVM64'},
        'i2.xlarge':    {'Arch': 'HVM64'},
        'i2.2xlarge':   {'Arch': 'HVM64'},
        'i2.4xlarge':   {'Arch': 'HVM64'},
        'i2.8xlarge':   {'Arch': 'HVM64'},
        'd2.xlarge':    {'Arch': 'HVM64'},
        'd2.2xlarge':   {'Arch': 'HVM64'},
        'd2.4xlarge':   {'Arch': 'HVM64'},
        'd2.8xlarge':   {'Arch': 'HVM64'},
        'hi1.4xlarge':  {'Arch': 'HVM64'},
        'hs1.8xlarge':  {'Arch': 'HVM64'},
        'cr1.8xlarge':  {'Arch': 'HVM64'},
        'cc2.8xlarge':  {'Arch': 'HVM64'}
        })

    template.add_mapping('AWSRegionArch2AMI', {
        'us-east-1': {'PV64': 'ami-0f4cfd64',
                      'HVM64': 'ami-0d4cfd66',
                      'HVMG2': 'ami-5b05ba30'},
        'us-west-2': {'PV64': 'ami-d3c5d1e3',
                      'HVM64': 'ami-d5c5d1e5',
                      'HVMG2': 'ami-a9d6c099'},
        'us-west-1': {'PV64': 'ami-85ea13c1',
                      'HVM64': 'ami-87ea13c3',
                      'HVMG2': 'ami-37827a73'},
        'eu-west-1': {'PV64': 'ami-d6d18ea1',
                      'HVM64': 'ami-e4d18e93',
                      'HVMG2': 'ami-72a9f105'},
        'eu-central-1': {'PV64': 'ami-a4b0b7b9',
                         'HVM64': 'ami-a6b0b7bb',
                         'HVMG2': 'ami-a6c9cfbb'},
        'ap-northeast-1': {'PV64': 'ami-1a1b9f1a',
                           'HVM64': 'ami-1c1b9f1c',
                           'HVMG2': 'ami-f644c4f6'},
        'ap-southeast-1': {'PV64': 'ami-d24b4280',
                           'HVM64': 'ami-d44b4286',
                           'HVMG2': 'ami-12b5bc40'},
        'ap-southeast-2': {'PV64': 'ami-ef7b39d5',
                           'HVM64': 'ami-db7b39e1',
                           'HVMG2': 'ami-b3337e89'},
        'sa-east-1': {'PV64': 'ami-5b098146',
                      'HVM64': 'ami-55098148',
                      'HVMG2': 'NOT_SUPPORTED'},
        'cn-north-1': {'PV64': 'ami-bec45887',
                       'HVM64': 'ami-bcc45885',
                       'HVMG2': 'NOT_SUPPORTED'}
        })

    template.add_mapping('Region2Principal', {
        'us-east-1': {'EC2Principal': 'ec2.amazonaws.com',
                      'OpsWorksPrincipal': 'opsworks.amazonaws.com'},
        'us-west-2': {'EC2Principal': 'ec2.amazonaws.com',
                      'OpsWorksPrincipal': 'opsworks.amazonaws.com'},
        'us-west-1': {'EC2Principal': 'ec2.amazonaws.com',
                      'OpsWorksPrincipal': 'opsworks.amazonaws.com'},
        'eu-west-1': {'EC2Principal': 'ec2.amazonaws.com',
                      'OpsWorksPrincipal': 'opsworks.amazonaws.com'},
        'ap-southeast-1': {'EC2Principal': 'ec2.amazonaws.com',
                           'OpsWorksPrincipal': 'opsworks.amazonaws.com'},
        'ap-northeast-1': {'EC2Principal': 'ec2.amazonaws.com',
                           'OpsWorksPrincipal': 'opsworks.amazonaws.com'},
        'ap-southeast-2': {'EC2Principal': 'ec2.amazonaws.com',
                           'OpsWorksPrincipal': 'opsworks.amazonaws.com'},
        'sa-east-1': {'EC2Principal': 'ec2.amazonaws.com',
                      'OpsWorksPrincipal': 'opsworks.amazonaws.com'},
        'cn-north-1': {'EC2Principal': 'ec2.amazonaws.com.cn',
                       'OpsWorksPrincipal': 'opsworks.amazonaws.com.cn'},
        'eu-central-1': {'EC2Principal': 'ec2.amazonaws.com',
                         'OpsWorksPrincipal': 'opsworks.amazonaws.com'}
        })

    # Parameters
    cachenodetype = template.add_parameter(Parameter(
        'ClusterNodeType',
        Description='The compute and memory capacity of the nodes in the Redis'
                    ' Cluster',
        Type='String',
        Default='cache.m1.small',
        AllowedValues=['cache.m1.small',
                       'cache.m1.large',
                       'cache.m1.xlarge',
                       'cache.m2.xlarge',
                       'cache.m2.2xlarge',
                       'cache.m2.4xlarge',
                       'cache.c1.xlarge'],
        ConstraintDescription='must select a valid Cache Node type.',
        ))

    instancetype = template.add_parameter(Parameter(
        'InstanceType',
        Description='WebServer EC2 instance type',
        Type='String',
        Default='t2.micro',
        AllowedValues=['t1.micro',
                       't2.micro',
                       't2.small',
                       't2.medium',
                       'm1.small',
                       'm1.medium',
                       'm1.large',
                       'm1.xlarge',
                       'm2.xlarge',
                       'm2.2xlarge',
                       'm2.4xlarge',
                       'm3.medium',
                       'm3.large',
                       'm3.xlarge',
                       'm3.2xlarge',
                       'c1.medium',
                       'c1.xlarge',
                       'c3.large',
                       'c3.xlarge',
                       'c3.2xlarge',
                       'c3.4xlarge',
                       'c3.8xlarge',
                       'c4.large',
                       'c4.xlarge',
                       'c4.2xlarge',
                       'c4.4xlarge',
                       'c4.8xlarge',
                       'g2.2xlarge',
                       'r3.large',
                       'r3.xlarge',
                       'r3.2xlarge',
                       'r3.4xlarge',
                       'r3.8xlarge',
                       'i2.xlarge',
                       'i2.2xlarge',
                       'i2.4xlarge',
                       'i2.8xlarge',
                       'd2.xlarge',
                       'd2.2xlarge',
                       'd2.4xlarge',
                       'd2.8xlarge',
                       'hi1.4xlarge',
                       'hs1.8xlarge',
                       'cr1.8xlarge',
                       'cc2.8xlarge',
                       'cg1.4xlarge'],
        ConstraintDescription='must be a valid EC2 instance type.',
        ))

    keyname = template.add_parameter(Parameter(
        'KeyName',
        Description='Name of an existing EC2 KeyPair to enable SSH access'
                    ' to the instance',
        Type='AWS::EC2::KeyPair::KeyName',
        ConstraintDescription='must be the name of an existing EC2 KeyPair.',
        ))

    sshlocation = template.add_parameter(Parameter(
        'SSHLocation',
        Description='The IP address range that can be used to SSH to'
                    ' the EC2 instances',
        Type='String',
        MinLength='9',
        MaxLength='18',
        Default='0.0.0.0/0',
        AllowedPattern='(\\d{1,3})\\.(\\d{1,3})\\.'
                       '(\\d{1,3})\\.(\\d{1,3})/(\\d{1,2})',
        ConstraintDescription='must be a valid IP CIDR range of the'
                              ' form x.x.x.x/x.'
        ))

    # Resources
    webserverrole = template.add_resource(iam.Role(
        'WebServerRole',
        AssumeRolePolicyDocument=Policy(
            Statement=[
                Statement(
                    Effect=Allow,
                    Action=[AssumeRole],
                    Principal=Principal('Service',
                                        [FindInMap('Region2Principal',
                                                   Ref('AWS::Region'),
                                                   'EC2Principal')]),
                    )
                ]
            ),
        Path='/',
    ))

    template.add_resource(iam.PolicyType(
        'WebServerRolePolicy',
        PolicyName='WebServerRole',
        PolicyDocument=awacs.aws.Policy(
            Statement=[awacs.aws.Statement(
                Action=[awacs.aws.Action("elasticache",
                        "DescribeCacheClusters")],
                Resource=["*"],
                Effect=awacs.aws.Allow
            )]
        ),
        Roles=[Ref(webserverrole)],
    ))

    webserverinstanceprofile = template.add_resource(iam.InstanceProfile(
        'WebServerInstanceProfile',
        Path='/',
        Roles=[Ref(webserverrole)],
    ))

    webserversg = template.add_resource(ec2.SecurityGroup(
        'WebServerSecurityGroup',
        GroupDescription='Enable HTTP and SSH access',
        SecurityGroupIngress=[
            ec2.SecurityGroupRule(
                IpProtocol='tcp',
                FromPort='22',
                ToPort='22',
                CidrIp=Ref(sshlocation),
                ),
            ec2.SecurityGroupRule(
                IpProtocol='tcp',
                FromPort='80',
                ToPort='80',
                CidrIp='0.0.0.0/0',
                )
            ]
        ))

    webserverinstance = template.add_resource(ec2.Instance(
        'WebServerInstance',
        Metadata=cloudformation.Metadata(
            cloudformation.Init({
                'config': cloudformation.InitConfig(
                    packages={
                        'yum': {
                            'httpd':     [],
                            'php':       [],
                            'php-devel': [],
                            'gcc':       [],
                            'make':      []
                            }
                        },

                    files=cloudformation.InitFiles({
                        '/var/www/html/index.php': cloudformation.InitFile(
                            content=Join('', [
                                '<?php\n',
                                'echo \"<h1>AWS CloudFormation sample'
                                ' application for Amazon ElastiCache'
                                ' Redis Cluster</h1>\";\n',
                                '\n',
                                '$cluster_config = json_decode('
                                'file_get_contents(\'/tmp/cacheclusterconfig\''
                                '), true);\n',
                                '$endpoint = $cluster_config[\'CacheClusters'
                                '\'][0][\'CacheNodes\'][0][\'Endpoint\'][\'Add'
                                'ress\'];\n',
                                '$port = $cluster_config[\'CacheClusters\'][0]'
                                '[\'CacheNodes\'][0][\'Endpoint\'][\'Port\'];'
                                '\n',
                                '\n',
                                'echo \"<p>Connecting to Redis Cache Cluster '
                                'node \'{$endpoint}\' on port {$port}</p>\";'
                                '\n',
                                '\n',
                                '$redis=new Redis();\n',
                                '$redis->connect($endpoint, $port);\n',
                                '$redis->set(\'testkey\', \'Hello World!\');'
                                '\n',
                                '$return = $redis->get(\'testkey\');\n',
                                '\n',
                                'echo \"<p>Retrieved value: $return</p>\";'
                                '\n',
                                '?>\n'
                                ]),
                            mode='000644',
                            owner='apache',
                            group='apache'
                            ),
                        '/etc/cron.d/get_cluster_config':
                            cloudformation.InitFile(
                                content='*/5 * * * * root'
                                        ' /usr/local/bin/get_cluster_config',
                                mode='000644',
                                owner='root',
                                group='root'
                                ),
                        '/usr/local/bin/get_cluster_config':
                            cloudformation.InitFile(
                                content=Join('', [
                                    '#! /bin/bash\n',
                                    'aws elasticache describe-cache-clusters ',
                                    '         --cache-cluster-id ',
                                    Ref('RedisCluster'),
                                    '         --show-cache-node-info'
                                    ' --region ', Ref('AWS::Region'),
                                    ' > /tmp/cacheclusterconfig\n'
                                    ]),
                                mode='000755',
                                owner='root',
                                group='root'
                                ),
                        '/usr/local/bin/install_phpredis':
                            cloudformation.InitFile(
                                content=Join('', [
                                    '#! /bin/bash\n',
                                    'cd /tmp\n',
                                    'wget https://github.com/nicolasff/'
                                    'phpredis/zipball/master -O phpredis.zip'
                                    '\n',
                                    'unzip phpredis.zip\n',
                                    'cd nicolasff-phpredis-*\n',
                                    'phpize\n',
                                    './configure\n',
                                    'make && make install\n',
                                    'touch /etc/php.d/redis.ini\n',
                                    'echo extension=redis.so > /etc/php.d/'
                                    'redis.ini\n'
                                    ]),
                                mode='000755',
                                owner='root',
                                group='root'
                                ),
                        '/etc/cfn/cfn-hup.conf': cloudformation.InitFile(
                            content=Join('', [
                                '[main]\n',
                                'stack=', Ref('AWS::StackId'), '\n',
                                'region=', Ref('AWS::Region'), '\n'
                                ]),
                            mode='000400',
                            owner='root',
                            group='root'
                            ),
                        '/etc/cfn/hooks.d/cfn-auto-reloader.conf':
                            cloudformation.InitFile(
                                content=Join('', [
                                    '[cfn-auto-reloader-hook]\n',
                                    'triggers=post.update\n',
                                    'path=Resources.WebServerInstance.Metadata'
                                    '.AWS::CloudFormation::Init\n',
                                    'action=/opt/aws/bin/cfn-init -v ',
                                    '         --stack ', Ref('AWS::StackName'),
                                    '         --resource WebServerInstance ',
                                    '         --region ', Ref('AWS::Region'),
                                    '\n',
                                    'runas=root\n'
                                    ]),
                                # Why doesn't the Amazon template have this?
                                # mode='000400',
                                # owner='root',
                                # group='root'
                                ),
                        }),

                    commands={
                        '01-install_phpredis': {
                            'command': '/usr/local/bin/install_phpredis'
                            },
                        '02-get-cluster-config': {
                            'command': '/usr/local/bin/get_cluster_config'
                            }
                        },

                    services={
                        "sysvinit": cloudformation.InitServices({
                            "httpd": cloudformation.InitService(
                                enabled=True,
                                ensureRunning=True,
                                ),
                            "cfn-hup": cloudformation.InitService(
                                enabled=True,
                                ensureRunning=True,
                                files=['/etc/cfn/cfn-hup.conf',
                                       '/etc/cfn/hooks.d/'
                                       'cfn-auto-reloader.conf']
                                ),
                            }),
                        },
                    )
                })
            ),
        ImageId=FindInMap('AWSRegionArch2AMI', Ref('AWS::Region'),
                          FindInMap('AWSInstanceType2Arch',
                                    Ref(instancetype), 'Arch')),
        InstanceType=Ref(instancetype),
        SecurityGroups=[Ref(webserversg)],
        KeyName=Ref(keyname),
        IamInstanceProfile=Ref(webserverinstanceprofile),
        UserData=Base64(Join('', [
            '#!/bin/bash -xe\n',
            'yum update -y aws-cfn-bootstrap\n',

            '# Setup the PHP sample application\n',
            '/opt/aws/bin/cfn-init -v ',
            '         --stack ', Ref('AWS::StackName'),
            '         --resource WebServerInstance ',
            '         --region ', Ref('AWS::Region'), '\n',

            '# Signal the status of cfn-init\n',
            '/opt/aws/bin/cfn-signal -e $? ',
            '         --stack ', Ref('AWS::StackName'),
            '         --resource WebServerInstance ',
            '         --region ', Ref('AWS::Region'), '\n'
            ])),
        CreationPolicy=CreationPolicy(
            ResourceSignal=ResourceSignal(Timeout='PT15M')
            ),
        Tags=Tags(Application=Ref('AWS::StackId'),
                  Details='Created using Troposhpere')
        ))

    redisclustersg = template.add_resource(elasticache.SecurityGroup(
        'RedisClusterSecurityGroup',
        Description='Lock the cluster down',
        ))

    template.add_resource(elasticache.SecurityGroupIngress(
        'RedisClusterSecurityGroupIngress',
        CacheSecurityGroupName=Ref(redisclustersg),
        EC2SecurityGroupName=Ref(webserversg),
        ))

    template.add_resource(elasticache.CacheCluster(
        'RedisCluster',
        Engine='redis',
        CacheNodeType=Ref(cachenodetype),
        NumCacheNodes='1',
        CacheSecurityGroupNames=[Ref(redisclustersg)],
        ))

    # Outputs
    template.add_output([
        Output(
            'WebsiteURL',
            Description='Application URL',
            Value=Join('', [
                'http://',
                GetAtt(webserverinstance, 'PublicDnsName'),

                ])
            )
        ])

    # Print CloudFormation Template
    print(template.to_json())
1345061
function loadLambdas() {
  const lambdasPath = path.join(process.cwd(), plugin.config.lambdasPath);

  // This event allows to inject code before loading all APIs
  return plugin.myrmex.fire('beforeLambdasLoad')
  .then(() => {
    // Retrieve configuration path of all Lambdas
    return Promise.promisify(fs.readdir)(lambdasPath);
  })
  .then((subdirs) => {
    // Load all Lambdas configurations
    const lambdaPromises = [];
    _.forEach(subdirs, (subdir) => {
      const lambdaPath = path.join(lambdasPath, subdir);
      // subdir is the identifier of the Lambda, so we pass it as the second argument
      lambdaPromises.push(loadLambda(lambdaPath, subdir));
    });
    return Promise.all(lambdaPromises);
  })
  .then((lambdas) => {
    // This event allows to inject code to add or delete or alter lambda configurations
    return plugin.myrmex.fire('afterLambdasLoad', lambdas);
  })
  .spread((lambdas) => {
    return Promise.resolve(lambdas);
  })
  .catch(e => {
    // In case the project does not have any Lambda yet, an exception will be thrown
    // We silently ignore it
    if (e.code === 'ENOENT' && path.basename(e.path) === 'lambdas') {
      return Promise.resolve([]);
    }
    return Promise.reject(e);
  });
}
688640
function deployAuctionRegistrar(deployer, tld) {
  var rootNode = getRootNodeFromTLD(tld);

  // Deploy the ENS first
  deployer.deploy(ENS)
    .then(() => {
      // Deploy the HashRegistrar and bind it with ENS
      // The last argument `0` specifies the auction start date to `now`
      return deployer.deploy(Registrar, ENS.address, rootNode.namehash, 0);
    })
    .then(function() {
      // Transfer the owner of the `rootNode` to the HashRegistrar
      return ENS.at(ENS.address).then((c) => c.setSubnodeOwner('0x0', rootNode.sha3, Registrar.address));
    });
}