Beispiel #1
0
    def Run(self, args):
        self._ValidateArgs(args)

        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        compute_client = holder.client
        resource_parser = holder.resources

        container_mount_disk = instances_flags.GetValidatedContainerMountDisk(
            holder, args.container_mount_disk, args.disk, args.create_disk)
        source_instance_template = instance_utils.GetSourceInstanceTemplate(
            args, resource_parser, self.SOURCE_INSTANCE_TEMPLATE)
        skip_defaults = instance_utils.GetSkipDefaults(
            source_instance_template)
        scheduling = instance_utils.GetScheduling(args,
                                                  compute_client,
                                                  skip_defaults,
                                                  support_min_node_cpu=False)
        service_accounts = instance_utils.GetServiceAccounts(
            args, compute_client, skip_defaults)
        user_metadata = instance_utils.GetValidatedMetadata(
            args, compute_client)
        boot_disk_size_gb = instance_utils.GetBootDiskSizeGb(args)
        instance_refs = instance_utils.GetInstanceRefs(args, compute_client,
                                                       holder)
        network_interfaces = self.GetNetworkInterfaces(
            args, resource_parser, compute_client, holder,
            instance_refs[0].project, instance_refs[0].zone,
            compute_scopes.ScopeEnum.ZONE, skip_defaults)
        image_uri = self.GetImageUri(args, compute_client, resource_parser,
                                     instance_refs)
        labels = containers_utils.GetLabelsMessageWithCosVersion(
            args.labels, image_uri, resource_parser,
            compute_client.messages.Instance)
        can_ip_forward = instance_utils.GetCanIpForward(args, skip_defaults)
        tags = containers_utils.CreateTagsMessage(compute_client.messages,
                                                  args.tags)
        confidential_vm = (args.IsSpecified('confidential_compute')
                           and args.confidential_compute)

        requests = []
        for instance_ref in instance_refs:
            metadata = containers_utils.CreateKonletMetadataMessage(
                compute_client.messages,
                args,
                instance_ref.Name(),
                user_metadata,
                container_mount_disk_enabled=self.
                _container_mount_disk_enabled,
                container_mount_disk=container_mount_disk)

            disks = []
            if self.CheckDiskMessageArgs(args, skip_defaults):
                disks = create_utils.CreateDiskMessages(
                    args=args,
                    instance_name=instance_ref.Name(),
                    project=instance_ref.project,
                    location=instance_ref.zone,
                    scope=compute_scopes.ScopeEnum.ZONE,
                    compute_client=compute_client,
                    resource_parser=resource_parser,
                    boot_disk_size_gb=boot_disk_size_gb,
                    image_uri=image_uri,
                    create_boot_disk=self._support_create_boot_disk,
                    support_nvdimm=self._support_nvdimm,
                    support_match_container_mount_disks=self.
                    _support_match_container_mount_disks)

            machine_type_uri = None
            if instance_utils.CheckSpecifiedMachineTypeArgs(
                    args, skip_defaults):
                machine_type_uri = create_utils.CreateMachineTypeUri(
                    args=args,
                    compute_client=compute_client,
                    resource_parser=resource_parser,
                    project=instance_ref.project,
                    location=instance_ref.zone,
                    scope=compute_scopes.ScopeEnum.ZONE,
                    confidential_vm=confidential_vm)

            guest_accelerators = create_utils.GetAccelerators(
                args=args,
                compute_client=compute_client,
                resource_parser=resource_parser,
                project=instance_ref.project,
                location=instance_ref.zone,
                scope=compute_scopes.ScopeEnum.ZONE)

            instance = compute_client.messages.Instance(
                canIpForward=can_ip_forward,
                disks=disks,
                guestAccelerators=guest_accelerators,
                description=args.description,
                labels=labels,
                machineType=machine_type_uri,
                metadata=metadata,
                minCpuPlatform=args.min_cpu_platform,
                name=instance_ref.Name(),
                networkInterfaces=network_interfaces,
                serviceAccounts=service_accounts,
                scheduling=scheduling,
                tags=tags)
            if args.private_ipv6_google_access_type is not None:
                instance.privateIpv6GoogleAccess = (
                    instances_flags.GetPrivateIpv6GoogleAccessTypeFlagMapper(
                        compute_client.messages).GetEnumForChoice(
                            args.private_ipv6_google_access_type))

            confidential_instance_config = (
                create_utils.BuildConfidentialInstanceConfigMessage(
                    messages=compute_client.messages, args=args))
            if confidential_instance_config:
                instance.confidentialInstanceConfig = confidential_instance_config

            has_threads_per_core = (self._support_threads_per_core
                                    and args.threads_per_core is not None)
            if (args.enable_nested_virtualization is not None
                    or has_threads_per_core):
                threads_per_core = args.threads_per_core if has_threads_per_core else None
                instance.advancedMachineFeatures = (
                    instance_utils.CreateAdvancedMachineFeaturesMessage(
                        compute_client.messages,
                        args.enable_nested_virtualization, threads_per_core))

            shielded_instance_config = create_utils.BuildShieldedInstanceConfigMessage(
                messages=compute_client.messages, args=args)
            if shielded_instance_config:
                instance.shieldedInstanceConfig = shielded_instance_config

            if self._support_network_performance_configs and \
                args.IsSpecified('network_performance_configs'):
                instance.networkPerformanceConfig = \
                    instance_utils.GetNetworkPerformanceConfig(args, compute_client)

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

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

        return compute_client.MakeRequests(requests)
    def _CreateRequests(self, args, holder, compute_client, resource_parser,
                        project, location, scope):
        # 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.

        name_pattern = args.name_pattern
        instance_names = args.predefined_names or []
        instance_count = args.count or len(instance_names)
        per_instance_props = encoding.DictToAdditionalPropertyMessage(
            {el: {}
             for el in instance_names}, compute_client.messages.
            BulkInsertInstanceResource.PerInstancePropertiesValue)

        location_policy = self.GetLocationPolicy(args, compute_client.messages)

        instance_min_count = instance_count
        if args.IsSpecified('min_count'):
            instance_min_count = args.min_count

        source_instance_template = self.GetSourceInstanceTemplate(
            args, resource_parser)
        skip_defaults = source_instance_template is not None

        scheduling = instance_utils.GetScheduling(
            args,
            compute_client,
            skip_defaults,
            support_node_affinity=False,
            support_min_node_cpu=self._support_min_node_cpu,
            support_host_error_timeout_seconds=self.
            _support_host_error_timeout_seconds,
            support_max_run_duration=self._support_max_run_duration)
        tags = instance_utils.GetTags(args, compute_client)
        labels = instance_utils.GetLabels(args,
                                          compute_client,
                                          instance_properties=True)
        metadata = instance_utils.GetMetadata(args, compute_client,
                                              skip_defaults)

        network_interfaces = create_utils.GetBulkNetworkInterfaces(
            args=args,
            resource_parser=resource_parser,
            compute_client=compute_client,
            holder=holder,
            project=project,
            location=location,
            scope=scope,
            skip_defaults=skip_defaults)

        create_boot_disk = not (
            instance_utils.UseExistingBootDisk((args.disk or []) +
                                               (args.create_disk or [])))
        image_uri = create_utils.GetImageUri(args, compute_client,
                                             create_boot_disk, project,
                                             resource_parser)

        shielded_instance_config = create_utils.BuildShieldedInstanceConfigMessage(
            messages=compute_client.messages, args=args)

        confidential_vm = False
        if self._support_confidential_compute:
            confidential_instance_config = (
                create_utils.BuildConfidentialInstanceConfigMessage(
                    messages=compute_client.messages, args=args))

            confidential_vm = (args.IsSpecified('confidential_compute')
                               and args.confidential_compute)

        service_accounts = create_utils.GetProjectServiceAccount(
            args, project, compute_client, skip_defaults)

        boot_disk_size_gb = instance_utils.GetBootDiskSizeGb(args)

        disks = []
        if create_utils.CheckSpecifiedDiskArgs(args=args,
                                               support_disks=False,
                                               skip_defaults=skip_defaults):

            #  Disks in bulk insert should be in READ_ONLY mode
            for disk in args.disk or []:
                disk['mode'] = 'ro'
            disks = create_utils.CreateDiskMessages(
                args=args,
                project=project,
                location=location,
                scope=scope,
                compute_client=compute_client,
                resource_parser=resource_parser,
                image_uri=image_uri,
                create_boot_disk=create_boot_disk,
                boot_disk_size_gb=boot_disk_size_gb,
                support_kms=True,
                support_nvdimm=self._support_nvdimm,
                support_source_snapshot_csek=self.
                _support_source_snapshot_csek,
                support_boot_snapshot_uri=self._support_boot_snapshot_uri,
                support_image_csek=self._support_image_csek,
                support_create_disk_snapshots=self.
                _support_create_disk_snapshots,
                use_disk_type_uri=False)

        machine_type_name = None
        if instance_utils.CheckSpecifiedMachineTypeArgs(args, skip_defaults):
            machine_type_name = instance_utils.CreateMachineTypeName(
                args, confidential_vm)

            # Check to see if the custom machine type ratio is supported
            instance_utils.CheckCustomCpuRamRatio(compute_client, project,
                                                  location, machine_type_name)

        can_ip_forward = instance_utils.GetCanIpForward(args, skip_defaults)
        guest_accelerators = create_utils.GetAcceleratorsForInstanceProperties(
            args=args, compute_client=compute_client)

        # Create an AdvancedMachineFeatures message if any arguments are supplied
        # that require one.
        advanced_machine_features = None
        if (args.enable_nested_virtualization is not None
                or args.threads_per_core is not None
                or (self._support_numa_node_count
                    and args.numa_node_count is not None)
                or (self._support_visible_core_count
                    and args.visible_core_count is not None)
                or args.enable_uefi_networking is not None):
            visible_core_count = args.visible_core_count if self._support_visible_core_count else None
            advanced_machine_features = (
                instance_utils.CreateAdvancedMachineFeaturesMessage(
                    compute_client.messages, args.enable_nested_virtualization,
                    args.threads_per_core, args.numa_node_count
                    if self._support_numa_node_count else None,
                    visible_core_count, args.enable_uefi_networking))

        parsed_resource_policies = []
        resource_policies = getattr(args, 'resource_policies', None)
        if resource_policies:
            for policy in resource_policies:
                resource_policy_ref = maintenance_util.ParseResourcePolicyWithScope(
                    resource_parser,
                    policy,
                    project=project,
                    location=location,
                    scope=scope)
                parsed_resource_policies.append(resource_policy_ref.Name())

        display_device = None
        if self._support_display_device and args.IsSpecified(
                'enable_display_device'):
            display_device = compute_client.messages.DisplayDevice(
                enableDisplay=args.enable_display_device)

        reservation_affinity = instance_utils.GetReservationAffinity(
            args, compute_client)

        instance_properties = compute_client.messages.InstanceProperties(
            canIpForward=can_ip_forward,
            description=args.description,
            disks=disks,
            guestAccelerators=guest_accelerators,
            labels=labels,
            machineType=machine_type_name,
            metadata=metadata,
            minCpuPlatform=args.min_cpu_platform,
            networkInterfaces=network_interfaces,
            serviceAccounts=service_accounts,
            scheduling=scheduling,
            tags=tags,
            resourcePolicies=parsed_resource_policies,
            shieldedInstanceConfig=shielded_instance_config,
            reservationAffinity=reservation_affinity,
            advancedMachineFeatures=advanced_machine_features)

        if self._support_secure_tags and args.secure_tags:
            instance_properties.secureTags = secure_tags_utils.GetSecureTags(
                args.secure_tags)
        if args.resource_manager_tags:
            ret_resource_manager_tags = resource_manager_tags_utils.GetResourceManagerTags(
                args.resource_manager_tags)
            if ret_resource_manager_tags is not None:
                properties_message = compute_client.messages.InstanceProperties
                instance_properties.resourceManagerTags = properties_message.ResourceManagerTagsValue(
                    additionalProperties=[
                        properties_message.ResourceManagerTagsValue.
                        AdditionalProperty(key=key, value=value)
                        for key, value in sorted(
                            six.iteritems(ret_resource_manager_tags))
                    ])

        if self._support_display_device and display_device:
            instance_properties.displayDevice = display_device

        if self._support_confidential_compute and confidential_instance_config:
            instance_properties.confidentialInstanceConfig = confidential_instance_config

        if self._support_erase_vss and args.IsSpecified(
                'erase_windows_vss_signature'):
            instance_properties.eraseWindowsVssSignature = args.erase_windows_vss_signature

        if self._support_post_key_revocation_action_type and args.IsSpecified(
                'post_key_revocation_action_type'):
            instance_properties.postKeyRevocationActionType = arg_utils.ChoiceToEnum(
                args.post_key_revocation_action_type, compute_client.messages.
                Instance.PostKeyRevocationActionTypeValueValuesEnum)

        if args.IsSpecified('network_performance_configs'):
            instance_properties.networkPerformanceConfig = (
                instance_utils.GetNetworkPerformanceConfig(
                    args, compute_client))

        bulk_instance_resource = compute_client.messages.BulkInsertInstanceResource(
            count=instance_count,
            instanceProperties=instance_properties,
            minCount=instance_min_count,
            perInstanceProperties=per_instance_props,
            sourceInstanceTemplate=source_instance_template,
            namePattern=name_pattern,
            locationPolicy=location_policy)

        if scope == compute_scopes.ScopeEnum.ZONE:
            instance_service = compute_client.apitools_client.instances
            request_message = compute_client.messages.ComputeInstancesBulkInsertRequest(
                bulkInsertInstanceResource=bulk_instance_resource,
                project=project,
                zone=location)
        elif scope == compute_scopes.ScopeEnum.REGION:
            instance_service = compute_client.apitools_client.regionInstances
            request_message = compute_client.messages.ComputeRegionInstancesBulkInsertRequest(
                bulkInsertInstanceResource=bulk_instance_resource,
                project=project,
                region=location)

        return instance_service, request_message
