youming1970 commented on PR #55323:
URL: https://github.com/apache/airflow/pull/55323#issuecomment-3264016881
Hey @potiuk,
thanks for the quick feedback! 🙏
Totally agree that the hand-rolled escaping I pushed is over-engineered for
an example DAG.
Using Python's std-lib `shlex.quote()` keeps the snippet short, readable and
100% safe from command-injection.
I'll push a new revision that:
1. moves the user input into Python first (no direct Jinja expansion),
2. quotes it with `shlex.quote()`, and
3. passes the already-quoted string to the BashOperator.
That removes the need for custom Jinja filters or complicated comments.
**Draft of the change**
```diff
@@
-from airflow.operators.bash import BashOperator
+import shlex
+from airflow.operators.bash import BashOperator
@@
-# (previous example had direct {{ dag_run.conf.get("message") }} usage)
-target_task = BashOperator(
- task_id="print_the_message",
- bash_command='echo "{{ dag_run.conf.get("message") }}"',
- dag=dag,
-)
+def prepare_message(**context):
+ """
+ Pull `message` from dag_run.conf and shell-quote it so it can be safely
+ embedded in a Bash command. Using the std-lib shlex.quote() protects
+ against command-injection without any custom logic.
+ """
+ raw_msg = context["dag_run"].conf.get("message", "")
+ return shlex.quote(str(raw_msg))
+
+prepare_msg = PythonOperator(
+ task_id="prepare_message",
+ python_callable=prepare_message,
+)
+
+target_task = BashOperator(
+ task_id="print_the_message",
+ bash_command="echo {{ ti.xcom_pull(task_ids='prepare_message') }}",
+)
+
+prepare_msg >> target_task
```
**Benefits**
• No manual escaping logic in Jinja.
• Example stays concise while demonstrating a best-practice pattern (move
input to Python ➜ validate/quote ➜ hand to Bash).
• Backward compatibility: nothing changes for end-users triggering the DAG;
they still supply `{"message": "hello"}`.
Let me know if this direction looks good—if so I'll commit the refactor and
update the PR description accordingly. 👍
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]