AWS ECS Docker Deployment Tool
512213
def cli(ctx, config, quiet):
    """"""
    ctx.obj = {}
    ctx.obj['config'] = load_config(config.read())  # yaml.load(config.read())
    ctx.obj['quiet'] = quiet
    log(ctx, ' * ' + rnd_scotty_quote() + ' * ')
648506
def primary_deployment(cluster)
      # Try to describe the existing service.
      description = begin
        Ecs.describe_services(cluster.name, [@name])
      rescue => e
        puts "Error: #{e}"
        nil
      end

      missing_service_warning = <<-STR
Can't find an existing service '#{name}'.  You'll probably need to
register one manually using the AWS console and set up any load balancers
you might need.
      STR

      if description.nil?
        puts missing_service_warning
        return nil
      end

      unless service = description.fetch("services")[0]
        puts missing_service_warning
        return nil
      end

      # Find the primary deployment.
      deployment = service.fetch("deployments").find do |d|
        d["status"] == "PRIMARY"
      end
      return nil if deployment.nil?

      # Extract a task definition `name:revision`.
      arn = deployment.fetch("taskDefinition")
      arn.split('/').last
    end
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
1308397
function installRequirements(targetFolder, serverless, options) {
  const targetRequirementsTxt = path.join(targetFolder, 'requirements.txt');

  serverless.cli.log(
    `Installing requirements from ${targetRequirementsTxt} ...`
  );

  const dockerCmd = [];
  const pipCmd = [
    options.pythonBin,
    '-m',
    'pip',
    'install',
    ...options.pipCmdExtraArgs
  ];
  const pipCmds = [pipCmd];
  const postCmds = [];
  // Check if we're using the legacy --cache-dir command...
  if (options.pipCmdExtraArgs.indexOf('--cache-dir') > -1) {
    if (options.dockerizePip) {
      throw 'Error: You can not use --cache-dir with Docker any more, please\n' +
        '         use the new option useDownloadCache instead.  Please see:\n' +
        '         https://github.com/UnitedIncome/serverless-python-requirements#caching';
    } else {
      serverless.cli.log('==================================================');
      serverless.cli.log(
        'Warning: You are using a deprecated --cache-dir inside\n' +
          '            your pipCmdExtraArgs which may not work properly, please use the\n' +
          '            useDownloadCache option instead.  Please see: \n' +
          '            https://github.com/UnitedIncome/serverless-python-requirements#caching'
      );
      serverless.cli.log('==================================================');
    }
  }

  if (!options.dockerizePip) {
    // Push our local OS-specific paths for requirements and target directory
    pipCmd.push(
      '-t',
      dockerPathForWin(targetFolder),
      '-r',
      dockerPathForWin(targetRequirementsTxt)
    );
    // If we want a download cache...
    if (options.useDownloadCache) {
      const downloadCacheDir = path.join(
        getUserCachePath(options),
        'downloadCacheslspyc'
      );
      serverless.cli.log(`Using download cache directory ${downloadCacheDir}`);
      fse.ensureDirSync(downloadCacheDir);
      pipCmd.push('--cache-dir', downloadCacheDir);
    }

    if (pipAcceptsSystem(options.pythonBin)) {
      pipCmd.push('--system');
    }
  }
  // If we are dockerizing pip
  if (options.dockerizePip) {
    // Push docker-specific paths for requirements and target directory
    pipCmd.push('-t', '/var/task/', '-r', '/var/task/requirements.txt');

    // Build docker image if required
    let dockerImage;
    if (options.dockerFile) {
      serverless.cli.log(
        `Building custom docker image from ${options.dockerFile}...`
      );
      dockerImage = buildImage(options.dockerFile);
    } else {
      dockerImage = options.dockerImage;
    }
    serverless.cli.log(`Docker Image: ${dockerImage}`);

    // Prepare bind path depending on os platform
    const bindPath = dockerPathForWin(getBindPath(serverless, targetFolder));

    dockerCmd.push('docker', 'run', '--rm', '-v', `${bindPath}:/var/task:z`);
    if (options.dockerSsh) {
      // Mount necessary ssh files to work with private repos
      dockerCmd.push(
        '-v',
        `${process.env.HOME}/.ssh/id_rsa:/root/.ssh/id_rsa:z`,
        '-v',
        `${process.env.HOME}/.ssh/known_hosts:/root/.ssh/known_hosts:z`,
        '-v',
        `${process.env.SSH_AUTH_SOCK}:/tmp/ssh_sock:z`,
        '-e',
        'SSH_AUTH_SOCK=/tmp/ssh_sock'
      );
    }

    // If we want a download cache...
    const dockerDownloadCacheDir = '/var/useDownloadCache';
    if (options.useDownloadCache) {
      const downloadCacheDir = path.join(
        getUserCachePath(options),
        'downloadCacheslspyc'
      );
      serverless.cli.log(`Using download cache directory ${downloadCacheDir}`);
      fse.ensureDirSync(downloadCacheDir);
      // This little hack is necessary because getBindPath requires something inside of it to test...
      // Ugh, this is so ugly, but someone has to fix getBindPath in some other way (eg: make it use
      // its own temp file)
      fse.closeSync(
        fse.openSync(path.join(downloadCacheDir, 'requirements.txt'), 'w')
      );
      const windowsized = getBindPath(serverless, downloadCacheDir);
      // And now push it to a volume mount and to pip...
      dockerCmd.push('-v', `${windowsized}:${dockerDownloadCacheDir}:z`);
      pipCmd.push('--cache-dir', dockerDownloadCacheDir);
    }

    if (options.dockerEnv) {
      // Add environment variables to docker run cmd
      options.dockerEnv.forEach(function(item) {
        dockerCmd.push('-e', item);
      });
    }

    if (process.platform === 'linux') {
      // Use same user so requirements folder is not root and so --cache-dir works
      if (options.useDownloadCache) {
        // Set the ownership of the download cache dir to root
        pipCmds.unshift(['chown', '-R', '0:0', dockerDownloadCacheDir]);
      }
      // Install requirements with pip
      // Set the ownership of the current folder to user
      pipCmds.push([
        'chown',
        '-R',
        `${process.getuid()}:${process.getgid()}`,
        '/var/task'
      ]);
      if (options.useDownloadCache) {
        // Set the ownership of the download cache dir back to user
        pipCmds.push([
          'chown',
          '-R',
          `${process.getuid()}:${process.getgid()}`,
          dockerDownloadCacheDir
        ]);
      }
    } else {
      // Use same user so --cache-dir works
      dockerCmd.push('-u', getDockerUid(bindPath));
    }
    dockerCmd.push(dockerImage);
  }

  // If enabled slimming, strip so files
  switch (getStripMode(options)) {
    case 'docker':
      pipCmds.push(getStripCommand(options, '/var/task'));
      break;
    case 'direct':
      postCmds.push(getStripCommand(options, dockerPathForWin(targetFolder)));
      break;
  }

  let spawnArgs = { shell: true };
  if (process.env.SLS_DEBUG) {
    spawnArgs.stdio = 'inherit';
  }
  let mainCmds = [];
  if (dockerCmd.length) {
    dockerCmd.push(...mergeCommands(pipCmds));
    mainCmds = [dockerCmd];
  } else {
    mainCmds = pipCmds;
  }
  mainCmds.push(...postCmds);

  serverless.cli.log(`Running ${quote(dockerCmd)}...`);

  filterCommands(mainCmds).forEach(([cmd, ...args]) => {
    const res = spawnSync(cmd, args);
    if (res.error) {
      if (res.error.code === 'ENOENT') {
        const advice =
          cmd.indexOf('python') > -1
            ? 'Try the pythonBin option'
            : 'Please install it';
        throw new Error(`${cmd} not found! ${advice}`);
      }
      throw res.error;
    }
    if (res.status !== 0) {
      throw new Error(res.stderr);
    }
  });
  // If enabled slimming, delete files in slimPatterns
  if (options.slim === true || options.slim === 'true') {
    deleteFiles(options, targetFolder);
  }
}
1353346
function (options, cb) {
		let outIP = options.out;
		let stack = options.infra.stack;
		
		if (outIP && stack.options.ElbName) {
			options.soajs.log.debug("Creating SOAJS network.");
			
			dockerUtils.getDeployer(options, (error, deployer) => {
				if(error){
					return cb(error);
				}
				
				deployer.listNetworks({}, (err, networks) => {
					if (err) {
						return cb(err);
					}
					
					let found = false;
					networks.forEach((oneNetwork) => {
						if (oneNetwork.Name === 'soajsnet') {
							found = true;
						}
					});
					
					if(found){
						return cb(null, true);
					}
					else{
						let networkParams = {
							Name: 'soajsnet',
							Driver: 'overlay',
							Internal: false,
							Attachable: true,
							CheckDuplicate: true,
							EnableIPv6: false,
							IPAM: {
								Driver: 'default'
							}
						};
						
						deployer.createNetwork(networkParams, (err) => {
							return cb(err, true);
						});
					}
				});
			});
		}
		else {
			return cb(null, false);
		}
	}