Beispiel #3
0
    def _CreateRequests(self, args, holder, compute_client, resource_parser,
                        project, location, scope):
        # 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.

        name_pattern = args.name_pattern
        instance_names = args.predefined_names or []
        instance_count = args.count or len(instance_names)
        per_instance_props = encoding.DictToAdditionalPropertyMessage(
            {el: {}
             for el in instance_names}, compute_client.messages.
            BulkInsertInstanceResource.PerInstancePropertiesValue)

        location_policy = self.GetLocationPolicy(args, compute_client.messages)

        instance_min_count = instance_count
        if args.IsSpecified('min_count'):
            instance_min_count = args.min_count

        source_instance_template = self.GetSourceInstanceTemplate(
            args, resource_parser)
        skip_defaults = source_instance_template is not None

        scheduling = instance_utils.GetScheduling(
            args,
            compute_client,
            skip_defaults,
            support_node_affinity=False,
            support_min_node_cpu=self._support_min_node_cpu,
            support_location_hint=self._support_location_hint)
        tags = instance_utils.GetTags(args, compute_client)
        labels = instance_utils.GetLabels(args,
                                          compute_client,
                                          instance_properties=True)
        metadata = instance_utils.GetMetadata(args, compute_client,
                                              skip_defaults)

        network_interfaces = create_utils.GetBulkNetworkInterfaces(
            args=args,
            resource_parser=resource_parser,
            compute_client=compute_client,
            holder=holder,
            project=project,
            location=location,
            scope=scope,
            skip_defaults=skip_defaults)

        create_boot_disk = True
        image_uri = create_utils.GetImageUri(args, compute_client,
                                             create_boot_disk, project,
                                             resource_parser)

        shielded_instance_config = create_utils.BuildShieldedInstanceConfigMessage(
            messages=compute_client.messages, args=args)

        if self._support_confidential_compute:
            confidential_instance_config = (
                create_utils.BuildConfidentialInstanceConfigMessage(
                    messages=compute_client.messages, args=args))

        service_accounts = create_utils.GetProjectServiceAccount(
            args, project, compute_client, skip_defaults)

        boot_disk_size_gb = instance_utils.GetBootDiskSizeGb(args)

        disks = []
        if create_utils.CheckSpecifiedDiskArgs(args=args,
                                               support_disks=False,
                                               skip_defaults=skip_defaults):
            disks = create_utils.CreateDiskMessages(
                args=args,
                project=project,
                location=location,
                scope=scope,
                compute_client=compute_client,
                resource_parser=resource_parser,
                image_uri=image_uri,
                create_boot_disk=create_boot_disk,
                boot_disk_size_gb=boot_disk_size_gb,
                support_nvdimm=self._support_nvdimm,
                support_disk_resource_policy=self.
                _support_disk_resource_policy,
                support_source_snapshot_csek=self.
                _support_source_snapshot_csek,
                support_boot_snapshot_uri=self._support_boot_snapshot_uri,
                support_image_csek=self._support_image_csek,
                support_create_disk_snapshots=self.
                _support_create_disk_snapshots,
                support_persistent_attached_disks=False,
                use_disk_type_uri=False)

        machine_type = 'n1-standard-1'
        if args.IsSpecified('machine_type'):
            machine_type = args.machine_type

        can_ip_forward = instance_utils.GetCanIpForward(args, skip_defaults)
        guest_accelerators = create_utils.GetAcceleratorsForInstanceProperties(
            args=args, compute_client=compute_client)

        # If either nested or threads_per_core are given, make an
        # AdvancedMachineFeatures message.
        advanced_machine_features = None
        if ((self._support_enable_nested_virtualization
             and args.enable_nested_virtualization is not None)
                or (self._support_threads_per_core
                    and args.threads_per_core is not None)):
            advanced_machine_features = (
                instance_utils.CreateAdvancedMachineFeaturesMessage(
                    compute_client.messages, args.enable_nested_virtualization,
                    args.threads_per_core))

        parsed_resource_policies = []
        resource_policies = getattr(args, 'resource_policies', None)
        if resource_policies:
            for policy in resource_policies:
                resource_policy_ref = maintenance_util.ParseResourcePolicyWithScope(
                    resource_parser,
                    policy,
                    project=project,
                    location=location,
                    scope=scope)
                parsed_resource_policies.append(resource_policy_ref.SelfLink())

        display_device = None
        if args.IsSpecified('enable_display_device'):
            display_device = compute_client.messages.DisplayDevice(
                enableDisplay=args.enable_display_device)

        reservation_affinity = instance_utils.GetReservationAffinity(
            args, compute_client)

        instance_properties = compute_client.messages.InstanceProperties(
            canIpForward=can_ip_forward,
            description=args.description,
            disks=disks,
            guestAccelerators=guest_accelerators,
            labels=labels,
            machineType=machine_type,
            metadata=metadata,
            minCpuPlatform=args.min_cpu_platform,
            networkInterfaces=network_interfaces,
            serviceAccounts=service_accounts,
            scheduling=scheduling,
            tags=tags,
            resourcePolicies=parsed_resource_policies,
            shieldedInstanceConfig=shielded_instance_config,
            displayDevice=display_device,
            reservationAffinity=reservation_affinity,
            advancedMachineFeatures=advanced_machine_features)

        if self._support_confidential_compute and confidential_instance_config:
            instance_properties.confidentialInstanceConfig = confidential_instance_config

        if self._support_erase_vss and \
          args.IsSpecified('erase_windows_vss_signature'):
            instance_properties.eraseWindowsVssSignature = args.erase_windows_vss_signature

        if self._support_post_key_revocation_action_type and args.IsSpecified(
                'post_key_revocation_action_type'):
            instance_properties.postKeyRevocationActionType = arg_utils.ChoiceToEnum(
                args.post_key_revocation_action_type, compute_client.messages.
                Instance.PostKeyRevocationActionTypeValueValuesEnum)

        bulk_instance_resource = compute_client.messages.BulkInsertInstanceResource(
            count=instance_count,
            instanceProperties=instance_properties,
            minCount=instance_min_count,
            perInstanceProperties=per_instance_props,
            sourceInstanceTemplate=source_instance_template,
            namePattern=name_pattern,
            locationPolicy=location_policy)

        if scope == compute_scopes.ScopeEnum.ZONE:
            instance_service = compute_client.apitools_client.instances
            request_message = compute_client.messages.ComputeInstancesBulkInsertRequest(
                bulkInsertInstanceResource=bulk_instance_resource,
                project=project,
                zone=location)
        elif scope == compute_scopes.ScopeEnum.REGION:
            instance_service = compute_client.apitools_client.regionInstances
            request_message = compute_client.messages.ComputeRegionInstancesBulkInsertRequest(
                bulkInsertInstanceResource=bulk_instance_resource,
                project=project,
                region=location)

        return instance_service, request_message
