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,34 @@
# -*- 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 Google Cloud Build."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.cloudbuild import transforms
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
class TriggerCreate(base.Group):
"""Create build triggers for Google Cloud Build."""
category = base.CI_CD_CATEGORY
@staticmethod
def Args(parser):
parser.display_info.AddTransforms(transforms.GetTransforms())

View File

@@ -0,0 +1,172 @@
# -*- 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.
"""Create Bitbucket Cloud trigger command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.cloudbuild import cloudbuild_util
from googlecloudsdk.api_lib.cloudbuild import trigger_config as trigger_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
class CreateBitbuckeCloud(base.CreateCommand):
"""Create a build trigger for a 2nd-gen Bitbucket Cloud repository."""
detailed_help = {
'EXAMPLES': """\
To create a push trigger with a 2nd-gen repository for all branches:
$ {command} --name="my-trigger" --service-account="projects/my-project/serviceAccounts/my-byosa@my-project.iam.gserviceaccount.com" --repository="projects/1234/locations/us-central1/connections/myconn/repositories/myrepo" --branch-pattern=".*" --build-config="cloudbuild.yaml" --region=us-central1
To create a pull request trigger with a 2nd-gen repository for main:
$ {command} --name="my-trigger" --service-account="projects/my-project/serviceAccounts/my-byosa@my-project.iam.gserviceaccount.com" --repository="projects/1234/locations/us-central1/connections/myconn/repositories/myrepo" --build-config="cloudbuild.yaml" --pull-request-pattern="^main$" --region=us-central1
""",
}
@staticmethod
def Args(parser):
"""Register flags for this command.
Args:
parser: An argparse.ArgumentParser-like object. It is mocked out in order
to capture some information, but behaves like an ArgumentParser.
"""
flag_config = trigger_utils.AddTriggerArgs(parser)
flag_config.add_argument(
'--repository',
help=(
'Repository resource (2nd gen) to use, in the format'
' "projects/*/locations/*/connections/*/repositories/*".'
),
)
ref_config = flag_config.add_mutually_exclusive_group(required=True)
trigger_utils.AddBranchPattern(ref_config)
trigger_utils.AddTagPattern(ref_config)
pr_config = ref_config.add_argument_group(help='Pull Request settings')
pr_config.add_argument(
'--pull-request-pattern',
metavar='REGEX',
required=True,
help="""\
Regular expression specifying which base git branch to match for
pull request events.
This pattern is used as a regex search for the base branch (the branch you are
trying to merge into) for pull request updates.
For example, --pull-request-pattern=foo will match "foo", "foobar", and "barfoo".
The syntax of the regular expressions accepted is the syntax accepted by
RE2 and described at https://github.com/google/re2/wiki/Syntax.
""",
)
trigger_utils.AddCommentControlArg(pr_config)
trigger_utils.AddBuildConfigArgs(flag_config, require_docker_image=True)
trigger_utils.AddRepoEventArgs(flag_config)
def ParseTriggerFromFlags(self, args):
"""Parses command line arguments into a build trigger.
Args:
args: An argparse arguments object.
Returns:
A build trigger object.
Raises:
RequiredArgumentException: If comment_control is defined but
pull_request_pattern isn't.
"""
messages = cloudbuild_util.GetMessagesModule()
trigger, done = trigger_utils.ParseTriggerArgs(args, messages)
if done:
return trigger
trigger.repositoryEventConfig = messages.RepositoryEventConfig(
repository=args.repository
)
cfg = trigger.repositoryEventConfig
if args.pull_request_pattern:
cfg.pullRequest = messages.PullRequestFilter(
branch=args.pull_request_pattern
)
if args.comment_control:
cfg.pullRequest.commentControl = (
messages.PullRequestFilter.CommentControlValueValuesEnum(
args.comment_control
)
)
else:
# Push event
cfg.push = messages.PushFilter(
branch=args.branch_pattern, tag=args.tag_pattern
)
trigger_utils.ParseBuildConfigArgs(trigger, args, messages, '')
trigger_utils.ParseRepoEventArgs(trigger, args)
return trigger
def Run(self, args):
"""This is what gets called when the user runs this command.
Args:
args: An argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
Some values that we want to print later.
"""
client = cloudbuild_util.GetClientInstance()
messages = cloudbuild_util.GetMessagesModule()
trigger = self.ParseTriggerFromFlags(args)
# Send the Create request
project = properties.VALUES.core.project.Get(required=True)
regionprop = properties.VALUES.builds.region.Get()
location = args.region or regionprop or cloudbuild_util.DEFAULT_REGION
parent = resources.REGISTRY.Create(
collection='cloudbuild.projects.locations',
projectsId=project,
locationsId=location,
).RelativeName()
created_trigger = client.projects_locations_triggers.Create(
messages.CloudbuildProjectsLocationsTriggersCreateRequest(
parent=parent, buildTrigger=trigger
)
)
trigger_resource = resources.REGISTRY.Parse(
None,
collection='cloudbuild.projects.locations.triggers',
api_version='v1',
params={
'projectsId': project,
'locationsId': location,
'triggersId': created_trigger.id,
},
)
log.CreatedResource(trigger_resource)
return created_trigger

View File

@@ -0,0 +1,172 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 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.
"""Create Bitbucket Data Center trigger command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.cloudbuild import cloudbuild_util
from googlecloudsdk.api_lib.cloudbuild import trigger_config as trigger_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
class CreateBitbucketDataCenter(base.CreateCommand):
"""Create a build trigger for a 2nd-gen Bitbucket Data Center repository."""
detailed_help = {
'EXAMPLES': """\
To create a push trigger with a 2nd-gen repository for all branches:
$ {command} --name="my-trigger" --service-account="projects/my-project/serviceAccounts/my-byosa@my-project.iam.gserviceaccount.com" --repository="projects/1234/locations/us-central1/connections/myconn/repositories/myrepo" --branch-pattern=".*" --build-config="cloudbuild.yaml" --region=us-central1
To create a pull request trigger with a 2nd-gen repository for main:
$ {command} --name="my-trigger" --service-account="projects/my-project/serviceAccounts/my-byosa@my-project.iam.gserviceaccount.com" --repository="projects/1234/locations/us-central1/connections/myconn/repositories/myrepo" --build-config="cloudbuild.yaml" --pull-request-pattern="^main$" --region=us-central1
""",
}
@staticmethod
def Args(parser):
"""Register flags for this command.
Args:
parser: An argparse.ArgumentParser-like object. It is mocked out in order
to capture some information, but behaves like an ArgumentParser.
"""
flag_config = trigger_utils.AddTriggerArgs(parser)
flag_config.add_argument(
'--repository',
help=(
'Repository resource (2nd gen) to use, in the format'
' "projects/*/locations/*/connections/*/repositories/*".'
),
)
ref_config = flag_config.add_mutually_exclusive_group(required=True)
trigger_utils.AddBranchPattern(ref_config)
trigger_utils.AddTagPattern(ref_config)
pr_config = ref_config.add_argument_group(help='Pull Request settings')
pr_config.add_argument(
'--pull-request-pattern',
metavar='REGEX',
required=True,
help="""\
Regular expression specifying which base git branch to match for
pull request events.
This pattern is used as a regex search for the base branch (the branch you are
trying to merge into) for pull request updates.
For example, --pull-request-pattern=foo will match "foo", "foobar", and "barfoo".
The syntax of the regular expressions accepted is the syntax accepted by
RE2 and described at https://github.com/google/re2/wiki/Syntax.
""",
)
trigger_utils.AddCommentControlArg(pr_config)
trigger_utils.AddBuildConfigArgs(flag_config, require_docker_image=True)
trigger_utils.AddRepoEventArgs(flag_config)
def ParseTriggerFromFlags(self, args):
"""Parses command line arguments into a build trigger.
Args:
args: An argparse arguments object.
Returns:
A build trigger object.
Raises:
RequiredArgumentException: If comment_control is defined but
pull_request_pattern isn't.
"""
messages = cloudbuild_util.GetMessagesModule()
trigger, done = trigger_utils.ParseTriggerArgs(args, messages)
if done:
return trigger
trigger.repositoryEventConfig = messages.RepositoryEventConfig(
repository=args.repository
)
cfg = trigger.repositoryEventConfig
if args.pull_request_pattern:
cfg.pullRequest = messages.PullRequestFilter(
branch=args.pull_request_pattern
)
if args.comment_control:
cfg.pullRequest.commentControl = (
messages.PullRequestFilter.CommentControlValueValuesEnum(
args.comment_control
)
)
else:
# Push event
cfg.push = messages.PushFilter(
branch=args.branch_pattern, tag=args.tag_pattern
)
trigger_utils.ParseBuildConfigArgs(trigger, args, messages, '')
trigger_utils.ParseRepoEventArgs(trigger, args)
return trigger
def Run(self, args):
"""This is what gets called when the user runs this command.
Args:
args: An argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
Some values that we want to print later.
"""
client = cloudbuild_util.GetClientInstance()
messages = cloudbuild_util.GetMessagesModule()
trigger = self.ParseTriggerFromFlags(args)
# Send the Create request
project = properties.VALUES.core.project.Get(required=True)
regionprop = properties.VALUES.builds.region.Get()
location = args.region or regionprop or cloudbuild_util.DEFAULT_REGION
parent = resources.REGISTRY.Create(
collection='cloudbuild.projects.locations',
projectsId=project,
locationsId=location,
).RelativeName()
created_trigger = client.projects_locations_triggers.Create(
messages.CloudbuildProjectsLocationsTriggersCreateRequest(
parent=parent, buildTrigger=trigger
)
)
trigger_resource = resources.REGISTRY.Parse(
None,
collection='cloudbuild.projects.locations.triggers',
api_version='v1',
params={
'projectsId': project,
'locationsId': location,
'triggersId': created_trigger.id,
},
)
log.CreatedResource(trigger_resource)
return created_trigger

