feat: Add new gcloud commands, API clients, and third-party libraries across various services.

This commit is contained in:
2026-01-01 20:26:35 +01:00
parent 5e23cbece0
commit a19e592eb7
25221 changed files with 8324611 additions and 0 deletions

View File

@@ -0,0 +1,33 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The command group for osconfig CLI."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.DefaultUniverseOnly
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.ALPHA,
base.ReleaseTrack.GA)
class Osconfig(base.Group):
"""Manage OS Config tasks for Compute Engine VM instances."""
category = base.TOOLS_CATEGORY
def Filter(self, context, args):
del context, args
base.EnableUserProjectQuota()

View File

@@ -0,0 +1,26 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The command group for os-config guest-policies CLI."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class OsconfigGuestPolicies(base.Group):
"""Manage guest OS policies for Compute Engine VM instances."""

View File

@@ -0,0 +1,80 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Implements command to create a new guest policy."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.compute.os_config import utils as osconfig_api_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute.os_config import utils as osconfig_command_utils
from googlecloudsdk.core import properties
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class Create(base.Command):
r"""Create a guest policy for a project.
## EXAMPLES
To create a guest policy `policy1` in the current project, run:
$ {command} policy1 --file=path_to_config_file
"""
@staticmethod
def Args(parser):
"""See base class."""
parser.add_argument(
'POLICY_ID',
type=str,
help="""\
Name of the guest policy to create.
This name must contain only lowercase letters, numbers, and hyphens,
start with a letter, end with a number or a letter, be between 1-63
characters, and unique within the project.""",
)
parser.add_argument(
'--file',
required=True,
help="""\
The JSON or YAML file with the guest policy to create. For information
about the guest policy format, see https://cloud.google.com/compute/docs/osconfig/rest/v1beta/projects.guestPolicies.""",
)
def Run(self, args):
"""See base class."""
release_track = self.ReleaseTrack()
client = osconfig_api_utils.GetClientInstance(release_track)
messages = osconfig_api_utils.GetClientMessages(release_track)
(guest_policy,
_) = osconfig_command_utils.GetResourceAndUpdateFieldsFromFile(
args.file, messages.GuestPolicy)
project = properties.VALUES.core.project.GetOrFail()
parent_path = osconfig_command_utils.GetProjectUriPath(project)
request = messages.OsconfigProjectsGuestPoliciesCreateRequest(
guestPolicy=guest_policy,
guestPolicyId=args.POLICY_ID,
parent=parent_path,
)
service = client.projects_guestPolicies
return service.Create(request)

View File

@@ -0,0 +1,61 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Implements command to delete a specified guest policy."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.compute.os_config import utils as osconfig_api_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute.os_config import utils as osconfig_command_utils
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class Delete(base.DeleteCommand):
"""Delete the specified guest policy.
## EXAMPLES
To delete the guest policy named `policy1` in the current project, run:
$ {command} policy1
"""
@staticmethod
def Args(parser):
"""See base class."""
parser.add_argument(
'POLICY_ID', type=str, help='Name of the guest policy to delete.')
def Run(self, args):
"""See base class."""
release_track = self.ReleaseTrack()
client = osconfig_api_utils.GetClientInstance(release_track)
messages = osconfig_api_utils.GetClientMessages(release_track)
project = properties.VALUES.core.project.GetOrFail()
guest_policy_name = osconfig_command_utils.GetGuestPolicyUriPath(
'projects', project, args.POLICY_ID)
request = messages.OsconfigProjectsGuestPoliciesDeleteRequest(
name=guest_policy_name)
service = client.projects_guestPolicies
response = service.Delete(request)
log.DeletedResource(guest_policy_name)
return response

View File

@@ -0,0 +1,57 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Implements command to describe a specified guest policy."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.compute.os_config import utils as osconfig_api_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute.os_config import utils as osconfig_command_utils
from googlecloudsdk.core import properties
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class Describe(base.DescribeCommand):
"""Describe the specified guest policy.
## EXAMPLES
To describe the guest policy `policy1` in the current project, run:
$ {command} policy1
"""
@staticmethod
def Args(parser):
"""See base class."""
parser.add_argument(
'POLICY_ID', type=str, help='Name of the guest policy to describe.')
def Run(self, args):
"""See base class."""
release_track = self.ReleaseTrack()
client = osconfig_api_utils.GetClientInstance(release_track)
messages = osconfig_api_utils.GetClientMessages(release_track)
project = properties.VALUES.core.project.GetOrFail()
request = messages.OsconfigProjectsGuestPoliciesGetRequest(
name=osconfig_command_utils.GetGuestPolicyUriPath(
'projects', project, args.POLICY_ID))
service = client.projects_guestPolicies
return service.Get(request)

View File

@@ -0,0 +1,104 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Implements command to list guest policies."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from apitools.base.py import list_pager
from googlecloudsdk.api_lib.compute.os_config import utils as osconfig_api_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute.os_config import utils as osconfig_command_utils
from googlecloudsdk.core import properties
def _TransformGuestPolicyDescription(resource):
"""Returns a length-limited guest policy description."""
max_len = 30 # Show only the first 30 characters if description is long.
description = resource.get('description', '')
return (description[:max_len] +
'..') if len(description) > max_len else description
def _MakeGetUriFunc(registry):
"""Returns a transformation function from a guest policy resource to URI."""
def UriFunc(resource):
parent_type = resource.name.split('/')[0]
ref = registry.Parse(
resource.name,
collection='osconfig.{}.guestPolicies'.format(parent_type))
return ref.SelfLink()
return UriFunc
def _Args(parser, release_track):
"""Parses input flags and sets up output formats."""
parser.display_info.AddFormat("""
table(
name.basename(),
description(),
create_time,
update_time
)
""")
parser.display_info.AddTransforms(
{'description': _TransformGuestPolicyDescription})
registry = osconfig_api_utils.GetRegistry(release_track)
parser.display_info.AddUriFunc(_MakeGetUriFunc(registry))
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class List(base.ListCommand):
"""List guest policies in a project.
## EXAMPLES
To list guest policies in the current project, run:
$ {command}
"""
@staticmethod
def Args(parser):
"""See base class."""
_Args(parser, base.ReleaseTrack.BETA)
def Run(self, args):
"""See base class."""
release_track = self.ReleaseTrack()
client = osconfig_api_utils.GetClientInstance(release_track)
messages = osconfig_api_utils.GetClientMessages(release_track)
project = properties.VALUES.core.project.GetOrFail()
request = messages.OsconfigProjectsGuestPoliciesListRequest(
pageSize=args.page_size,
parent=osconfig_command_utils.GetProjectUriPath(project),
)
service = client.projects_guestPolicies
return list_pager.YieldFromList(
service,
request,
limit=args.limit,
batch_size=osconfig_command_utils.GetListBatchSize(args),
field='guestPolicies',
batch_size_attribute='pageSize',
)

View File

@@ -0,0 +1,165 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Implements command to look up all effective guest policies of an instance."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.api_lib.compute.os_config import utils as osconfig_api_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute.instances import flags
from googlecloudsdk.core import log
from googlecloudsdk.core.resource import resource_projector
import six
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class Lookup(base.Command):
"""Display the guest policies that are applied to an instance.
## EXAMPLES
To view all guest policies that are applied to an instance named
`my-instance`, run:
$ {command} my-instance
"""
_OS_ARCHITECTURE_KEY = 'Architecture'
_OS_SHORTNAME_KEY = 'ShortName'
_OS_VERSION_KEY = 'Version'
_OS_INFO_FIELD_KEYS = (_OS_ARCHITECTURE_KEY, _OS_SHORTNAME_KEY,
_OS_VERSION_KEY)
def _GetInstanceRef(self, holder, args):
return flags.INSTANCE_ARG.ResolveAsResource(
args,
holder.resources,
scope_lister=flags.GetInstanceZoneScopeLister(holder.client),
)
def _GetGuestInventoryGuestAttributes(self, instance_ref):
try:
holder = base_classes.ComputeApiHolder(base.ReleaseTrack.GA)
client = holder.client
messages = client.messages
request = messages.ComputeInstancesGetGuestAttributesRequest(
instance=instance_ref.Name(),
project=instance_ref.project,
queryPath='guestInventory/',
zone=instance_ref.zone)
response = client.apitools_client.instances.GetGuestAttributes(request)
return response.queryValue.items
except Exception as e:
if ('The resource \'guestInventory/\' of type \'Guest Attribute\' was not'
' found.') in six.text_type(e):
return []
raise e
def _GetOsInfo(self, guest_attributes):
guest_attributes_json = resource_projector.MakeSerializable(
guest_attributes)
os_info = {}
for guest_attribute in guest_attributes_json:
guest_attribute_key = guest_attribute['key']
if guest_attribute_key in self._OS_INFO_FIELD_KEYS:
os_info[guest_attribute_key] = guest_attribute['value']
return os_info
def _CreateRequest(self, messages, instance_name, os_architecture,
os_shortname, os_version):
return messages.OsconfigProjectsZonesInstancesLookupEffectiveGuestPolicyRequest(
instance=instance_name,
lookupEffectiveGuestPolicyRequest=messages
.LookupEffectiveGuestPolicyRequest(
osArchitecture=os_architecture,
osShortName=os_shortname,
osVersion=os_version,
),
)
def _GetResponse(self, service, request):
return service.LookupEffectiveGuestPolicy(request)
@staticmethod
def Args(parser):
"""See base class."""
flags.INSTANCE_ARG.AddArgument(
parser, operation_type='look up guest policies for')
parser.display_info.AddFormat("""
table(
packages:format="table[box,title="PACKAGES"](
source,
package.name,
package.desiredState,
package.manager,
package.version)",
packageRepositories:format="table[box,title='PACKAGE REPOSITORIES'](
source,
packageRepository.apt:format='table[box,title="APT"](
uri,
distribution,
components.list())',
packageRepository.goo:format='table[box,title="GOO"](
name,
url)',
packageRepository.yum:format='table[box,title="YUM"](
id,
baseUrl)',
packageRepository.zypper:format='table[box,title="ZYPPER"](
id,
baseUrl)')",
softwareRecipes:format="table[box,title='SOFTWARE RECIPES'](
source,
softwareRecipe.name,
softwareRecipe.version,
softwareRecipe.desiredState
)"
)
""")
def Run(self, args):
"""See base class."""
release_track = self.ReleaseTrack()
holder = base_classes.ComputeApiHolder(release_track)
instance_ref = self._GetInstanceRef(holder, args)
guest_attributes = self._GetGuestInventoryGuestAttributes(instance_ref)
os_info = self._GetOsInfo(guest_attributes)
os_architecture = os_info.get(self._OS_ARCHITECTURE_KEY)
os_shortname = os_info.get(self._OS_SHORTNAME_KEY)
os_version = os_info.get(self._OS_VERSION_KEY)
client = osconfig_api_utils.GetClientInstance(release_track)
messages = osconfig_api_utils.GetClientMessages(release_track)
request = self._CreateRequest(messages, instance_ref.RelativeName(),
os_architecture, os_shortname, os_version)
response = self._GetResponse(client.projects_zones_instances, request)
if not any([
response.packages, response.packageRepositories,
response.softwareRecipes
]):
log.status.Print('No effective guest policy found for [{}].'.format(
instance_ref.RelativeName()))
return response