Beispiel #4
0
    def _CreateRequests(self, args, instance_refs, project, zone,
                        compute_client, resource_parser, holder):
        # 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.
        source_instance_template = self.GetSourceInstanceTemplate(
            args, resource_parser)
        skip_defaults = source_instance_template is not None

        source_machine_image = self.GetSourceMachineImage(
            args, resource_parser)
        skip_defaults = skip_defaults or source_machine_image is not None

        scheduling = instance_utils.GetScheduling(
            args,
            compute_client,
            skip_defaults,
            support_node_affinity=True,
            support_node_project=self._support_node_project,
            support_host_error_timeout_seconds=self.
            _support_host_error_timeout_seconds,
            support_max_run_duration=self._support_max_run_duration)
        tags = instance_utils.GetTags(args, compute_client)
        labels = instance_utils.GetLabels(args, compute_client)
        metadata = instance_utils.GetMetadata(args, compute_client,
                                              skip_defaults)
        boot_disk_size_gb = instance_utils.GetBootDiskSizeGb(args)

        network_interfaces = create_utils.GetNetworkInterfacesWithValidation(
            args=args,
            resource_parser=resource_parser,
            compute_client=compute_client,
            holder=holder,
            project=project,
            location=zone,
            scope=compute_scopes.ScopeEnum.ZONE,
            skip_defaults=skip_defaults,
            support_public_dns=self._support_public_dns,
            support_ipv6_assignment=self._support_ipv6_assignment)

        confidential_vm = (args.IsSpecified('confidential_compute')
                           and args.confidential_compute)

        create_boot_disk = not (
            instance_utils.UseExistingBootDisk((args.disk or []) +
                                               (args.create_disk or [])))

        image_uri = create_utils.GetImageUri(
            args,
            compute_client,
            create_boot_disk,
            project,
            resource_parser,
            confidential_vm,
            image_family_scope=args.image_family_scope,
            support_image_family_scope=True)

        shielded_instance_config = create_utils.BuildShieldedInstanceConfigMessage(
            messages=compute_client.messages, args=args)

        confidential_instance_config = (
            create_utils.BuildConfidentialInstanceConfigMessage(
                messages=compute_client.messages, args=args))

        csek_keys = csek_utils.CsekKeyStore.FromArgs(
            args, self._support_rsa_encrypted)

        project_to_sa = create_utils.GetProjectToServiceAccountMap(
            args, instance_refs, compute_client, skip_defaults)

        requests = []
        for instance_ref in instance_refs:

            disks = []
            if create_utils.CheckSpecifiedDiskArgs(
                    args=args,
                    skip_defaults=skip_defaults,
                    support_kms=self._support_kms):
                disks = create_utils.CreateDiskMessages(
                    args=args,
                    instance_name=instance_ref.Name(),
                    project=instance_ref.project,
                    location=instance_ref.zone,
                    scope=compute_scopes.ScopeEnum.ZONE,
                    compute_client=compute_client,
                    resource_parser=resource_parser,
                    boot_disk_size_gb=boot_disk_size_gb,
                    image_uri=image_uri,
                    create_boot_disk=create_boot_disk,
                    csek_keys=csek_keys,
                    holder=holder,
                    support_kms=self._support_kms,
                    support_nvdimm=self._support_nvdimm,
                    support_source_snapshot_csek=self.
                    _support_source_snapshot_csek,
                    support_boot_snapshot_uri=self._support_boot_snapshot_uri,
                    support_image_csek=self._support_image_csek,
                    support_create_disk_snapshots=self.
                    _support_create_disk_snapshots,
                    support_replica_zones=self._support_replica_zones,
                    support_multi_writer=self._support_multi_writer,
                    support_disk_architecture=self._support_disk_architecture)

            machine_type_uri = None
            if instance_utils.CheckSpecifiedMachineTypeArgs(
                    args, skip_defaults):
                machine_type_uri = instance_utils.CreateMachineTypeUri(
                    args=args,
                    compute_client=compute_client,
                    resource_parser=resource_parser,
                    project=instance_ref.project,
                    location=instance_ref.zone,
                    scope=compute_scopes.ScopeEnum.ZONE,
                    confidential_vm=confidential_vm)

            can_ip_forward = instance_utils.GetCanIpForward(
                args, skip_defaults)
            guest_accelerators = create_utils.GetAccelerators(
                args=args,
                compute_client=compute_client,
                resource_parser=resource_parser,
                project=instance_ref.project,
                location=instance_ref.zone,
                scope=compute_scopes.ScopeEnum.ZONE)

            instance = compute_client.messages.Instance(
                canIpForward=can_ip_forward,
                deletionProtection=args.deletion_protection,
                description=args.description,
                disks=disks,
                guestAccelerators=guest_accelerators,
                hostname=args.hostname,
                labels=labels,
                machineType=machine_type_uri,
                metadata=metadata,
                minCpuPlatform=args.min_cpu_platform,
                name=instance_ref.Name(),
                networkInterfaces=network_interfaces,
                serviceAccounts=project_to_sa[instance_ref.project],
                scheduling=scheduling,
                tags=tags)

            if self._support_instance_kms and args.CONCEPTS.instance_kms_key:
                instance.instanceEncryptionKey = kms_utils.MaybeGetKmsKey(
                    args,
                    compute_client.messages,
                    instance.instanceEncryptionKey,
                    instance_prefix=True)

            if self._support_secure_tag and args.secure_tags:
                instance.secureTags = secure_tags_utils.GetSecureTags(
                    args.secure_tags)

            if args.resource_manager_tags:
                ret_resource_manager_tags = resource_manager_tags_utils.GetResourceManagerTags(
                    args.resource_manager_tags)
                if ret_resource_manager_tags is not None:
                    params = compute_client.messages.InstanceParams
                    instance.params = params(
                        resourceManagerTags=params.ResourceManagerTagsValue(
                            additionalProperties=[
                                params.ResourceManagerTagsValue.
                                AdditionalProperty(key=key, value=value)
                                for key, value in sorted(
                                    six.iteritems(ret_resource_manager_tags))
                            ]))

            if args.private_ipv6_google_access_type is not None:
                instance.privateIpv6GoogleAccess = (
                    instances_flags.GetPrivateIpv6GoogleAccessTypeFlagMapper(
                        compute_client.messages).GetEnumForChoice(
                            args.private_ipv6_google_access_type))

            has_visible_core_count = (self._support_visible_core_count
                                      and args.visible_core_count is not None)
            if (args.enable_nested_virtualization is not None
                    or args.threads_per_core is not None
                    or (self._support_numa_node_count
                        and args.numa_node_count is not None)
                    or has_visible_core_count
                    or args.enable_uefi_networking is not None):
                visible_core_count = args.visible_core_count if has_visible_core_count else None
                instance.advancedMachineFeatures = (
                    instance_utils.CreateAdvancedMachineFeaturesMessage(
                        compute_client.messages,
                        args.enable_nested_virtualization,
                        args.threads_per_core, args.numa_node_count
                        if self._support_numa_node_count else None,
                        visible_core_count, args.enable_uefi_networking))

            resource_policies = getattr(args, 'resource_policies', None)
            if resource_policies:
                parsed_resource_policies = []
                for policy in resource_policies:
                    resource_policy_ref = maintenance_util.ParseResourcePolicyWithZone(
                        resource_parser,
                        policy,
                        project=instance_ref.project,
                        zone=instance_ref.zone)
                    parsed_resource_policies.append(
                        resource_policy_ref.SelfLink())
                instance.resourcePolicies = parsed_resource_policies

            if shielded_instance_config:
                instance.shieldedInstanceConfig = shielded_instance_config

            if confidential_instance_config:
                instance.confidentialInstanceConfig = confidential_instance_config

            if self._support_erase_vss and args.IsSpecified(
                    'erase_windows_vss_signature'):
                instance.eraseWindowsVssSignature = args.erase_windows_vss_signature

            if self._support_post_key_revocation_action_type and args.IsSpecified(
                    'post_key_revocation_action_type'):
                instance.postKeyRevocationActionType = arg_utils.ChoiceToEnum(
                    args.post_key_revocation_action_type,
                    compute_client.messages.Instance.
                    PostKeyRevocationActionTypeValueValuesEnum)

            if self._support_key_revocation_action_type and args.IsSpecified(
                    'key_revocation_action_type'):
                instance.keyRevocationActionType = arg_utils.ChoiceToEnum(
                    args.key_revocation_action_type, compute_client.messages.
                    Instance.KeyRevocationActionTypeValueValuesEnum)

            if args.IsSpecified('network_performance_configs'):
                instance.networkPerformanceConfig = instance_utils.GetNetworkPerformanceConfig(
                    args, compute_client)

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

            if source_instance_template:
                request.sourceInstanceTemplate = source_instance_template

            if source_machine_image:
                request.instance.sourceMachineImage = source_machine_image
                if args.IsSpecified('source_machine_image_csek_key_file'):
                    key = instance_utils.GetSourceMachineImageKey(
                        args, self.SOURCE_MACHINE_IMAGE, compute_client,
                        holder)
                    request.instance.sourceMachineImageEncryptionKey = key

            if self._support_machine_image_key and args.IsSpecified(
                    'source_machine_image_csek_key_file'):
                if not args.IsSpecified('source_machine_image'):
                    raise exceptions.RequiredArgumentException(
                        '`--source-machine-image`',
                        '`--source-machine-image-csek-key-file` requires '
                        '`--source-machine-image` to be specified`')

            if args.IsSpecified('enable_display_device'):
                request.instance.displayDevice = compute_client.messages.DisplayDevice(
                    enableDisplay=args.enable_display_device)

            request.instance.reservationAffinity = instance_utils.GetReservationAffinity(
                args, compute_client)

            requests.append(
                (compute_client.apitools_client.instances, 'Insert', request))
        return requests
