/*
gcloud compute images create example-image --source-disk example-disk --source-disk-zone ZONE
Can do this with the command line utility, but not with the API
Partially implemented code to do it with the API once it catches up...
2423
@Override
    public MachineImage capture(@Nonnull ImageCreateOptions options, @Nullable AsynchronousTask<MachineImage> task) throws CloudException, InternalException {
        Compute gce = provider.getGoogleCompute();
        ServerSupport server = new ServerSupport(provider);
        Image imageContent = new Image();

        try {
            VirtualMachine vm = server.getVirtualMachine(options.getVirtualMachineId());

            String[] disks = vm.getProviderVolumeIds(provider);
            server.terminateVm(options.getVirtualMachineId());

            Disk disk = gce.disks().get(provider.getContext().getAccountNumber(), vm.getProviderDataCenterId(), disks[0]).execute(); 
            imageContent.setName(getCapabilities().getImageNamingConstraints().convertToValidName(options.getName(), Locale.US));
            imageContent.setKind("compute#disk");
            imageContent.setSourceDisk(disk.getSelfLink());

            String derivedFrom = disk.getSourceImage().replaceAll(".*/", "");
            if (Platform.guess(derivedFrom) == Platform.UNKNOWN) {
                Boolean done = false;
                try {
                    while (!done) {
                        Image imagePrior = gce.images().get(provider.getContext().getAccountNumber(), derivedFrom).execute();
                        if (imagePrior.getDescription().startsWith("Derived from ")) {
                            derivedFrom = imagePrior.getDescription().replaceAll("Derived from ", "");
                            if (Platform.guess(derivedFrom) != Platform.UNKNOWN) {
                                done = true;
                                imageContent.setDescription(imagePrior.getDescription());
                            }
                        }
                    }
                } catch (Exception e) {
                    imageContent.setDescription(derivedFrom);  // best guess.
                }

            } else {
                imageContent.setDescription("Derived from " + derivedFrom);
            }
            Operation job = gce.images().insert(provider.getContext().getAccountNumber(), imageContent).execute();
            GoogleMethod method = new GoogleMethod(provider);
            method.getOperationComplete(provider.getContext(), job, GoogleOperationType.GLOBAL_OPERATION, "", "");

            String zone = disk.getZone();
            zone = zone.substring(zone.lastIndexOf("/") + 1);
            // now delete source disk...
            job = gce.disks().delete(provider.getContext().getAccountNumber(), zone, disk.getName()).execute();
            method.getOperationComplete(provider.getContext(), job, GoogleOperationType.ZONE_OPERATION, "", zone);
        } catch (Exception ex) {
            logger.error(ex.getMessage()); // CloudException: An error occurred: Invalid value for field 'image.hasRawDisk': 'false'.
            if (ex.getClass() == GoogleJsonResponseException.class) {
                GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex;
                throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage());
            } else
                throw new CloudException("An error occurred while deleting the image: " + ex.getMessage());
        }

        return getImage(provider.getContext().getAccountNumber() + "_" + options.getName());
    }
534715
def create_server_ec2(connection,
                      region,
                      disk_name,
                      disk_size,
                      ami,
                      key_pair,
                      instance_type,
                      tags={},
                      security_groups=None,
                      delete_on_termination=True,
                      log=False,
                      wait_for_ssh_available=True):
    

    if log:
        log_green("Started...")
        log_yellow("...Creating EC2 instance...")

    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 = connection.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':
        if log:
            log_yellow("Instance state: %s" % instance.state)
        sleep(10)
        instance.update()
    if log:
        log_green("Instance state: %s" % instance.state)
    if wait_for_ssh_available:
        wait_for_ssh(instance.public_dns_name)

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

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

    if log:
        log_green("Public dns: %s" % instance.public_dns_name)

    # returns our new instance
    return instance