View File

@@ -0,0 +1,78 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Implements command to update a specified guest policy."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.compute.os_config import utils as osconfig_api_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute.os_config import utils as osconfig_command_utils
from googlecloudsdk.core import properties
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class Update(base.Command):
r"""Update the specified guest policy for a project.
## EXAMPLES
To update the guest policy `policy1` in the project `project1`, run:
$ {command} policy1 \
--file=path_to_config_file --project=project1
"""
@staticmethod
def Args(parser):
"""See base class."""
parser.add_argument(
'POLICY_ID', type=str, help='Name of the guest policy to update.')
parser.add_argument(
'--file',
required=True,
help="""\
The JSON or YAML file with the updated guest policy.
If this file specifies an etag value, the update succeeds only if
the policy that is already in place has a matching etag value. If no
etag value is specified, the specifications in the updated policy file
replaces the existing policy.
For information about the guest policy format, see https://cloud.google.com/compute/docs/osconfig/rest/v1beta/projects.guestPolicies.
""")
def Run(self, args):
"""See base class."""
release_track = self.ReleaseTrack()
client = osconfig_api_utils.GetClientInstance(release_track)
messages = osconfig_api_utils.GetClientMessages(release_track)
(guest_policy,
_) = osconfig_command_utils.GetResourceAndUpdateFieldsFromFile(
args.file, messages.GuestPolicy)
project = properties.VALUES.core.project.GetOrFail()
request = messages.OsconfigProjectsGuestPoliciesPatchRequest(
guestPolicy=guest_policy,
name=osconfig_command_utils.GetGuestPolicyUriPath(
'projects', project, args.POLICY_ID),
updateMask=None,
)
service = client.projects_guestPolicies
return service.Patch(request)

View File

@@ -0,0 +1,26 @@
# -*- coding: utf-8 -*- #
# Copyright 2021 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The command group for osconfig instance-compliances CLI."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class OsconfigInstanceCompliances(base.Group):
"""Report compliance states for OS policies applied to a Compute Engine VM."""

View File

@@ -0,0 +1,52 @@
- release_tracks: [ALPHA]
help_text:
brief: Describe the compliance states for OS policies that are applied to a VM.
description: |
Describe the compliance states for OS policies that are applied to a VM.
examples: |
To report the compliance state of an instance `my-instance`
that has the instance ID `5678` in the current project
and location `us-central1-a`, run:
$ {command} 5678 --location=us-central1-a
request:
collection: osconfig.projects.locations.instanceOSPoliciesCompliances
# This command is implemented manually (without resources) so that
# its help documentation specifically allows instance IDs as the first
# positional paramater.
#
# Without this, a presubmit check will block this yaml file.
disable_resource_check: true
modify_request_hooks:
- googlecloudsdk.command_lib.compute.os_config.instance_os_policies_compliances.declarative:SetNameOnDescribeRequestHook
ALPHA:
api_version: v1alpha
arguments:
params:
- arg_name: instance
is_positional: true
help_text: |
ID or name of the Compute Engine VM instance to describe. For details on valid instance IDs,
refer to the criteria documented under the field `id` at:
https://cloud.google.com/compute/docs/reference/rest/v1/instances
- arg_name: location
help_text: |
Location of the VM instance to describe. If not specified, the property
`compute/zone` is used. For details on setting properties,
see: https://cloud.google.com/sdk/docs/properties
output:
format: |
default(
detailedState,
detailedStateReason,
instance,
lastComplianceCheckTime.date("%Y-%m-%dT%H:%M:%SZ"),
lastComplianceRunId,
name,
osPolicyCompliances,
state
)

View File

@@ -0,0 +1,35 @@
- release_tracks: [ALPHA]
help_text:
brief: List compliance states for OS policies that are applied to VMs.
description: |
List compliance states for OS policies that are applied to VMs.
examples: |
To list compliance states for OS policies that are applied to VMs in `my-project`
and location `us-central1-a`, run:
$ {command} --project=my-project --location=us-central1-a
request:
collection: osconfig.projects.locations.instanceOSPoliciesCompliances
ALPHA:
api_version: v1alpha
response:
id_field: name
arguments:
resource:
help_text: Location of the VMs.
spec: !REF googlecloudsdk.command_lib.compute.os_config.resources:location
output:
format: |
table(
name.basename():label=INSTANCE_ID,
instance:label=INSTANCE_NAME,
state,
detailed_state,
last_compliance_check_time.date("%Y-%m-%dT%H:%M:%SZ"),
last_compliance_run_id
)

View File

@@ -0,0 +1,27 @@
# -*- coding: utf-8 -*- #
# Copyright 2021 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The command group for osconfig inventory CLI."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.DefaultUniverseOnly
@base.ReleaseTracks(base.ReleaseTrack.GA, base.ReleaseTrack.ALPHA)
class OsconfigInventory(base.Group):
"""Display inventory of a Compute Engine VM."""

View File

@@ -0,0 +1,114 @@
- release_tracks: [GA, ALPHA]
help_text:
brief: Describe the inventory data for a Compute Engine VM instance.
description: |
Describe the inventory data for a Compute Engine VM instance.
examples: |
To describe the inventory of an instance `my-instance`
that has the instance ID `5678` in the current project
and location 'us-central1-a', run:
$ {command} my-instance --location=us-central1-a
request:
collection: osconfig.projects.locations.instances.inventories
# This command is implemented manually (without resources) so that
# its help documentation specifically allows instance IDs as the first
# positional paramater.
#
# Without this, a presubmit check will block this yaml file.
disable_resource_check: true
ALPHA:
api_version: v1alpha
GA:
api_version: v1
modify_request_hooks:
- googlecloudsdk.command_lib.compute.os_config.inventories.declarative:SetNameOnDescribeRequestHook
response:
id_field: name
modify_response_hooks:
- googlecloudsdk.command_lib.compute.os_config.inventories.declarative:CreateDescribeTableViewResponseHook
arguments:
params:
- arg_name: instance
is_positional: true
help_text: |
ID or name of the Compute Engine VM instance to describe. For details on valid instance IDs,
refer to the criteria documented under the field `id` at:
https://cloud.google.com/compute/docs/reference/rest/v1/instances
- arg_name: location
help_text: |
Location of the Compute Engine VM instance to describe. If not specified, the property
`compute/zone` is used. For details on setting properties,
see: https://cloud.google.com/sdk/docs/properties
- api_field: view
help_text: |
Specifies what information should be included in the
output. If unspecified, the default view is `basic`.
choices:
- arg_value: basic
enum_value: BASIC
help_text: Output is limited to operating system details.
- arg_value: full
enum_value: FULL
help_text: Output includes operating system details and package information.
output:
format: |
multi(
installed_packages.yumPackage:format=
"table[box,title='Installed Packages (Yum)']
(package_name:sort=1,architecture,version)",
installed_packages.aptPackage:format=
"table[box,title='Installed Packages (Apt)']
(package_name:sort=1,architecture,version)",
installed_packages.zypperPackage:format=
"table[box,title='Installed Packages (Zypper)']
(package_name:sort=1,architecture,version)",
installed_packages.googetPackage:format=
"table[box,title='Installed Packages (GooGet)']
(package_name:sort=1,architecture,version)",
installed_packages.cosPackage:format=
"table[box,title='Installed Packages (COS)']
(package_name:sort=1,architecture,version)",
installed_packages.zypperPatch:format=
"table[box,title='Installed Patches (Zypper Patch)']
(patch_name:sort=1,category,severity,summary)",
installed_packages.wuaPackage:format=
"table[all-box,title='Installed Packages (Windows Update Agent)']
(title:sort=1:wrap,categories.extract(name).flatten(separator=', '):wrap,kb_article_ids.list(),support_url)",
installed_packages.qfePackage:format=
"table[box,title='Installed Packages (Quick Fix Engineering)']
(caption:sort=1,description,hot_fix_id,install_time)",
installed_packages.windowsApplication:format=
"table[box,title='Installed Packages (Windows Application)']
(displayName:sort=1,displayVersion,publisher,installDate.date('%Y-%m-%d'))",
updatedable_packages.yumPackage:format=
"table[box,title='Package Updates Available (Yum)']
(package_name:sort=1,architecture,version)",
updatedable_packages.aptPackage:format=
"table[box,title='Package Updates Available (Apt)']
(package_name:sort=1,architecture,version)",
updatedable_packages.zypperPackage:format=
"table[box,title='Package Updates Available (Zypper)']
(package_name:sort=1,architecture,version)",
updatedable_packages.googetPackage:format=
"table[box,title='Package Updates Available (GooGet)']
(package_name:sort=1,architecture,version)",
updatedable_packages.cosPackage:format=
"table[box,title='Package Updates Available (COS)']
(package_name:sort=1,architecture,version)",
updatedable_packages.zypperPatch:format=
"table[box,title='Patches Available (Zypper Patch)']
(patch_name:sort=1,category,severity,summary)",
updatedable_packages.wuaPackage:format=
"table[all-box,title='Package Updates Available (Windows Update Agent)']
(title:sort=1:wrap,categories.extract(name).flatten(separator=', '):wrap,kb_article_ids.list(),support_url)",
updatedable_packages.qfePackage:format=
"table[box,title='Package Updates Available (Quick Fix Engineering)']
(caption:sort=1,description,hot_fix_id,install_time)",
system_information:format="default
(architecture,hostname,kernelRelease,kernelVersion,longName,osconfigAgentVersion,shortName,updateTime.date('%Y-%m-%dT%H:%M:%SZ'),version)"
)