Beispiel #5
0
def _RunCreate(compute_api,
               args,
               support_source_instance,
               support_kms=False,
               support_location_hint=False,
               support_post_key_revocation_action_type=False,
               support_threads_per_core=False,
               support_multi_writer=False):
  """Common routine for creating instance template.

  This is shared between various release tracks.

  Args:
      compute_api: The compute api.
      args: argparse.Namespace, An object that contains the values for the
        arguments specified in the .Args() method.
      support_source_instance: indicates whether source instance is supported.
      support_kms: Indicate whether KMS is integrated or not.
      support_location_hint: Indicate whether location hint is supported.
      support_post_key_revocation_action_type: Indicate whether
        post_key_revocation_action_type is supported.
      support_threads_per_core: Indicates whether changing the number of threads
        per core is supported.
      support_multi_writer: Indicates whether a disk can have multiple writers.

  Returns:
      A resource object dispatched by display.Displayer().
  """
  _ValidateInstancesFlags(args, support_kms=support_kms)
  instances_flags.ValidateNetworkTierArgs(args)

  instance_templates_flags.ValidateServiceProxyFlags(args)

  client = compute_api.client

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

  instance_template_ref = (
      Create.InstanceTemplateArg.ResolveAsResource(args, compute_api.resources))

  AddScopesForServiceProxy(args)
  AddServiceProxyArgsToMetadata(args)

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

  if hasattr(args, 'network_interface') and args.network_interface:
    network_interfaces = (
        instance_template_utils.CreateNetworkInterfaceMessages)(
            resources=compute_api.resources,
            scope_lister=flags.GetDefaultScopeLister(client),
            messages=client.messages,
            network_interface_arg=args.network_interface,
            region=args.region)
  else:
    network_tier = getattr(args, 'network_tier', None)
    stack_type = getattr(args, 'stack_type', None)
    ipv6_network_tier = getattr(args, 'ipv6_network_tier', None)
    network_interfaces = [
        instance_template_utils.CreateNetworkInterfaceMessage(
            resources=compute_api.resources,
            scope_lister=flags.GetDefaultScopeLister(client),
            messages=client.messages,
            network=args.network,
            private_ip=args.private_network_ip,
            region=args.region,
            subnet=args.subnet,
            address=(instance_template_utils.EPHEMERAL_ADDRESS
                     if not args.no_address and not args.address else
                     args.address),
            network_tier=network_tier,
            stack_type=stack_type,
            ipv6_network_tier=ipv6_network_tier)
    ]

  # Compute the shieldedInstanceConfig message.
  shieldedinstance_config_message = BuildShieldedInstanceConfigMessage(
      messages=client.messages, args=args)

  confidential_instance_config_message = (
      BuildConfidentialInstanceConfigMessage(
          messages=client.messages, args=args))

  node_affinities = sole_tenancy_util.GetSchedulingNodeAffinityListFromArgs(
      args, client.messages)

  location_hint = None
  if support_location_hint and args.IsSpecified('location_hint'):
    location_hint = args.location_hint

  scheduling = instance_utils.CreateSchedulingMessage(
      messages=client.messages,
      maintenance_policy=args.maintenance_policy,
      preemptible=args.preemptible,
      restart_on_failure=args.restart_on_failure,
      node_affinities=node_affinities,
      min_node_cpu=args.min_node_cpu,
      location_hint=location_hint)

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

  create_boot_disk = not (
      instance_utils.UseExistingBootDisk((args.disk or []) +
                                         (args.create_disk or [])))
  if create_boot_disk:
    image_expander = image_utils.ImageExpander(client, compute_api.resources)
    try:
      image_uri, _ = image_expander.ExpandImageFlag(
          user_project=instance_template_ref.project,
          image=args.image,
          image_family=args.image_family,
          image_project=args.image_project,
          return_image_resource=True)
    except utils.ImageNotFoundError as e:
      if args.IsSpecified('image_project'):
        raise e
      image_uri, _ = image_expander.ExpandImageFlag(
          user_project=instance_template_ref.project,
          image=args.image,
          image_family=args.image_family,
          image_project=args.image_project,
          return_image_resource=False)
      raise utils.ImageNotFoundError(
          'The resource [{}] was not found. Is the image located in another '
          'project? Use the --image-project flag to specify the '
          'project where the image is located.'.format(image_uri))
  else:
    image_uri = None

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

  persistent_disks = (
      instance_template_utils.CreatePersistentAttachedDiskMessages(
          client.messages, args.disk or []))

  persistent_create_disks = (
      instance_template_utils.CreatePersistentCreateDiskMessages(
          client,
          compute_api.resources,
          instance_template_ref.project,
          getattr(args, 'create_disk', []),
          support_kms=support_kms,
          support_multi_writer=support_multi_writer))

  if create_boot_disk:
    boot_disk_list = [
        instance_template_utils.CreateDefaultBootAttachedDiskMessage(
            messages=client.messages,
            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,
            image_uri=image_uri,
            kms_args=args,
            support_kms=support_kms)
    ]
  else:
    boot_disk_list = []

  local_nvdimms = create_utils.CreateLocalNvdimmMessages(
      args,
      compute_api.resources,
      client.messages,
  )

  local_ssds = create_utils.CreateLocalSsdMessages(
      args,
      compute_api.resources,
      client.messages,
  )

  disks = (
      boot_disk_list + persistent_disks + persistent_create_disks +
      local_nvdimms + local_ssds)

  machine_type = instance_utils.InterpretMachineType(
      machine_type=args.machine_type,
      custom_cpu=args.custom_cpu,
      custom_memory=args.custom_memory,
      ext=getattr(args, 'custom_extensions', None),
      vm_type=getattr(args, 'custom_vm_type', None))

  guest_accelerators = (
      instance_template_utils.CreateAcceleratorConfigMessages(
          client.messages, getattr(args, 'accelerator', None)))

  instance_template = client.messages.InstanceTemplate(
      properties=client.messages.InstanceProperties(
          machineType=machine_type,
          disks=disks,
          canIpForward=args.can_ip_forward,
          metadata=metadata,
          minCpuPlatform=args.min_cpu_platform,
          networkInterfaces=network_interfaces,
          serviceAccounts=service_accounts,
          scheduling=scheduling,
          tags=tags,
          guestAccelerators=guest_accelerators,
      ),
      description=args.description,
      name=instance_template_ref.Name(),
  )

  instance_template.properties.shieldedInstanceConfig = shieldedinstance_config_message

  instance_template.properties.reservationAffinity = instance_utils.GetReservationAffinity(
      args, client)

  instance_template.properties.confidentialInstanceConfig = (
      confidential_instance_config_message)

  if support_post_key_revocation_action_type and args.IsSpecified(
      'post_key_revocation_action_type'):
    instance_template.properties.postKeyRevocationActionType = arg_utils.ChoiceToEnum(
        args.post_key_revocation_action_type, client.messages.InstanceProperties
        .PostKeyRevocationActionTypeValueValuesEnum)

  if args.private_ipv6_google_access_type is not None:
    instance_template.properties.privateIpv6GoogleAccess = (
        instances_flags.GetPrivateIpv6GoogleAccessTypeFlagMapperForTemplate(
            client.messages).GetEnumForChoice(
                args.private_ipv6_google_access_type))

  # If either enable-nested-virtualization or threads-per-core are specified,
  # make an AdvancedMachineFeatures message.
  has_threads_per_core = (
      support_threads_per_core and args.threads_per_core is not None)
  if (args.enable_nested_virtualization is not None or has_threads_per_core):
    threads_per_core = args.threads_per_core if has_threads_per_core else None
    instance_template.properties.advancedMachineFeatures = (
        instance_utils.CreateAdvancedMachineFeaturesMessage(
            client.messages, args.enable_nested_virtualization,
            threads_per_core))

  request = client.messages.ComputeInstanceTemplatesInsertRequest(
      instanceTemplate=instance_template, project=instance_template_ref.project)

  request.instanceTemplate.properties.labels = ParseCreateArgsWithServiceProxy(
      args, client.messages.InstanceProperties.LabelsValue)

  _AddSourceInstanceToTemplate(compute_api, args, instance_template,
                               support_source_instance)

  return client.MakeRequests([(client.apitools_client.instanceTemplates,
                               'Insert', request)])
