<?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 Ammar Chalifah on Medium]]></title>
        <description><![CDATA[Stories by Ammar Chalifah on Medium]]></description>
        <link>https://medium.com/@ammarchalifah?source=rss-ee6b1b0fe714------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*bE0HpXUDPAVl0517yQEIaw.jpeg</url>
            <title>Stories by Ammar Chalifah on Medium</title>
            <link>https://medium.com/@ammarchalifah?source=rss-ee6b1b0fe714------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 04:37:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ammarchalifah/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[Self-Service Analytics with LLM + Tool Calling]]></title>
            <link>https://medium.com/data-science-collective/self-service-analytics-with-llm-tool-calling-dfb99873ae46?source=rss-ee6b1b0fe714------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfb99873ae46</guid>
            <category><![CDATA[dbt]]></category>
            <category><![CDATA[self-service-analytics]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[mcps]]></category>
            <dc:creator><![CDATA[Ammar Chalifah]]></dc:creator>
            <pubDate>Mon, 02 Jun 2025 10:32:39 GMT</pubDate>
            <atom:updated>2025-08-14T15:21:42.531Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mZllDO_pt3ODApdn0SM78g.jpeg" /><figcaption>Random image :D</figcaption></figure><p>I began my career in the data space more or less 3.5 years ago, as a “<em>data scientist</em>” in a mid-sized Indonesian SaaS company. Back then, we’re structured under the business team, and our productivity were eroded by answering ad hoc questions (a lot of them) from the business stakeholders. Most of them were simple questions,<em> like asking for monthly revenue numbers </em>or<em> customer retention metrics</em>, but we were still got frustrated by the volume of such requests.</p><p>At some point, we began to contemplate — is <strong><em>self-service analytics</em></strong> possible? We wanted to direct the business stakeholders to access this “tool” instead of sending us <em>quick questions </em>to get their questions answered. Dashboards, clean data models in BI tools, data discoverability platforms, SQL courses — all those alternatives never really hit the spot.</p><p>People have inertia and people don’t like changes. Expecting them to start speaking in SQL, or accessing BI tools to build some report themselves is unrealistic. They like to ask questions in natural language, and they expect answers in natural language.</p><p>The problem remains unsolved for years, until OpenAI opened the <em>Pandora’s box</em> a few years ago. Natural language conversation with artificial intelligence is now out in the open, and this seems like an<strong> ideal solution candidate for self-service analytics.</strong></p><h3>1. Today’s Data Platform Best Practice — Dbt</h3><p>Today’s data platform has become fairly standardized. Warehouses like Snowflake, Databricks or BigQuery hold the raw and transformed data. Regardless of the compute layer, almost all data platform uses <a href="https://www.getdbt.com/">dbt</a> to manage data modeling. This widespread adoption of dbt across companies is a catalyst of a better data governance &amp; documentation, which is the foundational layer to enable any kind of self service analytics in the downstream.</p><p>dbt handles transformation — writing SQL models that define how raw data is turned into usable tables. More importantly, dbt stores metadata: model descriptions, column-level documentation, relationships, tags, and dependencies. This metadata isn’t just for human readers. It encodes the structure and semantics of the data platform — making it ideal for machine understanding.</p><p>This information is stored by dbt as a JSON <a href="https://docs.getdbt.com/reference/artifacts/manifest-json">manifest</a> file. If we could expose this metadata to an intelligent system that understands language,<strong> it could map questions to models, understand relationships, and even write queries.</strong></p><h3>2. How LLMs + Tool Calling Enable Self-Service</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GwgpOiRyeRVLKzUJRkzU1A.png" /></figure><p>One simple design for self-service analytics involves running an LLM client with a set of tools, and expose this client to some interface: either chat or other text-based interfaces. Behind the scenes, it follows a simple but effective architecture:</p><ul><li>A lightweight backend handles chat messages and forwards user questions to the LLM client (OpenAI, Gemini, etc.).</li><li>Each LLM client is initialized with a system prompt that includes a curated subset of the dbt manifest — cleaned, filtered, and formatted for easy consumption.</li><li>The manifest gives the model visibility into what data exists, what it means, how it’s related, and what tables to use for specific questions.</li></ul><p>But the system does more than generate SQL. It also supports <strong>tool calling</strong> — which lets the LLM trigger specific functions like:</p><ul><li>Listing possible values in a dimension or reference table</li><li>Calling APIs for fresh, dynamic context (e.g. campaign names from a marketing platform)</li><li>Run SQL queries against data warehouse and fetch the output</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MrRbl7qrth84Fi6Kg72y-A.png" /></figure><p>Each time a user asks a question, the model selects the appropriate model(s), writes SQL, calls tools as needed, and returns the result in a readable format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fkQ9Oe2dm3HP6jVZ3IaZwQ.png" /></figure><h3>3. Best Practices for Building LLM-Based Analytics Systems</h3><p>There are a few things that can improve system reliability and reduce costs:</p><h4><strong>3.1. Manifest pruning</strong></h4><p>Two reasons, technical and economical.</p><p><strong><em>Technical reason: </em></strong>each model have a maximum token size for the model’s context, and we don’t want to fill up the context with dbt manifest without extra space left for follow up questions. Aside from context limit, reducing the size of the manifest would help the LLM to focus on information that matters and reduce the risk of hallucination.</p><p><strong><em>Economical reason: </em></strong>common LLM providers charges customers based on token count, both input &amp; output. Reducing the manifest size would significantly reduce the input token, which would help cut costs.</p><p>Pruning could be done on multiple levels:</p><p><strong>a) Metadata pruning:</strong> dbt’s manifest is a large JSON with all the information packed inside: model names, tests, dependencies, SQL queries, and other technical metadata. The simplest pruning method is cutting off the information that is not needed for query construction. Retaining only the necessary metadata — <em>full table name (schema + table), semantic relationships, table &amp; column descriptions, and tags — </em>would cut the token size significantly.</p><p><strong>b) Node filtering:</strong> instead of passing all models metadata to the pruned manifest, we could further improve the efficiency gain by limiting the types of models we process.</p><ul><li>Filter out all test table metadata</li><li>Filter out all staging/intermediate models</li></ul><p><strong>c) Domain pruning</strong>: one other method to reduce the manifest token size is by passing the manifest to the LLM prompt not as a system prompt, but as an additional context in the prompt chain. For each conversation, the LLM client classifies the question into a data domain (by executing a tool), and then dynamically prune and add the manifest into the prompt chain.</p><p>For example, if the incoming question is related to marketing, then the LLM would infer that marketing question needs data models from “marketing” domain, and selectively only include data models that are associated with that domain. This domain selection are done based on dbt project, tag, schema, or any other kind of identifiers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3esFCMHxor5Zqgm2LvxLjg.png" /><figcaption>Illustration of manifest pruning: nodes which are out-of-domain (here illustrated by <em>finance</em>), test nodes, and staging nodes are excluded from the final pruned manifest.</figcaption></figure><h4><strong>3.2. Clean &amp; documented data models</strong></h4><p>This solution would rely on clean &amp; logical data models and documented &amp; semantically connected documentations.</p><p>Ad hoc questions that require complex SQL — complex joins, multiple layers of CTEs, etc — would still perform poorly. However, clean data models that are intuitive even for machines, the ones that only need to be aggregated, joined to simple dimension tables, and other simple operations would be much easier to understand for LLMs.</p><p>Aside from the data modeling itself, one other must-haves is the documentation. It has to be clear for the LLMs what each table means, what each column means, and how each model is connected to each other (semantic relationship). On top of model definition, it would also be beneficial to include more metadata e.g. tags, owners, and partition keys.</p><h4><strong>3.3. Guardrails in system prompt</strong></h4><p>LLMs are confident, but not always correct. No data is better than bad data, so the prompt must include a specific instruction to return <em>no answer</em> if there is no available data model to answer incoming questions.</p><p>Aside from answer refusals, the system prompt could also include additional data governance guardrails. For example, one common problem in big enterprises is confusion regarding the correct source to get a metric. By explicitly instruct the LLM to comply to a set of data governance rules (e.g. use “<em>gmv_metrics</em>” table to answer all GMV related questions) in the system prompt, the room for error diminishes.</p><h4><strong>3.4. Access control</strong></h4><p>The system enforces user-level permissions, just like any other analytics layer. Tool calls and SQL execution are scoped to the user’s role.</p><h3>4. Implications for the Analytics Profession</h3><p>This shift won’t just impact how users access data, it will reshape data roles themselves. Analysts who primarily write simple SQL queries will face increasing automation. Tasks like pulling metrics, building one-off pivot tables, or slicing dashboards by a new dimension are now easily handled by LLMs.</p><p>Meanwhile, the role of analytics engineers becomes more central. Designing clean, reusable, and well-documented models — and structuring them for machine understanding — becomes a key responsibility. The quality of self-service answers now depends on the quality of the semantic layer.</p><p>There will still be a need for strategic analysis and storytelling, but the bar for entry-level and repetitive work is rising fast.</p><h3>5. Final Thoughts</h3><p>Every wave of automation starts by eating the most repetitive work. That’s what’s happening now in data teams. Generating simple insights from structured data is no longer a uniquely human task.</p><p>The idea that we can “just upskill” our way out of this is comforting, but not entirely realistic. As AI systems get better, the floor for human contribution keeps rising. Eventually, even complex tasks will be automated, and the nature of work will have to shift more fundamentally.</p><p>No job function is entirely safe — not analysts, not engineers, not cognitive workers more broadly. We might delude ourselves by thinking that there are labors that are safe from AI displacement, but I think that belief is a mere wishful thinking.</p><p>I firmly believe that no matter how complicated the task is, no matter the form — <em>cognitive, physical, or relationship-based</em>, all labors will be displaced eventually. The <strong>competitive forces at play</strong> (<em>both between nations &amp; corporations</em>), and the<strong> incentive system installed at every level</strong> (<em>investors wanting more returns, executives seeking more control &amp; efficiency, innovators seeking to use their runway to disrupt markets, the sheer volume of the money already invested in the AI industry, etc.</em>) will push people into automating more jobs and pushing working class to the side.</p><p>Our current economic systems are not built to handle this pace of disruption. And the tools we’re proposing today, while incredibly useful, are accelerating that shift.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfb99873ae46" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science-collective/self-service-analytics-with-llm-tool-calling-dfb99873ae46">Self-Service Analytics with LLM + Tool Calling</a> was originally published in <a href="https://medium.com/data-science-collective">Data Science Collective</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Web Scraping Using BeautifulSoup + Pushing Data to MySQL Database]]></title>
            <link>https://medium.com/codex/web-scraping-using-beautifulsoup-pushing-data-to-mysql-database-9de6af06e7b8?source=rss-ee6b1b0fe714------2</link>
            <guid isPermaLink="false">https://medium.com/p/9de6af06e7b8</guid>
            <category><![CDATA[book-depository]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[sqlalchemy]]></category>
            <category><![CDATA[beautifulsoup]]></category>
            <category><![CDATA[mysql]]></category>
            <dc:creator><![CDATA[Ammar Chalifah]]></dc:creator>
            <pubDate>Sun, 12 Sep 2021 09:01:27 GMT</pubDate>
            <atom:updated>2021-09-13T11:15:24.440Z</atom:updated>
            <content:encoded><![CDATA[<h4>Create your own dataset by regularly scrape and log data from websites.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Qt9ap-rO9kWcuXSx" /><figcaption>Photo by <a href="https://unsplash.com/@alfonsmc10?utm_source=medium&amp;utm_medium=referral">Alfons Morales</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this article, we will learn how to scrape data from web’s HTML content with BeautifulSoup, a popular Python package for web scraping. Then, we will learn how to push the data into a table in MySQL database.</p><h4>Scrape HTML data with BeautifulSoup</h4><p>BeautifulSoup is a Python package for parsing HTML and XML documents. Every website accessed via a web browser consists of HTML documents, which can be seen by inspecting the page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A9u3eUKlDvxdfvmEKJZxIQ.png" /><figcaption>Book Depository’s new release page and HTML. — Image by author.</figcaption></figure><p>Let’s say, you are a bookworm. You want to keep yourself updated with new books from Book Depository, and you want to update your list regularly. You can check New Release page in Book Depository’s website every now and then (by visiting <a href="https://www.bookdepository.com/top-new-releases">https://www.bookdepository.com/top-new-releases</a>), but you think it will be far easier to process those information if you can scrape the data and save it in tabular format.</p><p>After inspecting the elements of that website, you discovered that all book elements in that page are stored under div tag with &quot;book-item&quot; class. From each book-item elements, you can scrape various informations, such as ISBN, title, author name, published date, book format, and price. You want to record all informations, plus one additional information i.e. scraping date. So, now you have a rough plan for your web scraping journey: (1) first, scrape informations from HTML and convert it to tabular format, and (2) save the table to external location. For the sake of simplicity, we will use requests package to send a HTTP request to get the HTML response, use BeautifulSoup to parse the HTML, use pandas to convert the information to a DataFrame, and lastly push all data to a MySQL database by using sqlalchemy package.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kiYOne5pyiaH__aS1j5b0w.png" /><figcaption>HTML tags of book items in New Release page of Book Depository — Image by author.</figcaption></figure><p>Install BeautifulSoup using a Python package manager. If you use pip, install it by using pip install beautifulsoup4. Then, import several packages and start requesting the HTML via HTTP request.</p><pre>import requests<br>import pandas as pd<br>import datetime<br>from bs4 import BeautifulSoup<br>from sqlalchemy import create_engine</pre><pre>URL = &#39;<a href="https://www.bookdepository.com/top-new-releases">https://www.bookdepository.com/top-new-releases</a>&#39;<br>page = requests.get(URL)<br>soup = BeautiulSoup(page.content, &quot;html.parser&quot;)<br>books = soup.find_all(&quot;div&quot;, class_ = &quot;book-item&quot;)</pre><p>In the above code snippet, a get request was sent to the URL. The response stored in page variable, which later converted to a parsed data object by using BeautifulSoup object. Then, we take all HTML elements with book-item class and store it in books list. The books variable consists hundreds of book element, with each element looks like this:</p><pre>print(books[0])</pre><pre>===============</pre><pre>&lt;div class=&quot;book-item&quot; itemscope=&quot;&quot; itemtype=&quot;<a href="http://schema.org/Book">http://schema.org/Book</a>&quot;&gt;<br>&lt;div class=&quot;item-img&quot;&gt;<br>&lt;a href=&quot;/Mirror-Light-Hilary-Mantel/9780007481002&quot; itemprop=&quot;url&quot;&gt;<br>&lt;img alt=&quot;The Mirror and the Light&quot; class=&quot;lazy&quot; data-lazy=&quot;<a href="https://d1w7fb2mkkr3kw.cloudfront.net/assets/images/book/mid/9780/0074/9780007481002.jpg">https://d1w7fb2mkkr3kw.cloudfront.net/assets/images/book/mid/9780/0074/9780007481002.jpg</a>&quot;/&gt;<br>&lt;/a&gt;<br>&lt;/div&gt;<br>&lt;meta content=&quot;9780007481002&quot; itemprop=&quot;isbn&quot;/&gt;<br>&lt;meta content=&quot;The Mirror and the Light&quot; itemprop=&quot;name&quot;/&gt;<br>&lt;meta content=&quot;Hilary Mantel&quot; itemprop=&quot;contributor&quot;/&gt;<br>&lt;div class=&quot;item-info&quot;&gt;<br>&lt;h3 class=&quot;title&quot;&gt;<br>&lt;a href=&quot;/Mirror-Light-Hilary-Mantel/9780007481002&quot;&gt;<br>                    The Mirror and the Light&lt;br/&gt;<br>&lt;/a&gt;<br>&lt;/h3&gt;<br>&lt;p class=&quot;author&quot;&gt;<br>&lt;a href=&quot;/author/Hilary-Mantel&quot; itemprop=&quot;author&quot;&gt;Hilary Mantel&lt;/a&gt;<br>&lt;/p&gt;<br>&lt;div class=&quot;rating-wrap&quot;&gt;<br>&lt;a aria-label=&quot;Ratings for The Mirror and the Light&quot; href=&quot;/Mirror-Light-Hilary-Mantel/9780007481002&quot;&gt;<br>&lt;div class=&quot;stars&quot;&gt;<br>&lt;span class=&quot;star full-star&quot;&gt;&lt;/span&gt;<br>&lt;span class=&quot;star full-star&quot;&gt;&lt;/span&gt;<br>&lt;span class=&quot;star full-star&quot;&gt;&lt;/span&gt;<br>&lt;span class=&quot;star full-star&quot;&gt;&lt;/span&gt;<br>&lt;span class=&quot;star half-star&quot;&gt;&lt;/span&gt;<br>&lt;/div&gt;<br>&lt;/a&gt;<br>&lt;/div&gt;<br>&lt;p class=&quot;published&quot; itemprop=&quot;datePublished&quot;&gt;29 Apr 2021&lt;/p&gt;<br>&lt;p class=&quot;format&quot;&gt;Paperback&lt;/p&gt;<br>&lt;div class=&quot;price-wrap&quot;&gt;<br>&lt;p class=&quot;price&quot;&gt;<br>                        Rp271.455&lt;/p&gt;<br>&lt;/div&gt;<br>&lt;/div&gt;<br>&lt;div class=&quot;item-actions&quot;&gt;<br>&lt;div class=&quot;btn-wrap&quot;&gt;<br>&lt;a class=&quot;btn btn-sm btn-primary add-to-basket&quot; data-currency=&quot;IDR&quot; data-isbn=&quot;9780007481002&quot; data-price=&quot;271455&quot; data-ref=&quot;carousel&quot; data-show-related=&quot;false&quot; href=&quot;/basket/addisbn/isbn13/9780007481002&quot; rel=&quot;nofollow&quot;&gt;<br>                        Add to basket&lt;/a&gt;<br>&lt;/div&gt;<br>&lt;/div&gt;<br>&lt;/div&gt;</pre><p>Based on the element’s structure, we can determine where we want to scrape the informations that we need from. For instance, ISBN, price, and currency can be scraped from tag a with &quot;btn btn-sm btn-primary add-to-basket&quot; class. Title can be scraped from meta tag with &quot;name&quot; attribute for itemprop, where author name, book format, and published date can be scraped from p tags with &quot;author&quot;, &quot;format&quot;, and &quot;published&quot; class respectively.</p><p>For the first book element, each information can be scraped by using these lines of codes:</p><pre>book_title = books[0].find(&quot;meta&quot;, {&quot;itemprop&quot;:&quot;name&quot;}).get(&quot;content&quot;)</pre><pre>book_author = books[0].find(&quot;p&quot;, class_ = &quot;author&quot;).find(&quot;a&quot;).text</pre><pre>book_format = books[0].find(&quot;p&quot;, class_ = &quot;format&quot;).text</pre><pre>book_published = books[0].find(&quot;p&quot;, class_ = &quot;published&quot;).text</pre><pre>book_isbn = books[0].find(&quot;a&quot;, class_ = &quot;btn btn-sm btn-primary add-to-basket&quot;).get(&quot;data-isbn&quot;)</pre><pre>book_currency = books[0].find(&quot;a&quot;, class_ = &quot;btn btn-sm btn-primary add-to-basket&quot;).get(&quot;data-currency&quot;)</pre><pre>book_price = books[0].find(&quot;a&quot;, class_ = &quot;btn btn-sm btn-primary add-to-basket&quot;).get(&quot;data-price&quot;)</pre><p>To scrape information from all book elements, create a dictionary where each key corresponds to each column (e.g. title, author, or isbn), and each value contains a list of values for the respective columns. Then, iterate over to books variable and append each list by using the same method to scrape individual informations as shown in the previous code snippet.</p><pre>books_dict = {&#39;title&#39;:[], &#39;author&#39;:[], &#39;format&#39;:[], &#39;published&#39;:[], &#39;isbn&#39;:[], &#39;currency&#39;:[], &#39;price&#39;:[], &#39;date&#39;:[]}</pre><pre>for b in books:<br>     books_dict[&#39;title&#39;].append(b.find(&quot;meta&quot;, {&quot;itemprop&quot;:&quot;name&quot;}).get(&quot;content&quot;))<br>     books_dict[&#39;author&#39;].append(b.find(&quot;p&quot;, class_ = &quot;author&quot;).find(&quot;a&quot;).text)<br>     books_dict[&#39;format&#39;].append(b.find(&quot;p&quot;, class_ = &quot;format&quot;).text)<br>     books_dict[&#39;published&#39;].append(b.find(&quot;p&quot;, class_ = &quot;published&quot;).text)<br>     books_dict[&#39;isbn&#39;].append(b.find(&quot;a&quot;, class_ = &quot;btn btn-sm btn-primary add-to-basket&quot;).get(&quot;data-isbn&quot;))<br>     books_dict[&#39;currency&#39;].append(b.find(&quot;a&quot;, class_ = &quot;btn btn-sm btn-primary add-to-basket&quot;).get(&quot;data-currency&quot;))<br>     books_dict[&#39;price&#39;].append(b.find(&quot;a&quot;, class_ = &quot;btn btn-sm btn-primary add-to-basket&quot;).get(&quot;data-price&quot;))<br>     books_dict[&#39;date&#39;].append(datetime.date.today())</pre><p>Finally, convert the dictionary to a pandas DataFrame.</p><pre>df = pd.DataFrame.from_dict(books_dict)<br>df.head(5)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D-9ooZokU4M3tjBiIgehlA.png" /><figcaption>Scraped data in DataFrame format — Image by author</figcaption></figure><h4>Pushing DataFrame to MySQL Database</h4><p>Assume you have a MySQL database, with a table named &quot;book-depo-new-releases&quot;. Along with that table, you also have the username and password of your MySQL database, the host, and database name. To push dataframe to MySQL, create an engine with sqlalchemy, then push the data directly by utilizing pandas method.</p><pre>engine = create_engine(&#39;mysql+pymysql://&#39;+{USERNAME}+&#39;:&#39;+{PASSWORD}+&#39;@&#39;+{HOST}+&#39;/&#39;+{DATABASE})</pre><pre>df.to_sql(con=engine, name=&#39;book-depo-new-releases&#39;, if_exists=&#39;append&#39;, index=False)</pre><p>By using append option, you won’t overwrite previously written rows in that table. Moreover, the DataFrame’s index also won’t be written to the MySQL table.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9de6af06e7b8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/web-scraping-using-beautifulsoup-pushing-data-to-mysql-database-9de6af06e7b8">Web Scraping Using BeautifulSoup + Pushing Data to MySQL Database</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running Airflow with Docker on EC2 + CI/CD with GitLab]]></title>
            <link>https://medium.com/data-science/running-airflow-with-docker-on-ec2-ci-cd-with-gitlab-72326d4baeb4?source=rss-ee6b1b0fe714------2</link>
            <guid isPermaLink="false">https://medium.com/p/72326d4baeb4</guid>
            <category><![CDATA[airflow]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[gitlab]]></category>
            <category><![CDATA[ec2]]></category>
            <category><![CDATA[data-pipeline]]></category>
            <dc:creator><![CDATA[Ammar Chalifah]]></dc:creator>
            <pubDate>Fri, 03 Sep 2021 19:21:04 GMT</pubDate>
            <atom:updated>2021-09-04T14:16:58.754Z</atom:updated>
            <content:encoded><![CDATA[<h4>Create a simple data pipeline with basic commands and run your own cloud-based pipeline!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ev08pVDdUiqH38QR" /><figcaption>Photo by <a href="https://unsplash.com/@goshua13?utm_source=medium&amp;utm_medium=referral">Joshua Aragon</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I’ve been learning data science for a year, yet until several weeks ago I still found myself completely clueless on the engineering side. Data analysis and artificial intelligence are stuff on the top of the pyramid, which requires strong data pipeline foundation. With this post, I will share my lessons learned while trying to built a simple data pipeline using Airflow, an open source orchestration tool. This orchestrator is deployed on top of Amazon EC2, utilizing GitLab’s CI/CD to ease up development process. Okay, one by one, let’s talk about definition of each terms.</p><h4>Airflow</h4><p>Based on its website, Airflow is a “<em>platform created by the community to programmatically author, schedule and monitor workflows.” </em>Airflow usually used by Data Engineers to orchestrating workflows and pipelines. Let’s say a Data Engineer need to move data from a source to another destination four times a day (e.g. to keep the freshness of the data). Instead of doing that task manually, they can automate the script to run on a particular schedule using Airflow. Airflow can also be used to manage dependencies, monitor workflow executions, and visualize workflows.</p><p>Airflow needs to be installed in a machine. Instead of using local computer, it is better to install it in a cloud-based host to improve reliability.</p><h4><strong>Amazon EC2</strong></h4><p>Amazon EC2 (stands for Elastic Compute Cloud) is a rented cloud-based computers offered by Amazon Web Services. EC2 will serve as the host, which Airflow will be deployed on. EC2 is just a computer, like our local laptop/computer, but the machine will be up 99% of the time and managed by AWS team. We can ‘tunnel’ our way inside the command line interface of EC2’s machine by using SSH. Later on, we will learn how we can use SSH and git to deploy codes from a remote repository to EC2.</p><h4>Docker</h4><p>Airflow won’t be installed directly on EC2 local machine, but installed inside a Docker container. Docker is a set of platform that creates virtual OS called containers. We use Docker to reduce setups, as all setups will be managed by the maintainer of the Docker images (in this case, Airflow contributors). A Docker image contains <strong>application code, libraries, tools, dependencies and other files needed to make an application run</strong>. We will pull an image from Docker image registry, build it, start the container, and run Airflow inside.</p><h4>GitLab</h4><p>GitLab will be used as our repository and DevOps lifecycle tool. There are practically countless way we can utilize CI/CD in GitLab, but for the sake of simplicity we will only use the ‘CD’ part. Every time user merge any branch into the main branch, the deployment script will be triggered. Deployment pipeline consists of SSH tunneling into our EC2, pulling main branch from GitLab repository into EC2, write several variables to a file, and rebuild + restart the Docker container.</p><p>Before diving into the details, check <a href="https://github.com/ammarchalifah/airflow-pipeline">this repository</a>, which contains the complete codebase and summary of the steps that we will take to successfully create a continuous deployment pipeline of Airflow. Okay, let’s start!</p><h3>Setups</h3><h4>EC2</h4><p>Access AWS Console, then prepare an EC2 instance. I recommend using instance with ubuntu OS with lower-mid performance. Download the SSH key of your EC2 instance (usually ends with .pem suffix), and write down the IP address of your instance. Then, configure your instance to open all ports (at least open port 8080 to access the Airflow webserver). Lastly, access the EC2 by using the SSH key to install Docker and docker-compose from command line interface.</p><pre>ssh -i ssh-key.pem ubuntu@EC2_ADDRESS</pre><p><strong>Guide for EC2 provision:</strong> <a href="https://www.youtube.com/watch?v=YB_qanudIzA">https://www.youtube.com/watch?v=YB_qanudIzA</a></p><h4>GitLab</h4><p>Sign up on GitLab (<a href="https://medium.com/gitlab.com">https://gitlab.com</a>) and create a new project. Clone the contents from the <a href="https://github.com/ammarchalifah/airflow-pipeline">github repository</a> to our new GitLab repository. After the repository is filled with the codes, we need to configure GitLab runner and set repository variables. GitLab runner is used to execute CI/CD scripts which we defined in gitlab-ci.yml . Repository variables are used to store sensitive informations (such as username, password, IP address of your EC2, and SSH key of the EC2). Repository variables are loaded as environment variables in CI/CD pipelines, where it could be deployed to the server as variables/files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1MqFtfwnPVKhajonSkfDzQ.png" /><figcaption>Interface of GitLab’s repository. Image by author.</figcaption></figure><p>Follow instructions in <a href="https://docs.gitlab.com/runner/install/">GitLab runner configuration guide</a> to configure our runner. For me, I used EC2 instance with ubuntu OS to install my runner. You don’t have to configure your own runner if you activate GitLab’s free trial by giving your credit card information, as GitLab will provide a shared runner for you.</p><p><strong>GitLab Repository Variables</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T8qTNOl0DL8L97Z_AOVIBg.png" /><figcaption>Repository variables — Image by author.</figcaption></figure><p>There are six repository variables that we need to set. Go to <strong>Settings &gt; CI/CD &gt; Variables</strong>, click <strong>Expand</strong>, and start adding variables.</p><p>The first two are _AIRFLOW_WWW_USER_PASSWORD and _AIRFLOW_WWW_USER_USERNAME, which will be used to log in to the Airflow server once it is deployed. Choose any arbitrary value for these two variables.</p><p>The second pair is EC2_ADDRESS (IP address of your EC2 instance) and SSH_KEY_EC2 (SSH key of your EC2 instance, usually ends with .pem suffix). These values will be used to access your EC2 machine. Set SSH_KEY_EC2 as file instead of variable.</p><p>The last pair is GITLAB_PASSWORD and GITLAB_USERNAME, used for credentials to pulling commits from GitLab repository.</p><h3>Code Explanation</h3><p>Start by looking at the directory structure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*Pdhnhk0eUQaDmSq8Z655hQ.png" /><figcaption>Directory structure of this project — Image by author.</figcaption></figure><p>The three directories (dags, logs, and plugins) are basic Airflow directories. We leave logs and plugins (almost) empty, because those folders will be filled after deployment. Scripts that we wish to automate are written inside dags, which we will cover later.</p><p>During any push to GitLab’s repo, the scripts in .gitlab-ci.yml (which define CI/CD pipeline) will be triggered. The script execute series of commands to deploy the repository to EC2. Inside EC2, we will build the Docker container containing Airflow by using docker-compose up on the docker-compose.yaml.</p><h4>CI/CD Pipeline</h4><p>Before getting more complex, please refer to <a href="https://docs.gitlab.com/ee/ci/quick_start/">this guide</a> to understand what GitLab’s CI/CD is.</p><p>The CI/CD pipeline is defined in .gitlab-ci.yml.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e31781595730702227fca233e9d700a6/href">https://medium.com/media/e31781595730702227fca233e9d700a6/href</a></iframe><p>Because I’m using GitLab runner that executes pipelines using Docker, the default image is specified at the top. I used ubuntu:latest as my default Docker image.</p><p>As stated earlier, we won’t utilize the continuous integration aspect of CI/CD. We only use deployment that only triggered in main branch. That means all push to other branches beside main won’t results in deployment.</p><pre>deploy-prod:<br>  only:<br>   - main<br>  stage: deploy<br>  before_script: ...<br>  script: ...</pre><p>deploy-prod is the name of our pipeline, which will only run in main branch. The stage of this pipeline is deployment stage (in contrast to other stages such as testing or building). Commands are specified inside before_script and script.</p><pre>before_script:<br>- ls -la<br>- pwd<br>- &#39;which ssh-agent || ( apt-get update -y &amp;&amp; apt-get install openssh-client -y )&#39;<br>- eval $(ssh-agent -s)<br>- mkdir -p ~/.ssh<br>- chmod 700 ~/.ssh<br>- cat $SSH_KEY_EC2<br>- echo &quot;$(cat $SSH_KEY_EC2)&quot; &gt;&gt; ~/.ssh/ssh-key.pem<br>- chmod 400 ~/.ssh/ssh-key.pem<br>- cat ~/.ssh/ssh-key.pem<br>- echo -e &quot;Host *\n\tStrictHostKeyChecking no\n\n&quot; &gt; ~/.ssh/config<br>- apt-get update -y<br>- apt-get -y install rsync</pre><p>before_script consists of several commands that prepare our runner for deployment. The commands are used to install open-ssh, evaluate ssh-agent, dump SSH key from repository variable to file, change permission of the SSH key, set ssh config, and install rsync.</p><pre>ssh -i ~/.ssh/ssh-key.pem ubuntu@$EC2_ADDRESS \<br>&#39;git config --global --replace-all user.name &quot;Full Name&quot;<br>&amp;&amp; git config --global --replace-all user.email &quot;email@email.com&quot;<br>&#39;</pre><p>The script section are divided into three sections. Each sections are started with ssh tunneling into the EC2. The first section is used to set git config to use your full name and email as the global config.</p><pre>ssh -i ~/.ssh/ssh-key.pem ubuntu@$EC2_ADDRESS \<br>&#39;<br>if [ -d airflow-pipeline ];<br>then cd airflow-pipeline<br>&amp;&amp; git status<br>&amp;&amp; git restore .env<br>&amp;&amp; git pull --rebase<br>&amp;&amp; git status<br>&amp;&amp; sed -i s:%AIRFLOW_UID%:&#39;&quot;$(id -u)&quot;&#39;:g .env<br>&amp;&amp; sed -i s:%AIRFLOW_GID%:0:g .env<br>&amp;&amp; sed -i s:%_AIRFLOW_WWW_USER_USERNAME%:&#39;&quot;$_AIRFLOW_WWW_USER_USERNAME&quot;&#39;:g .env<br>&amp;&amp; sed -i s:%_AIRFLOW_WWW_USER_PASSWORD%:&#39;&quot;$_AIRFLOW_WWW_USER_PASSWORD&quot;&#39;:g .env<br>else git clone https://&#39;&quot;$GITLAB_USERNAME&quot;&#39;:&#39;&quot;$GITLAB_PASSWORD&quot;&#39;@gitlab.com/gitlab-group/gitlab-project.git<br>&amp;&amp; cd airflow-pipeline<br>&amp;&amp; ls -la<br>&amp;&amp; chmod 777 logs<br>&amp;&amp; sed -i s:%AIRFLOW_UID%:&#39;&quot;$(id -u)&quot;&#39;:g .env<br>&amp;&amp; sed -i s:%AIRFLOW_GID%:0:g .env<br>&amp;&amp; sed -i s:%_AIRFLOW_WWW_USER_USERNAME%:&#39;&quot;$_AIRFLOW_WWW_USER_USERNAME&quot;&#39;:g .env<br>&amp;&amp; sed -i s:%_AIRFLOW_WWW_USER_PASSWORD%:&#39;&quot;$_AIRFLOW_WWW_USER_PASSWORD&quot;&#39;:g .env<br>&amp;&amp; docker-compose up airflow-init;<br>fi&#39;</pre><p>The second section is used to pulling changes from main branch in GitLab repository and writing environment variables into .env file. Here we use conditions based on existence of the directory on the EC2 home directory. If we have cloned GitLab repository before, we only executed: restore all changes from .env file, pulling changes from remote GitLab repository, and writing environment variables to .env. If we haven’t, we start by cloning the repository, then write environment variables to .env file, and starting the Docker container.</p><pre>ssh -i ~/.ssh/ssh-key.pem ubuntu@$EC2_ADDRESS \<br>&#39;cd airflow-pipeline &amp;&amp;<br>if [ docker ps | grep -q keyword ];<br>then docker-compose down &amp;&amp; docker-compose up -d --build;<br>else docker-compose up -d --build;<br>fi;&#39;</pre><p>The latest section is used to restart the Docker to incorporate new changes.</p><p>CI/CD pipeline can be monitored on <strong>CI/CD &gt; Pipelines </strong>on GitLab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oKMZDswnPO7tIwOMbxhCOw.png" /><figcaption>GitLab CI/CD pipelines — Image by author.</figcaption></figure><p>If everything went smoothly, your Airflow webserver will be ready. Go to https://{EC2_ADDRESS}:8080 on browser to log in to the user interface. Log in with Airflow username and password that you set on the repository variables before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YDZDU8K7sUbl-TWpJj5qNw.png" /><figcaption>Airflow webserver login page — Image by author.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cm-F-m1KR6P2h5z-HFMo4w.png" /><figcaption>Interface of Airflow webserver — Image by author.</figcaption></figure><p>Later, any script you wish to automate can be written inside a DAG (or <em>directed acyclic graph, </em>a directed graph with no directed cycles. Tasks inside a DAG are framed as a node of a graph, where dependencies can be defined. <strong>Any changes in the repository could be deployed by pushing changes to GitLab repository, merge to main branch (or push to main branch directly), and wait until CI/CD pipeline succeeded.</strong></p><p>You can define many things inside a DAG, such as data ingestion tasks, data querying task, send automated email, scrape data, make API call, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*sqThaggrenKF9VARd69CIQ.png" /><figcaption>Dependency visualization inside a DAG — Image by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0PdyKBudnfOhF0iCL8erjg.png" /><figcaption>Task monitoring in a DAG— Image by author</figcaption></figure><h4>Why Specify .gitignore?</h4><p>It is not recommended to log Airflow activity locally. However, due to time and cost constraint, I log all activities locally, especially under /logs directory. Besides logs, DAG execution also create caches in /dags/__pycache__/. Hence, I ignored those files by using .gitignore to safely pull changes without causing conflicts.</p><h4>EC2 Inspection</h4><p>If anything goes wrong, you can always inspect what happens inside EC2 by using the SSH key.</p><pre>ssh -i ssh-key.pem ubuntu@EC2_ADDRESS</pre><p>Delete unused files, unused Docker images, or make any adjustments from inside!</p><h4><strong>References</strong></h4><p>[1] <a href="https://airflow.apache.org/">https://airflow.apache.org/</a><br>[2] <a href="https://aws.amazon.com/ec2/">https://aws.amazon.com/ec2/</a><br>[3] <a href="https://www.docker.com/">https://www.docker.com/</a><br>[4] <a href="https://about.gitlab.com/">https://about.gitlab.com/</a><br>[5] <a href="https://airflow.apache.org/docs/apache-airflow/stable/start/docker.html">https://airflow.apache.org/docs/apache-airflow/stable/start/docker.html</a> <br>[6] Code references from Bunga Amalia K for setting up GitLab runner</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72326d4baeb4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/running-airflow-with-docker-on-ec2-ci-cd-with-gitlab-72326d4baeb4">Running Airflow with Docker on EC2 + CI/CD with GitLab</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>