Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

airflow pass parameter from cli

Is there a way to pass a parameter to:

airflow trigger_dag dag_name {param}

?

I have a script that monitors a directory for files - when a file gets moves into the target directory I want to trigger the dag passing as a parameter the file path.

like image 537
bsd Avatar asked Jun 05 '17 06:06

bsd


People also ask

How do you pass parameters in Airflow?

You can pass parameters from the CLI using --conf '{"key":"value"}' and then use it in the DAG file as "{{ dag_run. conf["key"] }}" in templated field.

How do you trigger Airflow DAG parameters?

Trigger Airflow DAGs on a Schedule To specify the scheduling parameters, you define how many times the DAG will run by placing values in the “schedule_interval” parameter. And, to specify when Airflow should schedule DAG tasks, place the values in the “ start_date” parameter.

What is BashOperator in Airflow?

The Airflow BashOperator does exactly what you are looking for. It is a very simple but powerful operator, allowing you to execute either a bash script, a command or a set of commands from your DAGs.

How do I set an environment variable in Airflow?

As per this answer, the variables should be put in /etc/default/airflow (on Debian/Ubuntu) or /etc/sysconfig/airflow (on Centos/Redhat). Show activity on this post. If you are just running a local instance you should be able to use environment variables like you expect.


2 Answers

you can pass it like this:

airflow trigger_dag --conf {"file_variable": "/path/to/file"} dag_id

Then in your dag, you can access this variable using templating as follows:

{{ dag_run.conf.file_variable }}

If this doesn't work, sharing a simple version of your dag might help in getting better answers.

like image 130
Him Avatar answered Oct 04 '22 14:10

Him


yes you can. Your Dag should have a Dag and a Bask Task like this:

from airflow.operators.bash_operators import BashOperator

args = {'start_date':datetime.now(),
        'owner':'airflow',}
dag = DAG(
      dag_id='param_dag', 
      default_args=args,
      schedule_interval=None)

bash_task=BashOperator(
     task_id="bash_task" 
     bash_command= 'bash ~/path/bashscript.sh {{ dag_run.conf["parameter"] if dag_run else "" }} ', 
    //bashscript your script you want to run and the dag_run.conf will hold the parameter you want to pass
     dag=dag)

Now on your command line just type the command:

 airflow trigger_dag dag_id --conf '{"parameter":"~/path" }'
like image 32
Anmol Karki Avatar answered Oct 04 '22 13:10

Anmol Karki