signal success to the current CloudFormation stack.<br>
The resource is derived from the instance tags
<br>
Needed AWS actions:
<ul>
<li>ec2:DescribeInstances</li>
<li>cloudformation:SignalResource</li>
</ul>
420188
public void signalReady() {
        Map<String, String> hostTags = this.ec2Context.getInstanceTags();
        this.signalReady(hostTags.get(TAG_CLOUDFORMATION_STACK_NAME), hostTags.get(TAG_CLOUDFORMATION_LOGICAL_ID));
    }
1271753
def _onsuccess(cls, kmsg, result):
        
        logger.info(
            "{}.Success: {}[{}]: {}".format(
                cls.__name__, kmsg.entrypoint, kmsg.uuid, result
            ),
            extra=dict(
                kmsg=kmsg.dump(),
                kresult=ResultSchema().dump(result) if result else dict()
            )
        )
        return cls.onsuccess(kmsg, result)
979988
def show_instance(name, call=None):
    '''
    
    '''
    if call != 'action':
        raise SaltCloudSystemExit(
            'The show_instance action must be called with -a or --action.'
        )

    items = query(action='ve', command=name)

    ret = {}
    for item in items:
        if 'text' in item.__dict__:
            ret[item.tag] = item.text
        else:
            ret[item.tag] = item.attrib

        if item._children:
            ret[item.tag] = {}
            children = item._children
            for child in children:
                ret[item.tag][child.tag] = child.attrib

    __utils__['cloud.cache_node'](ret, __active_provider_name__, __opts__)
    return ret
764003
def list_stacks(awsclient):
    
    client_cf = awsclient.get_client('cloudformation')
    response = client_cf.list_stacks(
        StackStatusFilter=[
            'CREATE_IN_PROGRESS', 'CREATE_COMPLETE', 'ROLLBACK_IN_PROGRESS',
            'ROLLBACK_COMPLETE', 'DELETE_IN_PROGRESS', 'DELETE_FAILED',
            'UPDATE_IN_PROGRESS', 'UPDATE_COMPLETE_CLEANUP_IN_PROGRESS',
            'UPDATE_COMPLETE', 'UPDATE_ROLLBACK_IN_PROGRESS',
            'UPDATE_ROLLBACK_FAILED',
            'UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS',
            'UPDATE_ROLLBACK_COMPLETE',
        ]
    )
    result = {}
    stack_sum = 0
    for summary in response['StackSummaries']:
        result['StackName'] = summary["StackName"]
        result['CreationTime'] = summary['CreationTime']
        result['StackStatus'] = summary['StackStatus']
        print(json2table(result))
        stack_sum += 1
    print('listed %s stacks' % str(stack_sum))
322099
def create_ondemand_instances(ec2, image_id, spec, num_instances=1):
    
    instance_type = spec['instance_type']
    log.info('Creating %s instance(s) ... ', instance_type)
    for attempt in retry_ec2(retry_for=a_long_time,
                             retry_while=inconsistencies_detected):
        with attempt:
            return ec2.run_instances(image_id,
                                     min_count=num_instances,
                                     max_count=num_instances,
                                     **spec).instances