View File

@@ -0,0 +1,177 @@
# -*- 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.
"""Create Bitbucket Server trigger command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.cloudbuild import cloudbuild_util
from googlecloudsdk.api_lib.cloudbuild import trigger_config as trigger_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
class CreateBitbucketServer(base.CreateCommand):
"""Create a build trigger for a Bitbucket Server repository."""
detailed_help = {
'EXAMPLES':
"""\
To create a push trigger for all branches:
$ {command} --name="my-trigger" --service-account="projects/my-project/serviceAccounts/my-byosa@my-project.iam.gserviceaccount.com" --project-key="GoogleCloudPlatform" --repo-slug="cloud-builders" --bitbucket-server-config-resource="projects/1234/locations/global/bitbucketServerConfigs/5678" --branch-pattern=".*" --build-config="cloudbuild.yaml"
To create a pull request trigger for main:
$ {command} --name="my-trigger" --service-account="projects/my-project/serviceAccounts/my-byosa@my-project.iam.gserviceaccount.com" --project-key="GoogleCloudPlatform" --repo-slug="cloud-builders" --bitbucket-server-config-resource="projects/1234/locations/global/bitbucketServerConfigs/5678" --pull-request-pattern="^main$" --build-config="cloudbuild.yaml"
""",
}
@staticmethod
def Args(parser):
"""Register flags for this command.
Args:
parser: An argparse.ArgumentParser-like object. It is mocked out in order
to capture some information, but behaves like an ArgumentParser.
"""
flag_config = trigger_utils.AddTriggerArgs(parser)
flag_config.add_argument(
'--repo-slug', help='Bitbucket Server repository slug.', required=True)
flag_config.add_argument(
'--project-key', help='Bitbucket Server project key.', required=True)
flag_config.add_argument(
'--bitbucket-server-config-resource',
help='Bitbucket Server config resource name.',
required=True)
ref_config = flag_config.add_mutually_exclusive_group(required=True)
trigger_utils.AddBranchPattern(ref_config)
trigger_utils.AddTagPattern(ref_config)
pr_config = ref_config.add_argument_group(help='Pull Request settings')
pr_config.add_argument(
'--pull-request-pattern',
metavar='REGEX',
required=True,
help="""\
Regular expression specifying which base git branch to match for
pull request events.
This pattern is used as a regex search for the base branch (the branch you are
trying to merge into) for pull request updates.
For example, --pull-request-pattern=foo will match "foo", "foobar", and "barfoo".
The syntax of the regular expressions accepted is the syntax accepted by
RE2 and described at https://github.com/google/re2/wiki/Syntax.
""")
trigger_utils.AddCommentControlArg(pr_config)
trigger_utils.AddBuildConfigArgs(flag_config)
trigger_utils.AddRepoEventArgs(flag_config)
def ParseTriggerFromFlags(self, args):
"""Parses command line arguments into a build trigger.
Args:
args: An argparse arguments object.
Returns:
A build trigger object.
Raises:
RequiredArgumentException: If comment_control is defined but
pull_request_pattern isn't.
"""
project = properties.VALUES.core.project.Get(required=True)
messages = cloudbuild_util.GetMessagesModule()
trigger, done = trigger_utils.ParseTriggerArgs(args, messages)
if done:
return trigger
# Bitbucket Server config
bbs = messages.BitbucketServerTriggerConfig(
repoSlug=args.repo_slug,
projectKey=args.project_key,
bitbucketServerConfigResource=args.bitbucket_server_config_resource,
)
if args.pull_request_pattern:
bbs.pullRequest = messages.PullRequestFilter(
branch=args.pull_request_pattern
)
if args.comment_control:
bbs.pullRequest.commentControl = (
messages.PullRequestFilter.CommentControlValueValuesEnum(
args.comment_control
)
)
else:
# Push event
bbs.push = messages.PushFilter(
branch=args.branch_pattern, tag=args.tag_pattern
)
trigger.bitbucketServerTriggerConfig = bbs
default_image = 'gcr.io/%s/bitbucketserver-%s/%s:$COMMIT_SHA' % (
project,
args.project_key,
args.repo_slug,
)
trigger_utils.ParseBuildConfigArgs(trigger, args, messages, default_image)
trigger_utils.ParseRepoEventArgs(trigger, args)
return trigger
def Run(self, args):
"""This is what gets called when the user runs this command.
Args:
args: an argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
Some value that we want to have printed later.
"""
client = cloudbuild_util.GetClientInstance()
messages = cloudbuild_util.GetMessagesModule()
trigger = self.ParseTriggerFromFlags(args)
# Send the Create request
project = properties.VALUES.core.project.Get(required=True)
regionprop = properties.VALUES.builds.region.Get()
location = args.region or regionprop or cloudbuild_util.DEFAULT_REGION
parent = resources.REGISTRY.Create(
collection='cloudbuild.projects.locations',
projectsId=project,
locationsId=location).RelativeName()
created_trigger = client.projects_locations_triggers.Create(
messages.CloudbuildProjectsLocationsTriggersCreateRequest(
parent=parent, buildTrigger=trigger))
trigger_resource = resources.REGISTRY.Parse(
None,
collection='cloudbuild.projects.locations.triggers',
api_version='v1',
params={
'projectsId': project,
'locationsId': location,
'triggersId': created_trigger.id,
})
log.CreatedResource(trigger_resource)
return created_trigger

View File

@@ -0,0 +1,143 @@
# -*- 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.
"""Create Cloud Source Repositories trigger command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.cloudbuild import cloudbuild_util
from googlecloudsdk.api_lib.cloudbuild import trigger_config as trigger_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.source import resource_args as repo_resource
from googlecloudsdk.command_lib.util.concepts import concept_parsers
from googlecloudsdk.command_lib.util.concepts import presentation_specs
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
class CreateCSR(base.CreateCommand):
"""Create a build trigger from a Cloud Source Repository."""
detailed_help = {
'EXAMPLES':
"""\
To create a push trigger for all branches:
$ {command} --name="my-trigger" --service-account="projects/my-project/serviceAccounts/my-byosa@my-project.iam.gserviceaccount.com" --repo="my-repo" --branch-pattern=".*" --build-config="cloudbuild.yaml"
""",
}
@staticmethod
def Args(parser):
"""Register flags for this command.
Args:
parser: An argparse.ArgumentParser-like object. It is mocked out in order
to capture some information, but behaves like an ArgumentParser.
"""
flag_config = trigger_utils.AddTriggerArgs(parser)
repo_spec = presentation_specs.ResourcePresentationSpec(
'--repo', # This defines how the "anchor" or leaf argument is named.
repo_resource.GetRepoResourceSpec(),
'Cloud Source Repository.',
required=True,
prefixes=False)
concept_parsers.ConceptParser([repo_spec]).AddToParser(flag_config)
ref_config = flag_config.add_mutually_exclusive_group(required=True)
trigger_utils.AddBranchPattern(ref_config)
trigger_utils.AddTagPattern(ref_config)
trigger_utils.AddBuildConfigArgs(flag_config)
trigger_utils.AddRepoEventArgs(flag_config)
def ParseTriggerFromFlags(self, args):
"""Parses command line arguments into a build trigger.
Args:
args: An argparse arguments object.
Returns:
A build trigger object.
"""
messages = cloudbuild_util.GetMessagesModule()
trigger, done = trigger_utils.ParseTriggerArgs(args, messages)
if done:
return trigger
repo_ref = args.CONCEPTS.repo.Parse()
repo = repo_ref.reposId
trigger = messages.BuildTrigger(
name=args.name,
description=args.description,
serviceAccount=args.service_account,
triggerTemplate=messages.RepoSource(
repoName=repo,
branchName=args.branch_pattern,
tagName=args.tag_pattern,
),
)
trigger_utils.ParseRequireApproval(trigger, args, messages)
# Build Config
project = properties.VALUES.core.project.Get(required=True)
default_image = 'gcr.io/%s/%s:$COMMIT_SHA' % (project, repo)
trigger_utils.ParseBuildConfigArgs(trigger, args, messages, default_image)
trigger_utils.ParseRepoEventArgs(trigger, args)
return trigger
def Run(self, args):
"""This is what gets called when the user runs this command.
Args:
args: an argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
Some value that we want to have printed later.
"""
messages = cloudbuild_util.GetMessagesModule()
trigger = self.ParseTriggerFromFlags(args)
# Send the Create request
client = cloudbuild_util.GetClientInstance()
project = properties.VALUES.core.project.Get(required=True)
regionprop = properties.VALUES.builds.region.Get()
location = args.region or regionprop or cloudbuild_util.DEFAULT_REGION
parent = resources.REGISTRY.Create(
collection='cloudbuild.projects.locations',
projectsId=project,
locationsId=location).RelativeName()
created_trigger = client.projects_locations_triggers.Create(
messages.CloudbuildProjectsLocationsTriggersCreateRequest(
parent=parent, buildTrigger=trigger))
trigger_resource = resources.REGISTRY.Parse(
None,
collection='cloudbuild.projects.locations.triggers',
api_version='v1',
params={
'projectsId': project,
'locationsId': location,
'triggersId': created_trigger.id,
})
log.CreatedResource(trigger_resource)
return created_trigger

