示例#1
0
    def Run(self, args):
        """Creates and returns an InstanceGroups.Insert request.

    Args:
      args: the argparse arguments that this command was invoked with.

    Returns:
      request: a ComputeInstanceGroupsInsertRequest message object
    """
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client

        group_ref = (Create.ZONAL_INSTANCE_GROUP_ARG.ResolveAsResource(
            args,
            holder.resources,
            default_scope=compute_scope.ScopeEnum.ZONE,
            scope_lister=flags.GetDefaultScopeLister(client)))
        zone_resource_fetcher = zone_utils.ZoneResourceFetcher(client)
        zone_resource_fetcher.WarnForZonalCreation([group_ref])

        request = client.messages.ComputeInstanceGroupsInsertRequest(
            instanceGroup=client.messages.InstanceGroup(
                name=group_ref.Name(), description=args.description),
            zone=group_ref.zone,
            project=group_ref.project)

        return client.MakeRequests([(client.apitools_client.instanceGroups,
                                     'Insert', request)])
示例#2
0
  def CreateRequests(self, args):
    """Creates and returns an InstanceGroups.Insert request.

    Args:
      args: the argparse arguments that this command was invoked with.

    Returns:
      request: a ComputeInstanceGroupsInsertRequest message object
    """
    group_ref = (
        instance_groups_flags.ZONAL_INSTANCE_GROUP_ARG.ResolveAsResource(
            args, self.resources,
            default_scope=compute_scope.ScopeEnum.ZONE,
            scope_lister=flags.GetDefaultScopeLister(
                self.compute_client, self.project)))
    zone_resource_fetcher = zone_utils.ZoneResourceFetcher(self.compute_client)
    zone_resource_fetcher.WarnForZonalCreation([group_ref])

    request = self.messages.ComputeInstanceGroupsInsertRequest(
        instanceGroup=self.messages.InstanceGroup(
            name=group_ref.Name(),
            description=args.description),
        zone=group_ref.zone,
        project=self.project)

    return [request]
def GetInstanceRefs(args, client, holder):
  instance_refs = flags.INSTANCES_ARG.ResolveAsResource(
      args,
      holder.resources,
      scope_lister=compute_flags.GetDefaultScopeLister(client))
  # Check if the zone is deprecated or has maintenance coming.
  zone_resource_fetcher = zone_utils.ZoneResourceFetcher(client)
  zone_resource_fetcher.WarnForZonalCreation(instance_refs)
  return instance_refs
示例#4
0
 def WarnAboutScopeDeprecationsAndMaintenance(self, disk_refs, client):
   # Check if the zone is deprecated or has maintenance coming.
   zone_resource_fetcher = zone_utils.ZoneResourceFetcher(client)
   zone_resource_fetcher.WarnForZonalCreation(
       (ref for ref in disk_refs if ref.Collection() == 'compute.disks'))
   # Check if the region is deprecated or has maintenance coming.
   region_resource_fetcher = region_utils.RegionResourceFetcher(client)
   region_resource_fetcher.WarnForRegionalCreation(
       (ref for ref in disk_refs if ref.Collection() == 'compute.regionDisks'))
示例#5
0
 def CreateGroupReference(self, args, client, resources):
     group_ref = (instance_groups_flags.GetInstanceGroupManagerArg(
     ).ResolveAsResource)(args,
                          resources,
                          default_scope=compute_scope.ScopeEnum.ZONE,
                          scope_lister=flags.GetDefaultScopeLister(client))
     if _IsZonalGroup(group_ref):
         zonal_resource_fetcher = zone_utils.ZoneResourceFetcher(client)
         zonal_resource_fetcher.WarnForZonalCreation([group_ref])
     return group_ref