1318526
function start(mode, target, system, containerDef, container, out, cb) {

    out.preview({cmd: 'start instances', host: null, user: null, keyPath: null});
    if (mode === 'preview') {
      return cb(null);
    }

    var instanceType = container.specific.InstanceType ||
                       container.specific.instanceType ||
                       config.defaultInstanceType ||
                       'm3.medium';

    var imageId = container.specific.ImageId ||
                  container.specific.imageId ||
                  config.defaultImageId;

    var params = {'MaxCount': 1,
                  'MinCount': 1,
                  'EbsOptimized': false,
                  'InstanceInitiatedShutdownBehavior': 'stop',
                  'InstanceType': instanceType,
                  'ImageId': imageId,
                  'KeyName': config.defaultKeyName,
                  'SubnetId': config.defaultSubnetId,
                  'Monitoring': { Enabled: false }};
                  /*'EbsOptimized': container.specific.ebsOptimized,
                  'InstanceInitiatedShutdownBehavior': container.specific.instanceInitiatedShutdownBehavior,
                  'InstanceType': container.specific.instanceType,
                  'KeyName': container.specific.keyName,
                  'Monitoring': container.specific.monitoring};*/

    if (system.topology.containers[container.containedBy].type === 'aws-sg') {
      params.SecurityGroupIds = [system.topology.containers[container.containedBy].nativeId];
    }

    _ec2.runInstances(params, function(err, data) {
      if (err) { return cb(err, null); }
      var instance = data.Instances[0];

      pollInstanceStart(instance, function(err, newSpecific) {
        if (err) { return cb(err); }
        var tagParams = {Resources: [instance.InstanceId], Tags: container.specific.tags || []};
        tagParams.Tags.push({Key: 'nscale-system', Value: system.name + '-' + system.topology.name});
        tagParams.Tags.push({Key: 'nscale-id', Value: system.name + '-' + system.topology.name + '-' + container.id});
        if (containerDef.name) {
          tagParams.Tags.push({Key: 'Name', Value: container.id});
        }
        _ec2.createTags(tagParams, function() {
          if (err) { return cb(err); }
          var c = _.find(system.topology.containers, function(cont) { return cont.id === container.id; });
          c.nativeId = instance.InstanceId;
          c.specific = newSpecific;
          system.dirty = true;
          cb(null, system);
        });
      });
    });
  }
821141
def instance():
    
    # Record the starting time and print a starting message
    start_time = time.time()
    print(_green("Started..."))

    # Use boto to create an EC2 instance
    env.host_string = _create_ec2_instance()
    print(_green("Waiting 30 seconds for server to boot..."))
    time.sleep(30)
    
    # Configure the instance that was just created
    for item in tasks.configure_instance:
        try:
            print(_yellow(item['message']))
        except KeyError:
            pass
        globals()["_" + item['action']](item['params'])
    
    # Print out the final runtime and the public dns of the new instance
    end_time = time.time()
    print(_green("Runtime: %f minutes" % ((end_time - start_time) / 60)))
    print(_green("\nPLEASE ADD ADDRESS THIS TO YOUR ")),
    print(_yellow("project_conf.py")),
    print(_green(" FILE UNDER ")),
    print(_yellow("fabconf['EC2_INSTANCES'] : ")),
    print(_green(env.host_string))
913184
def run
      unless stack_exists?(@stack_name)
        puts "The stack #{@stack_name.color(:green)} does not exist."
        return
      end

      resp = cloudformation.describe_stacks(stack_name: @stack_name)
      stack = resp.stacks.first

      puts "The current status for the stack #{@stack_name.color(:green)} is #{stack.stack_status.color(:green)}"

      status_poller = Stack::Status.new(@stack_name)

      if stack.stack_status =~ /_IN_PROGRESS$/
        puts "Stack events (tailing):"
        # tail all events until done
        status_poller.hide_time_took = true
        status_poller.wait
      else
        puts "Stack events:"
        # show the last events that was user initiated
        status_poller.refresh_events
        status_poller.show_events(true)
      end
    end
