Skip to content

CloudBatchSubmitJobOperator runnable.container.commands does not interpret jinja templates #37217

Closed

Description

@ya7010

Description

CloudBatchSubmitJobOperator's runnable.container.commands is not expanded when the jinja template is used as a command argument.

Use case/motivation

I would like to pass logical_date to a script args to run in CloudBatch.

Related issues

No response

Are you willing to submit a PR?

  • Yes I am willing to submit a PR!

Code of Conduct

Activity

  1. added
    kind:feature
    needs-triage
    on Feb 7, 2024
  2. boring-cyborg commented on Feb 7, 2024

    @boring-cyborg

    Thanks for opening your first issue here! Be sure to follow the issue template! If you are willing to raise PR to address this issue please do so, no need to wait for approval.

  3. jscheffl commented on Feb 7, 2024

    @jscheffl
    Contributor

    Reason for not templating is probably that the Google Operator in https://github.com/apache/airflow/blob/main/airflow/providers/google/cloud/operators/cloud_batch.py#L60 does not describe the "command" field as template field (see https://airflow.apache.org/docs/apache-airflow/stable/howto/custom-operator.html#templating)

    From the descriptio of this field it would make sense to have this template-able. If you have a strong demand, please contribute a PR to the respective code section, else maybe you need to wait that somebody picks this up.

  4. added
    provider:google
    and removed
    needs-triage
    on Feb 7, 2024
  5. ya7010 commented on Feb 8, 2024

    @ya7010
    Author

    I am looking at this PR.

    I had added job to template_fields but it did not work.

    Cloud Batch job is a deep configuration class and I need to template the contents of self.job.task_groups[0].task_spec.runnables[0].container.commands.

    I have assigned execution arguments to self.commands and passed them to the self.job creation process (hoping they would be shared as a list), but this method is not working either.

    Is there anything else I can try?

  6. jscheffl commented on Feb 10, 2024

    @jscheffl
    Contributor

    Yes, (I am not an expert in this operator but...) if you take look to the docs, the Operator accepts either a dict or a class as Job definition. If you pass a dict then I assume the dict will implicitly be parsed to the object structure describing the workload/Job.
    Means in the instance of the operator change the template_fields variable and add the job field, pass the needed dict as string with the template fields. The template engine will parse the dict-string as template, replace the field. You need to define render_template_as_native_obj=True in the DAG as described in https://airflow.apache.org/docs/apache-airflow/stable/core-concepts/params.html#referencing-params-in-a-task

  7. ya7010 commented on Feb 11, 2024

    @ya7010
    Author

    Thanks for letting me know!

    Next week I will try to work on it.

  8. romsharon98 commented on Apr 17, 2024

    @romsharon98
    Contributor

    Thanks for letting me know!

    Next week I will try to work on it.

    Can we close this issue? @yassun7010

  9. ya7010 commented on Apr 17, 2024

    @ya7010
    Author

    @romsharon98

    Please close, Thank you!

    After some trial and error, we have switched to an implementation using task flow.

  10. raph-p commented on Dec 4, 2024

    @raph-p

    Hi team,

    Sorry to reopen this issue. We actually encountered the exact same issue and after an afternoon digging the operator code, we came across this issue.

    We have the same setup, where we want to pass a jinja template to the CloudBatchSubmitJobOperator (to pass the current date). At first we tried passing a job object as mentioned in the airflow/google provider docs, and then we tested passing the job as a dict as suggested by @jscheffl

    Passing the job as a dict produces the same result then when passed as Job object, ie. the template is not expanded/substituted at runtime.

  11. jscheffl commented on Dec 4, 2024

    @jscheffl
    Contributor

    @yassun7010 can you share details helping @raph-p to resolve the problem as well? Is there a clarification in documentation missing? Then we would be happy to receive a documentation contribution, e.g. via https://github.com/apache/airflow/edit/main/docs/apache-airflow/core-concepts/params.rst

  12. ya7010 commented on Dec 5, 2024

    @ya7010
    Author

    My solution is as follows:

    common code

    from typing import TYPE_CHECKING, cast
    from airflow.decorators import task
    from airflow import XComArg
    
    if TYPE_CHECKING:
        #  Tricks to reduce DAG analysis time.
        import google.cloud.batch_v1 as batch_v1
    
    
    @task
    def submit_cloud_batch_job(
        job_id: str,
        commands: list[str] | XComArg,
        /,
        *,
        envs: dict[str, str] | None = None,
    ) -> str:
        import google.cloud.batch_v1 as batch_v1
    
        client = batch_v1.BatchServiceClient()
        create_request = batch_v1.CreateJobRequest()
        runnable = batch_v1.Runnable()
    
        ...
    
        runnable.container.commands = cast(list[str], commands)
        
        ...
    
        client.create_job(request=create_request)
    
        return create_request.job_id

    DAG code

    import datetime
    
    from pathlib import Path
    
    from airflow.decorators import dag, task
    from airflow.models import DagRun
    
    from common_code import submit_cloud_batch_job
    
    @dag(
        dag_id=Path(__file__).stem,
        schedule_interval="0 0 * * *",
        start_date=datetime.datetime(2021, 1, 1),
    )
    def execute():
        @task()
        def make_commands(dag_run: DagRun | None = None):
            conf = dag_run.conf if dag_run else {}
    
            commands = [
                "python",
                "-m",
                "my-task",
            ]
    
            # You can pass any command argument you like from conf or Python code to Cloud Batch.
            if value := conf.get("my-option"):
                commands.extend(["--my-option", str(value)])
    
            return commands
    
        submit_cloud_batch_job(
            Path(__file__).stem,
            make_commands(),
        )
    
    
    execute()
  13. raph-p commented on Dec 5, 2024

    @raph-p

    Thank you so much @yassun7010

  14. raph-p commented on Sep 8, 2025

    @raph-p

    In case somebody encounters this issue, a quick & dirty hack is to extend the CloudBatchSubmitJobOperator class by creating a custom class that inherits from it. It adds the whole job field as template, allowing to pass the command (or env vars, or even more) as jinja template.
    We also decided to add the job_nameas well as the job_name, in case some would pass a dynamic name (i.e. including the execution date for example), as the name of a Batch Job must be unique.

    I'm not sure I'll have the time to do a fix in the airflow.provider myself, as I've never contributed to an open-source project and I'm not sure where to start.

    class CustomCloudBatchSubmitJobOperator(CloudBatchSubmitJobOperator):
        """
        Extends CloudBatchSubmitJobOperator by allowing jinja substitution of the  "job_name" and "job" fields
        """
        template_fields = ("project_id", "region", "gcp_conn_id", "impersonation_chain", "job_name", "job").  # this is the important line
        def __init__(
            self,
            project_id: str,
            region: str,
            job_name: str,
            job: dict | Job,
            polling_period_seconds: float = 10,
            timeout_seconds: float | None = None,
            gcp_conn_id: str = "google_cloud_default",
            impersonation_chain: str | Sequence[str] | None = None,
            deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
            **kwargs,
        ) -> None:
            super().__init__(
                project_id=project_id,
                region=region,
                job_name=job_name,
                job=job,
                polling_period_seconds=polling_period_seconds,
                timeout_seconds=timeout_seconds,
                gcp_conn_id=gcp_conn_id,
                impersonation_chain=impersonation_chain,
                deferrable=deferrable,
                **kwargs,
            )

    Regards

  15. jscheffl commented on Sep 8, 2025

    @jscheffl
    Contributor

    In case somebody encounters this issue, a quick & dirty hack is to extend the CloudBatchSubmitJobOperator class by creating a custom class that inherits from it.

    @raph-p it is not hard to open a PR, if it is a single line to change you can even make this via Github UI. Also my OSS Contribution started like this :-D

    You can make it also as describe above with a single line of code. From the instantiated operator in your Dag you can also directly adjust the template_fields attribute and extend the filed in one line of code in Dag code, no need to inherit a custom class from the original one.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:providersgood first issuekind:featureprovider:google

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions