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,41 @@
# -*- coding: utf-8 -*- #
# Copyright 2014 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.
"""Commands for reading and manipulating firewall rules."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(
base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
class FirewallRules(base.Group):
"""List, create, update, and delete Compute Engine firewall rules."""
FirewallRules.category = base.NETWORKING_CATEGORY
FirewallRules.detailed_help = {
'DESCRIPTION': """
Read and manipulate VPC firewall rules.
For more information about firewall rules, see the
[firewall rules documentation](https://cloud.google.com/vpc/docs/firewalls).
See also: [Firewall rules API](https://cloud.google.com/compute/docs/reference/rest/v1/firewalls).
""",
}

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.
"""Command group for managing Compute Engine firewall configurations."""
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 Config(base.Group):
"""Manage Compute Engine firewall configurations."""

View File

@@ -0,0 +1,38 @@
release_tracks: [ALPHA]
command_type: CONFIG_EXPORT
help_text:
brief: Export the configuration for a Compute Engine firewall.
description: |
*{command}* exports the configuration for a Compute Engine firewall.
Firewall configurations can be exported in
Kubernetes Resource Model (krm) or Terraform HCL formats. The
default format is `krm`.
Specifying `--all` allows you to export the configurations for all
firewalls within the project.
Specifying `--path` allows you to export the configuration(s) to
a local directory.
examples: |
To export the configuration for a firewall, run:
$ {command} my-firewall
To export the configuration for a firewall to a file, run:
$ {command} my-firewall --path=/path/to/dir/
To export the configuration for a firewall in Terraform
HCL format, run:
$ {command} my-firewall --resource-format=terraform
To export the configurations for all firewalls within a
project, run:
$ {command} --all
arguments:
resource:
help_text: Firewall to export the configuration for.
spec: !REF googlecloudsdk.command_lib.compute.resources:firewall

View File

@@ -0,0 +1,247 @@
# -*- coding: utf-8 -*- #
# Copyright 2014 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 creating firewall rules."""
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 import firewalls_utils
from googlecloudsdk.api_lib.compute import utils as compute_api
from googlecloudsdk.api_lib.util import apis
from googlecloudsdk.calliope import base
from googlecloudsdk.calliope import exceptions
from googlecloudsdk.command_lib.compute import resource_manager_tags_utils
from googlecloudsdk.command_lib.compute.firewall_rules import flags
from googlecloudsdk.command_lib.compute.networks import flags as network_flags
from googlecloudsdk.core.console import progress_tracker
import six
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.UniverseCompatible
class Create(base.CreateCommand):
"""Create a Compute Engine firewall rule."""
FIREWALL_RULE_ARG = None
NETWORK_ARG = None
@classmethod
def Args(cls, parser):
messages = apis.GetMessagesModule('compute',
compute_api.COMPUTE_GA_API_VERSION)
parser.display_info.AddFormat(flags.DEFAULT_LIST_FORMAT)
cls.FIREWALL_RULE_ARG = flags.FirewallRuleArgument()
cls.FIREWALL_RULE_ARG.AddArgument(parser, operation_type='create')
cls.NETWORK_ARG = network_flags.NetworkArgumentForOtherResource(
'The network to which this rule is attached.', required=False)
firewalls_utils.AddCommonArgs(
parser,
for_update=False,
with_egress_support=True,
with_service_account=True)
firewalls_utils.AddArgsForServiceAccount(parser, for_update=False)
flags.AddEnableLogging(parser)
flags.AddLoggingMetadata(parser, messages)
parser.display_info.AddCacheUpdater(flags.FirewallsCompleter)
def _CreateFirewall(self, holder, args):
client = holder.client
if args.rules and args.allow:
raise firewalls_utils.ArgumentValidationError(
'Can NOT specify --rules and --allow in the same request.')
if bool(args.action) ^ bool(args.rules):
raise firewalls_utils.ArgumentValidationError(
'Must specify --rules with --action.')
allowed = firewalls_utils.ParseRules(args.allow, client.messages,
firewalls_utils.ActionType.ALLOW)
network_ref = self.NETWORK_ARG.ResolveAsResource(args, holder.resources)
firewall_ref = self.FIREWALL_RULE_ARG.ResolveAsResource(
args, holder.resources)
firewall = client.messages.Firewall(
allowed=allowed,
name=firewall_ref.Name(),
description=args.description,
network=network_ref.SelfLink(),
sourceRanges=args.source_ranges,
sourceTags=args.source_tags,
targetTags=args.target_tags)
if args.disabled is not None:
firewall.disabled = args.disabled
firewall.direction = None
if args.direction and args.direction in ['EGRESS', 'OUT']:
firewall.direction = (
client.messages.Firewall.DirectionValueValuesEnum.EGRESS)
else:
firewall.direction = (
client.messages.Firewall.DirectionValueValuesEnum.INGRESS)
firewall.priority = args.priority
firewall.destinationRanges = args.destination_ranges
allowed = []
denied = []
if not args.action:
allowed = firewalls_utils.ParseRules(
args.allow, client.messages, firewalls_utils.ActionType.ALLOW)
elif args.action == 'ALLOW':
allowed = firewalls_utils.ParseRules(
args.rules, client.messages, firewalls_utils.ActionType.ALLOW)
elif args.action == 'DENY':
denied = firewalls_utils.ParseRules(
args.rules, client.messages, firewalls_utils.ActionType.DENY)
firewall.allowed = allowed
firewall.denied = denied
firewall.sourceServiceAccounts = args.source_service_accounts
firewall.targetServiceAccounts = args.target_service_accounts
if args.IsSpecified('logging_metadata') and not args.enable_logging:
raise exceptions.InvalidArgumentException(
'--logging-metadata',
'cannot toggle logging metadata if logging is not enabled.',
)
if args.IsSpecified('enable_logging'):
log_config = client.messages.FirewallLogConfig(enable=args.enable_logging)
if args.IsSpecified('logging_metadata'):
log_config.metadata = flags.GetLoggingMetadataArg(
client.messages
).GetEnumForChoice(args.logging_metadata)
firewall.logConfig = log_config
if args.IsSpecified(
'resource_manager_tags'
):
firewall.params = self._CreateFirewallParams(
client.messages, args.resource_manager_tags
)
return firewall, firewall_ref.project
def _CreateFirewallParams(self, messages, resource_manager_tags):
resource_manager_tags_map = (
resource_manager_tags_utils.GetResourceManagerTags(
resource_manager_tags
)
)
params = messages.FirewallParams
additional_properties = [
params.ResourceManagerTagsValue.AdditionalProperty(key=key, value=value)
for key, value in sorted(six.iteritems(resource_manager_tags_map))
]
return params(
resourceManagerTags=params.ResourceManagerTagsValue(
additionalProperties=additional_properties
)
)
def Run(self, args):
"""Issues requests necessary for adding firewall rules."""
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
client = holder.client
firewall, project = self._CreateFirewall(holder, args)
request = client.messages.ComputeFirewallsInsertRequest(
firewall=firewall, project=project)
with progress_tracker.ProgressTracker(
'Creating firewall',
autotick=False
) as tracker:
return client.MakeRequests([(client.apitools_client.firewalls, 'Insert',
request)], progress_tracker=tracker)
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class BetaCreate(Create):
"""Create a Compute Engine firewall rule."""
@classmethod
def Args(cls, parser):
messages = apis.GetMessagesModule('compute',
compute_api.COMPUTE_BETA_API_VERSION)
parser.display_info.AddFormat(flags.DEFAULT_LIST_FORMAT)
cls.FIREWALL_RULE_ARG = flags.FirewallRuleArgument()
cls.FIREWALL_RULE_ARG.AddArgument(parser, operation_type='create')
cls.NETWORK_ARG = network_flags.NetworkArgumentForOtherResource(
'The network to which this rule is attached.', required=False)
firewalls_utils.AddCommonArgs(
parser,
for_update=False,
with_egress_support=True,
with_service_account=True)
firewalls_utils.AddArgsForServiceAccount(parser, for_update=False)
flags.AddEnableLogging(parser)
flags.AddLoggingMetadata(parser, messages)
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class AlphaCreate(BetaCreate):
"""Create a Compute Engine firewall rule."""
@classmethod
def Args(cls, parser):
messages = apis.GetMessagesModule('compute',
compute_api.COMPUTE_ALPHA_API_VERSION)
parser.display_info.AddFormat(flags.DEFAULT_LIST_FORMAT)
cls.FIREWALL_RULE_ARG = flags.FirewallRuleArgument()
cls.FIREWALL_RULE_ARG.AddArgument(parser, operation_type='create')
cls.NETWORK_ARG = network_flags.NetworkArgumentForOtherResource(
'The network to which this rule is attached.', required=False)
firewalls_utils.AddCommonArgs(
parser,
for_update=False,
with_egress_support=True,
with_service_account=True)
firewalls_utils.AddArgsForServiceAccount(parser, for_update=False)
flags.AddEnableLogging(parser)
flags.AddLoggingMetadata(parser, messages)
Create.detailed_help = {
'brief': 'Create a Compute Engine firewall rule.',
'DESCRIPTION': """
*{command}* is used to create firewall rules to allow/deny
incoming/outgoing traffic.
""",
'EXAMPLES': """
To create a firewall rule allowing incoming TCP traffic on port 8080, run:
$ {command} example-service --allow=tcp:8080
--description="Allow incoming traffic on TCP port 8080" --direction=INGRESS
To create a firewall rule that allows TCP traffic through port 80 and
determines a list of specific IP address blocks that are allowed to make
inbound connections, run:
$ {command} tcp-rule --allow=tcp:80
--source-ranges="10.0.0.0/22,10.0.0.0/14" --description="Narrowing TCP traffic"
To list existing firewall rules, run:
$ gcloud compute firewall-rules list
For more detailed examples see
[](https://cloud.google.com/vpc/docs/using-firewalls)
""",
}

View File

@@ -0,0 +1,66 @@
# -*- coding: utf-8 -*- #
# Copyright 2014 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 deleting firewall rules."""
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 import utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute import flags as compute_flags
from googlecloudsdk.command_lib.compute.firewall_rules import flags
class Delete(base.DeleteCommand):
"""Delete Compute Engine firewall rules.
*{command}* deletes one or more Compute Engine firewall
rules.
## EXAMPLES
To delete a firewall rule, run:
$ {command} my-firewall-rule
"""
FIREWALL_ARG = None
@staticmethod
def Args(parser):
Delete.FIREWALL_ARG = flags.FirewallRuleArgument(plural=True)
Delete.FIREWALL_ARG.AddArgument(parser, operation_type='delete')
parser.display_info.AddCacheUpdater(flags.FirewallsCompleter)
def Run(self, args):
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
client = holder.client
firewall_refs = Delete.FIREWALL_ARG.ResolveAsResource(
args,
holder.resources,
scope_lister=compute_flags.GetDefaultScopeLister(client))
utils.PromptForDeletion(firewall_refs)
requests = []
for firewall_ref in firewall_refs:
requests.append((client.apitools_client.firewalls, 'Delete',
client.messages.ComputeFirewallsDeleteRequest(
**firewall_ref.AsDict())))
return client.MakeRequests(requests)

View File

@@ -0,0 +1,62 @@
# -*- coding: utf-8 -*- #
# Copyright 2014 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 describing firewall rules."""
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 import flags as compute_flags
from googlecloudsdk.command_lib.compute.firewall_rules import flags
class Describe(base.DescribeCommand):
"""Describe a Compute Engine firewall rule.
*{command}* displays all data associated with a Compute Engine
firewall rule in a project.
## EXAMPLES
To describe a firewall rule, run:
$ {command} my-firewall-rule
"""
FIREWALL_ARG = None
@staticmethod
def Args(parser):
# This factory method overrides help message - operation_type is baked in
# at argument construction time.
Describe.FIREWALL_ARG = flags.FirewallRuleArgument()
Describe.FIREWALL_ARG.AddArgument(parser, operation_type='describe')
def Run(self, args):
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
client = holder.client
firewall_ref = self.FIREWALL_ARG.ResolveAsResource(
args,
holder.resources,
scope_lister=compute_flags.GetDefaultScopeLister(client))
request = client.messages.ComputeFirewallsGetRequest(
**firewall_ref.AsDict())
return client.MakeRequests([(client.apitools_client.firewalls,
'Get', request)])[0]

View File

@@ -0,0 +1,81 @@
# -*- coding: utf-8 -*- #
# Copyright 2014 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 listing firewall rules."""
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 import lister
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute.firewall_rules import flags
from googlecloudsdk.core import log
RESOURCE_TYPE = 'firewall rules'
DETAILED_HELP = {
'brief':
'List Compute Engine ' + RESOURCE_TYPE,
'DESCRIPTION':
"""\
*{{command}}* displays all Compute Engine {0} in a project.
""".format(RESOURCE_TYPE)
}
EXAMPLE_FORMAT = """\
To list all {0} in a project in table form, run:
$ {{command}}
To list the URIs of all {0} in a project, run:
$ {{command}} --uri
To list all fields of all {0} in a project, run:
$ {{command}} --format="{1}"
"""
class List(base.ListCommand):
"""List Compute Engine firewall rules."""
@staticmethod
def Args(parser):
parser.display_info.AddFormat(flags.DEFAULT_LIST_FORMAT)
lister.AddBaseListerArgs(parser)
parser.display_info.AddCacheUpdater(flags.FirewallsCompleter)
def Run(self, args):
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
client = holder.client
request_data = lister.ParseNamesAndRegexpFlags(
args, holder.resources, holder.client.messages.Firewall)
list_implementation = lister.GlobalLister(client,
client.apitools_client.firewalls)
return lister.Invoke(request_data, list_implementation)
def Epilog(self, resources_were_displayed):
del resources_were_displayed
log.status.Print('\n' + flags.LIST_NOTICE)
List.detailed_help = DETAILED_HELP.copy()
List.detailed_help['EXAMPLES'] = EXAMPLE_FORMAT.format(
RESOURCE_TYPE, flags.LIST_WITH_ALL_FIELDS_FORMAT)

View File

@@ -0,0 +1,313 @@
# -*- coding: utf-8 -*- #
# Copyright 2014 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 updating firewall rules."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from apitools.base.py import encoding
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.api_lib.compute import firewalls_utils
from googlecloudsdk.api_lib.compute import utils as compute_api
from googlecloudsdk.api_lib.util import apis
from googlecloudsdk.calliope import base
from googlecloudsdk.calliope import exceptions as calliope_exceptions
from googlecloudsdk.command_lib.compute import exceptions
from googlecloudsdk.command_lib.compute.firewall_rules import flags
@base.ReleaseTracks(base.ReleaseTrack.GA)
class UpdateFirewall(base.UpdateCommand):
"""Update a firewall rule."""
with_egress_firewall = True
with_service_account = True
FIREWALL_RULE_ARG = None
@classmethod
def Args(cls, parser):
messages = apis.GetMessagesModule('compute',
compute_api.COMPUTE_GA_API_VERSION)
cls.FIREWALL_RULE_ARG = flags.FirewallRuleArgument()
cls.FIREWALL_RULE_ARG.AddArgument(parser, operation_type='update')
firewalls_utils.AddCommonArgs(
parser,
for_update=True,
with_egress_support=cls.with_egress_firewall,
with_service_account=cls.with_service_account)
firewalls_utils.AddArgsForServiceAccount(parser, for_update=True)
flags.AddEnableLogging(parser)
flags.AddLoggingMetadata(parser, messages)
def ValidateArgument(self, messages, args):
self.new_allowed = firewalls_utils.ParseRules(
args.allow, messages, firewalls_utils.ActionType.ALLOW)
args_unset = all(
x is None
for x in (args.allow, args.description, args.source_ranges,
args.source_tags, args.target_tags))
if self.with_egress_firewall:
args_unset = args_unset and all(
x is None
for x in (args.destination_ranges, args.priority, args.rules))
if self.with_service_account:
args_unset = args_unset and all(
x is None
for x in (args.source_service_accounts, args.target_service_accounts))
args_unset = args_unset and args.disabled is None
args_unset = (args_unset and args.enable_logging is None)
args_unset = args_unset and not args.logging_metadata
if args_unset:
raise exceptions.UpdatePropertyError(
'At least one property must be modified.')
if args.rules and args.allow:
raise firewalls_utils.ArgumentValidationError(
'Can NOT specify --rules and --allow in the same request.')
def Run(self, args):
"""Issues requests necessary to update the Firewall rules."""
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
client = holder.client
self.ValidateArgument(client.messages, args)
# Set the resource reference which is used in composing resource-get
# request.
resource_reference = self.FIREWALL_RULE_ARG.ResolveAsResource(
args, holder.resources)
get_request = self._GetGetRequest(client, resource_reference)
cleared_fields = []
objects = client.MakeRequests([get_request])
new_object = self.Modify(client, args, objects[0], cleared_fields)
# If existing object is equal to the proposed object or if
# Modify() returns None, then there is no work to be done, so we
# print the resource and exit.
if not new_object or objects[0] == new_object:
return objects[0]
with client.apitools_client.IncludeFields(cleared_fields):
resource_list = client.MakeRequests(
[self._GetSetRequest(client, resource_reference, new_object)])
return resource_list
def _GetGetRequest(self, client, resource_reference):
"""Returns the request for the existing Firewall resource."""
return (client.apitools_client.firewalls, 'Get',
client.messages.ComputeFirewallsGetRequest(
firewall=resource_reference.Name(),
project=resource_reference.project))
def _GetSetRequest(self, client, resource_reference, replacement):
request = client.messages.ComputeFirewallsPatchRequest(
firewall=replacement.name,
firewallResource=replacement,
project=resource_reference.project)
return (client.apitools_client.firewalls, 'Patch', request)
def _AddLoggingMetadata(self, messages, args, log_config):
if args.IsSpecified('logging_metadata'):
if log_config is None or not log_config.enable:
raise calliope_exceptions.InvalidArgumentException(
'--logging-metadata',
'cannot toggle logging metadata if logging is not enabled.')
log_config.metadata = flags.GetLoggingMetadataArg(
messages).GetEnumForChoice(args.logging_metadata)
def Modify(self, client, args, existing, cleared_fields):
"""Returns a modified Firewall message and included fields."""
if args.allow:
allowed = self.new_allowed
elif args.allow is None:
allowed = existing.allowed
else:
cleared_fields.append('allowed')
allowed = []
if args.description:
description = args.description
elif args.description is None:
description = existing.description
else:
cleared_fields.append('description')
description = None
if args.source_ranges:
source_ranges = args.source_ranges
elif args.source_ranges is None:
source_ranges = existing.sourceRanges
else:
cleared_fields.append('sourceRanges')
source_ranges = []
if args.source_tags:
source_tags = args.source_tags
elif args.source_tags is None:
source_tags = existing.sourceTags
else:
cleared_fields.append('sourceTags')
source_tags = []
if args.target_tags:
target_tags = args.target_tags
elif args.target_tags is None:
target_tags = existing.targetTags
else:
cleared_fields.append('targetTags')
target_tags = []
denied = []
if args.rules:
if existing.allowed:
allowed = firewalls_utils.ParseRules(args.rules, client.messages,
firewalls_utils.ActionType.ALLOW)
else:
denied = firewalls_utils.ParseRules(args.rules, client.messages,
firewalls_utils.ActionType.DENY)
elif args.rules is not None:
if existing.allowed:
cleared_fields.append('allowed')
allowed = []
else:
cleared_fields.append('denied')
denied = []
direction = existing.direction
if args.priority is None:
priority = existing.priority
else:
priority = args.priority
destination_ranges = []
if args.destination_ranges:
destination_ranges = args.destination_ranges
elif args.destination_ranges is None:
destination_ranges = existing.destinationRanges
else:
cleared_fields.append('destinationRanges')
source_service_accounts = []
if args.source_service_accounts:
source_service_accounts = args.source_service_accounts
elif args.source_service_accounts is None:
source_service_accounts = existing.sourceServiceAccounts
else:
cleared_fields.append('sourceServiceAccounts')
target_service_accounts = []
if args.target_service_accounts:
target_service_accounts = args.target_service_accounts
elif args.target_service_accounts is None:
target_service_accounts = existing.targetServiceAccounts
else:
cleared_fields.append('targetServiceAccounts')
if args.IsSpecified('enable_logging'):
log_config = client.messages.FirewallLogConfig(enable=args.enable_logging)
self._AddLoggingMetadata(client.messages, args, log_config)
else:
log_config = (
encoding.CopyProtoMessage(existing.logConfig)
if existing.logConfig is not None else None)
self._AddLoggingMetadata(client.messages, args, log_config)
new_firewall = client.messages.Firewall(
name=existing.name,
direction=direction,
priority=priority,
allowed=allowed,
denied=denied,
description=description,
network=existing.network,
sourceRanges=source_ranges,
sourceTags=source_tags,
destinationRanges=destination_ranges,
targetTags=target_tags,
sourceServiceAccounts=source_service_accounts,
targetServiceAccounts=target_service_accounts,
logConfig=log_config)
if args.disabled is not None:
new_firewall.disabled = args.disabled
return new_firewall
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class BetaUpdateFirewall(UpdateFirewall):
"""Update a firewall rule."""
@classmethod
def Args(cls, parser):
messages = apis.GetMessagesModule('compute',
compute_api.COMPUTE_BETA_API_VERSION)
cls.FIREWALL_RULE_ARG = flags.FirewallRuleArgument()
cls.FIREWALL_RULE_ARG.AddArgument(parser, operation_type='update')
firewalls_utils.AddCommonArgs(
parser,
for_update=True,
with_egress_support=cls.with_egress_firewall,
with_service_account=cls.with_service_account)
firewalls_utils.AddArgsForServiceAccount(parser, for_update=True)
flags.AddEnableLogging(parser)
flags.AddLoggingMetadata(parser, messages)
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class AlphaUpdateFirewall(BetaUpdateFirewall):
"""Update a firewall rule."""
@classmethod
def Args(cls, parser):
messages = apis.GetMessagesModule('compute',
compute_api.COMPUTE_ALPHA_API_VERSION)
cls.FIREWALL_RULE_ARG = flags.FirewallRuleArgument()
cls.FIREWALL_RULE_ARG.AddArgument(parser, operation_type='update')
firewalls_utils.AddCommonArgs(
parser,
for_update=True,
with_egress_support=cls.with_egress_firewall,
with_service_account=cls.with_service_account)
firewalls_utils.AddArgsForServiceAccount(parser, for_update=True)
flags.AddEnableLogging(parser)
flags.AddLoggingMetadata(parser, messages)
UpdateFirewall.detailed_help = {
'brief':
'Update a firewall rule.',
'DESCRIPTION':
"""\
*{command}* is used to update firewall rules that allow/deny
incoming/outgoing traffic. The firewall rule will only be updated for
arguments that are specifically passed. Other attributes will remain
unaffected. The `action` flag (whether to allow or deny matching
traffic) cannot be defined when updating a firewall rule; use
`gcloud compute firewall-rules delete` to remove the rule instead.
""",
'EXAMPLES': """\
To update the firewall rule ``RULE'' to enable logging, run:
$ {command} RULE --enable-logging
""",
}