452748
def ssh(ctx, cluster_id, key_file):
    """"""
    session = create_session(ctx.obj['AWS_PROFILE_NAME'])

    client = session.client('emr')
    result = client.describe_cluster(ClusterId=cluster_id)
    target_dns = result['Cluster']['MasterPublicDnsName']
    ssh_options = '-o StrictHostKeyChecking=no -o ServerAliveInterval=10'
    cmd = 'ssh {ssh_options}  -i {key_file} hadoop@{target_dns}'.format(
        ssh_options=ssh_options, key_file=key_file, target_dns=target_dns)
    subprocess.call(cmd, shell=True)
837745
def ecs_deploy(id, &block)
      service = Aws::Ecs.services(ecs_cluster_name, [resource(id)]).first
      taskdef = get_taskdef(service)

      ## convert to a hash and modify in block
      hash = taskdef_to_hash(taskdef)
      yield(hash) if block_given?

      taskdef = register_taskdef(hash)
      update_service(service, taskdef)
    end
1252643
function (options, cb) {
		let stack = options.infra.stack;
		
		let nginxDeploymentName = options.soajs.registry.code.toLowerCase() + '-nginx';
		let deployer = {};
		let deployerConfig = {
			url: `https://${options.soajs.registry.deployer.container.kubernetes.remote.nodes}:${options.soajs.registry.deployer.container.kubernetes.remote.apiPort}`,
			version: 'v1',
			auth: {
				bearer: options.soajs.registry.deployer.container.kubernetes.remote.auth.token
			},
			request: {strictSSL: false}
		};
		
		//build namespace
		let namespace = options.soajs.registry.deployer.container.kubernetes.remote.namespace.default;
		if (options.soajs.registry.deployer.container.kubernetes.remote.namespace.perService) {
			namespace += '-' + nginxDeploymentName;
		}
		
		deployer.core = new K8Api.Core(deployerConfig);
		let nginxServiceName = nginxDeploymentName + '-service';
		deployer.core.namespaces(namespace).services.get({name: nginxServiceName}, (error, service) => {
			if (error) {
				return cb(error);
			}
			
			if (!service || !service.metadata || !service.metadata.name || !service.spec) {
				return cb(new Error("Nginx deployment not found!"));
			}
			
			let DNSIPAddress;
			if (service.spec.type === 'LoadBalancer' && service.status && service.status.loadBalancer && service.status.loadBalancer.ingress) {
				DNSIPAddress = service.status.loadBalancer.ingress[0].ip; //NOTE: not sure about this, need access to a gke deployment to verify it
			} else if (service.spec.type === 'NodePort' && service.spec.clusterIP) {
				DNSIPAddress = service.spec.clusterIP;
			}
			
			let mockedResponse = {
				"id": stack.id
			};
			
			if (DNSIPAddress) {
				mockedResponse = {
					"id": stack.id,
					"dns": {
						"msg": "<table>" +
							"<thead>" +
							"<tr><th>Field Type</th><th>Field Value</th></tr>" +
							"</thead>" +
							"<tbody>" +
							"<tr><td>DNS Type</td><td>A</td></tr>" +
							"<tr class='even'><td>Domain Value</td><td>%domain%</td></tr>" +
							"<tr><td>IP Address</td><td>" + DNSIPAddress + "</td></tr>" +
							"<tr class='even'><td>TTL</td><td>5 minutes</td></tr>" +
							"</tbody>" +
							"</table>"
					}
				};
			}
			
			return cb(null, mockedResponse);
		});
	}
