All CloudFormation states listed here: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-describing-stacks.html
1816
def exit_unless_updateable!
      stack_name = Jets::Naming.parent_stack_name
      exists = stack_exists?(stack_name)
      return unless exists # continue because stack could be updating

      stack = cfn.describe_stacks(stack_name: stack_name).stacks.first
      status = stack["stack_status"]
      if status =~ /^ROLLBACK_/ ||
         status =~ /_IN_PROGRESS$/
        region = `aws configure get region`.strip rescue "us-east-1"
        url = "https://console.aws.amazon.com/cloudformation/home?region=#{region}#/stacks"
        puts "The parent stack of the #{Jets.config.project_name.color(:green)} project is not in an updateable state."
        puts "Stack name #{stack_name.color(:yellow)} status #{stack["stack_status"].color(:yellow)}"
        puts "Here's the CloudFormation url to check for more details #{url}"
        exit 1
      end
    end
636924
def create(definition: dict, version: str, parameter: tuple,
           region: str,
           disable_rollback: bool,
           dry_run: bool,
           force: bool,
           tag: List[str],
           timeout: int,
           keep_stacks: Optional[int],
           traffic: int,
           verbose: bool,
           remote: str,
           parameter_file: Optional[str]
           ):
    
    lizzy = setup_lizzy_client(remote)
    parameter = list(parameter) or []
    if parameter_file:
        parameter.extend(read_parameter_file(parameter_file))

    if not force:  # pragma: no cover
        # supporting artifact checking would imply copying a large amount of code
        # from senza, so it should be considered out of scope until senza
        # and lizzy client are merged
        warning("WARNING: "
                "Artifact checking is still not supported by lizzy-client.")

    with Action('Requesting new stack..') as action:
        new_stack, output = lizzy.new_stack(keep_stacks, traffic,
                                            definition, version,
                                            disable_rollback, parameter,
                                            region=region,
                                            dry_run=dry_run,
                                            tags=tag)

    stack_id = '{stack_name}-{version}'.format_map(new_stack)
    print(output)

    info('Stack ID: {}'.format(stack_id))

    if dry_run:
        info("Post deployment steps skipped")
        exit(0)

    with Action('Waiting for new stack...') as action:
        if verbose:
            print()  # ensure that new states will not be printed on the same line as the action

        last_state = None
        for state in lizzy.wait_for_deployment(stack_id, region=region):
            if state != last_state and verbose:
                click.echo(' {}'.format(state))
            else:
                action.progress()
            last_state = state

        # TODO be prepared to handle all final AWS CF states
        if last_state == 'ROLLBACK_COMPLETE':
            fatal_error(
                'Stack was rollback after deployment. Check your application log for possible reasons.')
        elif last_state != 'CREATE_COMPLETE':
            fatal_error('Deployment failed: {}'.format(last_state))

    info('Deployment Successful')

    if traffic is not None:
        with Action('Requesting traffic change..'):
            try:
                lizzy.traffic(stack_id, traffic, region=region)
            except requests.ConnectionError as e:
                connection_error(e, fatal=False)
            except requests.HTTPError as e:
                agent_error(e, fatal=False)

    # TODO unit test this
    if keep_stacks is not None:
        versions_to_keep = keep_stacks + 1
        stacks_to_remove_counter = 1
        end_time = datetime.datetime.utcnow() + datetime.timedelta(seconds=timeout)
        while stacks_to_remove_counter > 0 and datetime.datetime.utcnow() <= end_time:
            try:
                all_stacks = lizzy.get_stacks([new_stack['stack_name']],
                                              region=region)
            except requests.ConnectionError as e:
                connection_error(e, fatal=False)
                error("Failed to fetch old stacks. "
                      "Old stacks WILL NOT BE DELETED")
                exit(1)
            except requests.HTTPError as e:
                agent_error(e, fatal=False)
                error("Failed to fetch old stacks. "
                      "Old stacks WILL NOT BE DELETED")
                exit(1)
            else:
                sorted_stacks = sorted(all_stacks,
                                       key=lambda stack: stack['creation_time'])
                stacks_to_remove = sorted_stacks[:-versions_to_keep]
                stacks_to_remove_counter = len(stacks_to_remove)
                with Action('Deleting old stacks..'):
                    print()
                    for old_stack in stacks_to_remove:
                        old_stack_id = '{stack_name}-{version}'.format_map(
                            old_stack)
                        if old_stack['status'] in COMPLETE_STATES:
                            click.echo(' {}'.format(old_stack_id))
                            try:
                                lizzy.delete(old_stack_id, region=region)
                                stacks_to_remove_counter -= 1
                            except requests.ConnectionError as e:
                                connection_error(e, fatal=False)
                            except requests.HTTPError as e:
                                agent_error(e, fatal=False)
                        else:
                            click.echo(' > {} current status is {} trying '
                                       'again later'.format(old_stack_id,
                                                            old_stack['status']))
                if stacks_to_remove_counter > 0:
                    time.sleep(5)

        if datetime.datetime.utcnow() > end_time:
            click.echo('Timeout waiting for related stacks to be ready.')
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)
756126
function _doesEventContainsNestedStackId(stack) {
    if (stack.ResourceType !== 'AWS::CloudFormation::Stack') {
        return false;
    }
    if (stack.ResourceStatusReason !== 'Resource creation Initiated') {
        return false;
    }
    if (stack.ResourceStatus !== 'CREATE_IN_PROGRESS') {
        return false;
    }
    if (_.isNil(stack.PhysicalResourceId)) {
        return false;
    }

    return _hasLabelNestedStackName(stack.PhysicalResourceId);
}
693804
def get_events(self, stack_name, chronological=True):
        """"""
        next_token = None
        event_list = []
        while True:
            if next_token is not None:
                events = self.cloudformation.describe_stack_events(
                    StackName=stack_name, NextToken=next_token
                )
            else:
                events = self.cloudformation.describe_stack_events(
                    StackName=stack_name
                )
            event_list.append(events['StackEvents'])
            next_token = events.get('NextToken', None)
            if next_token is None:
                break
            time.sleep(GET_EVENTS_SLEEP)
        if chronological:
            return reversed(sum(event_list, []))
        else:
            return sum(event_list, [])