def _RunCreate(compute_api,
               args,
               support_source_instance,
               support_kms=False,
               support_post_key_revocation_action_type=False,
               support_multi_writer=False,
               support_mesh=False,
               support_host_error_timeout_seconds=False,
               support_numa_node_count=False,
               support_visible_core_count=False,
               support_disk_architecture=False,
               support_key_revocation_action_type=False,
               support_max_run_duration=False):
  """Common routine for creating instance template.

  This is shared between various release tracks.

  Args:
      compute_api: The compute api.
      args: argparse.Namespace, An object that contains the values for the
        arguments specified in the .Args() method.
      support_source_instance: indicates whether source instance is supported.
      support_kms: Indicate whether KMS is integrated or not.
      support_post_key_revocation_action_type: Indicate whether
        post_key_revocation_action_type is supported.
      support_multi_writer: Indicates whether a disk can have multiple writers.
      support_mesh: Indicates whether adding VM to a Anthos Service Mesh is
        supported.
      support_host_error_timeout_seconds: Indicate the timeout in seconds for
        host error detection.
      support_numa_node_count: Indicates whether setting NUMA node count is
        supported.
      support_visible_core_count: Indicates whether setting a custom visible
      support_disk_architecture: Storage resources can be used to create boot
        disks compatible with ARM64 or X86_64 machine architectures. If this
        field is not specified, the default is ARCHITECTURE_UNSPECIFIED.
      support_key_revocation_action_type: Indicate whether
        key_revocation_action_type is supported.
      support_max_run_duration: Indicate whether max-run-duration or
        termination-time issupported.

  Returns:
      A resource object dispatched by display.Displayer().
  """
  _ValidateInstancesFlags(
      args,
      support_kms=support_kms,
      support_max_run_duration=support_max_run_duration)
  instances_flags.ValidateNetworkTierArgs(args)

  instance_templates_flags.ValidateServiceProxyFlags(args)
  if support_mesh:
    instance_templates_flags.ValidateMeshFlag(args)

  client = compute_api.client

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

  instance_template_ref = (
      Create.InstanceTemplateArg.ResolveAsResource(args, compute_api.resources))

  AddScopesForServiceProxy(args)
  AddServiceProxyArgsToMetadata(args)

  if hasattr(args, 'network_interface') and args.network_interface:
    network_interfaces = (
        instance_template_utils.CreateNetworkInterfaceMessages)(
            resources=compute_api.resources,
            scope_lister=flags.GetDefaultScopeLister(client),
            messages=client.messages,
            network_interface_arg=args.network_interface,
            region=args.region)
  else:
    network_tier = getattr(args, 'network_tier', None)
    stack_type = getattr(args, 'stack_type', None)
    ipv6_network_tier = getattr(args, 'ipv6_network_tier', None)
    network_interfaces = [
        instance_template_utils.CreateNetworkInterfaceMessage(
            resources=compute_api.resources,
            scope_lister=flags.GetDefaultScopeLister(client),
            messages=client.messages,
            network=args.network,
            private_ip=args.private_network_ip,
            region=args.region,
            subnet=args.subnet,
            address=(instance_template_utils.EPHEMERAL_ADDRESS
                     if not args.no_address and not args.address else
                     args.address),
            network_tier=network_tier,
            stack_type=stack_type,
            ipv6_network_tier=ipv6_network_tier)
    ]

  if support_mesh:
    ConfigureMeshTemplate(args, instance_template_ref, network_interfaces)

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

  # Compute the shieldedInstanceConfig message.
  shieldedinstance_config_message = BuildShieldedInstanceConfigMessage(
      messages=client.messages, args=args)

  confidential_instance_config_message = (
      BuildConfidentialInstanceConfigMessage(
          messages=client.messages, args=args))

  node_affinities = sole_tenancy_util.GetSchedulingNodeAffinityListFromArgs(
      args, client.messages)

  location_hint = None
  if args.IsSpecified('location_hint'):
    location_hint = args.location_hint

  provisioning_model = None
  if (hasattr(args, 'provisioning_model') and
      args.IsSpecified('provisioning_model')):
    provisioning_model = args.provisioning_model

  termination_action = None
  if (hasattr(args, 'instance_termination_action') and
      args.IsSpecified('instance_termination_action')):
    termination_action = args.instance_termination_action

  max_run_duration = None
  if (hasattr(args, 'max_run_duration') and
      args.IsSpecified('max_run_duration')):
    max_run_duration = args.max_run_duration

  termination_time = None
  if (hasattr(args, 'termination_time') and
      args.IsSpecified('termination_time')):
    termination_time = args.termination_time

  host_error_timeout_seconds = None
  if support_host_error_timeout_seconds and args.IsSpecified(
      'host_error_timeout_seconds'):
    host_error_timeout_seconds = args.host_error_timeout_seconds
  scheduling = instance_utils.CreateSchedulingMessage(
      messages=client.messages,
      maintenance_policy=args.maintenance_policy,
      preemptible=args.preemptible,
      restart_on_failure=args.restart_on_failure,
      node_affinities=node_affinities,
      min_node_cpu=args.min_node_cpu,
      location_hint=location_hint,
      provisioning_model=provisioning_model,
      instance_termination_action=termination_action,
      host_error_timeout_seconds=host_error_timeout_seconds,
      max_run_duration=max_run_duration,
      termination_time=termination_time)

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

  create_boot_disk = not (
      instance_utils.UseExistingBootDisk((args.disk or []) +
                                         (args.create_disk or [])))
  if create_boot_disk:
    image_expander = image_utils.ImageExpander(client, compute_api.resources)
    try:
      image_uri, _ = image_expander.ExpandImageFlag(
          user_project=instance_template_ref.project,
          image=args.image,
          image_family=args.image_family,
          image_project=args.image_project,
          return_image_resource=True)
    except utils.ImageNotFoundError as e:
      if args.IsSpecified('image_project'):
        raise e
      image_uri, _ = image_expander.ExpandImageFlag(
          user_project=instance_template_ref.project,
          image=args.image,
          image_family=args.image_family,
          image_project=args.image_project,
          return_image_resource=False)
      raise utils.ImageNotFoundError(
          'The resource [{}] was not found. Is the image located in another '
          'project? Use the --image-project flag to specify the '
          'project where the image is located.'.format(image_uri))
  else:
    image_uri = None

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

  persistent_disks = (
      instance_template_utils.CreatePersistentAttachedDiskMessages(
          client.messages, args.disk or []))

  persistent_create_disks = (
      instance_template_utils.CreatePersistentCreateDiskMessages(
          client,
          compute_api.resources,
          instance_template_ref.project,
          getattr(args, 'create_disk', []),
          support_kms=support_kms,
          support_multi_writer=support_multi_writer,
          support_disk_architecture=support_disk_architecture))

  if create_boot_disk:
    boot_disk_list = [
        instance_template_utils.CreateDefaultBootAttachedDiskMessage(
            messages=client.messages,
            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,
            image_uri=image_uri,
            kms_args=args,
            support_kms=support_kms,
            disk_provisioned_iops=args.boot_disk_provisioned_iops)
    ]
  else:
    boot_disk_list = []

  local_nvdimms = create_utils.CreateLocalNvdimmMessages(
      args,
      compute_api.resources,
      client.messages,
  )

  local_ssds = create_utils.CreateLocalSsdMessages(
      args,
      compute_api.resources,
      client.messages,
  )

  disks = (
      boot_disk_list + persistent_disks + persistent_create_disks +
      local_nvdimms + local_ssds)

  machine_type = instance_utils.InterpretMachineType(
      machine_type=args.machine_type,
      custom_cpu=args.custom_cpu,
      custom_memory=args.custom_memory,
      ext=getattr(args, 'custom_extensions', None),
      vm_type=getattr(args, 'custom_vm_type', None))

  guest_accelerators = (
      instance_template_utils.CreateAcceleratorConfigMessages(
          client.messages, getattr(args, 'accelerator', None)))

  instance_template = client.messages.InstanceTemplate(
      properties=client.messages.InstanceProperties(
          machineType=machine_type,
          disks=disks,
          canIpForward=args.can_ip_forward,
          metadata=metadata,
          minCpuPlatform=args.min_cpu_platform,
          networkInterfaces=network_interfaces,
          serviceAccounts=service_accounts,
          scheduling=scheduling,
          tags=tags,
          guestAccelerators=guest_accelerators,
      ),
      description=args.description,
      name=instance_template_ref.Name(),
  )

  instance_template.properties.shieldedInstanceConfig = shieldedinstance_config_message

  instance_template.properties.reservationAffinity = instance_utils.GetReservationAffinity(
      args, client)

  instance_template.properties.confidentialInstanceConfig = (
      confidential_instance_config_message)

  if args.IsSpecified('network_performance_configs'):
    instance_template.properties.networkPerformanceConfig = (
        instance_utils.GetNetworkPerformanceConfig(args, client))

  if args.IsSpecified('resource_policies'):
    instance_template.properties.resourcePolicies = getattr(
        args, 'resource_policies', [])

  if support_post_key_revocation_action_type and args.IsSpecified(
      'post_key_revocation_action_type'):
    instance_template.properties.postKeyRevocationActionType = arg_utils.ChoiceToEnum(
        args.post_key_revocation_action_type, client.messages.InstanceProperties
        .PostKeyRevocationActionTypeValueValuesEnum)

  if support_key_revocation_action_type and args.IsSpecified(
      'key_revocation_action_type'):
    instance_template.properties.keyRevocationActionType = arg_utils.ChoiceToEnum(
        args.key_revocation_action_type, client.messages.InstanceProperties
        .KeyRevocationActionTypeValueValuesEnum)

  if args.private_ipv6_google_access_type is not None:
    instance_template.properties.privateIpv6GoogleAccess = (
        instances_flags.GetPrivateIpv6GoogleAccessTypeFlagMapperForTemplate(
            client.messages).GetEnumForChoice(
                args.private_ipv6_google_access_type))

  # Create an AdvancedMachineFeatures message if any of the features requiring
  # one have been specified.
  has_visible_core_count = (
      support_visible_core_count and args.visible_core_count is not None)
  if (args.enable_nested_virtualization is not None or
      args.threads_per_core is not None or
      (support_numa_node_count and args.numa_node_count is not None) or
      has_visible_core_count or args.enable_uefi_networking is not None):

    visible_core_count = args.visible_core_count if has_visible_core_count else None
    instance_template.properties.advancedMachineFeatures = (
        instance_utils.CreateAdvancedMachineFeaturesMessage(
            client.messages, args.enable_nested_virtualization,
            args.threads_per_core,
            args.numa_node_count if support_numa_node_count else None,
            visible_core_count, args.enable_uefi_networking))

  if args.resource_manager_tags:
    ret_resource_manager_tags = resource_manager_tags_utils.GetResourceManagerTags(
        args.resource_manager_tags)
    if ret_resource_manager_tags is not None:
      properties = client.messages.InstanceProperties
      instance_template.properties.resourceManagerTags = properties.ResourceManagerTagsValue(
          additionalProperties=[
              properties.ResourceManagerTagsValue.AdditionalProperty(
                  key=key, value=value) for key, value in sorted(
                      six.iteritems(ret_resource_manager_tags))
          ])

  request = client.messages.ComputeInstanceTemplatesInsertRequest(
      instanceTemplate=instance_template, project=instance_template_ref.project)

  request.instanceTemplate.properties.labels = ParseCreateArgsWithServiceProxy(
      args, client.messages.InstanceProperties.LabelsValue)

  _AddSourceInstanceToTemplate(compute_api, args, instance_template,
                               support_source_instance)

  return client.MakeRequests([(client.apitools_client.instanceTemplates,
                               'Insert', request)])