<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ender Frias on Medium]]></title>
        <description><![CDATA[Stories by Ender Frias on Medium]]></description>
        <link>https://medium.com/@enderfrias?source=rss-df539548492a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*O9GQPkCyR8I371tKDg8Dlw.jpeg</url>
            <title>Stories by Ender Frias on Medium</title>
            <link>https://medium.com/@enderfrias?source=rss-df539548492a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 10:13:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@enderfrias/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Airflow: How to deploy DAG and plugin changes without downtimes.]]></title>
            <link>https://enderfrias.medium.com/airflow-how-to-deploy-dag-and-plugin-changes-without-downtimes-5dd6239c4b14?source=rss-df539548492a------2</link>
            <guid isPermaLink="false">https://medium.com/p/5dd6239c4b14</guid>
            <category><![CDATA[continuous-delivery]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[airflow]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[Ender Frias]]></dc:creator>
            <pubDate>Mon, 21 Sep 2020 11:37:11 GMT</pubDate>
            <atom:updated>2021-01-27T16:24:55.363Z</atom:updated>
            <content:encoded><![CDATA[<p>I am writing this little guide with the hope of making life easier to any of my fellow Data Engineers.</p><p>Please have in mind that English is not my first language and that this is the very first time I dare to write anything like this in any blog.</p><h3>What is this guide good for?</h3><p>With this DAG you’ll be able to keep your dags and plugins directories up to date automatically, avoiding having to deploy a complete instance of Airflow for little to big DAG / plugin changes.</p><p>I have been using this approach in <em>staging</em> and in the <em>productive</em> environments without problems for these use cases:</p><p><em>DAGS</em>:</p><ul><li>New Dags</li><li>Changes in existing DAGS</li><li>New Directories ( dag_bags )</li></ul><p><em>CUSTOM PLUGINS</em>:</p><ul><li>New custom plugins</li><li>Changes in custom plugins</li></ul><h3>Workflow</h3><p>The complete workflow is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jW5byZRyJF82GKi1tEbfkQ.png" /><figcaption>01_dag_git_sync</figcaption></figure><p>1- A bash sensor is checking the <em>master</em> or <em>staging </em>branch for changes.</p><p>2- After a change is detected, a branch python operator will validate if the DAG is running for the first time or not and will either:</p><ul><li>git clone the whole repo to a temporary directory (If the process is running for the first time)</li><li>git pull changes if the repo has been previously cloned into said temporary directory</li></ul><p>3- A dummy operator just letting us know that the previous step finished.</p><p>4- Two bash tasks will run in parallel and willsync the DAGS and plugins directories with the latest changes</p><p>5- A bash operator will get the most recent <em>git hash </em>and will save it into an <em>XCOM. </em>(This will help us to keep a change log and get to a working git branch hash if necessary).</p><p>6- A python operator will save the latest hash into an Airflow Variable, this for easier and faster access to the currently running git branch hash</p><h3>Requirements:</h3><p><em>This guide assumes you already have Airflow installed and running.</em></p><p><strong>1- Airflow Variables</strong></p><p>Create or import these 3 Airflow variables:</p><pre>{<br>    &quot;current_branch_hash&quot;: &quot;&quot;,<br>    &quot;git_branch&quot;: &quot;master&quot;,<br>    &quot;git_repo&quot;: &quot;git@github.your_repo.git&quot;<br>}</pre><ul><li>current_branch_hash will work only as quick reference to know what version of your master or staging branches you are running.</li><li>git_branch will specify which branch should Airflow be in sync with, I have either <em>master</em> or <em>staging </em>in this variable.</li><li>git_repo the SSH git repo address as in:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*HJ8rsRKT1o-k4OH9dk7REg.png" /></figure><p><strong>2- Git Access:</strong></p><p>This approach connects to my GIT repo through an SSH Key, so make sure your airflow’s instance has an ssh key in:</p><pre>~/.ssh/key_with_access_to_git<br>~/.ssh/key_with_access_to_git.pub</pre><p>Make sure both keys have the right permissions:</p><pre>chmod 400 ~/.ssh/key_with_access_to_git<br>chmod 400 ~/.ssh/key_with_access_to_git.pub</pre><p>Also, you’ll need to to add the github host to your ~/.ssh/config file:</p><pre>Host github.com<br>        IdentityFile ~/.ssh/key_with_access_to_git<br>        IdentitiesOnly yes<br>        StrictHostKeyChecking no</pre><p>Next, Add the SSH key registered into your <a href="https://github.com/settings/ssh/new">GIT Repo</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uQg6PI_0aL6RnM79hW05Bg.png" /></figure><p>If you are stuck in this part, Follow <a href="https://docs.github.com/en/github/authenticating-to-github/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent">this guide</a> to create SSH Keys and link them to Github <strong>(just remember to generate the key without passphrase)</strong>.</p><p><a href="https://stackoverflow.com/questions/4565700/how-to-specify-the-private-ssh-key-to-use-when-executing-shell-command-on-git">This stack overflow question </a>helped me a lot too.</p><h3>DAG CODE</h3><p><em>Copy and paste</em> the following code in your dags directory with the filename: SYNC_FILE-DONT_DELETE.py</p><p><em>DO NOT RENAME, THIS FILENAME IS USED IN THE LINE 99 OF THE CODE,</em></p><pre>import logging, os<br>from datetime import datetime, timedelta</pre><pre>from airflow import DAG<br>from airflow.models import Variable<br>from airflow.operators.bash_operator import BashOperator<br>from airflow.operators.python_operator import PythonOperator, BranchPythonOperator<br>from airflow.operators.dummy_operator import DummyOperator<br>from airflow.contrib.sensors.bash_sensor import BashSensor</pre><pre>default_args = {<br>  &#39;owner&#39;: &#39;airflow&#39;,<br>  &#39;start_date&#39;: datetime(2019, 10, 16, 00, 00, 00),<br>  &#39;depend_on_past&#39;: False,<br>  &#39;catchup&#39;: False,<br>  &#39;retries&#39;: 5,<br>  &#39;retry_delay&#39;: timedelta(seconds=60),<br>  &#39;email&#39;: [&#39;<a href="/service/mailto:your@email.com">your@email.com</a>&#39;],<br>  &#39;email_on_failure&#39;: True,<br>  &#39;email_on_retry&#39;: True,<br>  &#39;provide_context&#39;: True<br>   }</pre><pre>home_directory = os.environ[&#39;AIRFLOW_HOME&#39;]<br>dags_directory = os.environ[&#39;AIRFLOW_HOME&#39;]+&quot;/dags/&quot;<br>plugins_directory = os.environ[&#39;AIRFLOW_HOME&#39;]+&quot;/plugins/&quot;</pre><pre>git_main_dags_directory = home_directory+&quot;/git_dags&quot;<br>git_dags_directory = git_main_dags_directory+&quot;/src/dags/&quot;<br>git_plugins_directory = git_main_dags_directory+&quot;/src/plugins/&quot;</pre><pre>git_branch = Variable.get(&quot;git_branch&quot;, default_var=&#39;staging&#39;)<br>git_repo = Variable.get(&quot;git_repo&quot;)<br>logging.info(git_repo)</pre><pre>def validate_git_dags_folder(**kwargs):<br> logging.info(&quot;validate_git_dags_folder STARTED&quot;)<br> if not os.path.exists(git_main_dags_directory):<br>  os.makedirs(git_main_dags_directory)</pre><pre>if len(os.listdir(git_main_dags_directory)) == 0:<br>  return &#39;git_clone&#39;</pre><pre>return &#39;git_pull&#39;</pre><pre>def save_branch_hash(**context):<br> return Variable.set(&#39;current_branch_hash&#39;, context[&#39;task_instance&#39;].xcom_pull(task_ids=&#39;get_last_branch_version&#39;))</pre><pre>with DAG(&#39;01_dag_git_sync&#39;,<br> default_args=default_args,<br> schedule_interval=&#39;* * * * *&#39;,<br> catchup=False) as dag:</pre><pre>sensor_dir_exists_cmd = &quot;&quot;&quot;<br>  # Check if the folder exists<br>  if [ ! -d {git_dags_directory} ]; then<br>   echo &quot;{git_dags_directory} does not exist. Will create it and git clone repo&quot;<br>   exit 0<br>  fi</pre><pre># check if there are changes in branch<br>  cd {git_dags_directory}<br>  git fetch<br>  local_hash=`git rev-parse {branch}`<br>  remote_hash=`git rev-parse origin/{branch}`</pre><pre># if [ $status -eq 0 ]<br>  if [ $local_hash != $remote_hash ]<br>   then<br>    echo &quot;{branch} is not updated... will pull recent changes&quot;<br>    exit 0<br>   else<br>    echo &quot;Everything is updated with branch {branch}&quot;<br>    exit 1<br>  fi<br>  &quot;&quot;&quot;.format(branch = git_branch, git_dags_directory = git_main_dags_directory)</pre><pre>sensor_dir_exists = BashSensor(task_id=&#39;git_changes_sensor&#39;, bash_command=sensor_dir_exists_cmd, poke_interval= 60,)</pre><pre>&quot;&quot;&quot; Validates if the git folder is empty or not &quot;&quot;&quot;<br>  validate_git_folder = BranchPythonOperator(task_id=&#39;validate_git_folder&#39;, python_callable=validate_git_dags_folder)</pre><pre>&quot;&quot;&quot; If the git folder is empty, clone the repo &quot;&quot;&quot;<br>  bash_command_clone = &quot;git clone --single-branch --branch {} {} {}&quot;.format(git_branch, git_repo, git_main_dags_directory)<br>  logging.info(&quot;bash command sent to server: {}&quot;.format(bash_command_clone))<br>  git_clone = BashOperator(task_id=&#39;git_clone&#39;, bash_command=bash_command_clone)</pre><pre>&quot;&quot;&quot; If the git folder is not empty, pull the latest changes &quot;&quot;&quot;<br>  bash_command_pull = &quot;git -C {} pull origin {}&quot;.format(git_main_dags_directory, git_branch)<br>  git_pull = BashOperator(task_id=&#39;git_pull&#39;, bash_command=bash_command_pull)</pre><pre>&quot;&quot;&quot; Dummy operator (DO NOT DELETE, IT WOULD BREAK THE FLOW) &quot;&quot;&quot;<br>  finished_pulling = DummyOperator(task_id=&#39;finished_pulling&#39;, dag=dag, trigger_rule=&#39;none_failed&#39;)</pre><pre>&quot;&quot;&quot; Sync Dags Directory &quot;&quot;&quot;<br>  bash_command_sync_dags = &quot;rsync -rv --delete --exclude &#39;*.pyc&#39; --exclude &#39;SYNC_FILE-DONT_DELETE.py&#39; {} {} &quot;.format(git_dags_directory, dags_directory)<br>  git_sync_dags = BashOperator(task_id=&#39;git_sync_dags&#39;, bash_command=bash_command_sync_dags)</pre><pre>&quot;&quot;&quot; Sync Plugin Directory &quot;&quot;&quot;<br>  bash_command_sync_plugins = &quot;rsync -rv --delete --exclude &#39;*.pyc&#39; {} {} &quot;.format(git_plugins_directory, plugins_directory)<br>  git_sync_plugins = BashOperator(task_id=&#39;git_sync_plugins&#39;, bash_command=bash_command_sync_plugins)</pre><pre>&quot;&quot;&quot; Get branch last hash and save it into an XCOM&quot;&quot;&quot;<br>  bash_command_get_branch_hash = &#39;git -C {} rev-parse {}&#39;.format(git_main_dags_directory, git_branch)<br>  get_branch_hash = BashOperator(task_id=&#39;get_last_branch_version&#39;, bash_command=bash_command_get_branch_hash, xcom_push=True)</pre><pre>&quot;&quot;&quot; Save HASH version into Airflow Variable&quot;&quot;&quot;<br>  save_branch_hash = PythonOperator(task_id=&#39;save_last_branch_version&#39;, python_callable=save_branch_hash, provide_context=True)</pre><pre>&quot;&quot;&quot; DAG Flow &quot;&quot;&quot;<br>  sensor_dir_exists &gt;&gt; validate_git_folder &gt;&gt; [git_clone, git_pull] &gt;&gt; finished_pulling &gt;&gt; [ git_sync_dags, git_sync_plugins ] &gt;&gt; get_branch_hash &gt;&gt; save_branch_hashChange Paths:</pre><p>If you don’t have an AIRFLOW_HOME environment variable, change the code in lines 24, 25, 26 to match your airflow home directory.</p><p>In the same lines, make sure the paths for the dags and plugins directories are correct:</p><pre>home_directory = os.environ[&#39;AIRFLOW_HOME&#39;]<br>dags_directory = os.environ[&#39;AIRFLOW_HOME&#39;]+&quot;/dags/&quot;<br>plugins_directory = os.environ[&#39;AIRFLOW_HOME&#39;]+&quot;/plugins/&quot;</pre><h3>Testing it</h3><p>After deploying your DAG, it should automatically trigger the first time and clone the repo.</p><p>Make a simple change in your master or staging branch and push changes to origin.</p><p>The sensor should detect the changes and trigger the whole process again.</p><h4>Get history of git branch hashes</h4><p>In Airflow go to: Admin &gt; XComs and add a filter:</p><p>Task Id = get_last_branch_version</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jcWzrOEfqh5YDjJxIbu76w.png" /></figure><p>This will get you all the branches, this should help you to go back to a working branch if needed.</p><h3>Notes</h3><ul><li>New Dags will take a while to appear in the DAGS list, this depends on the dag_dir_list_interval configuration.</li><li>For some reason, Airflow takes longer to notice changes to plugins, but in my experience they take about 1 or 2 minutes to be refreshed in Airflow.</li><li>This DAG is great for staging and production environments, but it’s a real pain for local changes, so <strong>when working locally, make sure to have this DAG turned off</strong> or else it will be overwriting your local changes every minute.</li><li>The Sensor is checking for new changes every 60 seconds, this can be changed in line 81 poke_interval=60 .</li><li>The Sensor will fail after 7 days of constantly working (I guess it’s an Airlfow task timeout setting) but it will immediately run again sensing for git changes.</li><li>Have in mind that a sensor always running means that 1 task is always running, hence, if your Airflow configuration is set to run 16 tasks simultaneously, you’ll always be using 1 so now you’ll have 15 task slots available.<br>This can be easily fixed changing the dag_concurrency configuration: dag_concurrency = 17</li></ul><p>I hope this guide was clear enough and that it can help more than 1 person.</p><p>Reach me in the comments if you have questions.</p><p>Thanks for reading</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5dd6239c4b14" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>