View File

@@ -0,0 +1,73 @@
- release_tracks: [GA, ALPHA]
help_text:
brief: List inventory data for all Compute Engine VM instances in a specified location.
description: |
List inventory data for all Compute Engine VM instances in a specified location.
The default page size is 25. To modify this, use the `--page-size` flag.
examples: |
To list the inventory of VMs in `my-project` and location `us-central1-a`, run:
$ {command} --project=my-project --location=us-central1-a
request:
collection: osconfig.projects.locations.instances.inventories
ALPHA:
api_version: v1alpha
GA:
api_version: v1
disable_resource_check: true
modify_request_hooks:
- googlecloudsdk.command_lib.compute.os_config.inventories.declarative:SetParentOnListRequestHook
- googlecloudsdk.command_lib.compute.os_config.declarative:SetDefaultPageSizeRequestHook:default_page_size=25
response:
id_field: name
modify_response_hooks:
- googlecloudsdk.command_lib.compute.os_config.inventories.declarative:CreateTableViewResponseHook
arguments:
params:
- arg_name: location
help_text: |
Location of the Compute Engine VM instances to list. If not specified, the property
`compute/zone` is used. For details on setting properties,
see: https://cloud.google.com/sdk/docs/properties
- api_field: view
help_text: |
Specifies what information should be included in the
output. If unspecified, the default view is `basic`.
choices:
- arg_value: basic
enum_value: BASIC
help_text: Output is limited to operating system details.
- arg_value: full
enum_value: FULL
help_text: Output includes operating system details and package information.
- arg_name: unmodified-api-response
hidden: true
default: false
help_text: |
Do not transform the response from API. Warning: the amount of data returned can be very
large.
output:
format: |
multi(
basic:format="table(
instance_id,
instance_name,
os,
osconfig_agent_version,
update_time.date('%Y-%m-%dT%H:%M:%SZ')
)",
full:format="table(
instance_id,
instance_name,
os,
installed_packages,
available_packages,
osconfig_agent_version,
update_time.date('%Y-%m-%dT%H:%M:%SZ')
)"
)

View File

@@ -0,0 +1,26 @@
# -*- coding: utf-8 -*- #
# Copyright 2021 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The command group for os-config guest-policies CLI."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.GA, base.ReleaseTrack.ALPHA)
class OsconfigPolicyAssignmentsReports(base.Group):
"""Manage OS policy asssignment reports."""

View File

@@ -0,0 +1,28 @@
- release_tracks: [GA, ALPHA]
help_text:
brief: Describe an OS policy assignment report
description: |
Describe an OS policy assignment report
## EXAMPLES
To describe the report of an OS policy assignment `my-assignment` for an instance `my-instance` in location `us-central1-a`:
$ {command} my-assignment --instance=my-instance --location=us-central1-a
Or use the relative names or URI of the resource, assuming the project ID is `my-project`:
$ {command} projects/my-project/locations/us-central1-a/instances/my-instance/osPolicyAssignments/my-assignment/report
$ {command} https://osconfig.googleapis.com/v1alpha/projects/my-project/locations/us-central1-a/instances/instance-name/osPolicyAssignments/assignment-id/report
request:
collection: osconfig.projects.locations.instances.osPolicyAssignments.reports
ALPHA:
api_version: v1alpha
arguments:
resource:
help_text: OS policy assignment report.
spec: !REF googlecloudsdk.command_lib.compute.os_config.resources:os_policy_assignment_report

View File

@@ -0,0 +1,60 @@
- release_tracks: [GA, ALPHA]
help_text:
brief: List OS policy assignment reports.
description: |
List OS policy assignment reports.
## EXAMPLES
To list reports OS policy assignment in location `us-central1-a`:
$ {command} --location=us-central1-a
To list reports of an instance `my-instance` in location `us-central1-a`:
$ {command} --location=us-central1-a --instance=my-instance
To list reports of an OS policy assignment `my-assignment` in location `us-central1-a`:
$ {command} --location=us-central1-a --assignment-id=my-assignment
request:
collection: osconfig.projects.locations.instances.osPolicyAssignments.reports
disable_resource_check: true
ALPHA:
api_version: v1alpha
modify_request_hooks:
- googlecloudsdk.command_lib.compute.os_config.os_policy_assignment_reports.declarative:SetParentOnListRequestHook
response:
id_field: name
modify_response_hooks:
- googlecloudsdk.command_lib.compute.os_config.os_policy_assignment_reports.declarative:CreateSummarizedListOSPolicyAssignmentReportsHook
arguments:
exclude: ['uri']
params:
- arg_name: location
help_text: |
Location of the OS policy assignment reports to list, will default to the user's compute/zone property if not specified.
- group:
help_text: Specify which instance or OS policy assignment to list reports for.
mutex: true
params:
- arg_name: instance
help_text: Either instance name or instance ID. If not provided, OSPolicyAssignmentReports for all instances in the project and location will be listed.
- arg_name: assignment-id
help_text: An OSPolicyAssignment ID. If not provided, OSPolicyAssignmentReports for all instances in the project and location will be listed.
output:
format: |
table(
instance,
assignment_id,
location,
update_time,
summary_str:label=SUMMARY
)

View File

@@ -0,0 +1,26 @@
# -*- coding: utf-8 -*- #
# Copyright 2021 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The command group for os-config guest-policies CLI."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.GA, base.ReleaseTrack.ALPHA)
class OsconfigPolicyAssignments(base.Group):
"""Manage OS policy assignments."""

View File

@@ -0,0 +1,39 @@
- release_tracks: [GA, ALPHA]
help_text:
brief: Create an OS policy assignment.
description: |
Create an OS policy assignment
## EXAMPLES
To create an OS policy assignment `my-assignment` in `my-project` and location `us-central1-a` with config file `/path/to/file/config.yaml`, run:
$ {command} my-assignment --project=my-project --location=us-central1-a --file=/path/to/file/config.yaml
request:
collection: osconfig.projects.locations.osPolicyAssignments
modify_request_hooks:
- googlecloudsdk.command_lib.compute.os_config.utils:ParseOSConfigAssignmentFile
ALPHA:
api_version: v1alpha
GA:
api_version: v1
async:
collection: osconfig.projects.locations.osPolicyAssignments.operations
ALPHA:
api_version: v1alpha
GA:
api_version: v1
response:
modify_response_hooks:
- googlecloudsdk.command_lib.compute.os_config.utils:LogOutOperationCommandForAsyncResponse
arguments:
resource:
help_text: Location to create the OS policy assignment in.
spec: !REF googlecloudsdk.command_lib.compute.os_config.resources:create_os_policy_assignment
params:
- _REF_: googlecloudsdk.command_lib.compute.os_config.flags:file

View File

@@ -0,0 +1,30 @@
- release_tracks: [GA, ALPHA]
help_text:
brief: Delete an OS policy assignment
description: |
Delete an OS policy assignment
## EXAMPLES
To delete an OS policy `my-assignment` in location `us-central1-a`:
$ {command} my-assignment --location=us-central1-a
request:
collection: osconfig.projects.locations.osPolicyAssignments
ALPHA:
api_version: v1alpha
GA:
api_version: v1
async:
collection: osconfig.projects.locations.osPolicyAssignments.operations
ALPHA:
api_version: v1alpha
GA:
api_version: v1
arguments:
resource:
help_text: OS policy assignment to delete.
spec: !REF googlecloudsdk.command_lib.compute.os_config.resources:os_policy_assignment

View File

@@ -0,0 +1,38 @@
- release_tracks: [GA, ALPHA]
help_text:
brief: Describe an OS policy assignment
description: |
Describe an OS policy assignment
## EXAMPLES
To describe an OS policy `my-assignment` in location `us-central1-a`:
$ {command} my-assignment --location=us-central1-a
request:
collection: osconfig.projects.locations.osPolicyAssignments
ALPHA:
api_version: v1alpha
GA:
api_version: v1
arguments:
resource:
help_text: OS policy assignment to describe.
spec: !REF googlecloudsdk.command_lib.compute.os_config.resources:os_policy_assignment
output:
format: |
default(
baseline,
description,
instanceFilter,
name,
osPolicies,
revisionCreateTime.date("%Y-%m-%dT%H:%M:%SZ"),
revisionId,
rollout,
rolloutState,
uid
)

View File

@@ -0,0 +1,36 @@
- release_tracks: [GA, ALPHA]
help_text:
brief: List OS policy assignments for a specified location.
description: |
List OS policy assignments.
## EXAMPLES
To list the OS policy assignments in `my-project` and location `us-central1-a`, run:
$ {command} --project=my-project --location=us-central1-a
request:
collection: osconfig.projects.locations.osPolicyAssignments
ALPHA:
api_version: v1alpha
GA:
api_version: v1
response:
id_field: name
arguments:
resource:
help_text: Location of the OS policy assignment to query.
spec: !REF googlecloudsdk.command_lib.compute.os_config.resources:location
output:
format: |
table(
name.basename():label=ASSIGNMENT_ID,
rollout_state,
revision_create_time.date("%Y-%m-%dT%H:%M:%SZ"),
revision_id
)