View File

@@ -0,0 +1,173 @@
# -*- coding: utf-8 -*- #
# Copyright 2025 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.
"""Create Developer Connect trigger command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.cloudbuild import cloudbuild_util
from googlecloudsdk.api_lib.cloudbuild import trigger_config as trigger_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
@base.UniverseCompatible
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA)
class CreateDeveloperConnect(base.CreateCommand):
"""Create a build trigger for a Developer Connect repository."""
detailed_help = {
'EXAMPLES': """\
To create a push trigger with a DC repository for all branches:
$ {command} --name="my-trigger" --service-account="projects/my-project/serviceAccounts/my-byosa@my-project.iam.gserviceaccount.com" --git-repository-link="projects/1234/locations/us-central1/connections/myconn/gitRepositoryLinks/mylink" --branch-pattern=".*" --build-config="cloudbuild.yaml" --region=us-central1
To create a pull request trigger with a DC repository for main:
$ {command} --name="my-trigger" --service-account="projects/my-project/serviceAccounts/my-byosa@my-project.iam.gserviceaccount.com" --repository="projects/1234/locations/us-central1/connections/myconn/gitRepositoryLinks/mylink" --build-config="cloudbuild.yaml" --pull-request-pattern="^main$" --region=us-central1
""",
}
@staticmethod
def Args(parser):
"""Register flags for this command.
Args:
parser: An argparse.ArgumentParser-like object. It is mocked out in order
to capture some information, but behaves like an ArgumentParser.
"""
flag_config = trigger_utils.AddTriggerArgs(parser)
flag_config.add_argument(
'--git-repository-link',
help=(
'Developer Connect resource to use, in the format'
' "projects/*/locations/*/connections/*/gitRepositoryLinks/*".'
),
)
ref_config = flag_config.add_mutually_exclusive_group(required=True)
trigger_utils.AddBranchPattern(ref_config)
trigger_utils.AddTagPattern(ref_config)
pr_config = ref_config.add_argument_group(help='Pull Request settings')
pr_config.add_argument(
'--pull-request-pattern',
metavar='REGEX',
required=True,
help="""\
Regular expression specifying which base git branch to match for
pull request events.
This pattern is used as a regex search for the base branch (the branch you are
trying to merge into) for pull request updates.
For example, --pull-request-pattern=foo will match "foo", "foobar", and "barfoo".
The syntax of the regular expressions accepted is the syntax accepted by
RE2 and described at https://github.com/google/re2/wiki/Syntax.
""",
)
trigger_utils.AddCommentControlArg(pr_config)
trigger_utils.AddBuildConfigArgs(flag_config, require_docker_image=True)
trigger_utils.AddRepoEventArgs(flag_config)
def ParseTriggerFromFlags(self, args):
"""Parses command line arguments into a build trigger.
Args:
args: An argparse arguments object.
Returns:
A build trigger object.
Raises:
RequiredArgumentException: If comment_control is defined but
pull_request_pattern isn't.
"""
messages = cloudbuild_util.GetMessagesModule()
trigger, done = trigger_utils.ParseTriggerArgs(args, messages)
if done:
return trigger
trigger.developerConnectEventConfig = messages.DeveloperConnectEventConfig(
gitRepositoryLink=args.git_repository_link
)
cfg = trigger.developerConnectEventConfig
if args.pull_request_pattern:
cfg.pullRequest = messages.PullRequestFilter(
branch=args.pull_request_pattern
)
if args.comment_control:
cfg.pullRequest.commentControl = (
messages.PullRequestFilter.CommentControlValueValuesEnum(
args.comment_control
)
)
else:
# Push event
cfg.push = messages.PushFilter(
branch=args.branch_pattern, tag=args.tag_pattern
)
trigger_utils.ParseBuildConfigArgs(trigger, args, messages, '')
trigger_utils.ParseRepoEventArgs(trigger, args)
return trigger
def Run(self, args):
"""This is what gets called when the user runs this command.
Args:
args: An argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
Some values that we want to print later.
"""
client = cloudbuild_util.GetClientInstance()
messages = cloudbuild_util.GetMessagesModule()
trigger = self.ParseTriggerFromFlags(args)
# Send the Create request
project = properties.VALUES.core.project.Get(required=True)
regionprop = properties.VALUES.builds.region.Get()
location = args.region or regionprop or cloudbuild_util.DEFAULT_REGION
parent = resources.REGISTRY.Create(
collection='cloudbuild.projects.locations',
projectsId=project,
locationsId=location,
).RelativeName()
created_trigger = client.projects_locations_triggers.Create(
messages.CloudbuildProjectsLocationsTriggersCreateRequest(
parent=parent, buildTrigger=trigger
)
)
trigger_resource = resources.REGISTRY.Parse(
None,
collection='cloudbuild.projects.locations.triggers',
api_version='v1',
params={
'projectsId': project,
'locationsId': location,
'triggersId': created_trigger.id,
},
)
log.CreatedResource(trigger_resource)
return created_trigger

View File

@@ -0,0 +1,204 @@
# -*- 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.
"""Create GitHub trigger command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.cloudbuild import cloudbuild_util
from googlecloudsdk.api_lib.cloudbuild import trigger_config as trigger_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
class CreateGitHub(base.CreateCommand):
"""Create a build trigger for a GitHub repository."""
detailed_help = {
'EXAMPLES':
"""\
To create a push trigger with a 1st-gen repository for all branches:
$ {command} --name="my-trigger" --service-account="projects/my-project/serviceAccounts/my-byosa@my-project.iam.gserviceaccount.com" --repo-owner="GoogleCloudPlatform" --repo-name="cloud-builders" --branch-pattern=".*" --build-config="cloudbuild.yaml"
To create a pull request trigger with a 1st-gen repository for master:
$ {command} --name="my-trigger" --service-account="projects/my-project/serviceAccounts/my-byosa@my-project.iam.gserviceaccount.com" --repo-owner="GoogleCloudPlatform" --repo-name="cloud-builders" --pull-request-pattern="^master$" --build-config="cloudbuild.yaml"
To create a pull request trigger with a 2nd gen repository for master:
$ {command} --name="my-trigger" --repository=projects/my-project/locations/us-central1/connections/my-conn/repositories/my-repo --pull-request-pattern="^master$" --build-config="cloudbuild.yaml" --region=us-central1
""",
}
@staticmethod
def Args(parser):
"""Register flags for this command.
Args:
parser: An argparse.ArgumentParser-like object. It is mocked out in order
to capture some information, but behaves like an ArgumentParser.
"""
flag_config = trigger_utils.AddTriggerArgs(parser)
gen_config = flag_config.add_mutually_exclusive_group(required=True)
gen_config.add_argument(
'--repository',
help=("""\
Repository resource (2nd gen) to use, in the format
"projects/*/locations/*/connections/*/repositories/*".
"""),
)
v1_config = gen_config.add_argument_group(
help='1st-gen repository settings.')
v1_config.add_argument(
'--repo-owner',
help='Owner of the GitHub Repository (1st gen).',
required=True)
v1_config.add_argument(
'--repo-name',
help='Name of the GitHub Repository (1st gen).',
required=True)
v1_config.add_argument(
'--enterprise-config',
help="""\
Resource name of the GitHub Enterprise config that should be applied to this
installation.
For example: "projects/{$project_id}/locations/{$location_id}/githubEnterpriseConfigs/{$config_id}
""")
ref_config = flag_config.add_mutually_exclusive_group(required=True)
trigger_utils.AddBranchPattern(ref_config)
trigger_utils.AddTagPattern(ref_config)
pr_config = ref_config.add_argument_group(help='Pull Request settings')
pr_config.add_argument(
'--pull-request-pattern',
metavar='REGEX',
required=True,
help="""\
A regular expression specifying which base git branch to match for
pull request events.
This pattern is used as a regex search for the base branch (the branch you are
trying to merge into) for pull request updates.
For example, --pull-request-pattern=foo will match "foo", "foobar", and "barfoo".
The syntax of the regular expressions accepted is the syntax accepted by
RE2 and described at https://github.com/google/re2/wiki/Syntax.
""")
trigger_utils.AddCommentControlArg(pr_config)
trigger_utils.AddBuildConfigArgs(flag_config)
trigger_utils.AddRepoEventArgs(flag_config)
trigger_utils.AddIncludeLogsArgs(flag_config)
def ParseTriggerFromFlags(self, args):
"""Parses command line arguments into a build trigger.
Args:
args: An argparse arguments object.
Returns:
A build trigger object.
Raises:
RequiredArgumentException: If comment_control is defined but
pull_request_pattern isn't.
"""
project = properties.VALUES.core.project.Get(required=True)
messages = cloudbuild_util.GetMessagesModule()
trigger, done = trigger_utils.ParseTriggerArgs(args, messages)
if done:
return trigger
if args.repo_owner and args.repo_name: # 1st-gen GitHub config
trigger.github = messages.GitHubEventsConfig(
owner=args.repo_owner,
name=args.repo_name,
enterpriseConfigResourceName=args.enterprise_config)
rcfg = trigger.github
else: # 2nd-gen (Repos API) config
trigger.repositoryEventConfig = messages.RepositoryEventConfig(
repository=args.repository)
rcfg = trigger.repositoryEventConfig
if args.pull_request_pattern:
rcfg.pullRequest = messages.PullRequestFilter(
branch=args.pull_request_pattern)
if args.comment_control:
rcfg.pullRequest.commentControl = (
messages.PullRequestFilter.CommentControlValueValuesEnum(
args.comment_control
)
)
else:
# Push event
rcfg.push = messages.PushFilter(
branch=args.branch_pattern, tag=args.tag_pattern)
default_image = 'gcr.io/%s/github.com/%s/%s:$COMMIT_SHA' % (
project, args.repo_owner, args.repo_name)
trigger_utils.ParseBuildConfigArgs(trigger, args, messages, default_image)
trigger_utils.ParseRepoEventArgs(trigger, args)
trigger_utils.ParseIncludeLogsWithStatus(trigger, args, messages)
return trigger
def Run(self, args):
"""This is what gets called when the user runs this command.
Args:
args: an argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
Some value that we want to have printed later.
"""
client = cloudbuild_util.GetClientInstance()
messages = cloudbuild_util.GetMessagesModule()
trigger = self.ParseTriggerFromFlags(args)
# Send the Create request
project = properties.VALUES.core.project.Get(required=True)
regionprop = properties.VALUES.builds.region.Get()
location = args.region or regionprop or cloudbuild_util.DEFAULT_REGION
parent = resources.REGISTRY.Create(
collection='cloudbuild.projects.locations',
projectsId=project,
locationsId=location).RelativeName()
created_trigger = client.projects_locations_triggers.Create(
messages.CloudbuildProjectsLocationsTriggersCreateRequest(
parent=parent, buildTrigger=trigger))
trigger_resource = resources.REGISTRY.Parse(
None,
collection='cloudbuild.projects.locations.triggers',
api_version='v1',
params={
'projectsId': project,
'locationsId': location,
'triggersId': created_trigger.id,
})
log.CreatedResource(trigger_resource)
return created_trigger