375709
private void deployInstance(final Node node, final InstanceContext instance, final CountingCompletionHandler<Void> counter) {
    data.put(instance.address(), Contexts.serialize(instance).encode(), new Handler<AsyncResult<String>>() {
      @Override
      public void handle(AsyncResult<String> result) {
        if (result.failed()) {
          counter.fail(result.cause());
        } else {
          if (!watchHandlers.containsKey(instance.address())) {
            final Handler<MapEvent<String, String>> watchHandler = new Handler<MapEvent<String, String>>() {
              @Override
              public void handle(MapEvent<String, String> event) {
                if (event.type().equals(MapEvent.Type.CREATE) || event.type().equals(MapEvent.Type.UPDATE)) {
                  handleReady(instance.address());
                } else if (event.type().equals(MapEvent.Type.DELETE)) {
                  handleUnready(instance.address());
                }
              }
            };
            // Watch the instance's status for changes. Once the instance has started
            // up, the component coordinator will set the instance's status key in the
            // cluster, indicating that the instance has completed started. Once all
            // instances in the network have completed startup the network will be started.
            data.watch(instance.status(), watchHandler, new Handler<AsyncResult<Void>>() {
              @Override
              public void handle(AsyncResult<Void> result) {
                if (result.failed()) {
                  counter.fail(result.cause());
                } else {
                  watchHandlers.put(instance.address(), watchHandler);
                  if (instance.component().isModule()) {
                    deployModule(node, instance, counter);
                  } else if (instance.component().isVerticle() && !instance.component().asVerticle().isWorker()) {
                    deployVerticle(node, instance, counter);
                  } else if (instance.component().isVerticle() && instance.component().asVerticle().isWorker()) {
                    deployWorkerVerticle(node, instance, counter);
                  }
                }
              }
            });
          } else {
            if (instance.component().isModule()) {
              deployModule(node, instance, counter);
            } else if (instance.component().isVerticle() && !instance.component().asVerticle().isWorker()) {
              deployVerticle(node, instance, counter);
            } else if (instance.component().isVerticle() && instance.component().asVerticle().isWorker()) {
              deployWorkerVerticle(node, instance, counter);
            }
          }
        }
      }
    });
  }
225038
def output_deployment_diagnostics(awsclient, deployment_id, log_group, start_time=None):
    
    headline = False
    for instance_id in _list_deployment_instances(awsclient, deployment_id):
        diagnostics = _get_deployment_instance_diagnostics(
            awsclient, deployment_id, instance_id)
        #if error_code != 'Success':
        if diagnostics is not None:
            error_code, script_name, message, log_tail = diagnostics
            # header
            if not headline:
                headline = True
                log.info('\ndeployment diagnostics:')
            # event logs
            log.info('Instance ID: %s', Fore.MAGENTA + instance_id + Fore.RESET)
            log.info('Error Code:  %s', error_code)
            log.info('Script Name: %s', script_name)
            log.info('Message:     %s', message)
            log.info('Log Tail:    %s', log_tail)
            # cloudwatch logs
            if check_log_stream_exists(awsclient, log_group, instance_id):
                logentries = get_log_events(
                    awsclient, log_group, instance_id,
                    datetime_to_timestamp(start_time))
                if logentries:
                    log.info('instance %s logentries', instance_id)
                    for e in logentries:
                        log.info(e['message'].strip())
814860
private Flowable<List<ServiceInstance>> convertInstancesResulttoServiceInstances(ListInstancesResult instancesResult) {
        List<ServiceInstance> serviceInstances = new ArrayList<>();
        for (InstanceSummary instanceSummary : instancesResult.getInstances()) {
            try {
                String uri = "http://" + instanceSummary.getAttributes().get("URI");
                ServiceInstance serviceInstance = new EC2ServiceInstance(instanceSummary.getId(), new URI(uri)).metadata(instanceSummary.getAttributes()).build();
                serviceInstances.add(serviceInstance);
            } catch (URISyntaxException e) {
                return Flowable.error(e);
            }
        }
        return Flowable.just(serviceInstances);
    }
598005
private void deployInstance(final InstanceContext instance, final CountingCompletionHandler<Void> counter) {
    // First we need to select a node from the component's deployment group
    // to which to deploy the component.
    // If the component doesn't specify a group then deploy to any node in the cluster.
    if (instance.component().group() != null) {
      cluster.getGroup(instance.component().group(), new Handler<AsyncResult<Group>>() {
        @Override
        public void handle(AsyncResult<Group> result) {
          if (result.failed()) {
            counter.fail(result.cause());
          } else {
            result.result().selectNode(instance.address(), new Handler<AsyncResult<Node>>() {
              @Override
              public void handle(AsyncResult<Node> result) {
                if (result.failed()) {
                  counter.fail(result.cause());
                } else {
                  deployInstance(result.result(), instance, counter);
                }
              }
            });
          }
        }
      });
    } else {
      cluster.selectNode(instance.address(), new Handler<AsyncResult<Node>>() {
        @Override
        public void handle(AsyncResult<Node> result) {
          if (result.failed()) {
            counter.fail(result.cause());
          } else {
            deployInstance(result.result(), instance, counter);
          }
        }
      });
    }
  }