View File

@@ -0,0 +1,39 @@
- release_tracks: [GA, ALPHA]
help_text:
brief: List the revisions of an OS policy assignment
description: |
List the revisions of an OS policy assignment
## EXAMPLES
To list the revisions of an OS policy `my-assignment` in location `us-central1-a`:
$ {command} my-assignment --location=us-central1-a
command_type: LIST
request:
collection: osconfig.projects.locations.osPolicyAssignments
disable_pagination: true
method: listRevisions
ALPHA:
api_version: v1alpha
GA:
api_version: v1
arguments:
resource:
help_text: OS policies assignment data to describe.
spec: !REF googlecloudsdk.command_lib.compute.os_config.resources:os_policy_assignment
response:
id_field: name
result_attribute: osPolicyAssignments
output:
format: |
table(
name.basename():label=ASSIGNMENT_ID,
rollout_state,
revision_create_time.date("%Y-%m-%dT%H:%M:%SZ"),
revision_id
)

View File

@@ -0,0 +1,26 @@
# -*- coding: utf-8 -*- #
# Copyright 2021 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The command group for os-config guest-policies CLI."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.GA, base.ReleaseTrack.ALPHA)
class OsconfigPolicyAssignmentsOperations(base.Group):
"""Manage long-running operations generated from creating or editing OS policy assignments."""

View File

@@ -0,0 +1,28 @@
- release_tracks: [GA, ALPHA]
help_text:
brief: Cancel an OS policy assignment operation
description: |
Cancel an OS policy assignment
## EXAMPLES
To cancel a long-running operation `operation-id` for OS policy assignment `my-assignment` in location `us-central1-a`:
$ {command} operation-id --location=us-central1-a --os-policy-assignment=my-assignment
Or pass the full operation name:
$ {command} projects/my-project/locations/us-central1-a/osPolicyAssignments/my-assignment/operations/operation-id
request:
collection: osconfig.projects.locations.osPolicyAssignments.operations
method: cancel
ALPHA:
api_version: v1alpha
GA:
api_version: v1
arguments:
resource:
help_text: OS policy assignment data to describe.
spec: !REF googlecloudsdk.command_lib.compute.os_config.resources:os_policy_assignment_operation

View File

@@ -0,0 +1,28 @@
- release_tracks: [GA, ALPHA]
help_text:
brief: Describe an OS policy assignment operation
description: |
Describe an OS policy assignment
## EXAMPLES
To describe an operation with`operation-id` for an OS policy assignment `my-assignment` in
location `us-central1-a`, run:
$ {command} operation-id --location=us-central1-a --os-policy-assignment=my-assignment
You can also describe an operation by passing the full operation name:
$ {command} projects/my-project/locations/us-central1-a/osPolicyAssignments/my-assignment/operations/operation-id
request:
collection: osconfig.projects.locations.osPolicyAssignments.operations
ALPHA:
api_version: v1alpha
GA:
api_version: v1
arguments:
resource:
help_text: OS policy assignment data to describe.
spec: !REF googlecloudsdk.command_lib.compute.os_config.resources:os_policy_assignment_operation

View File

@@ -0,0 +1,40 @@
- release_tracks: [GA, ALPHA]
help_text:
brief: Update an OS policy assignment.
description: |
Update an OS policy assignment
## EXAMPLES
To update an OS policy assignment `my-assignment` in location `us-central1-a` with config file `/path/to/file/config.yaml`, run:
$ {command} my-assignment --location=us-central1-a --file=/path/to/file/config.yaml
request:
collection: osconfig.projects.locations.osPolicyAssignments
modify_request_hooks:
- googlecloudsdk.command_lib.compute.os_config.utils:ParseOSConfigAssignmentFile
ALPHA:
api_version: v1alpha
GA:
api_version: v1
async:
collection: osconfig.projects.locations.osPolicyAssignments.operations
ALPHA:
api_version: v1alpha
GA:
api_version: v1
arguments:
resource:
help_text: OS policy assignment to update.
spec: !REF googlecloudsdk.command_lib.compute.os_config.resources:os_policy_assignment
params:
- _REF_: googlecloudsdk.command_lib.compute.os_config.flags:file
- api_field: allowMissing
arg_name: allow-missing
help_text: |
If set to true, and the OS policy assignment is not found, the new policy assignment
resource will be created.

View File

@@ -0,0 +1,162 @@
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command for importing machine images in OVF format into GCE."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import io
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.api_lib.compute import daisy_utils
from googlecloudsdk.api_lib.compute import utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute import exceptions as compute_exceptions
from googlecloudsdk.command_lib.compute.instances import flags as instances_flags
from googlecloudsdk.command_lib.compute.os_config import flags
from googlecloudsdk.core import log
from googlecloudsdk.core.console import console_io
from googlecloudsdk.core.resource import resource_printer
_OUTPUT_FILTER = []
_OS_UPGRADE_OPERATION_TYPE = 'os-upgrade'
_OS_CHOICES_SOURCE = [
'windows-2008r2',
]
_OS_CHOICES_TARGET = [
'windows-2012r2',
]
_OS_UPGRADE_PROMPT = 'The following instance will be upgraded.'
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA)
class OsUpgrade(base.Command):
"""Upgrade a instance's OS version."""
@classmethod
def Args(cls, parser):
parser.add_argument(
'--source-os',
required=True,
choices=sorted(_OS_CHOICES_SOURCE),
help='OS version of the source instance to upgrade.')
parser.add_argument(
'--target-os',
required=True,
choices=sorted(_OS_CHOICES_TARGET),
help='Version of the OS after upgrade.')
parser.add_argument(
'--create-machine-backup',
required=False,
action='store_true',
default=True,
help='When enabled, a machine image is created that backs up the '
'original state of your instance.')
parser.add_argument(
'--auto-rollback',
required=False,
action='store_true',
help='When auto rollback is enabled, the instance and its resources '
'are restored to their original state. Otherwise, the instance '
'and any temporary resources are left in the intermediate state '
'of the time of failure. This is useful for debugging.')
parser.add_argument(
'--use-staging-install-media',
required=False,
action='store_true',
help='Use staging install media. This flag is for testing only. Set to '
'true to upgrade with staging windows install media.',
hidden=True)
daisy_utils.AddCommonDaisyArgs(parser, operation='an upgrade')
daisy_utils.AddExtraCommonDaisyArgs(parser)
flags.INSTANCES_ARG_FOR_OS_UPGRADE.AddArgument(
parser, operation_type=_OS_UPGRADE_OPERATION_TYPE)
def _ValidateArgs(self, args, compute_client):
daisy_utils.ValidateZone(args, compute_client)
def Run(self, args):
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
client = holder.client
self._ValidateArgs(args, client)
ref = flags.INSTANCES_ARG_FOR_OS_UPGRADE.ResolveAsResource(
args, holder.resources,
scope_lister=instances_flags.GetInstanceZoneScopeLister(client))
instance_uri = 'projects/{0}/zones/{1}/instances/{2}'.format(
ref.project, ref.zone, ref.Name())
_PromptForUpgrade(ref, args)
args.zone = ref.zone
log.warning('Upgrading OS. This usually takes around 40 minutes but may '
'take up to 90 minutes.')
return daisy_utils.RunOsUpgradeBuild(
args=args,
output_filter=_OUTPUT_FILTER,
instance_uri=instance_uri,
release_track=self.ReleaseTrack().id.lower()
if self.ReleaseTrack() else None
)
OsUpgrade.detailed_help = {
'brief': 'Upgrade the instance''s OS version.',
'DESCRIPTION':
"""\
*{command}* upgrades the instance's OS version.
OS Upgrade involves:
* Create a snapshot and/or machine image for the instance.
* Create an install media disk and attach it to the instance.
* Upgrade the OS version.
* Cleanup install media disk after upgrade.
Virtual instances, snapshots, machine images, and disks in Compute Engine
and files stored on Cloud Storage incur charges. See [](https://cloud.google.com/compute/docs/images/importing-virtual-disks#resource_cleanup).
""",
'EXAMPLES':
"""\
To upgrade a instance named `my-instance` from windows-2008r2 to windows-2012r2, run:
$ {command} my-instance --source-os=windows-2008r2 --target-os=windows-2012r2
""",
}
def _PromptForUpgrade(ref, args):
"""Prompts the user to confirm upgrade of instance."""
scope_name = 'zone'
resource_type = utils.CollectionToResourceType(ref.Collection())
resource_name = utils.CamelCaseToOutputFriendly(resource_type)
prompt_item = '[{0}] in [{1}]'.format(ref.Name(), getattr(ref, scope_name))
prompt_title = 'The following {0} will be upgraded from {1} to {2}:'.format(
resource_name, args.source_os, args.target_os)
buf = io.StringIO()
fmt = 'list[title="{title}",always-display-title]'.format(title=prompt_title)
resource_printer.Print(prompt_item, fmt, out=buf)
prompt_message = buf.getvalue()
if not console_io.PromptContinue(message=prompt_message):
raise compute_exceptions.AbortedError('Upgrade aborted by user.')

View File

@@ -0,0 +1,26 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The command group for os-config patch-deployments CLI."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
class OsconfigPatchDeployments(base.Group):
"""Manage guest OS patch deployments for Compute Engine VM instances."""

View File