1002314
def deploy_stack(awsclient, context, conf, cloudformation, override_stack_policy=False):
    
    stack_name = _get_stack_name(conf)
    parameters = _generate_parameters(conf)
    if stack_exists(awsclient, stack_name):
        exit_code = _update_stack(awsclient, context, conf, cloudformation,
                                  parameters, override_stack_policy)
    else:
        exit_code = _create_stack(awsclient, context, conf, cloudformation,
                                  parameters)
    # add 'stack_output' to the context so it becomes available
    # in 'command_finalized' hook
    context['stack_output'] = _get_stack_outputs(
        awsclient.get_client('cloudformation'), stack_name)
    _call_hook(awsclient, conf, stack_name, parameters, cloudformation,
               hook='post_hook',
               message='CloudFormation is done, now executing post hook...')
    return exit_code
708812
def avail_locations(call=None):
    '''
    
    '''
    if call == 'action':
        raise SaltCloudSystemExit(
            'The avail_locations function must be called with '
            '-f or --function, or with the --list-locations option'
        )

    ret = {}

    params = {'Action': 'DescribeRegions'}
    result = aws.query(params,
                       location=get_location(),
                       provider=get_provider(),
                       opts=__opts__,
                       sigver='4')

    for region in result:
        ret[region['regionName']] = {
            'name': region['regionName'],
            'endpoint': region['regionEndpoint'],
        }

    return ret
640080
def platform
      # If you are declaring a new platform, you will need to tell
      # Train a bit about it.
      # If you were defining a cloud API, you should say you are a member
      # of the cloud family.

      # This plugin makes up a new platform.  Train (or rather InSpec) only
      # know how to read files on Windows and Un*x (MacOS is a kind of Un*x),
      # so we'll say we're part of those families.
      Train::Platforms.name('local-rot13').in_family('unix')
      Train::Platforms.name('local-rot13').in_family('windows')

      # When you know you will only ever run on your dedicated platform
      # (for example, a plugin named train-aws would only run on the AWS
      # API, which we report as the 'aws' platform).
      # force_platform! lets you bypass platform detection.
      # The options to this are not currently documented completely.

      # Use release to report a version number.  You might use the version
      # of the plugin, or a version of an important underlying SDK, or a
      # version of a remote API.
      force_platform!('local-rot13', release: TrainPlugins::LocalRot13::VERSION)
    end