221444
def create_server
      @log.info "Creating new server..."

      memory = ((is_cloudsigma? and @appliance_config.hardware.memory < 512) ? 512 : @appliance_config.hardware.memory)

      body = hash_to_request(
          'name' => "#{@appliance_config.name}-#{@appliance_config.version}.#{@appliance_config.release}",
          'cpu' => @appliance_config.hardware.cpus * 1000, # MHz
          'smp' => 'auto',
          'mem' => memory,
          'persistent' => 'true', # hack
          'ide:0:0' => @plugin_config['drive_uuid'],
          'boot' => 'ide:0:0',
          'nic:0:model' => 'e1000',
          'nic:0:dhcp' => 'auto',
          'vnc:ip' => 'auto',
          'vnc:password' => (0...8).map { (('a'..'z').to_a + ('A'..'Z').to_a)[rand(52)] }.join # 8 character VNC password
      )

      begin
        path = is_cloudsigma? ? '/servers/create' : '/servers/create/stopped'
        ret = response_to_hash(RestClient.post(api_url(path), body))

        @log.info "Server was registered with '#{ret['name']}' name as '#{ret['server']}' UUID. Use web UI or API tools to start your server."
      rescue => e
        @log.error e.info
        raise PluginError, "An error occurred while creating the server, #{e.message}. See logs for more info."
      end
    end
1302538
def avail_images(call=None):
    '''
    
    '''
    if call == 'action':
        raise SaltCloudSystemExit(
            'The avail_images function must be called with '
            '-f or --function, or with the --list-images option'
        )

    user = config.get_cloud_config_value(
        'user', get_configured_provider(), __opts__, search_global=False
    )

    img_url = config.get_cloud_config_value(
        'image_url',
        get_configured_provider(),
        __opts__,
        search_global=False,
        default='{0}{1}/{2}/images'.format(DEFAULT_LOCATION, JOYENT_API_HOST_SUFFIX, user)
    )

    if not img_url.startswith('http://') and not img_url.startswith('https://'):
        img_url = '{0}://{1}'.format(_get_proto(), img_url)

    rcode, data = query(command='my/images', method='GET')
    log.debug(data)

    ret = {}
    for image in data:
        ret[image['name']] = image
    return ret
1060390
func CreateGCECloudWithCloud(config *CloudConfig, c cloud.Cloud) (*Cloud, error) {
	gceCloud, err := CreateGCECloud(config)
	if err == nil {
		gceCloud.c = c
	}
	return gceCloud, err
}
1035815
public Operation createImage(String image, OperationOption... options) {
    ImageInfo imageInfo = ImageInfo.of(ImageId.of(image), DiskImageConfiguration.of(getDiskId()));
    return compute.create(imageInfo, options);
  }
1340861
def gcs(line, cell=None):
  
  parser = google.datalab.utils.commands.CommandParser(prog='%gcs', description="""
Execute various Google Cloud Storage related operations. Use "%gcs <command> -h"
for help on a specific command.
""")

  # TODO(gram): consider adding a move command too. I did try this already using the
  # objects.patch API to change the object name but that fails with an error:
  #
  # Value 'newname' in content does not agree with value 'oldname'. This can happen when a value
  # set through a parameter is inconsistent with a value set in the request.
  #
  # This is despite 'name' being identified as writable in the storage API docs.
  # The alternative would be to use a copy/delete.
  copy_parser = parser.subcommand('copy', 'Copy one or more Google Cloud Storage objects to a '
                                          'different location.')
  copy_parser.add_argument('-s', '--source', help='The name of the object(s) to copy', nargs='+')
  copy_parser.add_argument('-d', '--destination', required=True,
                           help='The copy destination. For multiple source objects this must be a '
                                'bucket.')
  copy_parser.set_defaults(func=_gcs_copy)

  create_parser = parser.subcommand('create', 'Create one or more Google Cloud Storage buckets.')
  create_parser.add_argument('-p', '--project', help='The project associated with the objects')
  create_parser.add_argument('-b', '--bucket', help='The name of the bucket(s) to create',
                             nargs='+')
  create_parser.set_defaults(func=_gcs_create)

  delete_parser = parser.subcommand('delete', 'Delete one or more Google Cloud Storage buckets or '
                                              'objects.')
  delete_parser.add_argument('-b', '--bucket', nargs='*',
                             help='The name of the bucket(s) to remove')
  delete_parser.add_argument('-o', '--object', nargs='*',
                             help='The name of the object(s) to remove')
  delete_parser.set_defaults(func=_gcs_delete)

  list_parser = parser.subcommand('list', 'List buckets in a project, or contents of a bucket.')
  list_parser.add_argument('-p', '--project', help='The project associated with the objects')
  list_parser.add_argument('-o', '--objects',
                           help='List objects under the given Google Cloud Storage path',
                           nargs='?')
  list_parser.set_defaults(func=_gcs_list)

  read_parser = parser.subcommand('read', 'Read the contents of a Google Cloud Storage object into '
                                          'a Python variable.')
  read_parser.add_argument('-o', '--object', help='The name of the object to read',
                           required=True)
  read_parser.add_argument('-v', '--variable', required=True,
                           help='The name of the Python variable to set')
  read_parser.set_defaults(func=_gcs_read)

  view_parser = parser.subcommand('view', 'View the contents of a Google Cloud Storage object.')
  view_parser.add_argument('-n', '--head', type=int, default=20,
                           help='The number of initial lines to view')
  view_parser.add_argument('-t', '--tail', type=int, default=20,
                           help='The number of lines from end to view')
  view_parser.add_argument('-o', '--object', help='The name of the object to view',
                           required=True)
  view_parser.set_defaults(func=_gcs_view)

  write_parser = parser.subcommand('write', 'Write the value of a Python variable to a Google '
                                            'Cloud Storage object.')
  write_parser.add_argument('-v', '--variable', help='The name of the source Python variable',
                            required=True)
  write_parser.add_argument('-o', '--object', required=True,
                            help='The name of the destination Google Cloud Storage object to write')
  write_parser.add_argument('-c', '--content_type', help='MIME type', default='text/plain')
  write_parser.set_defaults(func=_gcs_write)

  return google.datalab.utils.commands.handle_magic_line(line, cell, parser)