723488
def create(output_dir):
    """"""
    template_path = os.path.join(os.path.dirname(__file__), 'project_template')

    click.secho('Let\'s create a new component!', fg='green')
    name = click.prompt('What is the name of this component (ex. python-pip)?')

    click.secho('')
    click.secho('We assume this will be pushed to GitHub and Docker Hub eventually, but these don\'t have to exist yet.', fg='green')
    repo_owner = click.prompt('GitHub repo owner (i.e. your username or organization name)')
    repo_name = click.prompt('GitHub repo name', default=name)
    dockerhub_owner = click.prompt('Docker Hub repo owner', default=repo_owner)
    dockerhub_name = click.prompt('Docker Hub repo name', default=repo_name)

    license_owner = click.prompt('Who should be the copyright owner on project?', default=repo_owner)

    extra_context = {
        'name': name,
        'name_shields_io': name.replace('-', '--'),
        'current_year': datetime.datetime.now().year,
        'dependencies_cli_version': __version__,
        'repo_owner': repo_owner,
        'repo_name': repo_name,
        'dockerhub_owner': dockerhub_owner,
        'dockerhub_name': dockerhub_name,
        'license_owner': license_owner,
    }
    project_dir = cookiecutter(template_path, no_input=True, extra_context=extra_context, output_dir=output_dir)

    click.secho('')
    click.secho('{name} is ready to go, `cd {project_dir}` and try running `dependencies test`!'.format(name=name, project_dir=project_dir), fg='green')
    click.secho(
        'We started you out with a fully functioning component based in python.\n' +
        'Once you\'ve got a handle on how it works then you can change it to whatever language you want.'
    )