325184
def GetSummary(self):
    
    summary = rdf_client.ClientSummary()
    summary.client_id = self.client_id
    summary.timestamp = self.timestamp

    summary.system_info.release = self.os_release
    summary.system_info.version = str(self.os_version or "")
    summary.system_info.kernel = self.kernel
    summary.system_info.machine = self.arch
    summary.system_info.install_date = self.install_time
    kb = self.knowledge_base
    if kb:
      summary.system_info.fqdn = kb.fqdn
      summary.system_info.system = kb.os
      summary.users = kb.users
      summary.interfaces = self.interfaces
      summary.client_info = self.startup_info.client_info
      if kb.os_release:
        summary.system_info.release = kb.os_release
        if kb.os_major_version:
          summary.system_info.version = "%d.%d" % (kb.os_major_version,
                                                   kb.os_minor_version)

    hwi = self.hardware_info
    if hwi:
      summary.serial_number = hwi.serial_number
      summary.system_manufacturer = hwi.system_manufacturer
      summary.system_uuid = hwi.system_uuid

    cloud_instance = self.cloud_instance
    if cloud_instance:
      summary.cloud_type = cloud_instance.cloud_type
      if cloud_instance.cloud_type == "GOOGLE":
        summary.cloud_instance_id = cloud_instance.google.unique_id
      elif cloud_instance.cloud_type == "AMAZON":
        summary.cloud_instance_id = cloud_instance.amazon.instance_id
      else:
        raise ValueError("Bad cloud type: %s" % cloud_instance.cloud_type)
    return summary
186680
def create_stack_template(  self,
                                lambda_arn,
                                lambda_name,
                                api_key_required,
                                iam_authorization,
                                authorizer,
                                cors_options=None,
                                description=None,
                                endpoint_configuration=None
                            ):
        

        auth_type = "NONE"
        if iam_authorization and authorizer:
            logger.warn("Both IAM Authorization and Authorizer are specified, this is not possible. "
                        "Setting Auth method to IAM Authorization")
            authorizer = None
            auth_type = "AWS_IAM"
        elif iam_authorization:
            auth_type = "AWS_IAM"
        elif authorizer:
            auth_type = authorizer.get("type", "CUSTOM")

        # build a fresh template
        self.cf_template = troposphere.Template()
        self.cf_template.add_description('Automatically generated with Zappa')
        self.cf_api_resources = []
        self.cf_parameters = {}

        restapi = self.create_api_gateway_routes(
                                            lambda_arn,
                                            api_name=lambda_name,
                                            api_key_required=api_key_required,
                                            authorization_type=auth_type,
                                            authorizer=authorizer,
                                            cors_options=cors_options,
                                            description=description,
                                            endpoint_configuration=endpoint_configuration
                                        )
        return self.cf_template
675750
def stack_status
      resp = cfn.describe_stacks(stack_name: @parent_stack_name)
      status = resp.stacks[0].stack_status
      [resp, status]
    end
375256
def do_stack(self,args):
        """"""
        parser = CommandArgumentParser("stack")
        parser.add_argument(dest='stack',help='stack index or name');
        args = vars(parser.parse_args(args))

        print "loading stack {}".format(args['stack'])
        try:
            index = int(args['stack'])            
            stackSummary = self.wrappedStack['resourcesByTypeIndex']['AWS::CloudFormation::Stack'][index]
        except ValueError:
            stackSummary = self.wrappedStack['resourcesByTypeName']['AWS::CloudFormation::Stack'][args['stack']]

        self.stackResource(stackSummary.stack_name,stackSummary.logical_id)
1157868
def ls(ctx, name, list_instances):
    """"""
    session = create_session(ctx.obj['AWS_PROFILE_NAME'])

    client = session.client('elb')
    inst = {'LoadBalancerDescriptions': []}
    if name == '*':
        inst = client.describe_load_balancers()
    else:
        try:
            inst = client.describe_load_balancers(LoadBalancerNames=[name])
        except ClientError as e:
            click.echo(e, err=True)

    for i in inst['LoadBalancerDescriptions']:
        click.echo(i['LoadBalancerName'])
        if list_instances:
            for ec2 in i['Instances']:
                health = client.describe_instance_health(
                    LoadBalancerName=name,
                    Instances=[ec2]
                )
                click.echo('{0}\t{1}'.format(ec2['InstanceId'], health['InstanceStates'][0]['State']))
1276167
function buildDAXSubnetGroup(numZones = 0, { name = 'DAXSubnetGroup' } = {}) {
  if (numZones < 1) {
    return {};
  }

  const subnetIds = [];
  for (let i = 1; i <= numZones; i += 1) {
    subnetIds.push({ Ref: `${DB_SUBNET}Subnet${i}` });
  }

  return {
    [name]: {
      Type: 'AWS::DAX::SubnetGroup',
      Properties: {
        SubnetGroupName: {
          Ref: 'AWS::StackName',
        },
        Description: {
          Ref: 'AWS::StackName',
        },
        SubnetIds: subnetIds,
      },
    },
  };
}
391589
private function describeMainStack(CloudFormationException & $cloudFormationException = null)
    {
        $cloudFormation = $this->getService();

        try {
            $stack = $cloudFormation->describeStacks([
                'StackName' => $this->getName(),
            ]);

            return $stack['Stacks'];
        } catch (CloudFormationException $e) {
            $cloudFormationException = $e;
            $message = $e->getMessage();
        }

        if (1 === preg_match('/AccessDenied|403 Forbidden/i', $message)) {
            throw new \BuildException('You are not authorized to perform describeStacks on [' . $this->getName() . ']. Check the credentials and AWS policy');
        }

        if (1 ===  preg_match('/Could not resolve host/i', $message)) {
            throw new \BuildException("Could not resolve AWS host, thanks to check the AWS_REGION settings or connectivity");
        }

        return null;
    }
1183399
@Override
    public Map<String, List<CloudInstance>> getCloudInstances(CloudInstanceRepository repository) {
        DescribeInstancesResult instanceResult;
        if (null == settings.getFilters() || settings.getFilters().isEmpty() ) {
            instanceResult = ec2Client.describeInstances();
        } else {
            instanceResult = ec2Client.describeInstances(buildFilterRequest(settings.getFilters()));
        }
        DescribeAutoScalingInstancesResult autoScaleResult = autoScalingClient.describeAutoScalingInstances();
        List<AutoScalingInstanceDetails> autoScalingInstanceDetails = autoScaleResult.getAutoScalingInstances();
        Map<String, String> autoScaleMap = new HashMap<>();
        for (AutoScalingInstanceDetails ai : autoScalingInstanceDetails) {
            autoScaleMap.put(ai.getInstanceId(), ai.getAutoScalingGroupName());
        }

        Map<String, List<Instance>> ownerInstanceMap = new HashMap<>();

        List<Instance> instanceList = new ArrayList<>();
        List<Reservation> reservations = instanceResult.getReservations();
        for (Reservation currRes : reservations) {
            List<Instance> currInstanceList = currRes.getInstances();
            if (CollectionUtils.isEmpty(ownerInstanceMap.get(currRes.getOwnerId()))) {
                ownerInstanceMap.put(currRes.getOwnerId(), currRes.getInstances());
            } else {
                ownerInstanceMap.get(currRes.getOwnerId()).addAll(currRes.getInstances());
            }
            instanceList.addAll(currInstanceList);
        }

        Map<String, List<CloudInstance>> returnList = new HashMap<>();
        int i = 0;
        for (String acct : ownerInstanceMap.keySet()) {
            ArrayList<CloudInstance> rawDataList = new ArrayList<>();
            for (Instance currInstance : ownerInstanceMap.get(acct)) {
                i = i + 1;
                LOGGER.info("Collecting instance details for " + i + " of "
                        + instanceList.size() + ". Instance ID=" + currInstance.getInstanceId());
                CloudInstance object = getCloudInstanceDetails(acct,
                        currInstance, autoScaleMap, repository);
                rawDataList.add(object);
            }
            if (CollectionUtils.isEmpty(returnList.get(acct))) {
                returnList.put(acct, rawDataList);
            } else {
                returnList.get(acct).addAll(rawDataList);
            }
        }
        return returnList;
    }
87543
def _cl_aws_cli(cls, file_info, region):
        
        s3file = cls._S3_FILE % {"bucket": file_info.bucket,
                                 "key": file_info.key,
                                 "region": ""}
        command = [os.path.join(os.path.dirname(sys.executable), "aws"),
                   "s3", "cp", "--region", region, s3file]
        return (command, "awscli")