@@ -0,0 +1,98 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Implements command to create a new patch deployment."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.compute.os_config import utils as osconfig_api_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute.os_config import flags
from googlecloudsdk.command_lib.compute.os_config import utils as osconfig_command_utils
from googlecloudsdk.core import properties
def _GetReleaseTrackText(release_track):
if release_track == base.ReleaseTrack.BETA:
return 'beta '
else:
return ''
def _GetDetailedHelp(release_track):
"""Formats and returns detailed help for command."""
detailed_help = {
'DESCRIPTION':
"""\
*{command}* creates a patch deployment in a project from a specified file.
A patch deployment triggers a patch job to run at specific time(s)
according to a schedule, and applies instance filters and other patch
configurations to the patch job at run time. Alternatively, to run a patch
job on-demand, see *$ gcloud*
*{release_track}compute os-config patch-jobs execute*.
""".format(
command='{command}',
release_track=_GetReleaseTrackText(release_track)),
'EXAMPLES':
"""\
To create a patch deployment `patch-deployment-1` in the current project,
run:
$ {command} patch-deployment-1 --file=path_to_config_file
""",
}
return detailed_help
@base.ReleaseTracks(base.ReleaseTrack.GA)
class Create(base.Command):
"""Create a patch deployment for a project."""
detailed_help = _GetDetailedHelp(release_track=base.ReleaseTrack.GA)
@staticmethod
def Args(parser):
flags.AddPatchDeploymentsCreateFlags(parser, api_version='v1')
def Run(self, args):
release_track = self.ReleaseTrack()
client = osconfig_api_utils.GetClientInstance(release_track)
messages = osconfig_api_utils.GetClientMessages(release_track)
(patch_deployment,
_) = osconfig_command_utils.GetResourceAndUpdateFieldsFromFile(
args.file, messages.PatchDeployment)
project = properties.VALUES.core.project.GetOrFail()
parent_path = osconfig_command_utils.GetProjectUriPath(project)
request = messages.OsconfigProjectsPatchDeploymentsCreateRequest(
patchDeployment=patch_deployment,
patchDeploymentId=args.PATCH_DEPLOYMENT_ID,
parent=parent_path,
)
return client.projects_patchDeployments.Create(request)
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class CreateBeta(Create):
"""Create a patch deployment for a project."""
detailed_help = _GetDetailedHelp(release_track=base.ReleaseTrack.BETA)
@staticmethod
def Args(parser):
flags.AddPatchDeploymentsCreateFlags(parser, api_version='v1beta')

View File

@@ -0,0 +1,58 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Implements command to delete the specified patch deployment."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.compute.os_config import utils as osconfig_api_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute.os_config import resource_args
from googlecloudsdk.core import log
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
class Delete(base.DeleteCommand):
"""Delete the specified patch deployment."""
detailed_help = {
'EXAMPLES':
"""\
To delete the patch deployment `patch-deployment-1` in the current project,
run:
$ {command} patch-deployment-1
""",
}
@staticmethod
def Args(parser):
resource_args.AddPatchDeploymentResourceArg(parser, 'to delete.')
def Run(self, args):
patch_deployment_ref = args.CONCEPTS.patch_deployment.Parse()
patch_deployment_name = patch_deployment_ref.RelativeName()
release_track = self.ReleaseTrack()
client = osconfig_api_utils.GetClientInstance(release_track)
messages = osconfig_api_utils.GetClientMessages(release_track)
request = messages.OsconfigProjectsPatchDeploymentsDeleteRequest(
name=patch_deployment_name)
response = client.projects_patchDeployments.Delete(request)
log.DeletedResource(patch_deployment_name)
return response

View File

@@ -0,0 +1,53 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Implements command to describe the specified patch deployment."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.compute.os_config import utils as osconfig_api_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute.os_config import resource_args
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
class Describe(base.DescribeCommand):
"""Describe the specified patch deployment."""
detailed_help = {
'EXAMPLES':
"""\
To check the status of the patch deployment `patch-deployment-1` in the
current project, run:
$ {command} patch-deployment-1
""",
}
@staticmethod
def Args(parser):
resource_args.AddPatchDeploymentResourceArg(parser, 'to describe.')
def Run(self, args):
patch_deployment_ref = args.CONCEPTS.patch_deployment.Parse()
release_track = self.ReleaseTrack()
client = osconfig_api_utils.GetClientInstance(release_track)
messages = osconfig_api_utils.GetClientMessages(release_track)
request = messages.OsconfigProjectsPatchDeploymentsGetRequest(
name=patch_deployment_ref.RelativeName())
return client.projects_patchDeployments.Get(request)

View File

@@ -0,0 +1,169 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Implements command to list patch deployments."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from apitools.base.py import list_pager
from googlecloudsdk.api_lib.compute.os_config import utils as osconfig_api_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute.os_config import utils as osconfig_command_utils
from googlecloudsdk.core import properties
_DEFAULT_NO_VALUE = '---'
_ONE_TIME_SCHEDULE = 'oneTimeSchedule'
_RECURRING_SCHEDULE = 'recurringSchedule'
_LAST_EXECUTE_TIME = 'lastExecuteTime'
_NEXT_EXECUTE_TIME = 'nextExecuteTime'
def _TransformLastRun(resource):
return resource.get(_LAST_EXECUTE_TIME, _DEFAULT_NO_VALUE)
def _TransformNextRun(resource):
"""Returns the timestamp of the next scheduled run for this patch deployment."""
if _ONE_TIME_SCHEDULE in resource:
if resource.get(_LAST_EXECUTE_TIME, ''):
# This works as long as we don't allow user to update any patch deployment
# with a one-time schedule.
return _DEFAULT_NO_VALUE
else:
schedule = resource[_ONE_TIME_SCHEDULE]
return schedule.get('executeTime', _DEFAULT_NO_VALUE)
elif _RECURRING_SCHEDULE in resource:
schedule = resource[_RECURRING_SCHEDULE]
return schedule.get(_NEXT_EXECUTE_TIME, _DEFAULT_NO_VALUE)
else:
return _DEFAULT_NO_VALUE
def _TransformFrequency(resource):
"""Returns a string description of the patch deployment schedule."""
if _ONE_TIME_SCHEDULE in resource:
return 'Once: Scheduled for ' + resource[_ONE_TIME_SCHEDULE]['executeTime']
elif _RECURRING_SCHEDULE in resource:
output_format = 'Recurring - {} {}'
schedule = resource[_RECURRING_SCHEDULE]
if schedule['frequency'] == 'DAILY':
return output_format.format('Daily', '')
elif schedule['frequency'] == 'WEEKLY':
return output_format.format('Weekly', '')
elif schedule['frequency'] == 'MONTHLY':
if schedule['monthly'].get('weekDayOfMonth', ''):
return output_format.format('Monthly', 'on specific day(s)')
else:
return output_format.format('Monthly', 'on specific date(s)')
else:
return _DEFAULT_NO_VALUE
else:
return _DEFAULT_NO_VALUE
def _MakeGetUriFunc(registry):
"""Returns a transformation function from a patch deployment resource to an URI."""
def UriFunc(resource):
ref = registry.Parse(
resource.name,
params={
'projects': properties.VALUES.core.project.GetOrFail,
'patchDeployments': resource.name
},
collection='osconfig.projects.patchDeployments')
return ref.SelfLink()
return UriFunc
def _Args(parser, release_track):
"""Parses input flags and sets up output formats."""
parser.display_info.AddFormat("""
table(
name.basename(),
last_run(),
next_run(),
frequency()
)
""")
parser.display_info.AddTransforms({
'last_run': _TransformLastRun,
'next_run': _TransformNextRun,
'frequency': _TransformFrequency,
})
registry = osconfig_api_utils.GetRegistry(release_track)
parser.display_info.AddUriFunc(_MakeGetUriFunc(registry))
@base.ReleaseTracks(base.ReleaseTrack.GA)
class List(base.ListCommand):
"""List patch deployments in a project."""
detailed_help = {
'EXAMPLES':
"""\
To list all patch deployments in the current project, run:
$ {command}
""",
}
@staticmethod
def Args(parser):
_Args(parser, base.ReleaseTrack.GA)
def Run(self, args):
release_track = self.ReleaseTrack()
client = osconfig_api_utils.GetClientInstance(release_track)
messages = osconfig_api_utils.GetClientMessages(release_track)
project = properties.VALUES.core.project.GetOrFail()
request = messages.OsconfigProjectsPatchDeploymentsListRequest(
pageSize=args.page_size,
parent=osconfig_command_utils.GetProjectUriPath(project),
)
service = client.projects_patchDeployments
return list_pager.YieldFromList(
service,
request,
limit=args.limit,
batch_size=osconfig_command_utils.GetListBatchSize(args),
field='patchDeployments',
batch_size_attribute='pageSize',
)
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class ListBeta(List):
"""List patch deployments in a project."""
detailed_help = {
'EXAMPLES':
"""\
To list all patch deployments in the current project, run:
$ {command}
""",
}
@staticmethod
def Args(parser):
_Args(parser, base.ReleaseTrack.BETA)

View File

@@ -0,0 +1,56 @@
# -*- coding: utf-8 -*- #
# Copyright 2022 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Implements command to create a new patch deployment."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.compute.os_config import utils as osconfig_api_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute.os_config import resource_args
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
class Pause(base.Command):
"""Pause patch deployment in a project."""
detailed_help = {
'EXAMPLES':
"""\
To pause the patch deployment `patch-deployment-1` in the current project,
run:
$ {command} patch-deployment-1
""",
}
@staticmethod
def Args(parser):
resource_args.AddPatchDeploymentResourceArg(parser, 'to pause.')
def Run(self, args):
patch_deployment_ref = args.CONCEPTS.patch_deployment.Parse()
patch_deployment_name = patch_deployment_ref.RelativeName()
release_track = self.ReleaseTrack()
client = osconfig_api_utils.GetClientInstance(release_track)
messages = osconfig_api_utils.GetClientMessages(release_track)
request = messages.OsconfigProjectsPatchDeploymentsPauseRequest(
name=patch_deployment_name)
response = client.projects_patchDeployments.Pause(request)
return response

View File