示例#6
0
def WarnAboutScopeDeprecations(ips_refs, client):
    # Check if the zone is deprecated.
    zone_resource_fetcher = zone_utils.ZoneResourceFetcher(client)
    zone_resource_fetcher.WarnForZonalCreation(
        (ref for ref in ips_refs
         if ref.Collection() == 'compute.zoneInPlaceSnapshots'))
    # Check if the region is deprecated.
    region_resource_fetcher = region_utils.RegionResourceFetcher(client)
    region_resource_fetcher.WarnForRegionalCreation(
        (ref for ref in ips_refs
         if ref.Collection() == 'compute.regionInPlaceSnapshots'))
示例#7
0
 def CreateGroupReference(self, args):
     group_ref = (instance_groups_flags.
                  MULTISCOPE_INSTANCE_GROUP_MANAGER_ARG.ResolveAsResource)(
                      args,
                      self.resources,
                      default_scope=compute_scope.ScopeEnum.ZONE,
                      scope_lister=flags.GetDefaultScopeLister(
                          self.compute_client))
     if _IsZonalGroup(group_ref):
         zonal_resource_fetcher = zone_utils.ZoneResourceFetcher(
             self.compute_client)
         zonal_resource_fetcher.WarnForZonalCreation([group_ref])
     return group_ref
示例#8
0
 def CreateGroupReference(self, args, client, resources):
     if args.zones:
         zone_ref = resources.Parse(
             args.zones[0],
             collection='compute.zones',
             params={'project': properties.VALUES.core.project.GetOrFail})
         region = utils.ZoneNameToRegionName(zone_ref.Name())
         return resources.Parse(
             args.name,
             params={
                 'region': region,
                 'project': properties.VALUES.core.project.GetOrFail
             },
             collection='compute.regionInstanceGroupManagers')
     group_ref = (instance_groups_flags.GetInstanceGroupManagerArg(
     ).ResolveAsResource)(args,
                          resources,
                          default_scope=compute_scope.ScopeEnum.ZONE,
                          scope_lister=flags.GetDefaultScopeLister(client))
     if _IsZonalGroup(group_ref):
         zonal_resource_fetcher = zone_utils.ZoneResourceFetcher(client)
         zonal_resource_fetcher.WarnForZonalCreation([group_ref])
     return group_ref
示例#9
0
    def Run(self, args):
        compute_holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = compute_holder.client

        disk_refs = self.ValidateAndParse(args, compute_holder)

        size_gb = utils.BytesToGb(args.size)

        from_image = args.image or args.image_family
        if not size_gb and not args.source_snapshot and not from_image:
            if args.type and 'pd-ssd' in args.type:
                size_gb = constants.DEFAULT_SSD_DISK_SIZE_GB
            else:
                size_gb = constants.DEFAULT_STANDARD_DISK_SIZE_GB

        utils.WarnIfDiskSizeIsTooSmall(size_gb, args.type)

        requests = []

        # Check if the zone is deprecated or has maintenance coming.
        zone_resource_fetcher = zone_utils.ZoneResourceFetcher(client)
        zone_resource_fetcher.WarnForZonalCreation(
            (ref for ref in disk_refs if ref.Collection() == 'compute.disks'))
        # Check if the region is deprecated or has maintenance coming.
        region_resource_fetcher = region_utils.RegionResourceFetcher(client)
        region_resource_fetcher.WarnForRegionalCreation(
            (ref for ref in disk_refs
             if ref.Collection() == 'compute.regionDisks'))

        project_to_source_image = {}

        image_expander = image_utils.ImageExpander(client,
                                                   compute_holder.resources)

        for disk_ref in disk_refs:
            if from_image:
                if disk_ref.project not in project_to_source_image:
                    source_image_uri, _ = image_expander.ExpandImageFlag(
                        user_project=disk_ref.project,
                        image=args.image,
                        image_family=args.image_family,
                        image_project=args.image_project,
                        return_image_resource=False)
                    project_to_source_image[
                        disk_ref.project] = argparse.Namespace()
                    project_to_source_image[
                        disk_ref.project].uri = source_image_uri
            else:
                project_to_source_image[
                    disk_ref.project] = argparse.Namespace()
                project_to_source_image[disk_ref.project].uri = None

        snapshot_ref = disks_flags.SOURCE_SNAPSHOT_ARG.ResolveAsResource(
            args, compute_holder.resources)
        if snapshot_ref:
            snapshot_uri = snapshot_ref.SelfLink()
        else:
            snapshot_uri = None

        # This feature is only exposed in alpha/beta
        allow_rsa_encrypted = self.ReleaseTrack() in [
            base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA
        ]
        csek_keys = csek_utils.CsekKeyStore.FromArgs(args, allow_rsa_encrypted)

        for project in project_to_source_image:
            source_image_uri = project_to_source_image[project].uri
            project_to_source_image[project].keys = (
                csek_utils.MaybeLookupKeyMessagesByUri(
                    csek_keys, compute_holder.resources,
                    [source_image_uri, snapshot_uri], client.apitools_client))

        labels = None
        args_labels = getattr(args, 'labels', None)
        if args_labels:
            labels = client.messages.Disk.LabelsValue(additionalProperties=[
                client.messages.Disk.LabelsValue.AdditionalProperty(
                    key=key, value=value)
                for key, value in sorted(args.labels.iteritems())
            ])

        for disk_ref in disk_refs:
            if args.type:
                if disk_ref.Collection() == 'compute.disks':
                    type_ref = compute_holder.resources.Parse(
                        args.type,
                        collection='compute.diskTypes',
                        params={
                            'project': disk_ref.project,
                            'zone': disk_ref.zone
                        })
                elif disk_ref.Collection() == 'compute.regionDisks':
                    type_ref = compute_holder.resources.Parse(
                        args.type,
                        collection='compute.regionDiskTypes',
                        params={
                            'project': disk_ref.project,
                            'region': disk_ref.region
                        })
                type_uri = type_ref.SelfLink()
            else:
                type_uri = None

            if csek_keys:
                disk_key_or_none = csek_keys.LookupKey(
                    disk_ref, args.require_csek_key_create)
                disk_key_message_or_none = csek_utils.MaybeToMessage(
                    disk_key_or_none, client.apitools_client)
                kwargs = {
                    'diskEncryptionKey':
                    disk_key_message_or_none,
                    'sourceImageEncryptionKey':
                    project_to_source_image[disk_ref.project].keys[0],
                    'sourceSnapshotEncryptionKey':
                    project_to_source_image[disk_ref.project].keys[1]
                }
            else:
                kwargs = {}

            if disk_ref.Collection() == 'compute.disks':
                request = client.messages.ComputeDisksInsertRequest(
                    disk=client.messages.Disk(name=disk_ref.Name(),
                                              description=args.description,
                                              sizeGb=size_gb,
                                              sourceSnapshot=snapshot_uri,
                                              type=type_uri,
                                              **kwargs),
                    project=disk_ref.project,
                    sourceImage=project_to_source_image[disk_ref.project].uri,
                    zone=disk_ref.zone)
                if labels:
                    request.disk.labels = labels
                request = (client.apitools_client.disks, 'Insert', request)
            elif disk_ref.Collection() == 'compute.regionDisks':

                def SelfLink(zone, disk_ref):
                    return compute_holder.resources.Parse(
                        zone,
                        collection='compute.zones',
                        params={
                            'project': disk_ref.project
                        }).SelfLink()

                zones = [
                    SelfLink(zone, disk_ref) for zone in args.replica_zones
                ]
                request = client.messages.ComputeRegionDisksInsertRequest(
                    disk=client.messages.Disk(name=disk_ref.Name(),
                                              description=args.description,
                                              sizeGb=size_gb,
                                              sourceSnapshot=snapshot_uri,
                                              type=type_uri,
                                              replicaZones=zones,
                                              **kwargs),
                    project=disk_ref.project,
                    sourceImage=project_to_source_image[disk_ref.project].uri,
                    region=disk_ref.region)
                if labels:
                    request.disk.labels = labels

                request = (client.apitools_client.regionDisks, 'Insert',
                           request)

            requests.append(request)

        return client.MakeRequests(requests)