View File

@@ -0,0 +1,167 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 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.
"""Create GitLab trigger command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.cloudbuild import cloudbuild_util
from googlecloudsdk.api_lib.cloudbuild import trigger_config as trigger_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
class CreateGitLab(base.CreateCommand):
"""Create a build trigger for a 2nd-gen GitLab repository."""
detailed_help = {
'EXAMPLES': """\
To create a push trigger with a 2nd-gen repository for all branches:
$ {command} --name="my-trigger" --service-account="projects/my-project/serviceAccounts/my-byosa@my-project.iam.gserviceaccount.com" --repository="projects/1234/locations/us-central1/connections/myconn/repositories/myrepo" --branch-pattern=".*" --build-config="cloudbuild.yaml" --region=us-central1
To create a pull request trigger with a 2nd-gen repository for main:
$ {command} --name="my-trigger" --service-account="projects/my-project/serviceAccounts/my-byosa@my-project.iam.gserviceaccount.com" --repository="projects/1234/locations/us-central1/connections/myconn/repositories/myrepo" --build-config="cloudbuild.yaml" --pull-request-pattern="^main$" --region=us-central1
""",
}
@staticmethod
def Args(parser):
"""Register flags for this command.
Args:
parser: An argparse.ArgumentParser-like object. It is mocked out in order
to capture some information, but behaves like an ArgumentParser.
"""
flag_config = trigger_utils.AddGitLabEnterpriseTriggerArgs(parser)
flag_config.add_argument(
'--repository',
help=(
'Repository resource (2nd gen) to use, in the format'
' "projects/*/locations/*/connections/*/repositories/*".'
),
)
ref_config = flag_config.add_mutually_exclusive_group(required=True)
trigger_utils.AddBranchPattern(ref_config)
trigger_utils.AddTagPattern(ref_config)
pr_config = ref_config.add_argument_group(help='Pull Request settings')
pr_config.add_argument(
'--pull-request-pattern',
metavar='REGEX',
required=True,
help="""\
Regular expression specifying which base git branch to match for
pull request events.
This pattern is used as a regex search for the base branch (the branch you are
trying to merge into) for pull request updates.
For example, --pull-request-pattern=foo will match "foo", "foobar", and "barfoo".
The syntax of the regular expressions accepted is the syntax accepted by
RE2 and described at https://github.com/google/re2/wiki/Syntax.
""")
trigger_utils.AddCommentControlArg(pr_config)
trigger_utils.AddBuildConfigArgs(flag_config, require_docker_image=True)
trigger_utils.AddRepoEventArgs(flag_config)
def ParseTriggerFromFlags(self, args):
"""Parses command line arguments into a build trigger.
Args:
args: An argparse arguments object.
Returns:
A build trigger object.
Raises:
RequiredArgumentException: If comment_control is defined but
pull_request_pattern isn't.
"""
messages = cloudbuild_util.GetMessagesModule()
trigger, done = trigger_utils.ParseTriggerArgs(args, messages)
if done:
return trigger
trigger.repositoryEventConfig = messages.RepositoryEventConfig(
repository=args.repository
)
cfg = trigger.repositoryEventConfig
if args.pull_request_pattern:
cfg.pullRequest = messages.PullRequestFilter(
branch=args.pull_request_pattern
)
if args.comment_control:
cfg.pullRequest.commentControl = (
messages.PullRequestFilter.CommentControlValueValuesEnum(
args.comment_control
)
)
else:
# Push event
cfg.push = messages.PushFilter(
branch=args.branch_pattern, tag=args.tag_pattern
)
trigger_utils.ParseBuildConfigArgs(trigger, args, messages, '')
trigger_utils.ParseRepoEventArgs(trigger, args)
return trigger
def Run(self, args):
"""This is what gets called when the user runs this command.
Args:
args: An argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
Some values that we want to print later.
"""
client = cloudbuild_util.GetClientInstance()
messages = cloudbuild_util.GetMessagesModule()
trigger = self.ParseTriggerFromFlags(args)
# Send the Create request
project = properties.VALUES.core.project.Get(required=True)
regionprop = properties.VALUES.builds.region.Get()
location = args.region or regionprop or cloudbuild_util.DEFAULT_REGION
parent = resources.REGISTRY.Create(
collection='cloudbuild.projects.locations',
projectsId=project,
locationsId=location).RelativeName()
created_trigger = client.projects_locations_triggers.Create(
messages.CloudbuildProjectsLocationsTriggersCreateRequest(
parent=parent, buildTrigger=trigger))
trigger_resource = resources.REGISTRY.Parse(
None,
collection='cloudbuild.projects.locations.triggers',
api_version='v1',
params={
'projectsId': project,
'locationsId': location,
'triggersId': created_trigger.id,
})
log.CreatedResource(trigger_resource)
return created_trigger

View File

@@ -0,0 +1,131 @@
# -*- 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.
"""Create manual trigger command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.cloudbuild import cloudbuild_util
from googlecloudsdk.api_lib.cloudbuild import trigger_config as trigger_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
class CreateManual(base.CreateCommand):
"""Create a build trigger with a manual trigger event."""
detailed_help = {
'EXAMPLES':
"""\
To create a manual trigger that builds off branch `my-branch` in a GitHub repository named `my-repo`:
$ {command} --name=my-manual-trigger --build-config=cloudbuild.yaml --repo=https://www.github.com/owner/repo --repo-type=GITHUB --branch=my-branch
To create a manual trigger that builds off branch `my-branch` in a 2nd-gen GitHub repository resource:
$ {command} --name=my-manual-trigger --build-config=cloudbuild.yaml --repository=projects/my-proj/locations/us-west1/connections/my-conn/repositories/my-repo --branch=my-branch
""",
}
@staticmethod
def Args(parser):
"""Register flags for this command.
Args:
parser: An argparse.ArgumentParser-like object.
"""
flag_config = trigger_utils.AddTriggerArgs(parser)
trigger_utils.AddBuildConfigArgs(flag_config)
trigger_utils.AddGitRepoSource(flag_config)
def Run(self, args):
"""This is what gets called when the user runs this command.
Args:
args: An argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
The newly created trigger.
"""
client = cloudbuild_util.GetClientInstance()
messages = cloudbuild_util.GetMessagesModule()
trigger = messages.BuildTrigger()
if args.trigger_config:
trigger = cloudbuild_util.LoadMessageFromPath(
path=args.trigger_config,
msg_type=messages.BuildTrigger,
msg_friendly_name='build trigger config',
skip_camel_case=['substitutions'])
else:
trigger = ParseTriggerFromFlags(args)
# Send the Create request
project = properties.VALUES.core.project.Get(required=True)
regionprop = properties.VALUES.builds.region.Get()
location = args.region or regionprop or cloudbuild_util.DEFAULT_REGION
parent = resources.REGISTRY.Create(
collection='cloudbuild.projects.locations',
projectsId=project,
locationsId=location).RelativeName()
created_trigger = client.projects_locations_triggers.Create(
messages.CloudbuildProjectsLocationsTriggersCreateRequest(
parent=parent, buildTrigger=trigger))
trigger_resource = resources.REGISTRY.Parse(
None,
collection='cloudbuild.projects.locations.triggers',
api_version='v1',
params={
'projectsId': project,
'locationsId': location,
'triggersId': created_trigger.id,
})
log.CreatedResource(trigger_resource)
return created_trigger
def ParseTriggerFromFlags(args):
"""Parse arguments into a BuildTrigger proto.
Args:
args: An argparse.Namespace. All the arguments that were provided to this
command invocation.
Returns:
A BuildTrigger proto object.
"""
messages = cloudbuild_util.GetMessagesModule()
trigger, done = trigger_utils.ParseTriggerArgs(args, messages)
if done:
return trigger
trigger.name = args.name
# Build Config
project = properties.VALUES.core.project.Get(required=True)
default_image = 'gcr.io/%s/gcb-%s:$COMMIT_SHA' % (project, args.name)
trigger_utils.ParseBuildConfigArgs(
trigger, args, messages, default_image, need_repo=True)
return trigger