@@ -0,0 +1,56 @@
# -*- coding: utf-8 -*- #
# Copyright 2022 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Implements command to create a new patch deployment."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.compute.os_config import utils as osconfig_api_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute.os_config import resource_args
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
class Resume(base.Command):
"""Resume patch deployment in a project."""
detailed_help = {
'EXAMPLES':
"""\
To resume the patch deployment `patch-deployment-1` in the current project,
run:
$ {command} patch-deployment-1
""",
}
@staticmethod
def Args(parser):
resource_args.AddPatchDeploymentResourceArg(parser, 'to resume.')
def Run(self, args):
patch_deployment_ref = args.CONCEPTS.patch_deployment.Parse()
patch_deployment_name = patch_deployment_ref.RelativeName()
release_track = self.ReleaseTrack()
client = osconfig_api_utils.GetClientInstance(release_track)
messages = osconfig_api_utils.GetClientMessages(release_track)
request = messages.OsconfigProjectsPatchDeploymentsResumeRequest(
name=patch_deployment_name)
response = client.projects_patchDeployments.Resume(request)
return response

View File

@@ -0,0 +1,81 @@
# -*- coding: utf-8 -*- #
# Copyright 2021 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Implements command to update a specified patch deployment."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.compute.os_config import utils as osconfig_api_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute.os_config import flags
from googlecloudsdk.command_lib.compute.os_config import utils as osconfig_command_utils
from googlecloudsdk.core import properties
@base.ReleaseTracks(base.ReleaseTrack.GA)
class Update(base.Command):
"""Update patch deployment in a project."""
detailed_help = {
'DESCRIPTION':
"""\
Updates a patch deployment in a project. To update the patch deployment,
you must specify a configuration file.
""",
'EXAMPLES':
"""\
To update a patch deployment `patch-deployment-1` in the current project,
run:
$ {command} patch-deployment-1 --file=path_to_config_file
""",
}
@staticmethod
def Args(parser):
flags.AddPatchDeploymentsUpdateFlags(
parser, api_version='v1', release_track='')
def Run(self, args):
"""See base class."""
release_track = self.ReleaseTrack()
client = osconfig_api_utils.GetClientInstance(release_track)
messages = osconfig_api_utils.GetClientMessages(release_track)
(patch_deployment,
_) = osconfig_command_utils.GetResourceAndUpdateFieldsFromFile(
args.file, messages.PatchDeployment)
project = properties.VALUES.core.project.GetOrFail()
request = messages.OsconfigProjectsPatchDeploymentsPatchRequest(
patchDeployment=patch_deployment,
name=osconfig_command_utils.GetPatchDeploymentUriPath(
project, args.PATCH_DEPLOYMENT_ID),
updateMask=None,
)
service = client.projects_patchDeployments
return service.Patch(request)
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class UpdateBeta(Update):
"""Update a patch deployment in a project."""
@staticmethod
def Args(parser):
flags.AddPatchDeploymentsUpdateFlags(
parser, api_version='v1beta', release_track='beta')

View File

@@ -0,0 +1,26 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The command group for os-config patch-jobs CLI."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
class OsconfigPatchJobs(base.Group):
"""Manage OS patches for Compute Engine VMs."""

View File

@@ -0,0 +1,53 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Implements command to cancel a given active OS patch job."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.compute.os_config import utils as osconfig_api_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute.os_config import resource_args
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
class Cancel(base.Command):
"""Cancel a specific OS patch job which must currently be active.
## EXAMPLES
To cancel the patch job `job1`, run:
$ {command} job1
"""
@staticmethod
def Args(parser):
resource_args.AddPatchJobResourceArg(parser, 'to cancel.')
def Run(self, args):
patch_job_ref = args.CONCEPTS.patch_job.Parse()
release_track = self.ReleaseTrack()
client = osconfig_api_utils.GetClientInstance(release_track)
messages = osconfig_api_utils.GetClientMessages(release_track)
request = messages.OsconfigProjectsPatchJobsCancelRequest(
cancelPatchJobRequest=None,
name=patch_job_ref.RelativeName(),
)
return client.projects_patchJobs.Cancel(request)

View File

@@ -0,0 +1,51 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Implements command to describe a given OS patch job."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.compute.os_config import utils as osconfig_api_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute.os_config import resource_args
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
class Describe(base.DescribeCommand):
"""Describe a specified OS patch job.
## EXAMPLES
To check the status of the patch job `job1`, run:
$ {command} job1
"""
@staticmethod
def Args(parser):
resource_args.AddPatchJobResourceArg(parser, 'to describe.')
def Run(self, args):
patch_job_ref = args.CONCEPTS.patch_job.Parse()
release_track = self.ReleaseTrack()
client = osconfig_api_utils.GetClientInstance(release_track)
messages = osconfig_api_utils.GetClientMessages(release_track)
request = messages.OsconfigProjectsPatchJobsGetRequest(
name=patch_job_ref.RelativeName())
return client.projects_patchJobs.Get(request)

View File

@@ -0,0 +1,169 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Implements command to list ongoing and completed patch jobs."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from apitools.base.py import list_pager
from googlecloudsdk.api_lib.compute.os_config import utils as osconfig_api_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute.os_config import utils as osconfig_command_utils
from googlecloudsdk.core import properties
_DEFAULT_LIMIT = 10
def _TransformPatchJobDisplayName(resource):
"""Returns the display name of a patch job."""
max_len = 15 # Show only the first 15 characters if display name is long.
if resource.get('displayName', ''):
name = resource['displayName']
elif resource.get('patchDeployment', ''):
name = osconfig_command_utils.GetResourceName(resource['patchDeployment'])
else:
name = ''
return (name[:max_len] + '..') if len(name) > max_len else name
def _TransformPatchJobDescription(resource):
max_len = 30 # Show only the first 30 characters if description is long.
description = resource.get('description', '')
return (description[:max_len] +
'..') if len(description) > max_len else description
def _TransformState(resource):
state = resource.get('state', '')
if 'instanceDetailsSummary' in resource:
num_instances_pending_reboot = int(resource['instanceDetailsSummary'].get(
'instancesSucceededRebootRequired', '0'))
if state == 'SUCCEEDED' and num_instances_pending_reboot > 0:
return 'SUCCEEDED_INSTANCES_PENDING_REBOOT'
return state
def _TransformNumInstances(resource):
"""Sums up number of instances in a patch job."""
if 'instanceDetailsSummary' not in resource:
return None
instance_details_summary = resource['instanceDetailsSummary']
num_instances = 0
for status in instance_details_summary:
num_instances += int(instance_details_summary.get(status, 0))
return num_instances
def _MakeGetUriFunc(registry):
"""Returns a transformation function from a patch job resource to an URI."""
def UriFunc(resource):
ref = registry.Parse(
resource.name,
params={
'projects': properties.VALUES.core.project.GetOrFail,
'patchJobs': resource.name
},
collection='osconfig.projects.patchJobs')
return ref.SelfLink()
return UriFunc
def _Args(parser, release_track):
"""Parses input flags and sets up output formats."""
base.LIMIT_FLAG.SetDefault(parser, _DEFAULT_LIMIT)
parser.display_info.AddFormat("""
table(
name.basename():label=ID,
display_name():label=NAME,
description(),
create_time,
update_time,
state(),
targeted_instances()
)
""")
parser.display_info.AddTransforms({
'display_name': _TransformPatchJobDisplayName,
'description': _TransformPatchJobDescription,
'state': _TransformState,
'targeted_instances': _TransformNumInstances,
})
registry = osconfig_api_utils.GetRegistry(release_track)
parser.display_info.AddUriFunc(_MakeGetUriFunc(registry))
@base.ReleaseTracks(base.ReleaseTrack.GA)
class List(base.ListCommand):
"""List ongoing and completed patch jobs.
## EXAMPLES
To list patch jobs in the current project, run:
$ {command}
"""
@staticmethod
def Args(parser):
_Args(parser, base.ReleaseTrack.GA)
def Run(self, args):
project = properties.VALUES.core.project.GetOrFail()
release_track = self.ReleaseTrack()
client = osconfig_api_utils.GetClientInstance(release_track)
messages = osconfig_api_utils.GetClientMessages(release_track)
request = messages.OsconfigProjectsPatchJobsListRequest(
pageSize=args.page_size,
parent=osconfig_command_utils.GetProjectUriPath(project))
return list_pager.YieldFromList(
client.projects_patchJobs,
request,
limit=args.limit,
batch_size=osconfig_command_utils.GetListBatchSize(args),
field='patchJobs',
batch_size_attribute='pageSize',
)
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class ListBeta(List):
"""List ongoing and completed patch jobs.
## EXAMPLES
To list patch jobs in the current project, run:
$ {command}
"""
@staticmethod
def Args(parser):
_Args(parser, base.ReleaseTrack.BETA)

View File

@@ -0,0 +1,89 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Implements command to list the instance details for an OS patch job."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from apitools.base.py import list_pager
from googlecloudsdk.api_lib.compute.os_config import utils as osconfig_api_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute.os_config import resource_args
from googlecloudsdk.core.resource import resource_projector
def _TransformFailureReason(resource):
max_len = 80 # Show the first 80 characters if failure reason is long.
message = resource.get('failureReason', '')
return (message[:max_len] + '..') if len(message) > max_len else message
def _PostProcessListResult(results):
# Inject a "zone" field into the output resources for easy filtering.
results_json = resource_projector.MakeSerializable(results)
for result in results_json:
result['zone'] = result['name'].split('/')[3]
return results_json
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
class ListInstanceDetails(base.ListCommand):
"""List the instance details for an OS patch job.
## EXAMPLES
To list the instance details for each instance in the patch job `job1`, run:
$ {command} job1
"""
@staticmethod
def Args(parser):
base.URI_FLAG.RemoveFromParser(parser) # InstanceDetails have no URI.
resource_args.AddPatchJobResourceArg(parser, 'to list instance details.')
parser.display_info.AddFormat("""
table(
name.basename(),
zone,
state,
failure_reason()
)
""")
parser.display_info.AddTransforms(
{'failure_reason': _TransformFailureReason})
def Run(self, args):
patch_job_ref = args.CONCEPTS.patch_job.Parse()
release_track = self.ReleaseTrack()
client = osconfig_api_utils.GetClientInstance(release_track)
messages = osconfig_api_utils.GetClientMessages(release_track)
request = messages.OsconfigProjectsPatchJobsInstanceDetailsListRequest(
pageSize=args.page_size, parent=patch_job_ref.RelativeName())
results = list(
list_pager.YieldFromList(
client.projects_patchJobs_instanceDetails,
request,
limit=args.limit,
batch_size=args.page_size,
field='patchJobInstanceDetails',
batch_size_attribute='pageSize'),)
return _PostProcessListResult(results)