167760
function deploy(mode, target, system, containerDef, container, out, cb) {
    var executor = prepareAndGetExecutor(target, out, 'deploying');
    executor.deploy(mode, target, system, containerDef, container, out, function(err) {
      cb(err);
    });
  }
1283331
function main() {
  var argv = require('yargs')
    .usage('Usage: $0 [options]')
    .example('$0 -s https://user:pass@host/db -b <bucket>', 'Backup db to bucket')
    .options({
      'source': { alias: 's', nargs: 1, demandOption: true, describe: 'Source database URL' },
      'bucket': { alias: 'b', nargs: 1, demandOption: true, describe: 'Destination bucket' },
      'prefix': { alias: 'p', nargs: 1, describe: 'Prefix for backup object key', default: 'couchbackup' },
      's3url': { nargs: 1, describe: 'S3 endpoint URL' },
      'awsprofile': { nargs: 1, describe: 'The profile section to use in the ~/.aws/credentials file', default: 'default' }
    })
    .help('h').alias('h', 'help')
    .epilog('Copyright (C) IBM 2017')
    .argv;

  const sourceUrl = argv.source;
  const backupName = new url.URL(sourceUrl).pathname.split('/').filter(function(x) { return x; }).join('-');
  const backupBucket = argv.bucket;
  const backupKeyPrefix = `${argv.prefix}-${backupName}`;
  const shallow = argv.shallow;

  const backupKey = `${backupKeyPrefix}-${new Date().toISOString()}`;

  const s3Endpoint = argv.s3url;
  const awsProfile = argv.awsprofile;

  // Creds are from ~/.aws/credentials, environment etc. (see S3 docs).
  const awsOpts = {
    signatureVersion: 'v4',
    credentials: new AWS.SharedIniFileCredentials({ profile: awsProfile })
  };
  if (typeof s3Endpoint !== 'undefined') {
    awsOpts.endpoint = new AWS.Endpoint(s3Endpoint);
  }
  const s3 = new AWS.S3(awsOpts);

  debug(`Creating a new backup of ${s(sourceUrl)} at ${backupBucket}/${backupKey}...`);
  bucketAccessible(s3, backupBucket)
    .then(() => {
      return backupToS3(sourceUrl, s3, backupBucket, backupKey, shallow);
    })
    .then(() => {
      debug('done.');
    })
    .catch((reason) => {
      debug(`Error: ${reason}`);
      process.exit(1);
    });
}
989476
def _create_server_ec2(region,
                       access_key_id,
                       secret_access_key,
                       disk_name,
                       disk_size,
                       ami,
                       key_pair,
                       instance_type,
                       username,
                       tags={},
                       security_groups=None):
    
    conn = connect_to_ec2(region, access_key_id, secret_access_key)

    log_green("Started...")
    log_yellow("...Creating EC2 instance...")

    # we need a larger boot device to store our cached images
    ebs_volume = EBSBlockDeviceType()
    ebs_volume.size = disk_size
    bdm = BlockDeviceMapping()
    bdm[disk_name] = ebs_volume

    # get an ec2 ami image object with our choosen ami
    image = conn.get_all_images(ami)[0]
    # start a new instance
    reservation = image.run(1, 1,
                            key_name=key_pair,
                            security_groups=security_groups,
                            block_device_map=bdm,
                            instance_type=instance_type)

    # and get our instance_id
    instance = reservation.instances[0]

    #  and loop and wait until ssh is available
    while instance.state == u'pending':
        log_yellow("Instance state: %s" % instance.state)
        sleep(10)
        instance.update()
    log_green("Instance state: %s" % instance.state)
    wait_for_ssh(instance.public_dns_name)

    # update the EBS volumes to be deleted on instance termination
    for dev, bd in instance.block_device_mapping.items():
        instance.modify_attribute('BlockDeviceMapping',
                                  ["%s=%d" % (dev, 1)])

    # add a tag to our instance
    conn.create_tags([instance.id], tags)

    log_green("Public dns: %s" % instance.public_dns_name)
    # finally save the details or our new instance into the local state file
    save_ec2_state_locally(instance_id=instance.id,
                           region=region,
                           username=username,
                           access_key_id=access_key_id,
                           secret_access_key=secret_access_key)