View File

@@ -0,0 +1,139 @@
# -*- 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.
"""Create Pub/Sub trigger command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.cloudbuild import cloudbuild_util
from googlecloudsdk.api_lib.cloudbuild import trigger_config as trigger_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
class CreatePubSub(base.CreateCommand):
"""Create a build trigger with a Pub/Sub trigger event."""
detailed_help = {
'EXAMPLES':
"""\
To create a Pub/Sub trigger that listens to topic `my-topic` and builds off branch `my-branch` in a GitHub repository named `my-repo`:
$ {command} --name=my-pubsub-trigger --service-account="projects/my-project/serviceAccounts/my-byosa@my-project.iam.gserviceaccount.com" --topic=projects/my-project/topics/my-topic --repo=https://www.github.com/owner/repo --repo-type=GITHUB --branch=my-branch
To create a Pub/Sub trigger that listens to topic `my-topic` and builds off branch `my-branch` in a 2nd-gen GitHub repository resource:
$ {command} --name=my-pubsub-trigger --service-account="projects/my-project/serviceAccounts/my-byosa@my-project.iam.gserviceaccount.com" --repository=projects/my-proj/locations/us-west1/connections/my-conn/repositories/my-repo --branch=my-branch
""",
}
@staticmethod
def Args(parser):
"""Register flags for this command.
Args:
parser: An argparse.ArgumentParser-like object.
"""
flag_config = trigger_utils.AddTriggerArgs(parser)
flag_config.add_argument(
'--topic',
help='The topic to which this trigger should subscribe.',
required=True)
trigger_utils.AddBuildConfigArgs(flag_config)
trigger_utils.AddGitRepoSource(flag_config)
trigger_utils.AddFilterArg(flag_config)
def Run(self, args):
"""This is what gets called when the user runs this command.
Args:
args: An argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
The newly created trigger.
"""
client = cloudbuild_util.GetClientInstance()
messages = cloudbuild_util.GetMessagesModule()
trigger = messages.BuildTrigger()
if args.trigger_config:
trigger = cloudbuild_util.LoadMessageFromPath(
path=args.trigger_config,
msg_type=messages.BuildTrigger,
msg_friendly_name='build trigger config',
skip_camel_case=['substitutions'])
else:
trigger = ParseTriggerFromFlags(args)
# Send the Create request
project = properties.VALUES.core.project.Get(required=True)
regionprop = properties.VALUES.builds.region.Get()
location = args.region or regionprop or cloudbuild_util.DEFAULT_REGION
parent = resources.REGISTRY.Create(
collection='cloudbuild.projects.locations',
projectsId=project,
locationsId=location).RelativeName()
created_trigger = client.projects_locations_triggers.Create(
messages.CloudbuildProjectsLocationsTriggersCreateRequest(
parent=parent, buildTrigger=trigger))
trigger_resource = resources.REGISTRY.Parse(
None,
collection='cloudbuild.projects.locations.triggers',
api_version='v1',
params={
'projectsId': project,
'locationsId': location,
'triggersId': created_trigger.id,
})
log.CreatedResource(trigger_resource)
return created_trigger
def ParseTriggerFromFlags(args):
"""Parse arguments into a BuildTrigger proto.
Args:
args: An argparse.Namespace. All the arguments that were provided to this
command invocation.
Returns:
A BuildTrigger proto object.
"""
messages = cloudbuild_util.GetMessagesModule()
trigger, done = trigger_utils.ParseTriggerArgs(args, messages)
if done:
return trigger
trigger.name = args.name
trigger.pubsubConfig = messages.PubsubConfig(topic=args.topic)
# Build Config
project = properties.VALUES.core.project.Get(required=True)
default_image = 'gcr.io/%s/gcb-%s:$COMMIT_SHA' % (project, args.name)
trigger_utils.ParseBuildConfigArgs(
trigger, args, messages, default_image, need_repo=True)
trigger.filter = args.subscription_filter
return trigger

View File

@@ -0,0 +1,186 @@
# -*- 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.
"""Create GCB v2 repo trigger command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.cloudbuild import cloudbuild_util
from googlecloudsdk.api_lib.cloudbuild import trigger_config as trigger_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.calliope.concepts import concepts
from googlecloudsdk.command_lib.cloudbuild import resource_args
from googlecloudsdk.command_lib.util.concepts import concept_parsers
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
# TODO(b/224569250): Remove hidden label once GCB repo trigger is released.
@base.Hidden
class CreateRepository(base.CreateCommand):
"""Create a build trigger for a GCB v2 repository."""
detailed_help = {
'EXAMPLES':
"""\
To create a push trigger for all branches:
$ {command} --name="my-trigger" --service-account="projects/my-project/serviceAccounts/my-byosa@my-project.iam.gserviceaccount.com" --repository=projects/my-project/locations/my-location/connections/my-connection/repositories/my-repository --branch-pattern=".*" --build-config="cloudbuild.yaml"
To create a pull request trigger for master:
$ {command} --name="my-trigger" --service-account="projects/my-project/serviceAccounts/my-byosa@my-project.iam.gserviceaccount.com" --repository=projects/my-project/locations/my-location/connections/my-connection/repositories/my-repository --pull-request-pattern="^master$" --build-config="cloudbuild.yaml"
""",
}
@staticmethod
def Args(parser):
"""Register flags for this command.
Args:
parser: An argparse.ArgumentParser-like object. It is mocked out in order
to capture some information, but behaves like an ArgumentParser.
"""
region_spec = concepts.ResourceSpec(
'cloudbuild.projects.locations',
resource_name='region',
projectsId=concepts.DEFAULT_PROJECT_ATTRIBUTE_CONFIG,
locationsId=resource_args.RegionAttributeConfig())
concept_parsers.ConceptParser.ForResource(
'--region',
region_spec,
'Cloud region',
required=True).AddToParser(parser)
messages = cloudbuild_util.GetMessagesModule()
flag_config = trigger_utils.AddTriggerArgs(parser, add_region_flag=False)
flag_config.add_argument(
'--repository', help='Resource name of the GCB v2 repository.',
required=True)
ref_config = flag_config.add_mutually_exclusive_group(required=True)
trigger_utils.AddBranchPattern(ref_config)
trigger_utils.AddTagPattern(ref_config)
pr_config = ref_config.add_argument_group(help='Pull Request settings')
pr_config.add_argument(
'--pull-request-pattern',
metavar='REGEX',
required=True,
help="""\
A regular expression specifying which base git branch to match for
pull request events.
This pattern is used as a regex search for the base branch (the branch you are
trying to merge into) for pull request updates.
For example, --pull-request-pattern=foo will match "foo", "foobar", and "barfoo".
The syntax of the regular expressions accepted is the syntax accepted by
RE2 and described at https://github.com/google/re2/wiki/Syntax.
""")
pr_config.add_argument(
'--comment-control',
default=messages.PullRequestFilter.CommentControlValueValuesEnum
.COMMENTS_ENABLED,
help='Require a repository collaborator or owner to comment \'/gcbrun\' on a pull request before running the build.'
)
build_config = (
trigger_utils.AddBuildConfigArgs(flag_config, add_docker_args=False))
trigger_utils.AddBuildDockerArgs(build_config, require_docker_image=True)
trigger_utils.AddRepoEventArgs(flag_config)
def ParseTriggerFromFlags(self, args):
"""Parses command line arguments into a build trigger.
Args:
args: An argparse arguments object.
Returns:
A build trigger object.
Raises:
RequiredArgumentException: If comment_control is defined but
pull_request_pattern isn't.
"""
messages = cloudbuild_util.GetMessagesModule()
trigger, done = trigger_utils.ParseTriggerArgs(args, messages)
if done:
return trigger
# GCB v2 Repo config
repo = messages.RepositoryEventConfig(repository=args.repository)
if args.pull_request_pattern:
repo.pullRequest = messages.PullRequestFilter(
branch=args.pull_request_pattern)
if args.comment_control:
repo.pullRequest.commentControl = messages.PullRequestFilter.CommentControlValueValuesEnum(
args.comment_control)
else:
# Push event
repo.push = messages.PushFilter(
branch=args.branch_pattern, tag=args.tag_pattern)
trigger.repositoryEventConfig = repo
trigger_utils.ParseBuildConfigArgs(
trigger, args, messages, default_image=None)
trigger_utils.ParseRepoEventArgs(trigger, args)
return trigger
def Run(self, args):
"""This is what gets called when the user runs this command.
Args:
args: an argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
Some value that we want to have printed later.
"""
client = cloudbuild_util.GetClientInstance()
messages = cloudbuild_util.GetMessagesModule()
trigger = self.ParseTriggerFromFlags(args)
# Send the Create request
project = properties.VALUES.core.project.Get(required=True)
location = args.region
if location is None:
location = properties.VALUES.builds.region.Get(required=True)
location = location.split('/')[-1]
parent = resources.REGISTRY.Create(
collection='cloudbuild.projects.locations',
projectsId=project,
locationsId=location).RelativeName()
created_trigger = client.projects_locations_triggers.Create(
messages.CloudbuildProjectsLocationsTriggersCreateRequest(
parent=parent, buildTrigger=trigger))
trigger_resource = resources.REGISTRY.Parse(
None,
collection='cloudbuild.projects.locations.triggers',
api_version='v1',
params={
'projectsId': project,
'locationsId': location,
'triggersId': created_trigger.id,
})
log.CreatedResource(trigger_resource)
return created_trigger