13331
def describe_change_set(awsclient, change_set_name, stack_name):
    
    client = awsclient.get_client('cloudformation')

    status = None
    while status not in ['CREATE_COMPLETE', 'FAILED']:
        response = client.describe_change_set(
            ChangeSetName=change_set_name,
            StackName=stack_name)
        status = response['Status']
        # print('##### %s' % status)
        if status == 'FAILED':
            print(response['StatusReason'])
        elif status == 'CREATE_COMPLETE':
            for change in response['Changes']:
                print(json2table(change['ResourceChange']))
23800
function askCloudFormation() {
    if (this.abort) return null;
    const done = this.async();
    const prompts = [
        {
            type: 'input',
            name: 'cloudFormationName',
            message: "Please enter your stack's name. (must be unique within a region)",
            default: this.aws.cloudFormationName || this.baseName,
            validate: input => {
                if (_.isEmpty(input) || !input.match(CLOUDFORMATION_STACK_NAME)) {
                    return 'Stack name must contain letters, digits, or hyphens ';
                }
                return true;
            }
        }
    ];

    return this.prompt(prompts).then(props => {
        const cloudFormationName = props.cloudFormationName;
        if (cloudFormationName) {
            this.aws.cloudFormationName = cloudFormationName;
            while (this.aws.cloudFormationName.includes('_')) {
                this.aws.cloudFormationName = _.replace(this.aws.cloudFormationName, '_', '');
            }
            this.log(`CloudFormation Stack name will be ${this.aws.cloudFormationName}`);
            done();
        } else {
            this.abort = true;
            done();
        }
    });
}
153410
private void deployInstances(List<InstanceContext> instances, final Handler<AsyncResult<Void>> doneHandler) {
    final CountingCompletionHandler<Void> counter = new CountingCompletionHandler<Void>(instances.size()).setHandler(doneHandler);
    for (final InstanceContext instance : instances) {
      // Before deploying the instance, check if the instance is already deployed in
      // the network's cluster.
      deploymentIDs.get(instance.address(), new Handler<AsyncResult<String>>() {
        @Override
        public void handle(AsyncResult<String> result) {
          if (result.failed()) {
            counter.fail(result.cause());
          } else if (result.result() == null) {
            // If no deployment ID has been assigned to the instance then that means it hasn't
            // yet been deployed. Deploy the instance.
            deployInstance(instance, counter);
          } else {
            // Even if the instance is already deployed, update its context in the cluster.
            // It's possible that the instance's connections could have changed with the update.
            data.put(instance.address(), Contexts.serialize(instance).encode(), new Handler<AsyncResult<String>>() {
              @Override
              public void handle(AsyncResult<String> result) {
                if (result.failed()) {
                  counter.fail(result.cause());
                } else {
                  counter.succeed();
                }
              }
            });
          }
        }
      });
    }
  }
552621
def handle_stack_error(e)
      case e.message
      when /is in ROLLBACK_COMPLETE state and can not be updated/
        puts "The #{@stack_name} stack is in #{"ROLLBACK_COMPLETE".color(:red)} and cannot be updated. Deleted the stack and try again."
        region = `aws configure get region`.strip rescue 'us-east-1'
        url = "https://console.aws.amazon.com/cloudformation/home?region=#{region}"
        puts "Here's the CloudFormation console url: #{url}"
        exit 1
      when /No updates are to be performed/
        puts "There are no updates to be performed. Exiting.".color(:yellow)
        exit 1
      else
        raise
      end
    end
1010010
def describe_instances(id=nil)
      begin
        @describe_instances = ec2.describe_instances.reservationSet.item.map do |r|
          r.instancesSet.item.map do |i|
            inst_options = i.merge(r.merge(:cloud => cloud)).merge(cloud.cloud_provider.dsl_options)
            Ec2Instance.new(inst_options)
          end
        end.flatten
      rescue AWS::InvalidClientTokenId => e # AWS credentials invalid
        puts "Error contacting AWS: #{e}"
        raise e
      rescue Exception => e
        []
      end
    end