745396
def node_ls(server=str):
    '''
    
    '''
    try:
        salt_return = {}
        client = docker.APIClient(base_url='unix://var/run/docker.sock')
        service = client.nodes(filters=({'name': server}))
        getdata = salt.utils.json.dumps(service)
        dump = salt.utils.json.loads(getdata)
        for items in dump:
            docker_version = items['Description']['Engine']['EngineVersion']
            platform = items['Description']['Platform']
            hostnames = items['Description']['Hostname']
            ids = items['ID']
            role = items['Spec']['Role']
            availability = items['Spec']['Availability']
            status = items['Status']
            version = items['Version']['Index']
            salt_return.update({'Docker Version': docker_version,
                                'Platform': platform,
                                'Hostname': hostnames,
                                'ID': ids,
                                'Roles': role,
                                'Availability': availability,
                                'Status': status,
                                'Version': version})
    except TypeError:
        salt_return = {}
        salt_return.update({'Error': 'The server arg is missing or you not targeting a Manager node?'})
    return salt_return
726748
def main():
    

    # Log info and above to console
    logging.basicConfig(
        format='%(levelname)s: %(message)s', level=logging.INFO)

    # Get command line input/output arguments
    msg = 'Instantly deploy static HTML sites to S3 at the command line.'
    parser = argparse.ArgumentParser(description=msg)
    parser.add_argument(
        'www_dir',
        help='Directory containing the HTML files for your website.'
    )
    parser.add_argument(
        'bucket_name',
        help='Name of S3 bucket to deploy to, e.g. mybucket.'
    )
    args = parser.parse_args()

    # Deploy the site to S3!
    deploy(args.www_dir, args.bucket_name)
572374
def deploy(environment_options)
      environment_parameter_guard(environment_options)
      if no_op?
        puts 'Nothing to deploy.'
        return
      end

      deployment_start_message = 'Deploying '
      deployment_start_message += "#{dynamo_tables.length} Dynamo Tables, " unless dynamo_tables.empty?
      deployment_start_message += "#{lambdas.length} Lambdas, " unless lambdas.empty?
      deployment_start_message += "#{api_gateways.length} API Gateways " unless api_gateways.empty?
      deployment_start_message += "to Environment: #{environment_options.name}"
      puts deployment_start_message

      total_time_start = Time.now

      services_time_start = total_time_start
      dynamo_tables.each { |table| table.deploy(environment_options, @dynamo_client, @region) }
      services_time_end = Time.now

      unless dynamo_tables.empty?
        puts "Deploying #{dynamo_tables.length} Table(s) took: \
        #{Time.at(services_time_end - services_time_start).utc.strftime('%H:%M:%S')}"
      end

      services_time_start = Time.now
      lambdas.each { |lambda| lambda.deploy(environment_options, @lambda_client, @region) }
      services_time_end = Time.now

      unless lambdas.empty?
        puts "Deploying #{lambdas.length} Lambda(s) took: \
        #{Time.at(services_time_end - services_time_start).utc.strftime('%H:%M:%S')}"
      end

      services_time_start = Time.now
      api_gateways.each { |apig| apig.deploy(environment_options, @api_gateway_client, @region) }
      services_time_end = Time.now

      unless api_gateways.empty?
        puts "Deploying #{api_gateways.length} API Gateway(s) took: \
        #{Time.at(services_time_end - services_time_start).utc.strftime('%H:%M:%S')}"
      end

      total_time_end = Time.now

      puts "Total API Deployment took: \
      #{Time.at(total_time_end - total_time_start).utc.strftime('%H:%M:%S')}"
      puts "Successfully deployed API to #{environment_options.name}"

      true
    end
