Skip to content

Commit

Permalink
feat: batch create job with service account (#11909)
Browse files Browse the repository at this point in the history
* feat: batch create job with service account

* fix: correct docstring

* 🦉 Updates from OwlBot post-processor

See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md

---------

Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com>
  • Loading branch information
BigBlackWolf and gcf-owl-bot[bot] authored Jun 27, 2024
1 parent 9a23fe1 commit 8346b62
Show file tree
Hide file tree
Showing 2 changed files with 122 additions and 0 deletions.
96 changes: 96 additions & 0 deletions batch/create/create_with_service_account.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
# Copyright 2024 Google LLC
#
# 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.

# [START batch_create_custom_serive_account]
from google.cloud import batch_v1


def create_with_custom_service_account_job(
project_id: str, region: str, job_name: str, service_account_email: str
) -> batch_v1.Job:
"""
This method shows how to create a sample Batch Job that will run
a simple command on Cloud Compute instances with custom service account.
Args:
project_id: project ID or project number of the Cloud project you want to use.
region: name of the region you want to use to run the job. Regions that are
available for Batch are listed on: https://cloud.google.com/batch/docs/get-started#locations
job_name: the name of the job that will be created.
It needs to be unique for each project and region pair.
service_account_email: custom service account email
Returns:
A job object representing the job created.
"""
client = batch_v1.BatchServiceClient()

# Define what will be done as part of the job.
task = batch_v1.TaskSpec()
runnable = batch_v1.Runnable()
runnable.script = batch_v1.Runnable.Script()
runnable.script.text = "echo Hello world! from task ${BATCH_TASK_INDEX}. This job has a total of ${BATCH_TASK_COUNT} tasks."
task.runnables = [runnable]
task.max_retry_count = 2
task.max_run_duration = "3600s"

# Tasks are grouped inside a job using TaskGroups.
# Currently, it's possible to have only one task group.
group = batch_v1.TaskGroup()
group.task_count = 4
group.task_spec = task

# Policies are used to define on what kind of virtual machines the tasks will run on.
# Read more about local disks here: https://cloud.google.com/compute/docs/disks/persistent-disks
policy = batch_v1.AllocationPolicy.InstancePolicy()
policy.machine_type = "e2-standard-4"
instances = batch_v1.AllocationPolicy.InstancePolicyOrTemplate()
instances.policy = policy
allocation_policy = batch_v1.AllocationPolicy()
allocation_policy.instances = [instances]

# Defines the service account for Batch-created VMs. If omitted, the [default account]
# More details: https://cloud.google.com/compute/docs/access/service-accounts#default_service_account
service_account = batch_v1.ServiceAccount()
service_account.email = service_account_email
allocation_policy.service_account = service_account

job = batch_v1.Job()
job.task_groups = [group]
job.allocation_policy = allocation_policy
job.labels = {"env": "testing", "type": "script"}

create_request = batch_v1.CreateJobRequest()
create_request.job = job
create_request.job_id = job_name
# The job's parent is the region in which the job will run
create_request.parent = f"projects/{project_id}/locations/{region}"

return client.create_job(create_request)


# [END batch_create_custom_serive_account]

if __name__ == "__main__":
import google.auth

PROJECT = google.auth.default()[1]
REGION = "europe-west4"
# Existing service account name within the project specified above.
name = "test-account-name"
service_account_email = f"{name}@{PROJECT}.iam.gserviceaccount.com"
job = create_with_custom_service_account_job(
PROJECT, REGION, "sa-job-batch3", service_account_email
)
print(job)
26 changes: 26 additions & 0 deletions batch/tests/test_basics.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,13 @@

import google.auth
from google.cloud import batch_v1
from google.cloud import resourcemanager_v3
import pytest

from ..create.create_with_container_no_mounting import create_container_job
from ..create.create_with_gpu_no_mounting import create_gpu_job
from ..create.create_with_script_no_mounting import create_script_job
from ..create.create_with_service_account import create_with_custom_service_account_job

from ..delete.delete_job import delete_job
from ..get.get_job import get_job
Expand Down Expand Up @@ -54,6 +56,16 @@ def job_name():
return f"test-job-{uuid.uuid4().hex[:10]}"


@pytest.fixture()
def service_account() -> str:
client = resourcemanager_v3.ProjectsClient()
request = resourcemanager_v3.GetProjectRequest()
request.name = f"projects/{PROJECT}"
project = client.get_project(request)
project_number = project.name.split("/")[-1]
return f"{project_number}[email protected]"


def _test_body(test_job: batch_v1.Job, additional_test: Callable = None, region=REGION):
start_time = time.time()
try:
Expand Down Expand Up @@ -102,6 +114,10 @@ def _check_logs(job, capsys):
assert all("Hello world!" in log_msg for log_msg in output)


def _check_service_account(job: batch_v1.Job, service_account_email: str):
assert job.allocation_policy.service_account.email == service_account_email


@flaky(max_runs=3, min_passes=1)
def test_script_job(job_name, capsys):
job = create_script_job(PROJECT, REGION, job_name)
Expand All @@ -118,3 +134,13 @@ def test_container_job(job_name):
def test_create_gpu_job(job_name):
job = create_gpu_job(PROJECT, REGION, ZONE, job_name)
_test_body(job, additional_test=lambda: _check_tasks)


@flaky(max_runs=3, min_passes=1)
def test_service_account_job(job_name, service_account):
job = create_with_custom_service_account_job(
PROJECT, REGION, job_name, service_account
)
_test_body(
job, additional_test=lambda: _check_service_account(job, service_account)
)

0 comments on commit 8346b62

Please sign in to comment.