View File

@@ -0,0 +1,29 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The command group for os-config policy-orchestrators CLI."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.UniverseCompatible
@base.ReleaseTracks(
base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA, base.ReleaseTrack.GA
)
class OsconfigPolicyOrchestrators(base.Group):
"""Manage VM Manager policy orchestrators."""

View File

@@ -0,0 +1,88 @@
- release_tracks: [GA, BETA, ALPHA]
help_text:
brief: Create a policy orchestrator
description: |
Create a policy orchestrator.
## EXAMPLES
To create a policy orchestrator `my-orchestrator` in folder `123456` for OS policy assignment
with config file `/path/to/file/config.yaml`, run:
$ {command} my-orchestrator --folder=123456 --policy-type os_policy_assignment_v1 \
--policy-file=/path/to/file/config.yaml
To create a policy orchestrator `my-orchestrator` in folder `123456` that deletes OS Policy
assignments with id `my-policy`, run:
$ {command} my-orchestrator --folder=123456 --policy-type os_policy_assignment_v1 \
--action delete --policy-id my-policy
request:
collection:
- osconfig.projects.locations.global.policyOrchestrators
- osconfig.folders.locations.global.policyOrchestrators
- osconfig.organizations.locations.global.policyOrchestrators
method: create
modify_request_hooks:
- googlecloudsdk.command_lib.compute.os_config.utils:ModifyOrchestrorPolicyCreateRequest
ALPHA:
api_version: v2alpha
BETA:
api_version: v2beta
GA:
api_version: v2
async:
collection:
- osconfig.projects.locations.operations
- osconfig.folders.locations.operations
- osconfig.organizations.locations.operations
ALPHA:
api_version: v2alpha
BETA:
api_version: v2beta
GA:
api_version: v2
arguments:
resource:
help_text: Policy orchestrator to create.
spec: !REF googlecloudsdk.command_lib.compute.os_config.resources:policy_orchestrator
params:
- arg_name: action
help_text: Action to be taken on policy.
default: upsert
choices:
- arg_value: UPSERT
help_text: Create or update a policy. `policy-file` must be specified.
- arg_value: DELETE
help_text: Delete a policy with a given name. `policy-id` must be specified.
- arg_name: policy-id
help_text: Policy id. Must be specified for `DELETE` action.
- arg_name: policy-type
help_text: Policy type to use.
required: true
choices:
- arg_value: OS_POLICY_ASSIGNMENT_V1
help_text: OS policy assignment v1.
- arg_name: state
help_text: State of the policy orchestrator.
default: ACTIVE
choices:
- arg_value: ACTIVE
help_text: Creates a policy orchestrator in `ACTIVE` state.
- arg_value: STOPPED
help_text: Creates a policy orchestrator in `STOPPED` state.
- _REF_: googlecloudsdk.command_lib.compute.os_config.flags:policy-file
- arg_name: include-projects
help_text: |
Applies policy to selected projects. Comma-separated list of project numbers. Can be used
together with `--include-folders`.
- arg_name: include-folders
help_text: |
Applies policy to selected folders. Comma-separated list of folder numbers. Can beused
together with `--include-projects`.
- arg_name: include-locations
help_text: |
Applies policy to selected locations, e.g. `us-central1-a`.

View File

@@ -0,0 +1,41 @@
- release_tracks: [GA, BETA, ALPHA]
help_text:
brief: Delete a policy orchestrator
description: |
Delete a policy orchestrator and cancel ongoing rollouts (best-effort).
## EXAMPLES
To delete a policy orchestrator `my-orchestrator` in the folder `123456`:
$ {command} my-orchestrator --folder=123456
request:
collection:
- osconfig.projects.locations.global.policyOrchestrators
- osconfig.folders.locations.global.policyOrchestrators
- osconfig.organizations.locations.global.policyOrchestrators
ALPHA:
api_version: v2alpha
BETA:
api_version: v2beta
GA:
api_version: v2
method: delete
arguments:
resource:
help_text: policy orchestrator to delete.
spec: !REF googlecloudsdk.command_lib.compute.os_config.resources:policy_orchestrator
async:
collection:
- osconfig.projects.locations.operations
- osconfig.folders.locations.operations
- osconfig.organizations.locations.operations
ALPHA:
api_version: v2alpha
BETA:
api_version: v2beta
GA:
api_version: v2

View File

@@ -0,0 +1,28 @@
- release_tracks: [GA, BETA, ALPHA]
help_text:
brief: Describe a policy orchestrator
description: |
Get the details of a policy orchestrator.
## EXAMPLES
To describe a policy orchestrator `my-orchestrator`:
$ {command} my-orchestrator
request:
collection:
- osconfig.projects.locations.global.policyOrchestrators
- osconfig.folders.locations.global.policyOrchestrators
- osconfig.organizations.locations.global.policyOrchestrators
ALPHA:
api_version: v2alpha
BETA:
api_version: v2beta
GA:
api_version: v2
arguments:
resource:
help_text: The policy orchestrator to describe.
spec: !REF googlecloudsdk.command_lib.compute.os_config.resources:policy_orchestrator

View File

@@ -0,0 +1,44 @@
- release_tracks: [GA, BETA, ALPHA]
help_text:
brief: List policy orchestrators.
description: |
List policy orchestrators.
## EXAMPLES
To list the policy orchestrators in folder `123456`, run:
$ {command} --folder 123456
request:
collection:
- osconfig.projects.locations.global.policyOrchestrators
- osconfig.folders.locations.global.policyOrchestrators
- osconfig.organizations.locations.global.policyOrchestrators
modify_request_hooks:
- googlecloudsdk.command_lib.compute.os_config.utils:ModifyOrchestrorPolicyListRequest
ALPHA:
api_version: v2alpha
BETA:
api_version: v2beta
GA:
api_version: v2
response:
id_field: name
arguments:
resource:
help_text: Project, folder or organization to list policy orchestrators from.
spec: !REF googlecloudsdk.command_lib.compute.os_config.resources:project_folder_organization
output:
format: |
table(
name.basename():label=POLICY_ORCHESTRATOR_ID,
action,
orchestrationState.currentIterationState.state,
createTime.date("%Y-%m-%dT%H:%M:%SZ"),
updateTime.date("%Y-%m-%dT%H:%M:%SZ")
)

View File

@@ -0,0 +1,103 @@
- release_tracks: [GA, BETA, ALPHA]
help_text:
brief: Update a policy orchestrator
description: |
Update a policy orchestrator.
## EXAMPLES
To update an policy orchestrator `my-orchestrator` in folder `123456` with config file
`/path/to/file/config.yaml`, run:
$ {command} my-orchestrator --folder=123456 --policy-file=/path/to/file/config.yaml
To update an policy orchestrator `my-orchestrator` in folder `123456` with state STOPPED, run:
$ {command} my-orchestrator --folder=123456 --state=stopped
request:
collection:
- osconfig.projects.locations.global.policyOrchestrators
- osconfig.folders.locations.global.policyOrchestrators
- osconfig.organizations.locations.global.policyOrchestrators
method: patch
modify_request_hooks:
- googlecloudsdk.command_lib.compute.os_config.utils:ModifyOrchestrorPolicyUpdateRequest
ALPHA:
api_version: v2alpha
BETA:
api_version: v2beta
GA:
api_version: v2
async:
collection:
- osconfig.projects.locations.operations
- osconfig.folders.locations.operations
- osconfig.organizations.locations.operations
ALPHA:
api_version: v2alpha
BETA:
api_version: v2beta
GA:
api_version: v2
arguments:
resource:
help_text: Policy orchestrator to update.
spec: !REF googlecloudsdk.command_lib.compute.os_config.resources:policy_orchestrator
params:
- arg_name: action
help_text: Action to be taken on policy.
choices:
- arg_value: UPSERT
help_text: Create or update a policy. `policy-file` must be specified.
- arg_value: DELETE
help_text: Delete a policy with a given name. `policy-id` must be specified.
- arg_name: policy-id
help_text: Policy id. Must be specified for `DELETE` action.
- arg_name: state
help_text: State of the policy orchestrator.
choices:
- arg_value: ACTIVE
help_text: Updates the policy orchestrator to `ACTIVE` state.
- arg_value: STOPPED
help_text: Updates the policy orchestrator to `STOPPED` state.
- _REF_: googlecloudsdk.command_lib.compute.os_config.flags:policy-file
- group:
help_text: |
Projects to include in the policy orchestrator. Comma separated list of project numbers.
If `include-projects` is set, `clear-projects` must not be set.
mutex: true
params:
- arg_name: include-projects
help_text: Applies policy to selected projects only.
- arg_name: clear-projects
help_text: Clears included projects from policy orchestrator selectors.
type: bool
- group:
help_text: |
Folders to include in the policy orchestrator. Comma-separated list of folder numbers.
If `--include-folders` is set, `--clear-folders` must not be set.
mutex: true
params:
- arg_name: include-folders
help_text: Applies policy to selected folders only.
- arg_name: clear-folders
help_text: Clears included folders from policy orchestrator selectors.
type: bool
- group:
help_text: |
Locations to include in the policy orchestrator, e.g. `us-central1-a`.
If `include-locations` is set, `clear-locations` must not be set.
mutex: true
params:
- arg_name: include-locations
help_text: Applies policy to selected locations only.
- arg_name: clear-locations
help_text: Clears included locations from policy orchestrator selectors.
type: bool
update:
read_modify_update: true
disable_auto_field_mask: true

View File

@@ -0,0 +1,26 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The command group for os-config project-feature-settings CLI."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.GA)
class OsconfigProjectFeatureSettings(base.Group):
"""Manage VM Manager project feature settings."""