81432
def parser_setup():
    
    parser = argparse.ArgumentParser(description="Control AWS instances from"
                                     " the command line with: list, start,"
                                     " stop or ssh.", prog='awss',
                                     usage="\tawss {command} [ 'NAME' ] "
                                     "[ '-i ID' ] [ OPTIONS ]\n\t{command} ="
                                     " list | start | stop | ssh")
    parser.add_argument('-v', '--version', action="version",
                        version="awss {0}".format(__version__))

    subparsers = parser.add_subparsers(title="For additional help on"
                                       " command parameters", dest='command',
                                       description="type 'awss {command} -h',"
                                       " where {command} is: list, start,"
                                       " stop or ssh")

    # Parser for LIST command
    parser_list = subparsers.add_parser('list', description="List AWS "
                                        "instances from the command line. "
                                        "'awss list' will list instances"
                                        " specified using combinations of "
                                        "NAME, instance-id and current-state."
                                        "  If no specifications are given, "
                                        " all instances will be listed."
                                        "  ex: 'awss list TEST "
                                        "-r' will list instances named 'TEST'"
                                        " that are currently running.",
                                        usage="\tawss list [none] [NAME] [-i "
                                        "ID] [-r] [-s] [OPTIONS]")
    parser_list.add_argument('instname', nargs='?', metavar='NAME',
                             help='specify instance by name')
    parser_list.add_argument('-i', '--id', action="store",
                             help='specify instance by id')
    parser_list.add_argument('-s', '--stopped', action='store_const',
                             dest="inst_state", const="stopped",
                             help='list stopped instances')
    parser_list.add_argument('-r', '--running', action='store_const',
                             dest="inst_state", const="running",
                             help='list running instances')
    parser_list.add_argument('-d', '--debug', action="count",
                             default=0, help=argparse.SUPPRESS)
    parser_list.set_defaults(func=cmd_list)

    # Parser for START command
    parser_start = subparsers.add_parser('start', usage="\tawss start [NAME]"
                                         " [-i ID] [-h]",
                                         description="Start an AWS instance"
                                         " from the command line.")
    parser_start.add_argument('instname', nargs='?', metavar='NAME',
                              help='specify instance by name')
    parser_start.add_argument('-i', '--id', action="store",
                              help='specify instance-id')
    parser_start.add_argument('-d', '--debug', action="count",
                              default=0, help=argparse.SUPPRESS)
    parser_start.set_defaults(func=cmd_startstop)

    # Parser for STOP command
    parser_stop = subparsers.add_parser('stop', usage="\tawss stop [NAME]"
                                        " [-i ID] [-h]",
                                        description="Stop an AWS instance"
                                        " from the command line.")
    parser_stop.add_argument('instname', nargs='?', metavar='NAME',
                             help='specify instance by name')
    parser_stop.add_argument('-i', '--id', action="store",
                             help='specify instance-id')
    parser_stop.add_argument('-d', '--debug', action="count",
                             default=0, help=argparse.SUPPRESS)
    parser_stop.set_defaults(func=cmd_startstop)

    # Parser for SSH command
    parser_ssh = subparsers.add_parser('ssh', usage="\tawss ssh [NAME]"
                                       " [-i ID] [-u USER] [-p] [-h]",
                                       description="Connect to an AWS i"
                                       "nstance via ssh.")
    parser_ssh.add_argument('instname', nargs='?', metavar='NAME',
                            help='specify instance by name')
    parser_ssh.add_argument('-i', '--id', action="store",
                            help='specify instance-id')
    parser_ssh.add_argument('-u', '--user', action="store",
                            help='override default username for ssh')
    parser_ssh.add_argument('-p', '--nopem', action="store_true",
                            default=False, help='connect without PEM key')
    parser_ssh.add_argument('-d', '--debug', action="count",
                            default=0, help=argparse.SUPPRESS)
    parser_ssh.set_defaults(func=cmd_ssh)
    return parser
543517
def run_ec2_import(self, config_file_location, description, region='us-east-1'):
        
        import_cmd = "aws ec2 import-image --description '{}' --profile '{}' --region '{}' --output 'json'" \
                     " --disk-containers file://{}"\
            .format(description, self.aws_project, region, config_file_location)
        try:
            res = subprocess.check_output(shlex.split(import_cmd), stderr=subprocess.STDOUT)
        except subprocess.CalledProcessError as e:
            print "Error importing to ec2"
            print "output: {}".format(e.output)
            sys.exit(5)

        print "got res: {}".format(res)
        res_json = json.loads(res)
        task_running, import_id = self.check_task_status_and_id(res_json)
        return import_id