556288
def create(vm_, call=None):
    '''
    '''
    prov = get_configured_provider(vm_)
    if not prov:
        return
    # we cant use profile as a configuration key as it conflicts
    # with salt cloud internals
    profile = vm_.get(
        'lxc_profile',
        vm_.get('container_profile', None))

    event_data = vm_.copy()
    event_data['profile'] = profile

    __utils__['cloud.fire_event'](
        'event',
        'starting create',
        'salt/cloud/{0}/creating'.format(vm_['name']),
        args=__utils__['cloud.filter_event']('creating', event_data, ['name', 'profile', 'provider', 'driver']),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    ret = {'name': vm_['name'], 'changes': {}, 'result': True, 'comment': ''}
    if 'pub_key' not in vm_ and 'priv_key' not in vm_:
        log.debug('Generating minion keys for %s', vm_['name'])
        vm_['priv_key'], vm_['pub_key'] = salt.utils.cloud.gen_keys(
            salt.config.get_cloud_config_value(
                'keysize', vm_, __opts__))
    # get the minion key pair to distribute back to the container
    kwarg = copy.deepcopy(vm_)
    kwarg['host'] = prov['target']
    kwarg['profile'] = profile

    __utils__['cloud.fire_event'](
        'event',
        'requesting instance',
        'salt/cloud/{0}/requesting'.format(vm_['name']),
        args=__utils__['cloud.filter_event']('requesting', vm_, ['name', 'profile', 'provider', 'driver']),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    cret = _runner().cmd('lxc.cloud_init', [vm_['name']], kwarg=kwarg)
    ret['runner_return'] = cret
    ret['result'] = cret['result']
    if not ret['result']:
        ret['Error'] = 'Error while creating {0},'.format(vm_['name'])
    else:
        ret['changes']['created'] = 'created'

    # When using cloud states to manage LXC containers
    # __opts__['profile'] is not implicitly reset between operations
    # on different containers. However list_nodes will hide container
    # if profile is set in opts assuming that it have to be created.
    # But in cloud state we do want to check at first if it really
    # exists hence the need to remove profile from global opts once
    # current container is created.
    if 'profile' in __opts__:
        __opts__['internal_lxc_profile'] = __opts__['profile']
        del __opts__['profile']

    __utils__['cloud.fire_event'](
        'event',
        'created instance',
        'salt/cloud/{0}/created'.format(vm_['name']),
        args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    return ret
1243471
def create(gandi, name, vm, size, snapshotprofile, datacenter, source,
           background):
    
    try:
        gandi.datacenter.is_opened(datacenter, 'iaas')
    except DatacenterLimited as exc:
        gandi.echo('/!\ Datacenter %s will be closed on %s, '
                   'please consider using another datacenter.' %
                   (datacenter, exc.date))

    if vm:
        vm_dc = gandi.iaas.info(vm)
        vm_dc_id = vm_dc['datacenter_id']
        dc_id = int(gandi.datacenter.usable_id(datacenter))
        if vm_dc_id != dc_id:
            gandi.echo('/!\ VM %s datacenter will be used instead of %s.'
                       % (vm, datacenter))
        datacenter = vm_dc_id

    output_keys = ['id', 'type', 'step']
    name = name or randomstring('vdi')

    disk_type = 'data'
    oper = gandi.disk.create(name, vm, size, snapshotprofile, datacenter,
                             source, disk_type, background)

    if background:
        output_generic(gandi, oper, output_keys)

    return oper
978918
def create(vm_):
    '''
    
    '''
    deploy = config.get_cloud_config_value('deploy', vm_, __opts__)
    key_filename = config.get_cloud_config_value(
        'ssh_key_file', vm_, __opts__, search_global=False, default=None
    )
    if key_filename is not None and not os.path.isfile(key_filename):
        raise SaltCloudConfigError(
            'The defined ssh_key_file \'{0}\' does not exist'.format(
                key_filename
            )
        )

    vm_['key_filename'] = key_filename

    __utils__['cloud.fire_event'](
        'event',
        'starting create',
        'salt/cloud/{0}/creating'.format(vm_['name']),
        args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )
    conn = get_conn()

    if 'instance_id' in vm_:
        # This was probably created via another process, and doesn't have
        # things like salt keys created yet, so let's create them now.
        if 'pub_key' not in vm_ and 'priv_key' not in vm_:
            log.debug('Generating minion keys for \'%s\'', vm_['name'])
            vm_['priv_key'], vm_['pub_key'] = __utils__['cloud.gen_keys'](
                config.get_cloud_config_value(
                    'keysize',
                    vm_,
                    __opts__
                )
            )
    else:
        # Put together all of the information required to request the instance,
        # and then fire off the request for it
        request_instance(conn=conn, call='action', vm_=vm_)
    data = show_instance(vm_.get('instance_id', vm_['name']), conn=conn, call='action')
    log.debug('VM is now running')

    def __query_node(vm_):
        data = show_instance(vm_['name'], conn=conn, call='action')
        if 'wait_for_metadata' in vm_:
            for key, value in six.iteritems(vm_.get('wait_for_metadata', {})):
                log.debug('Waiting for metadata: %s=%s', key, value)
                if data['metadata'].get(key, None) != value:
                    log.debug('Metadata is not ready: %s=%s', key, data['metadata'].get(key))
                    return False
        return preferred_ip(vm_, data[ssh_interface(vm_)])
    try:
        ip_address = __utils__['cloud.wait_for_fun'](
            __query_node,
            vm_=vm_
        )
    except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
        try:
            # It might be already up, let's destroy it!
            destroy(vm_['name'])
        except SaltCloudSystemExit:
            pass
        finally:
            raise SaltCloudSystemExit(six.text_type(exc))
    log.debug('Using IP address %s', ip_address)

    salt_interface = __utils__['cloud.get_salt_interface'](vm_, __opts__)
    salt_ip_address = preferred_ip(vm_, data[salt_interface])
    log.debug('Salt interface set to: %s', salt_ip_address)

    if not ip_address:
        raise SaltCloudSystemExit('A valid IP address was not found')

    vm_['ssh_host'] = ip_address
    vm_['salt_host'] = salt_ip_address

    ret = __utils__['cloud.bootstrap'](vm_, __opts__)
    ret.update(data)

    log.info('Created Cloud VM \'%s\'', vm_['name'])
    log.debug(
        '\'%s\' VM creation details:\n%s',
        vm_['name'], pprint.pformat(data)
    )

    event_data = {
        'name': vm_['name'],
        'profile': vm_['profile'],
        'provider': vm_['driver'],
        'instance_id': data['id'],
        'floating_ips': data['floating_ips'],
        'fixed_ips': data['fixed_ips'],
        'private_ips': data['private_ips'],
        'public_ips': data['public_ips'],
    }

    __utils__['cloud.fire_event'](
        'event',
        'created instance',
        'salt/cloud/{0}/created'.format(vm_['name']),
        args=__utils__['cloud.filter_event']('created', event_data, list(event_data)),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )
    __utils__['cloud.cachedir_index_add'](vm_['name'], vm_['profile'], 'nova', vm_['driver'])
    return ret
797390
def create(self, vm_, local_master=True):
        '''
        
        '''
        output = {}

        minion_dict = salt.config.get_cloud_config_value(
            'minion', vm_, self.opts, default={}
        )

        alias, driver = vm_['provider'].split(':')
        fun = '{0}.create'.format(driver)
        if fun not in self.clouds:
            log.error(
                'Creating \'%s\' using \'%s\' as the provider '
                'cannot complete since \'%s\' is not available',
                vm_['name'], vm_['provider'], driver
            )
            return

        deploy = salt.config.get_cloud_config_value('deploy', vm_, self.opts)
        make_master = salt.config.get_cloud_config_value(
            'make_master',
            vm_,
            self.opts
        )

        if deploy:
            if not make_master and 'master' not in minion_dict:
                log.warning(
                    'There\'s no master defined on the \'%s\' VM settings.',
                    vm_['name']
                )

            if 'pub_key' not in vm_ and 'priv_key' not in vm_:
                log.debug('Generating minion keys for \'%s\'', vm_['name'])
                priv, pub = salt.utils.cloud.gen_keys(
                    salt.config.get_cloud_config_value(
                        'keysize',
                        vm_,
                        self.opts
                    )
                )
                vm_['pub_key'] = pub
                vm_['priv_key'] = priv
        else:
            # Note(pabelanger): We still reference pub_key and priv_key when
            # deploy is disabled.
            vm_['pub_key'] = None
            vm_['priv_key'] = None

        key_id = minion_dict.get('id', vm_['name'])

        domain = vm_.get('domain')
        if vm_.get('use_fqdn') and domain:
            minion_dict['append_domain'] = domain

        if 'append_domain' in minion_dict:
            key_id = '.'.join([key_id, minion_dict['append_domain']])

        if make_master is True and 'master_pub' not in vm_ and 'master_pem' not in vm_:
            log.debug('Generating the master keys for \'%s\'', vm_['name'])
            master_priv, master_pub = salt.utils.cloud.gen_keys(
                salt.config.get_cloud_config_value(
                    'keysize',
                    vm_,
                    self.opts
                )
            )
            vm_['master_pub'] = master_pub
            vm_['master_pem'] = master_priv

        if local_master is True and deploy is True:
            # Accept the key on the local master
            salt.utils.cloud.accept_key(
                self.opts['pki_dir'], vm_['pub_key'], key_id
            )

        vm_['os'] = salt.config.get_cloud_config_value(
            'script',
            vm_,
            self.opts
        )

        try:
            vm_['inline_script'] = salt.config.get_cloud_config_value(
                'inline_script',
                vm_,
                self.opts
            )
        except KeyError:
            pass

        try:
            alias, driver = vm_['provider'].split(':')
            func = '{0}.create'.format(driver)
            with salt.utils.context.func_globals_inject(
                self.clouds[fun],
                __active_provider_name__=':'.join([alias, driver])
            ):
                output = self.clouds[func](vm_)
            if output is not False and 'sync_after_install' in self.opts:
                if self.opts['sync_after_install'] not in (
                        'all', 'modules', 'states', 'grains'):
                    log.error('Bad option for sync_after_install')
                    return output

                # A small pause helps the sync work more reliably
                time.sleep(3)

                start = int(time.time())
                while int(time.time()) < start + 60:
                    # We'll try every <timeout> seconds, up to a minute
                    mopts_ = salt.config.DEFAULT_MASTER_OPTS
                    conf_path = '/'.join(self.opts['conf_file'].split('/')[:-1])
                    mopts_.update(
                        salt.config.master_config(
                            os.path.join(conf_path,
                                         'master')
                        )
                    )

                    client = salt.client.get_local_client(mopts=mopts_)

                    ret = client.cmd(
                        vm_['name'],
                        'saltutil.sync_{0}'.format(self.opts['sync_after_install']),
                        timeout=self.opts['timeout']
                    )
                    if ret:
                        log.info(
                            six.u('Synchronized the following dynamic modules: '
                                  '  {0}').format(ret)
                        )
                        break
        except KeyError as exc:
            log.exception(
                'Failed to create VM %s. Configuration value %s needs '
                'to be set', vm_['name'], exc
            )
        # If it's a map then we need to respect the 'requires'
        # so we do it later
        try:
            opt_map = self.opts['map']
        except KeyError:
            opt_map = False
        if self.opts['parallel'] and self.opts['start_action'] and not opt_map:
            log.info('Running %s on %s', self.opts['start_action'], vm_['name'])
            client = salt.client.get_local_client(mopts=self.opts)
            action_out = client.cmd(
                vm_['name'],
                self.opts['start_action'],
                timeout=self.opts['timeout'] * 60
            )
            output['ret'] = action_out
        return output
1024023
public void createHardDisk(int diskSizeMB, VirtualDiskType type, VirtualDiskMode mode) throws Exception {
        VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec();
        VirtualDeviceConfigSpec diskSpec = new VirtualDeviceConfigSpec();

        VirtualDiskFlatVer2BackingInfo diskfileBacking = new VirtualDiskFlatVer2BackingInfo();
        diskfileBacking.setFileName("");
        diskfileBacking.setDiskMode(mode.toString());
        diskfileBacking.setThinProvisioned(type == VirtualDiskType.thin);

        VirtualSCSIController scsiController = getFirstAvailableController(VirtualSCSIController.class);
        int unitNumber = getFirstFreeUnitNumberForController(scsiController);
        VirtualDisk disk = new VirtualDisk();
        disk.setControllerKey(scsiController.key);
        disk.setUnitNumber(unitNumber);
        disk.setBacking(diskfileBacking);
        disk.setCapacityInKB(1024 * diskSizeMB);
        disk.setKey(-1);

        diskSpec.setOperation(VirtualDeviceConfigSpecOperation.add);
        diskSpec.setFileOperation(VirtualDeviceConfigSpecFileOperation.create);
        diskSpec.setDevice(disk);
        VirtualDeviceConfigSpec[] vdiskSpecArray = {diskSpec};

        vmConfigSpec.setDeviceChange(vdiskSpecArray);
        Task task = vm.reconfigVM_Task(vmConfigSpec);

        task.waitForTask(200, 100);
    }
350341
function buildNatInstance(imageId, zones = [], { name = 'NatInstance' } = {}) {
  if (!imageId) {
    return {};
  }
  if (!Array.isArray(zones) || zones.length < 1) {
    return {};
  }

  return {
    [name]: {
      Type: 'AWS::EC2::Instance',
      DependsOn: 'InternetGatewayAttachment',
      Properties: {
        AvailabilityZone: {
          'Fn::Select': ['0', zones],
        },
        BlockDeviceMappings: [
          {
            DeviceName: '/dev/xvda',
            Ebs: {
              VolumeSize: 10,
              VolumeType: 'gp2',
              DeleteOnTermination: true,
            },
          },
        ],
        ImageId: imageId, // amzn-ami-vpc-nat-hvm-2018.03.0.20181116-x86_64-ebs
        InstanceType: 't2.micro',
        Monitoring: false,
        NetworkInterfaces: [
          {
            AssociatePublicIpAddress: true,
            DeleteOnTermination: true,
            Description: 'eth0',
            DeviceIndex: '0',
            GroupSet: [
              {
                Ref: 'NatSecurityGroup',
              },
            ],
            SubnetId: {
              Ref: `${PUBLIC_SUBNET}Subnet1`,
            },
          },
        ],
        SourceDestCheck: false, // required for a NAT instance
        Tags: [
          {
            Key: 'Name',
            Value: {
              'Fn::Join': [
                '-',
                [
                  {
                    Ref: 'AWS::StackName',
                  },
                  'nat',
                ],
              ],
            },
          },
        ],
      },
    },
  };
}
822536
@Override
  @VisibleForTesting
  protected void configureBuckets(GoogleCloudStorageFileSystem gcsFs) throws IOException {
    rootBucket = initUri.getAuthority();
    checkArgument(rootBucket != null, "No bucket specified in GCS URI: %s", initUri);
    // Validate root bucket name
    pathCodec.getPath(rootBucket, /* objectName= */ null, /* allowEmptyObjectName= */ true);
    logger.atFine().log(
        "GHFS.configureBuckets: GoogleHadoopFileSystem root in bucket: %s", rootBucket);
  }
241414
def show_image(kwargs, call=None):
    '''
    
    '''
    if call != 'function':
        raise SaltCloudSystemExit(
            'The show_image action must be called with -f or --function.'
        )

    params = {'ImageId.1': kwargs['image'],
              'Action': 'DescribeImages'}
    result = aws.query(params,
                       setname='tagSet',
                       location=get_location(),
                       provider=get_provider(),
                       opts=__opts__,
                       sigver='4')
    log.info(result)

    return result
749963
def copy_topology_image(source, target):
    
    files = glob.glob(os.path.join(source, '*.png'))

    for file in files:
        shutil.copy(file, target)
493028
def create(cls, datacenter, memory, cores, ip_version, bandwidth,
               login, password, hostname, image, run, background, sshkey,
               size, vlan, ip, script, script_args, ssh):
        """"""
        from gandi.cli.modules.network import Ip, Iface
        if not background and not cls.intty():
            background = True

        datacenter_id_ = int(Datacenter.usable_id(datacenter))

        if not hostname:
            hostname = randomstring('vm')
            disk_name = 'sys_%s' % hostname[2:]
        else:
            disk_name = 'sys_%s' % hostname.replace('.', '')

        vm_params = {
            'hostname': hostname,
            'datacenter_id': datacenter_id_,
            'memory': memory,
            'cores': cores,
        }

        if login:
            vm_params['login'] = login

        if run:
            vm_params['run'] = run

        if password:
            vm_params['password'] = password

        if ip_version:
            vm_params['ip_version'] = ip_version
            vm_params['bandwidth'] = bandwidth

        if script:
            with open(script) as fd:
                vm_params['script'] = fd.read()
            if script_args:
                vm_params['script_args'] = script_args

        vm_params.update(cls.convert_sshkey(sshkey))

        # XXX: name of disk is limited to 15 chars in ext2fs, ext3fs
        # but api allow 255, so we limit to 15 for now
        disk_params = {'datacenter_id': vm_params['datacenter_id'],
                       'name': disk_name[:15]}

        if size:
            if isinstance(size, tuple):
                prefix, size = size
            disk_params['size'] = size

        sys_disk_id_ = int(Image.usable_id(image, datacenter_id_))

        ip_summary = []
        if ip_version == 4:
            ip_summary = ['v4', 'v6']
        elif ip_version == 6:
            ip_summary = ['v6']

        if vlan:
            ip_ = None
            ip_summary.append('private')
            if ip:
                try:
                    ip_ = Ip.info(ip)
                except Exception:
                    pass
                else:
                    if not Ip._check_and_detach(ip_, None):
                        return
            if ip_:
                iface_id = ip_['iface_id']
            else:
                ip_create = Ip.create(4,
                                      vm_params['datacenter_id'],
                                      bandwidth,
                                      None,
                                      vlan,
                                      ip)

                iface_id = ip_create['iface_id']

            # if there is a public ip, will attach this one later, else give
            # the iface to vm.create
            if not ip_version:
                vm_params['iface_id'] = iface_id

        result = cls.call('hosting.vm.create_from', vm_params, disk_params,
                          sys_disk_id_)

        cls.echo('* Configuration used: %d cores, %dMb memory, ip %s, '
                 'image %s, hostname: %s, datacenter: %s' %
                 (cores, memory, '+'.join(ip_summary), image, hostname,
                  datacenter))

        # background mode, bail out now (skip interactive part)
        if background and (not vlan or not ip_version):
            return result

        # interactive mode, run a progress bar
        cls.echo('Creating your Virtual Machine %s.' % hostname)
        cls.display_progress(result)
        cls.echo('Your Virtual Machine %s has been created.' % hostname)

        vm_id = None
        for oper in result:
            if oper.get('vm_id'):
                vm_id = oper.get('vm_id')
                break

        if vlan and ip_version:
            attach = Iface._attach(iface_id, vm_id)
            if background:
                return attach

        if 'ssh_key' not in vm_params and 'keys' not in vm_params:
            return

        if vm_id and ip_version:
            cls.wait_for_sshd(vm_id)
            if ssh:
                cls.ssh_keyscan(vm_id)
                cls.ssh(vm_id, 'root', None)