View File

@@ -0,0 +1,25 @@
- release_tracks: [GA]
help_text:
brief: |
Get all VM Manager project feature settings.
description: |
Get all VM Manager project feature settings.
examples: |
To get project feature settings for project `my-project`:
$ {command} --project=my-project
arguments:
resource:
spec: !REF googlecloudsdk.command_lib.compute.os_config.resources:project_global
is_positional: false
help_text: |
The project to read the feature settings from.
request:
api_version: v1
disable_resource_check: true
collection: osconfig.projects.locations.global
method: getProjectFeatureSettings
modify_request_hooks:
- googlecloudsdk.command_lib.compute.os_config.utils:UpdateProjectFeatureSettingsResource

View File

@@ -0,0 +1,44 @@
- release_tracks: [GA]
help_text:
brief: |
Update VM Manager project feature settings.
description: |
Update VM Manager project feature settings.
examples: |
To update project feature settings for project `my-project`:
$ {command} --project=my-project --patch-and-config-feature-set=full
arguments:
resource:
spec: !REF googlecloudsdk.command_lib.compute.os_config.resources:project_global
is_positional: false
help_text: |
The project to modify the feature settings for.
params:
- arg_name: patch-and-config-feature-set
api_field: projectFeatureSettings.patchAndConfigFeatureSet
help_text: |
Specifies the feature set for VM Manager.
required: true
choices:
- arg_value: osconfig-b
enum_value: OSCONFIG_B
help_text: Limited feature set. Enables only the basic set of features.
- arg_value: limited
enum_value: OSCONFIG_B
help_text: Limited feature set. Enables only the basic set of features (alias for osconfig-b).
- arg_value: osconfig-c
enum_value: OSCONFIG_C
help_text: Full set of VM Manager functionality.
- arg_value: full
enum_value: OSCONFIG_C
help_text: Full set of VM Manager functionality (alias for osconfig-c).
request:
api_version: v1
disable_resource_check: true
collection: osconfig.projects.locations.global
method: updateProjectFeatureSettings
modify_request_hooks:
- googlecloudsdk.command_lib.compute.os_config.utils:UpdateProjectFeatureSettingsResource

View File

@@ -0,0 +1,161 @@
# -*- coding: utf-8 -*- #
# Copyright 2022 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command for troubleshooting problems with the VM Manager."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute.instances import flags
from googlecloudsdk.command_lib.compute.os_config import troubleshooter
@base.ReleaseTracks(base.ReleaseTrack.GA)
class Troubleshoot(base.Command):
"""Troubleshoot VM Manager issues."""
def _ResolveInstance(self, holder, compute_client, args):
"""Resolves the arguments into an instance.
Args:
holder: the api holder
compute_client: the compute client
args: The command line arguments.
Returns:
An instance reference to a VM.
"""
resources = holder.resources
instance_ref = flags.INSTANCE_ARG.ResolveAsResource(
args,
resources,
scope_lister=flags.GetInstanceZoneScopeLister(compute_client))
return instance_ref
@staticmethod
def Args(parser):
flags.INSTANCE_ARG.AddArgument(parser)
def Run(self, args):
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
compute_client = holder.client
instance_ref = self._ResolveInstance(holder, compute_client, args)
troubleshooter.Troubleshoot(compute_client,
instance_ref,
self.ReleaseTrack())
return
Troubleshoot.detailed_help = {
'brief':
'Troubleshoot issues with the setup of VM Manager on a specified VM '
'instance',
'DESCRIPTION':
"""
*{command}* troubleshoots issues with the setup of VM Manager on a specified
VM instance
The troubleshoot command investigates the following settings or configurations for your VM Manager setup:\n
- Checks if the OS Config API is enabled in the project.
- Checks if the required metadata is set up correctly in the VM instance.
- Checks if the latest version of the OS Config agent is running on the VM instance.
- Checks if a service account is attached to the VM instance.
- Checks if the VM Manager service agent is enabled.
- Checks if the VM instance has a public IP or Private Google Access.
""",
'EXAMPLES': """
To troubleshoot an instance named `my-instance` in zone `us-west1-a`, run
$ {command} my-instance --zone=us-west1-a
"""
}
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class TroubleshootAlpha(base.Command):
"""(ALPHA) Troubleshoot VM Manager issues."""
def _ResolveInstance(self, holder, compute_client, args):
"""Resolves the arguments into an instance.
Args:
holder: the api holder
compute_client: the compute client
args: The command line arguments.
Returns:
An instance reference to a VM.
"""
resources = holder.resources
instance_ref = flags.INSTANCE_ARG.ResolveAsResource(
args,
resources,
scope_lister=flags.GetInstanceZoneScopeLister(compute_client))
return instance_ref
@staticmethod
def Args(parser):
flags.INSTANCE_ARG.AddArgument(parser)
parser.add_argument('--enable-log-analysis',
required=False,
action='store_true',
help=(
'Enable the checking of audit logs created by Cloud'
' Logging. The troubleshooter checks the VM\'s '
'Cloud Logging logs and serial log output for '
'errors, provides you with the analysis data, and '
'allows you to download the logs.'
))
def Run(self, args):
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
compute_client = holder.client
instance_ref = self._ResolveInstance(holder, compute_client, args)
troubleshooter.Troubleshoot(compute_client,
instance_ref,
self.ReleaseTrack(),
analyze_logs=args.enable_log_analysis)
return
TroubleshootAlpha.detailed_help = {
'brief':
'Troubleshoot issues with the setup of VM Manager on a specified VM '
'instance',
'DESCRIPTION':
"""
*{command}* troubleshoots issues with the setup of VM Manager on a specified
VM instance
The troubleshoot command investigates the following settings or configurations for your VM Manager setup:\n
- Checks if the OS Config API is enabled in the project.\n
- Checks if the required metadata is set up correctly in the VM instance.\n
- Checks if the latest version of the OS Config agent is running on the VM instance.\n
- Checks if a service account is attached to the VM instance.\n
- Checks if the VM Manager service agent is enabled.\n
- Checks if the VM instance has a public IP or Private Google Access.
""",
'EXAMPLES': """
To troubleshoot an instance named `my-instance` in zone `us-west1-a`, run
$ {command} my-instance --zone=us-west1-a
To troubleshoot the same instance in the same zone with log analysis, run
$ {command} my-instance --zone=us-west1-a --enable-log-analysis
"""
}

View File

@@ -0,0 +1,26 @@
# -*- coding: utf-8 -*- #
# Copyright 2021 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The command group for osconfig vulnerability reports CLI."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.GA, base.ReleaseTrack.ALPHA)
class OsconfigVulnerabilityReport(base.Group):
"""Display vulnerability reports for a Compute Engine VM."""

View File

@@ -0,0 +1,55 @@
- release_tracks: [GA, ALPHA]
help_text:
brief: Describe the vulnerability report data for a Compute Engine VM instance.
description: |
Describe the vulnerability report data for a Compute Engine VM instance.
examples: |
To describe the vulnerability report of an instance `my-instance`
that has the instance ID `5678` in the current project
and location 'us-central1-a', run:
$ {command} my-instance --location=us-central1-a
request:
collection: osconfig.projects.locations.instances.vulnerabilityReports
# This command is implemented manually (without resources) so that
# its help documentation specifically allows instance IDs as the first
# positional paramater.
#
# Without this, a presubmit check will block this yaml file.
disable_resource_check: true
ALPHA:
api_version: v1alpha
GA:
api_version: v1
modify_request_hooks:
- googlecloudsdk.command_lib.compute.os_config.vulnerability_reports.declarative:SetNameOnDescribeRequestHook
response:
id_field: name
modify_response_hooks:
- googlecloudsdk.command_lib.compute.os_config.vulnerability_reports.declarative:CreateDescribeTableViewResponseHook
arguments:
params:
- arg_name: instance
is_positional: true
help_text: |
ID or name of the Compute Engine VM instance to describe. For details on valid instance IDs,
refer to the criteria documented under the field `id` at:
https://cloud.google.com/compute/docs/reference/rest/v1/instances
- arg_name: location
help_text: |
Location of the Compute Engine VM instance to describe. If not specified, the property
`compute/zone` is used. For details on setting properties,
see: https://cloud.google.com/sdk/docs/properties
output:
format: |
multi(
vulnerabilities:format=
"table[box,title='Vulnerabilities']
(details.cve:sort=1,details.severity,details.cvssV3.baseScore:label=CVSS_V3_SCORE,createTime.date('%Y-%m-%dT%H:%M:%SZ'))",
report_information:format="default(name, updateTime.date('%Y-%m-%dT%H:%M:%SZ'))"
)

View File

@@ -0,0 +1,41 @@
- release_tracks: [GA, ALPHA]
help_text:
brief: List vulnerability report data for all Compute Engine VM instances in a specified location.
description: |
List vulnerability report data for all Compute Engine VM instances in a specified location.
The default page size is 25. To modify this, use the `--page-size` flag.
examples: |
To list the vulnerability report of Compute Engine VM instances in `my-project`
and location `us-central1-a`, run:
$ {command} --project=my-project --location=us-central1-a
request:
collection: osconfig.projects.locations.instances.vulnerabilityReports
ALPHA:
api_version: v1alpha
GA:
api_version: v1
disable_resource_check: true
modify_request_hooks:
- googlecloudsdk.command_lib.compute.os_config.vulnerability_reports.declarative:SetParentOnListRequestHook
- googlecloudsdk.command_lib.compute.os_config.declarative:SetDefaultPageSizeRequestHook:default_page_size=25
response:
id_field: name
arguments:
params:
- arg_name: location
help_text: |
Location of the Compute Engine VM instances to list. If not specified, the property
`compute/zone` is used. For details on setting properties,
see: https://cloud.google.com/sdk/docs/properties
output:
format: |
table(
name.segment(-2):label=INSTANCE_ID,
vulnerabilities.len():label=VULNERABILITY_COUNT,
update_time.date("%Y-%m-%dT%H:%M:%SZ")
)