示例#10
0
    def Run(self, args):
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client

        source_instance_template = self.GetSourceInstanceTemplate(
            args, holder.resources)
        # gcloud creates default values for some fields in Instance resource
        # when no value was specified on command line.
        # When --source-instance-template was specified, defaults are taken from
        # Instance Template and gcloud flags are used to override them - by default
        # fields should not be initialized.
        skip_defaults = source_instance_template is not None

        instances_flags.ValidateDockerArgs(args)
        instances_flags.ValidateDiskCommonFlags(args)
        instances_flags.ValidateLocalSsdFlags(args)
        instances_flags.ValidateServiceAccountAndScopeArgs(args)
        if instance_utils.UseExistingBootDisk(args.disk or []):
            raise exceptions.InvalidArgumentException(
                '--disk', 'Boot disk specified for containerized VM.')

        if (skip_defaults and not args.IsSpecified('maintenance_policy')
                and not args.IsSpecified('preemptible')
                and not args.IsSpecified('restart_on_failure')):
            scheduling = None
        else:
            scheduling = instance_utils.CreateSchedulingMessage(
                messages=client.messages,
                maintenance_policy=args.maintenance_policy,
                preemptible=args.preemptible,
                restart_on_failure=args.restart_on_failure)

        if args.no_service_account:
            service_account = None
        else:
            service_account = args.service_account
        if (skip_defaults and not args.IsSpecified('scopes')
                and not args.IsSpecified('no_scopes')
                and not args.IsSpecified('service_account')
                and not args.IsSpecified('no_service_account')):
            service_accounts = []
        else:
            service_accounts = instance_utils.CreateServiceAccountMessages(
                messages=client.messages,
                scopes=[] if args.no_scopes else args.scopes,
                service_account=service_account)

        user_metadata = metadata_utils.ConstructMetadataMessage(
            client.messages,
            metadata=args.metadata,
            metadata_from_file=args.metadata_from_file)
        containers_utils.ValidateUserMetadata(user_metadata)

        boot_disk_size_gb = utils.BytesToGb(args.boot_disk_size)
        utils.WarnIfDiskSizeIsTooSmall(boot_disk_size_gb, args.boot_disk_type)

        instance_refs = instances_flags.INSTANCES_ARG.ResolveAsResource(
            args,
            holder.resources,
            scope_lister=flags.GetDefaultScopeLister(client))

        # Check if the zone is deprecated or has maintenance coming.
        zone_resource_fetcher = zone_utils.ZoneResourceFetcher(client)
        zone_resource_fetcher.WarnForZonalCreation(instance_refs)

        instances_flags.ValidatePublicDnsFlags(args)

        if (skip_defaults and not args.IsSpecified('network')
                and not args.IsSpecified('subnet')
                and not args.IsSpecified('private_network_ip')
                and not args.IsSpecified('no_address')
                and not args.IsSpecified('address')
                and not args.IsSpecified('network_tier')
                and not args.IsSpecified('no_public_dns')
                and not args.IsSpecified('public_dns')
                and not args.IsSpecified('no_public_ptr')
                and not args.IsSpecified('public_ptr')
                and not args.IsSpecified('no_public_ptr_domain')
                and not args.IsSpecified('public_ptr_domain')):
            network_interfaces = []
        else:
            network_interfaces = [
                instance_utils.CreateNetworkInterfaceMessage(
                    resources=holder.resources,
                    compute_client=client,
                    network=args.network,
                    subnet=args.subnet,
                    private_network_ip=args.private_network_ip,
                    no_address=args.no_address,
                    address=args.address,
                    instance_refs=instance_refs,
                    network_tier=args.network_tier,
                    no_public_dns=getattr(args, 'no_public_dns', None),
                    public_dns=getattr(args, 'public_dns', None),
                    no_public_ptr=getattr(args, 'no_public_ptr', None),
                    public_ptr=getattr(args, 'public_ptr', None),
                    no_public_ptr_domain=getattr(args, 'no_public_ptr_domain',
                                                 None),
                    public_ptr_domain=getattr(args, 'public_ptr_domain', None))
            ]

        if (skip_defaults and not args.IsSpecified('machine_type')
                and not args.IsSpecified('custom_cpu')
                and not args.IsSpecified('custom_memory')):
            machine_type_uris = [None for _ in instance_refs]
        else:
            machine_type_uris = instance_utils.CreateMachineTypeUris(
                resources=holder.resources,
                compute_client=client,
                machine_type=args.machine_type,
                custom_cpu=args.custom_cpu,
                custom_memory=args.custom_memory,
                ext=getattr(args, 'custom_extensions', None),
                instance_refs=instance_refs)

        image_uri = containers_utils.ExpandCosImageFlag(client)

        args_labels = getattr(args, 'labels', None)
        labels = None
        if args_labels:
            labels = client.messages.Instance.LabelsValue(
                additionalProperties=[
                    client.messages.Instance.LabelsValue.AdditionalProperty(
                        key=key, value=value)
                    for key, value in sorted(args.labels.iteritems())
                ])

        if skip_defaults and not args.IsSpecified('can_ip_forward'):
            can_ip_forward = None
        else:
            can_ip_forward = args.can_ip_forward

        requests = []
        for instance_ref, machine_type_uri in zip(instance_refs,
                                                  machine_type_uris):
            metadata = containers_utils.CreateMetadataMessage(
                client.messages, args.run_as_privileged,
                args.container_manifest, args.docker_image, args.port_mappings,
                args.run_command, user_metadata, instance_ref.Name())
            request = client.messages.ComputeInstancesInsertRequest(
                instance=client.messages.Instance(
                    canIpForward=can_ip_forward,
                    disks=(self._CreateDiskMessages(holder, args,
                                                    boot_disk_size_gb,
                                                    image_uri, instance_ref,
                                                    skip_defaults)),
                    description=args.description,
                    machineType=machine_type_uri,
                    metadata=metadata,
                    minCpuPlatform=args.min_cpu_platform,
                    name=instance_ref.Name(),
                    networkInterfaces=network_interfaces,
                    serviceAccounts=service_accounts,
                    scheduling=scheduling,
                    tags=containers_utils.CreateTagsMessage(
                        client.messages, args.tags)),
                project=instance_ref.project,
                zone=instance_ref.zone)
            if labels:
                request.instance.labels = labels
            if source_instance_template:
                request.sourceInstanceTemplate = source_instance_template

            requests.append(
                (client.apitools_client.instances, 'Insert', request))

        return client.MakeRequests(requests)