View File

@@ -0,0 +1,145 @@
# -*- 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.
"""Create Webhook trigger command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.cloudbuild import cloudbuild_util
from googlecloudsdk.api_lib.cloudbuild import trigger_config as trigger_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
class CreateWebhook(base.CreateCommand):
"""Create a build trigger with a Webhook trigger event."""
detailed_help = {
'EXAMPLES':
"""\
To create a Webhook trigger that requires secret `projects/my-project/secrets/my-secret/versions/2` and builds off branch `my-branch` in a GitHub repository named `my-repo`:
$ {command} --name=my-webhook-trigger --service-account="projects/my-project/serviceAccounts/my-byosa@my-project.iam.gserviceaccount.com" --secret=projects/my-project/secrets/my-secret/versions/2 --repo=https://www.github.com/owner/repo --repo-type=GITHUB --branch=my-branch
To create a Webhook trigger that requires secret `projects/my-project/secrets/my-secret/versions/2` and builds off branch `my-branch` in a 2nd-gen GitHub repository:
$ {command} --name=my-webhook-trigger --service-account="projects/my-project/serviceAccounts/my-byosa@my-project.iam.gserviceaccount.com" --secret=projects/my-project/secrets/my-secret/versions/2 --branch=my-branch --repository=projects/my-proj/locations/us-west1/connections/my-conn/repositories/my-repo
""",
}
@staticmethod
def Args(parser):
"""Register flags for this command.
Args:
parser: An argparse.ArgumentParser-like object.
"""
flag_config = trigger_utils.AddTriggerArgs(parser)
flag_config.add_argument(
'--secret',
help=("""\
The full path of the secret version required to validate webhook requests
against this trigger.
For example, projects/my-project/secrets/my-secret/versions/1.
"""),
required=True,
)
trigger_utils.AddBuildConfigArgs(flag_config)
trigger_utils.AddGitRepoSource(flag_config)
trigger_utils.AddFilterArg(flag_config)
def Run(self, args):
"""This is what gets called when the user runs this command.
Args:
args: An argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
The newly created trigger.
"""
client = cloudbuild_util.GetClientInstance()
messages = cloudbuild_util.GetMessagesModule()
trigger = messages.BuildTrigger()
if args.trigger_config:
trigger = cloudbuild_util.LoadMessageFromPath(
path=args.trigger_config,
msg_type=messages.BuildTrigger,
msg_friendly_name='build trigger config',
skip_camel_case=['substitutions'])
else:
trigger = ParseTriggerFromFlags(args)
# Send the Create request
project = properties.VALUES.core.project.Get(required=True)
regionprop = properties.VALUES.builds.region.Get()
location = args.region or regionprop or cloudbuild_util.DEFAULT_REGION
parent = resources.REGISTRY.Create(
collection='cloudbuild.projects.locations',
projectsId=project,
locationsId=location).RelativeName()
created_trigger = client.projects_locations_triggers.Create(
messages.CloudbuildProjectsLocationsTriggersCreateRequest(
parent=parent, buildTrigger=trigger))
trigger_resource = resources.REGISTRY.Parse(
None,
collection='cloudbuild.projects.locations.triggers',
api_version='v1',
params={
'projectsId': project,
'locationsId': location,
'triggersId': created_trigger.id,
})
log.CreatedResource(trigger_resource)
return created_trigger
def ParseTriggerFromFlags(args):
"""Parse arguments into a BuildTrigger proto.
Args:
args: An argparse.Namespace. All the arguments that were provided to this
command invocation.
Returns:
A BuildTrigger proto object.
"""
messages = cloudbuild_util.GetMessagesModule()
trigger, done = trigger_utils.ParseTriggerArgs(args, messages)
if done:
return trigger
trigger.name = args.name
trigger.webhookConfig = messages.WebhookConfig(secret=args.secret)
# Build Config
project = properties.VALUES.core.project.Get(required=True)
default_image = 'gcr.io/%s/gcb-%s:$COMMIT_SHA' % (project, args.name)
trigger_utils.ParseBuildConfigArgs(
trigger, args, messages, default_image, need_repo=True)
trigger.filter = args.subscription_filter
return trigger