示例#11
0
    def _CreateRequests(self, args, compute_client, resource_parser):
        # This feature is only exposed in alpha/beta
        allow_rsa_encrypted = self.ReleaseTrack() in [
            base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA
        ]
        self.csek_keys = csek_utils.CsekKeyStore.FromArgs(
            args, allow_rsa_encrypted)

        scheduling = instance_utils.CreateSchedulingMessage(
            messages=compute_client.messages,
            maintenance_policy=args.maintenance_policy,
            preemptible=args.preemptible,
            restart_on_failure=args.restart_on_failure)

        if args.tags:
            tags = compute_client.messages.Tags(items=args.tags)
        else:
            tags = None

        metadata = metadata_utils.ConstructMetadataMessage(
            compute_client.messages,
            metadata=args.metadata,
            metadata_from_file=args.metadata_from_file)

        # If the user already provided an initial Windows password and
        # username through metadata, then there is no need to check
        # whether the image or the boot disk is Windows.

        boot_disk_size_gb = utils.BytesToGb(args.boot_disk_size)
        utils.WarnIfDiskSizeIsTooSmall(boot_disk_size_gb, args.boot_disk_type)

        instance_refs = instances_flags.INSTANCES_ARG.ResolveAsResource(
            args,
            resource_parser,
            scope_lister=flags.GetDefaultScopeLister(compute_client))

        # Check if the zone is deprecated or has maintenance coming.
        zone_resource_fetcher = zone_utils.ZoneResourceFetcher(compute_client)
        zone_resource_fetcher.WarnForZonalCreation(instance_refs)

        network_interface_arg = getattr(args, 'network_interface', None)
        if network_interface_arg:
            network_interfaces = instance_utils.CreateNetworkInterfaceMessages(
                resources=resource_parser,
                compute_client=compute_client,
                network_interface_arg=network_interface_arg,
                instance_refs=instance_refs,
                support_network_tier=self._support_network_tier)
        else:
            if self._support_public_dns is True:
                instances_flags.ValidatePublicDnsFlags(args)

            network_tier = getattr(args, 'network_tier', None)

            network_interfaces = [
                instance_utils.CreateNetworkInterfaceMessage(
                    resources=resource_parser,
                    compute_client=compute_client,
                    network=args.network,
                    subnet=args.subnet,
                    private_network_ip=args.private_network_ip,
                    no_address=args.no_address,
                    address=args.address,
                    instance_refs=instance_refs,
                    network_tier=network_tier,
                    no_public_dns=getattr(args, 'no_public_dns', None),
                    public_dns=getattr(args, 'public_dns', None),
                    no_public_ptr=getattr(args, 'no_public_ptr', None),
                    public_ptr=getattr(args, 'public_ptr', None),
                    no_public_ptr_domain=getattr(args, 'no_public_ptr_domain',
                                                 None),
                    public_ptr_domain=getattr(args, 'public_ptr_domain', None))
            ]

        machine_type_uris = instance_utils.CreateMachineTypeUris(
            resources=resource_parser,
            compute_client=compute_client,
            project=instance_refs[0].project,
            machine_type=args.machine_type,
            custom_cpu=args.custom_cpu,
            custom_memory=args.custom_memory,
            ext=getattr(args, 'custom_extensions', None),
            instance_refs=instance_refs)

        create_boot_disk = not instance_utils.UseExistingBootDisk(args.disk
                                                                  or [])
        if create_boot_disk:
            image_expander = image_utils.ImageExpander(compute_client,
                                                       resource_parser)
            image_uri, _ = image_expander.ExpandImageFlag(
                user_project=instance_refs[0].project,
                image=args.image,
                image_family=args.image_family,
                image_project=args.image_project,
                return_image_resource=False)
        else:
            image_uri = None

        # A list of lists where the element at index i contains a list of
        # disk messages that should be set for the instance at index i.
        disks_messages = []

        # A mapping of zone to boot disk references for all existing boot
        # disks that are being attached.
        # TODO(b/36050875): Simplify since resources.Resource is now hashable.
        existing_boot_disks = {}

        for instance_ref in instance_refs:
            persistent_disks, boot_disk_ref = (
                instance_utils.CreatePersistentAttachedDiskMessages(
                    resource_parser, compute_client, self.csek_keys, args.disk
                    or [], instance_ref))
            persistent_create_disks = (
                instance_utils.CreatePersistentCreateDiskMessages(
                    compute_client, resource_parser, self.csek_keys,
                    getattr(args, 'create_disk', []), instance_ref))
            local_ssds = []
            for x in args.local_ssd or []:
                local_ssds.append(
                    instance_utils.CreateLocalSsdMessage(
                        resource_parser, compute_client.messages,
                        x.get('device-name'), x.get('interface'),
                        x.get('size'), instance_ref.zone))

            if create_boot_disk:
                boot_disk = instance_utils.CreateDefaultBootAttachedDiskMessage(
                    compute_client,
                    resource_parser,
                    disk_type=args.boot_disk_type,
                    disk_device_name=args.boot_disk_device_name,
                    disk_auto_delete=args.boot_disk_auto_delete,
                    disk_size_gb=boot_disk_size_gb,
                    require_csek_key_create=(args.require_csek_key_create
                                             if self.csek_keys else None),
                    image_uri=image_uri,
                    instance_ref=instance_ref,
                    csek_keys=self.csek_keys)
                persistent_disks = [boot_disk] + persistent_disks
            else:
                existing_boot_disks[boot_disk_ref.zone] = boot_disk_ref
            disks_messages.append(persistent_disks + persistent_create_disks +
                                  local_ssds)

        accelerator_args = getattr(args, 'accelerator', None)

        project_to_sa = {}
        requests = []
        for instance_ref, machine_type_uri, disks in zip(
                instance_refs, machine_type_uris, disks_messages):
            if instance_ref.project not in project_to_sa:
                scopes = None
                if not args.no_scopes and not args.scopes:
                    # User didn't provide any input on scopes. If project has no default
                    # service account then we want to create a VM with no scopes
                    request = (
                        compute_client.apitools_client.projects, 'Get',
                        compute_client.messages.ComputeProjectsGetRequest(
                            project=instance_ref.project))
                    errors = []
                    result = compute_client.MakeRequests([request], errors)
                    if not errors:
                        if not result[0].defaultServiceAccount:
                            scopes = []
                            log.status.Print(
                                'There is no default service account for project {}. '
                                'Instance {} will not have scopes.'.format(
                                    instance_ref.project, instance_ref.Name))
                if scopes is None:
                    scopes = [] if args.no_scopes else args.scopes

                if args.no_service_account:
                    service_account = None
                else:
                    service_account = args.service_account
                service_accounts = instance_utils.CreateServiceAccountMessages(
                    messages=compute_client.messages,
                    scopes=scopes,
                    service_account=service_account)
                project_to_sa[instance_ref.project] = service_accounts

            instance = compute_client.messages.Instance(
                canIpForward=args.can_ip_forward,
                disks=disks,
                description=args.description,
                machineType=machine_type_uri,
                metadata=metadata,
                name=instance_ref.Name(),
                networkInterfaces=network_interfaces,
                serviceAccounts=project_to_sa[instance_ref.project],
                scheduling=scheduling,
                tags=tags)
            if getattr(args, 'min_cpu_platform', None):
                instance.minCpuPlatform = args.min_cpu_platform
            if accelerator_args:
                accelerator_type_name = accelerator_args['type']
                accelerator_type_ref = resource_parser.Parse(
                    accelerator_type_name,
                    collection='compute.acceleratorTypes',
                    params={
                        'project': instance_ref.project,
                        'zone': instance_ref.zone
                    })
                # Accelerator count is default to 1.
                accelerator_count = int(accelerator_args.get('count', 1))
                accelerators = instance_utils.CreateAcceleratorConfigMessages(
                    compute_client.messages, accelerator_type_ref,
                    accelerator_count)
                instance.guestAccelerators = accelerators

            request = compute_client.messages.ComputeInstancesInsertRequest(
                instance=instance,
                project=instance_ref.project,
                zone=instance_ref.zone)

            sole_tenancy_host_arg = getattr(args, 'sole_tenancy_host', None)
            if sole_tenancy_host_arg:
                sole_tenancy_host_ref = resource_parser.Parse(
                    sole_tenancy_host_arg,
                    collection='compute.hosts',
                    params={
                        'project': instance_ref.project,
                        'zone': instance_ref.zone
                    })
                request.instance.host = sole_tenancy_host_ref.SelfLink()
            requests.append(
                (compute_client.apitools_client.instances, 'Insert', request))
        return requests
    def CreateRequests(self, args):
        instances_flags.ValidateDockerArgs(args)
        instances_flags.ValidateDiskCommonFlags(args)
        instances_flags.ValidateLocalSsdFlags(args)
        instances_flags.ValidateServiceAccountAndScopeArgs(args)
        if instance_utils.UseExistingBootDisk(args.disk or []):
            raise exceptions.InvalidArgumentException(
                '--disk', 'Boot disk specified for containerized VM.')

        scheduling = instance_utils.CreateSchedulingMessage(
            messages=self.messages,
            maintenance_policy=args.maintenance_policy,
            preemptible=args.preemptible,
            restart_on_failure=args.restart_on_failure)

        if args.no_service_account:
            service_account = None
        else:
            service_account = args.service_account
        service_accounts = instance_utils.CreateServiceAccountMessages(
            messages=self.messages,
            scopes=[] if args.no_scopes else args.scopes,
            service_account=service_account)

        user_metadata = metadata_utils.ConstructMetadataMessage(
            self.messages,
            metadata=args.metadata,
            metadata_from_file=args.metadata_from_file)
        containers_utils.ValidateUserMetadata(user_metadata)

        boot_disk_size_gb = utils.BytesToGb(args.boot_disk_size)
        utils.WarnIfDiskSizeIsTooSmall(boot_disk_size_gb, args.boot_disk_type)

        instance_refs = instances_flags.INSTANCES_ARG.ResolveAsResource(
            args,
            self.resources,
            scope_lister=flags.GetDefaultScopeLister(self.compute_client,
                                                     self.project))

        # Check if the zone is deprecated or has maintenance coming.
        zone_resource_fetcher = zone_utils.ZoneResourceFetcher(
            self.compute_client)
        zone_resource_fetcher.WarnForZonalCreation(instance_refs)

        instances_flags.ValidatePublicDnsFlags(args)

        network_interface = instance_utils.CreateNetworkInterfaceMessage(
            resources=self.resources,
            compute_client=self.compute_client,
            network=args.network,
            subnet=args.subnet,
            private_network_ip=args.private_network_ip,
            no_address=args.no_address,
            address=args.address,
            instance_refs=instance_refs,
            network_tier=args.network_tier,
            no_public_dns=getattr(args, 'no_public_dns', None),
            public_dns=getattr(args, 'public_dns', None),
            no_public_ptr=getattr(args, 'no_public_ptr', None),
            public_ptr=getattr(args, 'public_ptr', None),
            no_public_ptr_domain=getattr(args, 'no_public_ptr_domain', None),
            public_ptr_domain=getattr(args, 'public_ptr_domain', None))

        machine_type_uris = instance_utils.CreateMachineTypeUris(
            resources=self.resources,
            compute_client=self.compute_client,
            project=self.project,
            machine_type=args.machine_type,
            custom_cpu=args.custom_cpu,
            custom_memory=args.custom_memory,
            ext=getattr(args, 'custom_extensions', None),
            instance_refs=instance_refs)

        image_uri = containers_utils.ExpandCosImageFlag(self.compute_client)

        args_labels = getattr(args, 'labels', None)
        labels = None
        if args_labels:
            labels = self.messages.Instance.LabelsValue(additionalProperties=[
                self.messages.Instance.LabelsValue.AdditionalProperty(
                    key=key, value=value)
                for key, value in sorted(args.labels.iteritems())
            ])

        requests = []
        for instance_ref, machine_type_uri in zip(instance_refs,
                                                  machine_type_uris):
            metadata = containers_utils.CreateMetadataMessage(
                self.messages, args.run_as_privileged, args.container_manifest,
                args.docker_image, args.port_mappings, args.run_command,
                user_metadata, instance_ref.Name())
            request = self.messages.ComputeInstancesInsertRequest(
                instance=self.messages.Instance(
                    canIpForward=args.can_ip_forward,
                    disks=(self._CreateDiskMessages(args, boot_disk_size_gb,
                                                    image_uri, instance_ref)),
                    description=args.description,
                    machineType=machine_type_uri,
                    metadata=metadata,
                    minCpuPlatform=args.min_cpu_platform,
                    name=instance_ref.Name(),
                    networkInterfaces=[network_interface],
                    serviceAccounts=service_accounts,
                    scheduling=scheduling,
                    tags=containers_utils.CreateTagsMessage(
                        self.messages, args.tags),
                ),
                project=self.project,
                zone=instance_ref.zone)
            if labels:
                request.instance.labels = labels
            requests.append(request)

        return requests