<?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 Zalán Tóth on Medium]]></title>
        <description><![CDATA[Stories by Zalán Tóth on Medium]]></description>
        <link>https://medium.com/@zlaval?source=rss-8af538bf2181------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*SamW9kXEX76--HZDqgJ_7w.jpeg</url>
            <title>Stories by Zalán Tóth on Medium</title>
            <link>https://medium.com/@zlaval?source=rss-8af538bf2181------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 17:54:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@zlaval/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[Business Data Visualization - a fast and easy way]]></title>
            <link>https://zlaval.medium.com/business-data-visualization-a-fast-and-easy-way-15588eed9b99?source=rss-8af538bf2181------2</link>
            <guid isPermaLink="false">https://medium.com/p/15588eed9b99</guid>
            <category><![CDATA[dbt]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[etl]]></category>
            <category><![CDATA[metabase]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Zalán Tóth]]></dc:creator>
            <pubDate>Sat, 27 May 2023 13:10:33 GMT</pubDate>
            <atom:updated>2023-05-27T13:10:33.420Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ArYUwVSLbrMk4Nc0.jpg" /></figure><p>Many organizations need to visualize their business data, which is often difficult to do. Thanks to the popularity of microservices architecture, data are usually stored in multiple databases. Executing queries for data visualization can be slow and causes high pressure on the business database - especially if we’re not using read replicas - thus slowing down the application. It is also challenging to link data together from different databases. The required data can be dirty, their structure and format may not be suitable for visualization.</p><p>There are several options available to solve this problem, some of which include:</p><ul><li><strong>Developing a custom analytics system</strong><br>This entails creating at least a new service that retrieves the necessary data from the microservices - or directly from their databases. Then it has to normalize the data to create the required views for displaying the charts. Depending on the quantity and quality of the data, this can be a complex task. Additionally, UI needs to be created, which is capable of rendering the appropriate charts. The advantage of this solution is it can be highly customized, but it requires significantly more development time.</li><li><strong>Cloud-based analytics system</strong><br>Most of the Cloud Providers offer their own solution for data analysis and visualization. For example <a href="https://azure.microsoft.com/hu-hu/products/analysis-services/">Azure Analysis Services</a> or <a href="https://aws.amazon.com/free/analytics/?trk=42e49763-8e86-4ed0-b113-6c98259a1416&amp;sc_channel=ps&amp;ef_id=CjwKCAjwvJyjBhApEiwAWz2nLaMgzRY9dMpG1UN-pstc4bJeXKYPUugm4FPXTp4_9_431azLeEAjFxoC5ZkQAvD_BwE:G:s&amp;s_kwcid=AL!4422!3!645251373815!p!!g!!aws%20business%20intelligence!19571722920!146073145420">AWS Analytics and Data Lake Products</a>. Using these services - depending on the provider - we can quickly and easily build our solution. The downside is that it might be more expensive and also be challenging to implement unique requirements.</li><li><strong>Component-based analytics system</strong><br>There are many pre-made services which we can combine for building our analytics platform. Essentially, this one is the combination of the previous two approaches. Cheaper than the cloud-based option and faster to do than building a custom solution. The individual building blocks can also be replaced with custom implementation as needed. This approach helps achieve the best balance between cost, effort, and development time. However, compromises need to be made among these three.</li></ul><p>In this article, we are going to build a component-based analytics system. Each component can be run locally, on-premise or on cloud-based platforms. Additionally, these components can used in form of Software-as-a-Service.</p><h4>Components</h4><p>The following list includes the software components we are going to use:</p><ul><li><a href="https://www.postgresql.org/">PostgreSQL</a>, Business and BI database.</li><li><a href="https://www.mongodb.com/">MongoDB</a>, Business database.</li><li><a href="https://www.docker.com/products/docker-desktop/">Docker</a>, Containerization platform.</li><li><a href="https://www.metabase.com/">Metabase</a>, Data visualization tool.</li><li><a href="https://airbyte.com/">Airbyte</a>, ELT system for copying data.</li><li>Data Injector, Scheduled job for inserting test data.</li></ul><h4>System Overview</h4><p>The test data is stored in two different databases. The scheduled job will continuously inset new rows into them to simulates two microservices. The first database is a PostgreSQL, which stores the users of the system. The second one is a MongoDB, where the orders of the users and - for the sake of simplicity - the products are stored.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*qe2fxit0mEY-LvC_DoSyCA.png" /><figcaption>Services</figcaption></figure><p>Our goal is to create a simple dashboard where we can display the total revenue from sales, the quantity of sold products, the current price of the products and their price changes over time on line chart. Additionally, we want to show the amount spent by users on each product.</p><p>The demo databases contain ten users and thirty products. The scheduled job will insert new orders - using random users and products - into this in every minute. Furthermore, the job modifies the prices of a few products to randomly generated values in each run. The source code for the job is available on this <a href="https://github.com/zlaval/data_analytics-plaform/tree/master/datainjector">link</a>.</p><p>The dashboard we build can be seen in the following image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0N7jI2Mr-U5AfiAUvyM-uQ.png" /><figcaption>Metabase Dashboard</figcaption></figure><h4>Platform architecture</h4><p>In the first step, we transfer the necessary data for analytics from the business databases into the BI db. For this, we utilize an <a href="https://learn.microsoft.com/en-us/azure/architecture/data-guide/relational-data/etl">ETL/ELT</a> system - in our case, Airbyte - which is capable to copy the data from different sources to the destination based on specified rules. Multiple alternative solutions are available to do this, such as Fivetran or Dataddo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*SW2y5yHWzEYAZusNpRZcdA.png" /><figcaption>Export Load Transform system</figcaption></figure><p>As a business intelligence (BI) database, we are using PostgreSQL in the demo, which is suitable for analyzing smaller datasets, typically up to a few hundred GBs. There are dedicated data warehouses available for real world analytics, such as Google BigQuery or Amazon Redshift. If the relational database becomes the bottleneck of our system, it is worth considering to migrate the system to these solutions.</p><p>Next, we have to transform the raw data into the appropriate format for visualization. We will use <a href="https://www.getdbt.com/">DBT</a> (Data Build Tool) modelling tool, which can be integrated into most of the ELT/ETL systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*4eOXSl3tF5zef2YvPH8nWQ.png" /><figcaption>Data transformation using ETL/ELT</figcaption></figure><p>After the data was loaded and transformed, we just need to visualize it. For this, we are going to use <a href="https://www.metabase.com/">Metabase</a>. The charts can be created using no-code editor or SQL queries with some additional configurations. We can then add these charts to the desired dashboard. We can use complex queries for the charts, although in most cases it is advisable to transform the data into the appropriate format using DBT (Data Build Tool) transformations. This is especially important when dealing with queries involving multiple table joins as the dashboard loading time can be significantly slower compared to a single-table query, where filtering conditions may not even be necessary. Metabase supports dashboard embedding into websites. The application can be run in containerized environments or we can also use through online service subscription.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*Z7OpbPmBGg5Ho3B9UrVm7w.png" /><figcaption>Data analytics platform</figcaption></figure><p>Before we build the platform, let’s review the business data tables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*M97rXs4GWuojSkL5KkV10Q.png" /><figcaption>Business tables</figcaption></figure><p>Users are stored in a PostgreSQL database. The table contains the user’s ID, name, and email address. The orders and products are stored in MongoDB collections. The orders document stores the ordered product’s ID, the customer’s ID, the timestamp of the order and a sub-document containing the order details. To make building the platform more interesting, we store the products in an <a href="https://learn.microsoft.com/en-us/azure/architecture/patterns/event-sourcing">Event Sourcing</a>-based data table. For each modification, a new document will be inserted into the collection. By aggregating these modifications in chronological order, we obtain the current state of the products. In this example, we’ll omit the creation of snapshots from these aggregates.</p><p>Now that we understand the architecture, let’s start assembling the platform.</p><h4>Deploy the Platform</h4><p>To start the platform, we need running Docker. The compose file and the source code of the job can be downloaded from <a href="https://github.com/zlaval/data_analytics-plaform">here</a>. The components are defined in theairbyte-compose.yml and platform-compose.yml manifest files. It can be deployed by the following command:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/510206d5a2d2737d70541879bcefa4df/href">https://medium.com/media/510206d5a2d2737d70541879bcefa4df/href</a></iframe><p>The installation may take a few minutes as it needs to download the containers and build a new one from the Job source code.</p><h4>Airbyte configuration</h4><p>Once the platform has started, we need to configure the database connections. Airbyte UI runs on <a href="http://localhost:8000/">localhost:8000</a> url. The default username and password are airbyte/password. After login, we can add new data sources and destinations. First, let’s connect the Postgres and MongoDB business databases as sources, and the BI Postgres database as destination. <br>Here are their parameters:</p><p><strong>Postgres Business:</strong></p><ul><li>Source database</li><li>Port: 10010</li><li>DB Name: postgres</li></ul><p><strong>MongoDB Business:</strong></p><ul><li>Source database</li><li>Port: 10020</li><li>DB Name: admin</li></ul><p><strong>Postgres Business:</strong></p><ul><li>Destination database</li><li>Port: 10030</li><li>DB Name: postgres</li></ul><p>The username and password for the databases are admin/admin123. The image below shows an example of a filled form. We can finalise the connection by clicking on the Set up source/destination button. The destination database needs to be created only once, then we can reuse it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OXoGjYor4xFikZiINuneIw.png" /><figcaption>Database configuration</figcaption></figure><p>After we have connected the databases, we need to specify the run frequency of the synchronization. For this demo, let’s choose the Cron type and set the value to */1 * * * * ? - copy-paste not always works. For testing purposes, it is good to have frequent synchronization, but in a real environment, this can be modified according to specific needs. We can select which tables do we want to synchronize from the source databases and set the synchronization mode as well. Let’s use Incremantal Append so only new data will be copied in each synchronization cycle. The value of the Cursor field has to be the primary key - id. Finally, on the Normalization &amp; Transformation card we can specify what should happen to the data after the copy. For now, let’s use raw data option. The Normalized tabular data setting would try to restore the original table structure. It works quite well with relational databases but not as well with document-based ones. We will address this issue later using DBT.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*82og-KUMay76YEiuw05q6w.png" /><figcaption>Sync configuration</figcaption></figure><p>The raw data tables should be in the BI database now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/1*HbyYYgdPF_N_zNjZ3H6GfQ.png" /><figcaption>Tables of raw data</figcaption></figure><p>In addition to the Airbyte metadata, the content of the business tables are represented in JSON format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Un_dxvjTJ6QbyfmDJzOxFQ.png" /><figcaption>Exported users</figcaption></figure><p>Each synchronized table contains three columns: a unique identifier, a JSONB column for the data and one holds the timestamp of the synchronization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/317/1*ft0U8_hc0GGp3DfLP6Eoxw.png" /><figcaption>Airbyte table structure</figcaption></figure><h4>DBT transformation</h4><p>In order to work with the data quickly and conveniently, we have to transform them into the appropriate format. For this, we will use DBT to automate the process. The scripts run after each data synchronization and transform the data applying the specified rules. The files used for the demo can be found <a href="https://github.com/zlaval/data_analytics-plaform/tree/master/transformations/models">here</a>.</p><p>The goal of the demo is not to build up comprehensive analytic database or provide a detailed overview of DBT, but we will take a look at some examples to illustrate how transformations look in practice.</p><p>In the examples, we extract the price changes of products from the raw data table called <em>airbyte_raw_</em>* and create a new table that contains the historical information. From this table, we generate another one for represent the current state of the products. Finally, we create a view that includes the product names and the number of associated orders for it.</p><p>We extract the necessary data from the JSONB object and transform it accordingly. PostgreSQL has built-in functions for handling these JSON objects. <br>Using the is_incremental() macro provided by DBT we can ensure that only newly synchronized data are processed. In the configuration header, we can specify the indices for the table and define the unique key, which allows for updating existing records instead of insertion.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40661cd872658580fd648ca15213b6a8/href">https://medium.com/media/40661cd872658580fd648ca15213b6a8/href</a></iframe><p>After that, we generate the products table from the historical data. This table contains the latest price for each product. Since the job - after initializing product data including their names - only inserts the identifier and the current price of the products, we need to preserve the name from the first sync, while taking the price from the latest one.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e3a125225288c3a16209f06d969439d/href">https://medium.com/media/6e3a125225288c3a16209f06d969439d/href</a></iframe><p>After creating the tables for products and orders - which can be found following the link mentioned earlier - we also create a view that represents the quantity of sold products.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/741450fdfc35e41fdf7893dc48cca450/href">https://medium.com/media/741450fdfc35e41fdf7893dc48cca450/href</a></iframe><p>As we have created the models, all we need to do is associate the transformations with an Airbyte connection. It can download the DBT project from a public Git repository and running it. The configuration can be seen on the following picture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yhEMezHqrOcTPiz89LV3SQ.png" /><figcaption>DBT transformation configuration</figcaption></figure><p>After saving - we have to save in the popup and on the card as well - the tables specified in the descriptors will be created during the next synchronization.</p><h4>Metabase</h4><p>In the last step, we will assemble the charts. Metabase runs on port 10000. After registration, we have to establish the database connection. Since Metabase and the BI database are connected to the same Docker network, we can use the container name as host.</p><p>BI database connection parameters:</p><ul><li>host: bi-db-pg</li><li>port: 5432</li><li>db name: postgres</li><li>user/pw: admin/admin123</li></ul><p>In the administrator settings - top right - on the Data Model tab we can see the available data models and set the field types. For example, we can set the type of the Price column in Products table as Currency, thus the values appears in the charts will be formated automatically.</p><p>Schema changes are automatically updated at certain intervals but if we want them to show up immediately, we can manually initiate synchronization on the Databases tab.</p><p>In this example, DBT creates all tables in the public schema. In a real environment, it is good practice separating intermediate and fact tables into different schemas and grant access to Metabase only the data it needs for visualization. Let’s leave the administrator panel now.</p><p>We can create new dashboards containing our charts using the New button. The built-in no-code editor - called questions - or SQL can be used for createing the individual charts.</p><p>But why do we need to transform the data if we could write the queries directly in Metabase? There are several reasons for this:</p><ul><li>Working with cleaned and consolidated data is easier.</li><li>Queries on optimized dataset are faster, so as the rendering time of the charts.</li><li>Well-organized data allows even non-technical users to create their dashboards.</li></ul><p>If possible, it is good to merge the necessary data into separate fact tables. This way, each chart can use a single table. However, it is important to be cautious as overly optimized data can also cause issues.</p><p>The table containing the quantity of products sold is a good example for this, as it does not allow filtering by timestamps.</p><p>Let’s create our first chart. By selecting the Question option after pressing the New button, we can choose the data source and the working table. In the no-code editor, we can join multiple tables for the selected one, group the data by columns, perform well known SQL functions, filter and sort the data, as shown in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ILzMt7qkpYrHgZEYnahyfw.png" /><figcaption>Changes of products price</figcaption></figure><p>By clicking on the Visualize button a table will be generated containing the results of the composed query. Here, we can select the chart type and also add other settings for it like goals, stack it and so on.</p><p>Available types for charts:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*z8i_TEWhLfP3WoDGGW9jSw.png" /><figcaption>Diagram types</figcaption></figure><p>We can configure which columns to be displayed on the axes, break down the data based on selected columns and choose from many other options to customize the chart. By clicking on the Save button, we can finalize it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ZS7k1orHo6Cp94qt07aDw.png" /><figcaption>Products price changes</figcaption></figure><p>Using the created charts, we can build up our dashboard where we are able to adjust their size and position.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JiptOvOghA4KtRlTxOBjfw.png" /><figcaption>Dashboard</figcaption></figure><p>We can also create charts using the SQL editor. Additionally, we can modify the code of the existing charts created by no-code editor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PqtVT_kQFyWl0LnLV_KORA.png" /><figcaption>Sum of spend of users per products</figcaption></figure><p>We have the option to define filters for the dashboards allowing users to further refine the displayed results. The charts are automatically refreshed based on the selected filter values. Note that while filters work automatically for charts created by no-code editor, using SQL we have to manually add template variables for them. Detailed instructions can be found <a href="https://www.metabase.com/learn/sql-questions/sql-variables#introduction-to-sql-variables-and-filter-widgets">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l8x3nIHNgZZc_OVa1Qa50g.png" /><figcaption>Filter for product names</figcaption></figure><p>Data used for the given chart can be also download in the selected format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dwc5042JKp_w96XHoWkqYg.png" /><figcaption>Download data</figcaption></figure><p>We can embed the dashboards into our own web applications. Additionally, we have the option to generate unique links to the dashboards via the Metabase API. This allows us, for example, to specify fix, unmodifiable filters for tenants, users… to only see their own data, but they can still use the dashboard’s filter for dates or product IDs and so on. Detailed instructions for this can be found <a href="https://www.metabase.com/docs/latest/embedding/start">here</a>.</p><p>We have seen how easily we can visualize business data. Of course, it is not necessary to manually set up the entire environment. All the applications used here are available as online services, where we can configure our system within minutes. This option is faster but, of course, it comes with additional costs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15588eed9b99" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[HUN] Üzleti adatok vizualizációja egyszerűen és gyorsan]]></title>
            <link>https://zlaval.medium.com/hun-%C3%BCzleti-adatok-vizualiz%C3%A1ci%C3%B3ja-egyszer%C5%B1en-%C3%A9s-gyorsan-37222e911f4b?source=rss-8af538bf2181------2</link>
            <guid isPermaLink="false">https://medium.com/p/37222e911f4b</guid>
            <category><![CDATA[airbyte]]></category>
            <category><![CDATA[etl]]></category>
            <category><![CDATA[metabase]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Zalán Tóth]]></dc:creator>
            <pubDate>Fri, 26 May 2023 17:36:27 GMT</pubDate>
            <atom:updated>2023-05-26T18:10:35.734Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ArYUwVSLbrMk4Nc0.jpg" /></figure><p>Számos szervezet számára szükséges az üzleti adatok grafikus megjelenítése. Ennek megvalósítása az esetek többségében nem egyszerű feladat. A mikroszolgáltatás architektúra népszerűségének köszönhetően az adatok általában több adatbázisaiban tárolva érhetők el. A megjelenítéshez szükséges lekérdezések végrehajtása sok időt vehet igénybe, mely terheli az üzleti adatbázist, - főleg ha nem használunk read replica db-t - ezáltal lassítva a alkalmazást. Nehézkes a különböző adatbázisokban található adatok összekapcsolása, a szükséges adatok szennyezettek lehetnek, illetve a struktúrájuk és formátumuk nem biztos, hogy megfelelő.</p><p>A probléma megoldására több lehetőség áll rendelkezésre. Ezek, a teljesség igénye nélkül:</p><ul><li><strong>Egyedi analitikai rendszer fejlesztése<br></strong>Ehhez létre kell hoznunk egy új szolgáltatást, mely elkéri a szükséges adatokat a megfelelő mikroszolgáltatásoktól - vagy közvetlenül az adatbázisukból - majd ezeket az adatokat normalizálva létrehozza a diagramok megjelenítéséhez szükséges adatstruktúrákat. Az adatok mennyiségétől és minőségétől függően ez bonyolult lehet.<br>Emellett létre kell hozni a megjelenítésért felelős szoftvert is, amely képes az adatokból a megfelelő diagramok kirajzolására.<br>Előnye hogy bármi személyre szabható, cserébe sok fejlesztést igényel.</li><li><strong>Felhő alapú analitikai rendszer</strong><br>A legtöbb felhőszolgáltató biztosít saját megoldást is adatelemzésre és vizualizációra. Ilyen például az <a href="https://azure.microsoft.com/hu-hu/products/analysis-services/">Azure Analysis Services</a>, vagy az AWS szolgáltatás csomagja, az <a href="https://aws.amazon.com/free/analytics/?trk=42e49763-8e86-4ed0-b113-6c98259a1416&amp;sc_channel=ps&amp;ef_id=CjwKCAjwvJyjBhApEiwAWz2nLaMgzRY9dMpG1UN-pstc4bJeXKYPUugm4FPXTp4_9_431azLeEAjFxoC5ZkQAvD_BwE:G:s&amp;s_kwcid=AL!4422!3!645251373815!p!!g!!aws%20business%20intelligence!19571722920!146073145420">AWS Analytics</a>. Ezek használatával -szolgáltatótól függően - gyorsan és kényelmesen elkészíthetjük a megoldásunkat. Hátránya, hogy hosszú távon drágább lehet, illetve nehézkes az egyedi igények megvalósítása.</li><li><strong>Komponens alapú analitikai rendszer<br></strong>Számos szolgáltatás létezik, melyek kombinálásával gyorsan felépíthetjük az analitikai megoldásunkat. Ez gyakorlatilag a fenti kettő kombinációja. A felhő alapúnál olcsóbb és az egyedi fejlesztésnél gyorsabb. Az egyes rétegeket akár saját megoldásra is cserélhetjük. Ennek segítségével érhetjük el a legjobb ‘ár - befektetett munka -elkészülési idő’ arányt. Természetesen ezek között kompromisszumot kell kötnünk.</li></ul><p>Ebben a bejegyzésben egy komponens alapú analitikai rendszert fogunk építeni. Minden komponens futtatható lokálisan, on-premise, vagy felhő alapú platformon is, emellett SAAS formában bérelhetők is.</p><h4>Komponensek</h4><p>Az alábbi lista a felhasznált szoftvereket tartalmazza:</p><ul><li><a href="https://www.postgresql.org/">PostgreSQL</a>, üzleti-, és BI adatbázis</li><li><a href="https://www.mongodb.com/">MongoDB</a>, üzleti adatbázis</li><li><a href="https://www.docker.com/products/docker-desktop/">Docker</a>, konténerizációs platform</li><li><a href="https://www.metabase.com/">Metabase</a>, adat vizualizációs eszköz</li><li><a href="https://airbyte.com/">Airbyte</a>, ELT rendszer az adatok mozgatásához</li><li>Data Injector, teszt adatokat beszúró ütemezett job</li></ul><h4>Áttekintés</h4><p>Az adatok két adatbázisba kerülnek tárolásra, melyeket egy adatbeszúró job tölt folyamatosan - két mikroszolgáltatást szimulálva. Az első egy PostgreSQL adatbázis, mely a felhasználók adatait tárolja. A másik pedig MongoDB, melyben a felhasználók megrendelései, valamint - az egyszerűség kedvéért - a termékek adatai találhatók.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*qe2fxit0mEY-LvC_DoSyCA.png" /><figcaption>Szolgáltatások</figcaption></figure><p>Célunk egy egyszerű dashboardon megjeleníteni az eladásokból származó összbevételt, a termékekből eladott darabszámot, a termékek aktuális árát, valamint árának változását vonaldiagramon, illetve a felhasználók által termékenként elköltött összeget.</p><p>A teszt rendszer tíz felhasználót és harminc terméket tartalmaz.<br>Az adatokat töltő ütemezett job percenként újabb megrendeléseket szúr be az adatbázisba véletlenszerű felhasználóhoz, véletlenszerű termékre.<br>Ezenkívül minden futánál pár termék árát módosítja egy szintén véletlen generált értékre. A job forráskódja elérhető a <a href="https://github.com/zlaval/data_analytics-plaform/tree/master/datainjector">linkre</a> kattintva.</p><p>A végeredmény az alábbi képen látható:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0N7jI2Mr-U5AfiAUvyM-uQ.png" /><figcaption>Metabase Dashboard</figcaption></figure><h4>A Platform felépítése</h4><p>Első lépésben a szükséges adatokat az üzleti adatbázisból átmásoljuk az elemzésre szolgáló BI adatbázisba. Ehhez egy <a href="https://learn.microsoft.com/hu-hu/azure/architecture/data-guide/relational-data/etl">ETL/ELT</a> - jelen esetben AirByte - rendszert fogunk használni, ami a megadott szabályok alapján a forrás adatbázisokból az adatokat átmozgatja a cél adatbázisba. Valós környezetben több alternatíva közül is választhatunk - pl Fivetran, Dataddo - bérelt platformként.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*SW2y5yHWzEYAZusNpRZcdA.png" /><figcaption>Export Load Transform system</figcaption></figure><p>Üzleti intelligencia - BI - adatbázisként a példában PostgreSQL-t használunk, mely megfelelő kisebb mennyiségű, - max pár száz GB - egyszerűbb adathalmaz elemzéséhez. Léteznek üzleti elemzésre kifejlesztett adattárházak, mint például Google BigQuery vagy Amazon Redshift. Amennyiben a relációs adatbázis szűk keresztmetszet, érdemes ezekre áttérni.</p><p>Következő lépésként az átmásolt nyers adatokból létre kell hoznunk a vizualizációhoz szükséges megfelelő adatstruktúrákat és transzformálni az adatokat a megfelelő formátumra. Ebben segít a <a href="https://www.getdbt.com/">DBT</a> modellező és transzformációs program, mely a legtöbb ELT rendszerbe becsatornázható.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*4eOXSl3tF5zef2YvPH8nWQ.png" /><figcaption>Data transformation using ETL</figcaption></figure><p>Miután az adatok a helyükre kerültek, már csak meg kell jelenítenünk őket. Ehhez hívjuk segítségül a <a href="https://www.metabase.com/">Metabase</a> alkalmazást. A diagramokat a no-code szerkesztő, vagy egyszerű SQL, illetve pár beállítás segítségével létrehozhatjuk, majd ezekből összeállíthatjuk a szükséges dashboardot. Bonyolultabb lekérdezéseket is megfogalmazhatunk egy-egy diagramhoz, bár az esetek többségében érdemes inkább DBT transzformáció segítségével a megfelelő formátumra hozni az adatokat, hisz a sok táblakapcsolattal rendelkező lekérdezések esetén a dashboard betöltési ideje jóval lassabb lehet, mint egy egytáblás lekérdezés esetén, ahol esetleg szűrőfeltétel megadása sem szükséges. A Metabase támogatja a dashboardok beágyazását weboldalakba. Az alkalmazás futtatható konténerizáltan, de elérhető online szolgáltatásként is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*Z7OpbPmBGg5Ho3B9UrVm7w.png" /><figcaption>Data analytics platform</figcaption></figure><p>Mielőtt felépítjük a platformot, tekintsük át az üzleti adatbázisok tartalmát.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*M97rXs4GWuojSkL5KkV10Q.png" /><figcaption>Üzleti táblák</figcaption></figure><p>A felhasználók tábla Postgres adatbázisban foglal helyet. Tartalmazza a felhasználó azonosítóját, nevét és email címét. A megrendeléseket és termékeket MongoDB-ben tároljuk. A megrendelések gyűjteményben található minden dokumentum magába foglalja a megrendelt termék, valamint a megrendelő azonosítóját, a megrendelés dátumát, illetve a megrendelés részleteit tartalmazó aldokumentumot. Hogy egy kicsit érdekessebbé tegyük a platformot, a termékeket nem egyszerű dokumentumként - adatbázis bejegyzés - tároljuk, hanem egy <a href="https://learn.microsoft.com/hu-hu/azure/architecture/patterns/event-sourcing">Event Sourcing</a> - belinkelem, de nem vagyok hajlandó magyarul leírni - alapú adattáblát emulálunk. A gyűjteménybe minden egyes módosításhoz egy új dokumentum kerül beszúrásra. Ezen módosításokat időrendben összesítve kapjuk meg az adott termék aktuális állapotát. A példában eltekintünk a snapshotok létrehozásától.</p><p>Most hogy már ismerjük az architectúrát, kezdjük el a platform összeszerelését.</p><h4>A Platform indítása</h4><p>A komponensek elindításához futó Docker szükséges. A telepítést leíró compose fájlok és a job forráskódja letölthető <a href="https://github.com/zlaval/data_analytics-plaform">innen</a>. Az airbyte-compose.yml és platform-compose.yml által definiált komponensek telepítése a következő parancs kiadásával indítható:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/510206d5a2d2737d70541879bcefa4df/href">https://medium.com/media/510206d5a2d2737d70541879bcefa4df/href</a></iframe><p>A telepítés pár percet igénybe vehet, mivel le kell tölteni az alkalmazáshoz használt konténereket, valamint fel kell építeni egy új konténert a Job forráskódjából.</p><h4>Airbyte konfigurálása</h4><p>Miután elindult a platform, fel kell konfigurálni az adatbázis kapcsolatokat.<br>Az AirByte a <a href="http://localhost:8000/">localhost:8000</a> url címen érhető el. A felhasználónév és jelszó pedig airbyte/password. Belépés után lehetőség van új forrás felvételére. Kössük be először a Postgres, majd a MongoDB üzleti adatbázist, cél adatbázisként pedig a másik Postgres adatbázist. Ezek paraméterei:</p><p><strong>Postgres Business:</strong></p><ul><li>Source adatbázis</li><li>Port: 10010</li><li>DB Name: postgres</li></ul><p><strong>MongoDB Business:</strong></p><ul><li>Source adatbázis</li><li>Port: 10020</li><li>DB Name: admin</li></ul><p><strong>Postgres Business:</strong></p><ul><li>Destination adatbázis</li><li>Port: 10030</li><li>DB Name: postgres</li></ul><p>A felhasználónév és jelszó minden adatbázisnál admin/admin123. Az alábbi képen látható egy űrlap kitöltés minta. A Set up source/destination<em> </em>gombbal hozhatjuk létre a kapcsolatot. A destination adatbázist elég egyszer létrehozni, utána újra felhasználhatjuk.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OXoGjYor4xFikZiINuneIw.png" /><figcaption>Adatbázis beállítása</figcaption></figure><p>Miután összekapcsoltuk az adatbázisokat, meg kell adnunk, milyen időközönként szeretnénk futtatni a szinkronizálást. A demóhoz válasszuk a Cron típust és az értéke legyen */1 * * * * ?- innen kimásolva néha hibát okoz. A teszteléshez jó a minél gyakoribb szinkronizálás, valós környezetben ez az igényeknek megfelelően módosítható. A forrásoknál kijelölhetjük, mely táblákat szeretnénk szinkronizálni, illetve kiválaszthatjuk a szinkronizálás módját is. Állítsuk ezt Incremantal Append értékre, így minden szinkronizációs ciklusban csak az új adatok kerülnek másolásra. A Cursor field értéke az elsődleges azonosító legyen — id. Végül a Normalization &amp; Transformation kártyán lehetőségünk van megadni, mi történjen az adatokkal a másolás után. Egyelőre állítsuk nyers adatra. A Normalized tabular data opció megpróbálja visszaállítani az eredeti tábla szerketetét. Ez relációs adatbázisok esetén egész jól működik, dokumentum alapúaknál nem annyira. Később DBT segítségével oldjuk meg a problémát.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*82og-KUMay76YEiuw05q6w.png" /></figure><p>Miután összekötöttük az adatbázisokat, a BI adatbázisban megjelennek az nyers adatokat tartalmazó táblák.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/1*HbyYYgdPF_N_zNjZ3H6GfQ.png" /><figcaption>Nyers adatokat tartalmazó táblák</figcaption></figure><p>A metaadatok mellett az üzleti tábla tartalma JSON objektumként kerül reprezentálásra.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Un_dxvjTJ6QbyfmDJzOxFQ.png" /><figcaption>Exported user data</figcaption></figure><p>Minden szinkronizációs tábla három oszlopot tartalmaz, egy egyedi azonosítót, az adatokat tartalmazó JSONB oszlopot, valamint a szinkronizáció időpontját.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/317/1*ft0U8_hc0GGp3DfLP6Eoxw.png" /><figcaption>Airbyte táblaszerkezet</figcaption></figure><h4>DBT transzformáció</h4><p>Ahhoz, hogy az adatokkal gyorsan és kényelmesen dolgozhassunk, a megfelelő formátumra kell hoznunk őket. Ehhez DBT-t használunk, mellyel a folyamatot automatizálni tudjuk. A szkriptek minden szinkronizáció után lefutnak és transzformálják az adatokat a megadott módon. A demóhoz használt fájlokat <a href="https://github.com/zlaval/data_analytics-plaform/tree/master/transformations/models">itt</a> lehet böngészni.</p><p>A demónak nem célja teljes körű adatbázist felépíteni, illeve a DBT részletes bemutatása sem, de álljon itt pár példa, hogy is néz ki egy transzformáció a gyakorlatban.</p><p>A példában a termékeket árának változását nyers adatként tartalmazó _airbyte_raw_* táblából állítjuk elő a termékek hisztorikus adatait tartalmazó táblát, majd ebből a termékek aktuális állapotát tartalmazó újabb táblát. Végül pedig egy viewt, mely a termékek nevét és a hozzájuk kapcsolódó megrendelések számát tartalmazza.</p><p>A JSONB objektumból kinyerjük a tábla felépítéséhez szükséges adatokat és a megfelelő formátumra alakítjuk azokat. A Postgres rendelkezik <a href="https://www.postgresql.org/docs/current/functions-json.html">beépített funkciókkal</a> JSON objektumok kezeléséhez. <br>A DBT által biztosított is_incremental() makró segítségével megoldhatjuk, hogy csak az újonnan szinkronizált adatok kerüljenek feldolgozásra. A konfigurációs fejlécben pedig felvehetjük a létrehozandó tábla indexeit, megadhatjuk az elsődleges kulcsot, mely segítségével a már létező rekordok nem beszúrásra, hanem frissítésre kerülnek.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40661cd872658580fd648ca15213b6a8/href">https://medium.com/media/40661cd872658580fd648ca15213b6a8/href</a></iframe><p>A következő lépésben a hisztorikus táblából előállítjuk a termékek táblát. Ez a tábla minden termékhez mindig a legfrissebb árat tartalmazza. Mivel a job az adatok inicializálása után - ahol a név is bekerül - csak az azonosítót és az aktuális árat szúrja be, így a nevet meg kell őriznünk, az árból viszont a legutolsó módosításban szereplőt vesszük.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e3a125225288c3a16209f06d969439d/href">https://medium.com/media/6e3a125225288c3a16209f06d969439d/href</a></iframe><p>A termékek és a rendelések - ez a korábban említett csomagban található - táblák után létrehozzuk az eladott termékszámot tartalmazó nézetet is.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/741450fdfc35e41fdf7893dc48cca450/href">https://medium.com/media/741450fdfc35e41fdf7893dc48cca450/href</a></iframe><p>A modellek elkészítése után nincs más dolgunk, mint hozzárendelni a transzformációkat valamelyik kapcsolathoz. Az Airbyte képes publikus Git repositoryból letölteni a DBT projectet és futtatni. A konfiguráció az alábbi példán látható.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yhEMezHqrOcTPiz89LV3SQ.png" /><figcaption>DBT transzformáció beállítása</figcaption></figure><p>Mentés után a következő szinkronizálásnál létrejönnek a leírókban megadott táblák.</p><h4>Metabase</h4><p>Az utolsó lépésben a diagramokat készítjük el. A Metabase a 10000-es porton érhető el. A regisztráció után az adatbázis kapcsolat felépítése következik. Mivel a Metabase és a BI adatbázis közös Docker hálózatba van kapcsolva, így használhatjuk a konténer nevét hálózati címként.</p><p>BI adatbázis kapcsolat paraméterei:</p><ul><li>host: bi-db-pg</li><li>port: 5432</li><li>db name: postgres</li><li>user/pw: admin/admin123</li></ul><p>A kapcsolat felépítése után az adminisztrátor beállításoknál a Data Model tabfülön láthatjuk a használható adatmodeleket, illetve beállíthatjuk a mezők típusát - pl a Products tábla Price mezőjét Currency formátumra, kiválasztva a megfelelő pénznemet, így a diagramokon formázva jelennek meg ezek az adatok. <br>A séma változások automatikusan frissítésre kerülnek bizonyos időközönként, de amennyiben szeretnénk azonnal látni őket, a Databases tabfülön lehetőségünk van manuális szinkronizálásra indítására is.</p><p>Ebben a példában a DBT minden táblát a public sémába készít el. Valós környezetben érdemes csak a megjelenítésre szánt adatokat ide tenni és csak ehhez hozzáférést adni a Matabasenek.</p><p>Kilépve az adminisztrátor felületről, a New gomb segítségével hozhatunk létre új diagramot, vagy diagramokat tartalmazó dashboardot. A diagram létrehozásához használhatjuk a beépített no-code editort - questions - vagy akár SQL-t is. <br>Felmerülhet a kérdés, hogy mi szükség az adatok transzformációjára, ha a Metabase felületén is megírhatnánk a lekérdezéseket. Ennek több oka is van:</p><ul><li>A tisztított, összemásolt adatokkal könnyebb dolgozni.</li><li>Gyorsabbak a lekérdezések, így a diagramok renderelési ideje is rövidebb.</li><li>A jól szervezett adatokkal akár az IT-hoz nem értő kollégák is elkészíthetik a megfelelő dashboardokat.</li></ul><p>Érdemes ezért - amennyiben lehetséges - a szükséges adatokat egy-egy fact táblába összefűzni. Így minden diagram egy táblát használ. Figyelni kell azonban arra, hogy a túloptimalizált adatok is okozhatnak problémát. <br>Erre a korábban létrehozott, termékek eladott darabszámát tartalmazó tábla jó példa, mivel a táblában nem tudunk egy adott időszakra szűrni.</p><p>Hozzuk létre az első diagramot. A Question opcióra kattintva kiválaszthatjuk az adatforrást, majd táblát, amivel dolgozni szeretnénk. Ezután összekapcsolhatjuk a forrás táblát más táblákkal, csoportosíthatjuk az adatokat oszlopok szerint, melyen az SQL-ből ismert műveleteket is elvégezhetjük, ahogy az alábbi képen is látható.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ILzMt7qkpYrHgZEYnahyfw.png" /><figcaption>Termékek árának válzotása</figcaption></figure><p>A Visualize gombra kattintva megjelenik az összeállított lekérdezés eredményét tartalmazó táblázat. Itt további beállításokat is eszközölhetünk.</p><p>Kiválaszthatjuk a diagram típust:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*z8i_TEWhLfP3WoDGGW9jSw.png" /><figcaption>Diagram típusok</figcaption></figure><p>Beállíthatjuk a tengelyeken megjelenítendő oszlopokat, bonthatjuk az adatokat egy kiválasztott oszlop szerint és sok egyéb lehetőség közül választhatunk a diagram személyre szabáshoz. A mentés gombra kattintva pedig véglegesíthetjük őket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ZS7k1orHo6Cp94qt07aDw.png" /><figcaption>Termék árának változása</figcaption></figure><p>Az elkészült diagramok felhasználásával létrehozhatjuk a dashboardjainkat. Itt beállíthatjuk a méretüket és elhelyezkedésüket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JiptOvOghA4KtRlTxOBjfw.png" /><figcaption>Dashboard</figcaption></figure><p>Az SQL opcióra kattintva az SQL editort is használhatjuk diagram létrehozásához. De akár a no-code editorban létrehozott diagram kódját is módosíthatjuk a segítségével.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PqtVT_kQFyWl0LnLV_KORA.png" /><figcaption>Felhasználók összes költése termékenként</figcaption></figure><p>A dashboardokhoz definiálhatunk szűrőket, mely segítségével a felhasználók tovább finomíthatják az megjelenő eredményeket. A diagramok a szűrőkben kiválasztott értékek szerint frissülnek. <br>Figyelni kell arra, hogy míg no-code esetében ezek automatikusan működnek, SQL-nél nekünk kell template változót hozzáadni a lekérdezéshez. Erről <a href="https://www.metabase.com/learn/sql-questions/sql-variables#introduction-to-sql-variables-and-filter-widgets">itt</a> található részletes leírás.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l8x3nIHNgZZc_OVa1Qa50g.png" /><figcaption>Szűrő a terméknevekre</figcaption></figure><p>Az egyes chartokhoz tartozó adatokat akár le is tölthetjük a kiválasztott formátumban.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dwc5042JKp_w96XHoWkqYg.png" /><figcaption>Adatok letöltése</figcaption></figure><p>A dashboardokat ezután beágyazhatjuk a saját alkalmazásunkba. Továbbá lehetőségünk van a Metabase API-n keresztül egyedi linkeket generálni a dashboardokhoz. Így például megoldható, hogy adott tenant, vagy felhasználó csak a saját adatait lássa - fix szűrőt beállítva például a felhasználó azonosítójára, melyet ő nem lát és nem módosíthat, de a dashboard szűrőjét ugyanúgy tudja használni, például dátum, vagy termék azonosítóra. Ennek részletes leírása <a href="https://www.metabase.com/docs/latest/embedding/start">itt</a> található.</p><p>Láthattuk, hogy egész egyszerűen vizualizálhatjuk az üzleti adatokat. Természetesen a teljes környezetet nem szükséges kézzel felépíteni. Minden itt használt alkalmazás elérhető szolgáltatásként is, ahol néhány egyszerű kattintással beállíthatjuk a rendszerünket. Ez az opció gyorsabb, de természetesen költségesebb is.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37222e911f4b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Terraform AWS Infrastructe Step-by-Step Guide 6/6 — Instance Module]]></title>
            <link>https://awstip.com/terraform-aws-infrastructe-step-by-step-guide-6-6-instance-module-6385fa3cf178?source=rss-8af538bf2181------2</link>
            <guid isPermaLink="false">https://medium.com/p/6385fa3cf178</guid>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Zalán Tóth]]></dc:creator>
            <pubDate>Wed, 12 Oct 2022 22:50:03 GMT</pubDate>
            <atom:updated>2022-10-15T15:18:38.829Z</atom:updated>
            <content:encoded><![CDATA[<h3>Terraform AWS Infrastructure Step-by-Step Guide 6/6 — Instance Module</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*qsrz6Ct-gmLgEjLpyyj2hw.png" /></figure><h4>Content</h4><ul><li><a href="https://medium.com/p/7c01e9fd4b14">Overview</a></li><li><a href="https://medium.com/p/4c05c2896d">Terraform Backend</a></li><li><a href="https://medium.com/p/3aabed3f0515">Main Module</a></li><li><a href="https://medium.com/p/59c4e453077">Network Module</a></li><li><a href="https://medium.com/p/6dc90d2d210b">Database Module</a></li><li><strong>Instance Module</strong></li></ul><p>In this article we are going to create the EC2 instances and deploy our application on them.</p><p>Let’s create the module and add the necessary files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*Kwh5HiVH4M9waA5aWk6e1A.png" /></figure><p>We have to define several variables in the variables.tf file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b17b17fe17fa3433075fd04a1def265b/href">https://medium.com/media/b17b17fe17fa3433075fd04a1def265b/href</a></iframe><p>The ssh key comes from the terraform.fvar file and it will be copied to the virtual machines thus we can do ssh login to the instances. <br>The alb object holds the output of the load balancer and its security group from the Network Module. We are going to bind the EC2 instances to this load balancer so it can route traffic towards the application. <br>The SG of the ALB will be assigned to the SG of the application, in this way the ALB will be able to connect to the app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/202/1*ZlLqgRYnpO2MBFfnW2BkjA.png" /></figure><p>The instances will be created in the public networks so we pass the public subnets together with the vpc to the module. The application has to connect to the database as well thus we also hand over the credentials from the Database Module.</p><p>From now on we can setup the module in the root/main.tf and pass over the aforementioned variables.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b9afca661a72f52bb03186009998647/href">https://medium.com/media/6b9afca661a72f52bb03186009998647/href</a></iframe><h4>Main.tf</h4><p>Let’s create the required resources and bind the whole system together.</p><p>We define the <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html">AMI </a>— operating system — for the EC2 instances. The image might differ from this one depends on the region. <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/finding-an-ami.html#finding-an-ami-console">Here</a> is the detailed explanation about the image.<br>We are going to filter to the amzn2 v5.10 image and using the most recent version. The filter name is the name of the field we want to filtering by. In this case we filter by the image name, but we could do it by <a href="https://aws.amazon.com/amazon-linux-ami/">id</a> as well. The values accept a list of regex and returns with all the matching images.<br>A real image name looks like the folowing value.</p><blockquote>amzn2-ami-hvm-2.0.20180810-x86_64-gp2</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3961d091b67fc81074a6229506647ab3/href">https://medium.com/media/3961d091b67fc81074a6229506647ab3/href</a></iframe><p>The next one is the SG. It is similar to the ones we have created earlier but we add a new ingress role for ssh. We will use the default port — 22 — and enable the connection from everywhere. The application will run on port 8080 and accept traffic only from the ALB so the SG of the ALB has to be attached to this security group.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/131d964f7b1e6a3aad904b70cd08a5c5/href">https://medium.com/media/131d964f7b1e6a3aad904b70cd08a5c5/href</a></iframe><p>For routing traffic from the ALB to one of our instance we have to group them together. In this way ALB will be informed if an instance is created or destroyed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*Qfmb1OJ78VNP7JOT_16bLQ.png" /></figure><p>The application will listen on the <em>HTTP 8080</em> port and we also enable the health check on the root path. This path will be provided by the application and it returns HTTP 200 response when the application is up and running.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/17b1c1cbebcf9786274d0b326d799f51/href">https://medium.com/media/17b1c1cbebcf9786274d0b326d799f51/href</a></iframe><p>We can bind the ALB to a TG by adding a listener to it. First we have to select the load balancer which can be done by the <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html"><em>arn</em></a><em> </em>of the ALB. The ALB listen on the port 80 though we can define multiple ports — <em>from_port </em>and <em>to_port </em>ALB properties — and set individual listener for every port. The action is forward so we pass the request towards the TG as is. We could also modify the request, filter it and so on. At last the listener has to be attached to the TG.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a18c4e083dafa292faeb719aac58c86b/href">https://medium.com/media/a18c4e083dafa292faeb719aac58c86b/href</a></iframe><p>Before we create the EC2 resources we are going to create a launch template and attach it to the ASG. It will install the application on startup.</p><p>We are going to deploy a simple <a href="https://go.dev/">go</a> application which connects to the database and provides three urls.</p><ul><li>GET / - for health check</li><li>GET /user - for listing the users from the database</li><li>POST /user - for saving new user</li></ul><p>Let’s define the cloud_config.yaml file.<br>The zip archive contains the plain go source code.<br>It has to be unpacked on the server then compile and run. For this two packages have to be installed — unzip and golang-go. The script will create a new file called config.json and writes the database properties into it. The application will read this file for the connection string and connect to the database. Runcmd executes each commands line by line. First it will download the zip from github then unpack it, build the application and run it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4432b2dca038f1c0075d03b3dac0ce6/href">https://medium.com/media/c4432b2dca038f1c0075d03b3dac0ce6/href</a></iframe><p>Terraform reads the content of the cloud_config.json by the <em>cloudinit_config </em>data structure. In the <em>templatefile </em>method we can pass the path of the file along with the configuration of the database. Configs will be extracted from the <em>db_config </em>variable. This is why we could use the simple names in the <em>connection_string </em>propery of the json file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/12b85ef659947297965fdc783dd76137/href">https://medium.com/media/12b85ef659947297965fdc783dd76137/href</a></iframe><p>The ssh key also has to be created for the instance.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/28fc77b02c5130aabfa5ffed136e1ed0/href">https://medium.com/media/28fc77b02c5130aabfa5ffed136e1ed0/href</a></iframe><p>When new EC2 has to be created the ASG will use a launch template for setting up the instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*8W1FzacZPpnWqHjFO8QchA.png" /></figure><p>The launch template uses the AMI we have created earlier. The instance_type is t2.micro which is in the free tier. We add the ssh key as well together with the application’s cloud config and set the SG. In this way every EC2 instances will be configured in the same way.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2371b5a1d9e22248a8a1d5376432e126/href">https://medium.com/media/2371b5a1d9e22248a8a1d5376432e126/href</a></iframe><p>For instance creation from the template we have to define the ASG.<br>The minimum number of the EC2 instances is 1 and the maximum is 3 thus ASG can create up to 3 instances or downscale to 1 instance. The desired capacity is the default instance count before any scaling events. The instances will be provisioned in the <em>public a</em> and <em>public b</em> subnets, these values come from the Network Module. All instances will be grouped together in the previously created target group so ALB can register the instances and access them.<br>We also set the <em>launch_template </em>for application installation here. <br>By default terraform detects any changes in the manifest files. We can ignore changes using <a href="https://www.terraform.io/language/meta-arguments/lifecycle#ignore_changes">lifecycle methods</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1fe3a02101004285bacc468ca59a06e/href">https://medium.com/media/c1fe3a02101004285bacc468ca59a06e/href</a></iframe><p>The Instance Module is ready for provisioning. It would create two EC2 instances. In real environment load is changing from time to time. We can run as many instance as we need for the highest load, but in the meantime — when the traffic was low — it would burn our balance. We can setup autoscaling to solve this problem.</p><p>First we have to add scaling policy. One for upscaling and another one for downscaling. We attach the ASG to these policies with 30 sec cooldown — it won’t create or destroy any instances after the previous scaling event within the time window, it is useful when we have multiple alarms as the cooldown can prevent overscaling when multiple events come from different sources. Scaling adjusment is the number of instance we want to being created/destroyed on a scaling event. The adjusment type is <em>ChangeInCapacity </em>which mean we add or remove as many instances as we defined in the adjusment property. There are <a href="https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-scaling-simple-step.html#as-scaling-adjustment">multiple options</a> though.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/070f12c46e9046a926cb9ee71b5f21d4/href">https://medium.com/media/070f12c46e9046a926cb9ee71b5f21d4/href</a></iframe><p>Next we have to add metric alarm for monitoring the CPU utilization, set the threshold and execute the scaling policies on alarm/ok events.</p><p>We are going to scale out when the average CPU utilization of the EC2 instances in the ASG is <a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/cloudwatch_metric_alarm#comparison_operator">greater than</a> 80% — for testing purpose you can lower the value. Period is the time in seconds while the system collects and aggregate the data points by the value of the <em>statistic </em>property and then check it using the comparison operator against the threshold and scale up or down the system if necessary. This is a very basic yet working scaling mechanism. As we are monitoring EC2 instances so the namespace is <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/aws-services-cloudwatch-metrics.html">AWS/EC2</a>. You can check the available metrics for EC2 <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/viewing_metrics_with_cloudwatch.html">here</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e60b3f6f903b75891ae8e6ebe09448ef/href">https://medium.com/media/e60b3f6f903b75891ae8e6ebe09448ef/href</a></iframe><p>We have to attach the SG of the instances to the Database`s SG so add it to the outputs.ft file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5a4633ce7cbd454f85c31b84d731ea9/href">https://medium.com/media/d5a4633ce7cbd454f85c31b84d731ea9/href</a></iframe><p>Before provisioning we have to uncomment several line of codes in the root folder and in the Database Module as well.</p><p>Enable the following line in the root/main.tf file under the database section.</p><pre>app_security_group = module.instance.security_group</pre><p>The variables in the Database Module’s variables.tf file.</p><pre>variable &quot;app_security_group&quot; {<br>  type = any<br>}</pre><p>And the security group in themain.tf file of the Database Module under the <em>aws_security_group</em> resource.</p><pre>security_groups = [var.app_security_group.id]</pre><p>Let’s provision the infrastructure and check the resources on the console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YFdQcosU-g6Id2aAhIlJMA.png" /><figcaption>Target Group</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DteAir_6zMRjfrFBc9Ypag.png" /><figcaption>Auto Scaling Group</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jdz_UfvGGtAwYlhNnnJAMA.png" /><figcaption>EC2</figcaption></figure><p>After the instance is created it takes a couple of minutes while go downloads all dependencies and compile the application.</p><p>You can check the DNS name of the ALB on the Load Balancer page of the AWS Console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GeEGsDPb5yJ0qa7dOtguzA.png" /></figure><p>We can also print it to the console using the root/outputs.ft file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed1689a1806e90983fc784fe3c0ccd3c/href">https://medium.com/media/ed1689a1806e90983fc784fe3c0ccd3c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*Jd1BMnh70zt-tYe3ow9MCA.png" /><figcaption>console output</figcaption></figure><p>When everything is up and running we can use the application. <br>I’m gonna use <a href="https://www.postman.com/downloads/">Postman</a> for testing purposes.</p><p>The route path returns with HTTP 200 which means the application is healthy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VhHLrwtvJWffSaW4nUgJKA.png" /></figure><p>We can POST new users using the <em>/user</em> endpoint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oz8jc6rAG5XRT-BotPdXdg.png" /></figure><p>After the users were added the <em>GET /user</em> request retrieves the users from the database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MGHCu7ND0hkOWnlAoCI2BA.png" /></figure><p>We can also login to our EC2 instances from the terminal. You can find the public IP address of the instances on the EC2 console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*7-d2u7N-TAVA4w0sp39sLA.png" /></figure><p>Our journey comes to the end. Thank you for reading.</p><p><a href="https://github.com/zlaval/devops/tree/master/infra/terraform/aws-infra">Infrastructure source code</a>.<br><a href="https://github.com/zlaval/go-rest">Application source code</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6385fa3cf178" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/terraform-aws-infrastructe-step-by-step-guide-6-6-instance-module-6385fa3cf178">Terraform AWS Infrastructe Step-by-Step Guide 6/6 — Instance Module</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Terraform AWS Infrastructe Step-by-Step Guide 5/6 — Database Module]]></title>
            <link>https://awstip.com/terraform-aws-infrastructe-step-by-step-guide-5-6-database-module-6dc90d2d210b?source=rss-8af538bf2181------2</link>
            <guid isPermaLink="false">https://medium.com/p/6dc90d2d210b</guid>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Zalán Tóth]]></dc:creator>
            <pubDate>Wed, 05 Oct 2022 19:44:50 GMT</pubDate>
            <atom:updated>2022-10-12T22:51:14.918Z</atom:updated>
            <content:encoded><![CDATA[<h3>Terraform AWS Infrastructe Step-by-Step Guide 5/6 — Database Module</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*qsrz6Ct-gmLgEjLpyyj2hw.png" /></figure><h4>Content</h4><ul><li><a href="https://medium.com/p/7c01e9fd4b14">Overview</a></li><li><a href="https://zlaval.medium.com/terraform-aws-infrastructe-step-by-step-guide-2-6-backend-4c05c2896d">Terraform Backend</a></li><li><a href="https://zlaval.medium.com/terraform-aws-infrastructe-step-by-step-guide-3-6-main-module-3aabed3f0515">Main Module</a></li><li><a href="https://zlaval.medium.com/terraform-aws-infrastructe-step-by-step-guide-4-6-network-module-59c4e453077">Network Module</a></li><li><strong>Database Module</strong></li><li><a href="https://zlaval.medium.com/terraform-aws-infrastructe-step-by-step-guide-6-6-instance-module-6385fa3cf178">Instance Module</a></li></ul><p>In this article we are going to setup the RDS postgres instance in the private subnets. Let’s take a quick look on the following diagram which depicts the desired result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*sqEFs7PN7wY92i7ZkWRrVQ.png" /></figure><p>We have created the subnets previously but we have to group them together into a database subnet group. We are also going to create a security group for our db instance and provision the database itself.</p><p>Create a new module first with the necassary manifests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*2z6B3USZxtCv4RMtprFz_Q.png" /><figcaption>Module Structure</figcaption></figure><p>Let’s start with the variables.tf file. We will use the <em>namespace</em> and <em>project_name</em> in the same way as we did before but in this module the <em>vpc </em>and <em>subnet</em> variables are also required. These values comes from the output of the Network module. As we don’t want to model the whole vpc object we use the typeany , this is more flexible though not typesafe.</p><p>When we install the application, it has to connect to the database. For this we must connect the EC2 instances’ SG to the SG of the database. Currently the instance module does not exists so comment it out until we implement that module too.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a7f52d1f694d71538f16a694ae18453/href">https://medium.com/media/7a7f52d1f694d71538f16a694ae18453/href</a></iframe><p>The subnet object also comes from the Network module. Only the private subnets are necessery for this module so the public ones are omited.<br>As a reminder here is the <em>subnet </em>output of the Network module.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c60dd08ad6e99a1bbf4f888db06f4e26/href">https://medium.com/media/c60dd08ad6e99a1bbf4f888db06f4e26/href</a></iframe><p>Before we start to build it up, let’s add the module to the main.tf of the root folder. Do not forget to initialize the module using the terraform initcommand.</p><p>We also pass the variables from the network module using the following expression.</p><blockquote>module.&lt;module_name&gt;.&lt;output_variable&gt;</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/99062a4dd9f464b5b16a9d83f75cf1d4/href">https://medium.com/media/99062a4dd9f464b5b16a9d83f75cf1d4/href</a></iframe><p>We are gonna continue with the main.ft in the Database module.</p><p>The database requires username, database name and password. The first two are static so we define them in a local variable. The password will be created by the <em>random </em>provider (check the <em>required_providers </em>property in the versions.ft file). For the sake of simiplicity the password won’t contain special chars.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3392a3c564ee128a9e0cc499868a96c/href">https://medium.com/media/f3392a3c564ee128a9e0cc499868a96c/href</a></iframe><p>As we have discussed the database subnet group is mandatory. The subnet group has to have subnets at least from two AZs. RDS will automatically choose subnet (and IP) from the group. <br>In this tutorial we are going to create a simple db instance but we could provision multiAZ database and read replicas as well. <br>Read replicas can help us to balance the read queries across the instances and unburdens the master instance. This is vital for read heavy systems under stress. In this case all writes still go to the master instance and data are replicated asynchronously across the read instances. <br>MultiAZ replica is a synchronous standby instance. If the master instance becomes unavailable AWS automatically update the DNS record to point to the standby instance instead of the current master and promote it as the new master. We can use this for building highly available, fault tolerant systems. I’m gonna write about it in detail later.</p><p>Back to the db subnet group. We add the two private subnets to it and use the namespace and project_name concatenated with the -group postfix as resource name.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c65bb8fe12bb6aafd34e59c832a9135/href">https://medium.com/media/0c65bb8fe12bb6aafd34e59c832a9135/href</a></iframe><p>Next we create the SG. It is almost the same as the one we created for the load balancer but instead of the <em>cidr_blocks </em>property, we use security_group. This means we only accept traffic from the specified SG — in our case the application will be protect by the <em>app_security_group</em>, so the db will only accept traffic from there — on the port 5432, which is the default port of PostgreSQL.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ada2357e1c395b6ff37def4ac488048/href">https://medium.com/media/1ada2357e1c395b6ff37def4ac488048/href</a></iframe><p>At last we create the DB. We are going to use db.t2.micro <a href="https://instances.vantage.sh/rds/?region=eu-central-1">instance</a>. This is free tier eligible. The maximum <a href="https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Concepts.DBInstanceClass.html#Concepts.DBInstanceClass.Support">engine version</a> depends on the instance type but we can set the <em>allow_majon_version_update </em>propery for automatic patch installation. Ten Gb storage will be allocated, this is enugh for a smaller production ready system. We use the predefined local variables for username and db_name and <em>random </em>for password.<br>We set the subnet group and SG properties as well, then switch off the multiAZ replication and set the <em>skip_final_snapshot </em>to true. This should be false on a real system as it will create a backup on DB deletion. The last property is the <em>backup_retention_period</em>. We do not want to retain backups so set it to zero day.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74d9ea4e5db28e08028d2c4a2d532ccd/href">https://medium.com/media/74d9ea4e5db28e08028d2c4a2d532ccd/href</a></iframe><p>Before the provision, let’s fill up the outputs.tf file. We need some output values from the DB so we map them into the db config variable and we will use them for connecting the application to this DB instance.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b737407fedc22f5503a3f6e8962f126/href">https://medium.com/media/7b737407fedc22f5503a3f6e8962f126/href</a></iframe><p>Optionally you can add the db config to the root/outputs.tf , this will print the values to the console.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6651de8d57747cc33310ecafde4c0c00/href">https://medium.com/media/6651de8d57747cc33310ecafde4c0c00/href</a></iframe><p>Sensitive marks the output as protected data and hide it.</p><p>Now the RDS instance can be provisioned. After it finishes, check the AWS console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DjmKy2z2BmCoOyIsqjQiYA.png" /><figcaption>RDS/Databases</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gD5K46b5e_SJK0Ui42MwlQ.png" /><figcaption>Subnet Group</figcaption></figure><p>The database is in the private subnet so we cannot connect to it but the application can. Sometimes of course we have to check the db, for this there is a loophole called <a href="https://aws.amazon.com/quickstart/architecture/linux-bastion/">Bastion</a> server.</p><p>In the last article we are going to create the EC2 instances, setup auto scaling, bind it to the ALB, install the application and test the system.</p><p><a href="https://github.com/zlaval/devops/tree/master/infra/terraform/aws-infra">Source Code</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6dc90d2d210b" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/terraform-aws-infrastructe-step-by-step-guide-5-6-database-module-6dc90d2d210b">Terraform AWS Infrastructe Step-by-Step Guide 5/6 — Database Module</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Terraform AWS Infrastructe Step-by-Step Guide 4/6 - Network Module]]></title>
            <link>https://awstip.com/terraform-aws-infrastructe-step-by-step-guide-4-6-network-module-59c4e453077?source=rss-8af538bf2181------2</link>
            <guid isPermaLink="false">https://medium.com/p/59c4e453077</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Zalán Tóth]]></dc:creator>
            <pubDate>Sun, 02 Oct 2022 21:06:56 GMT</pubDate>
            <atom:updated>2022-10-12T22:51:04.840Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*qsrz6Ct-gmLgEjLpyyj2hw.png" /></figure><h4>Content</h4><ul><li><a href="https://zlaval.medium.com/terraform-aws-infrastructe-step-by-step-guide-1-5-overview-7c01e9fd4b14">Overview</a></li><li><a href="https://zlaval.medium.com/terraform-aws-infrastructe-step-by-step-guide-2-6-backend-4c05c2896d">Terraform Backend</a></li><li><a href="https://zlaval.medium.com/terraform-aws-infrastructe-step-by-step-guide-3-6-main-module-3aabed3f0515">Main Module</a></li><li><strong>Network Module</strong></li><li><a href="https://zlaval.medium.com/terraform-aws-infrastructe-step-by-step-guide-5-6-database-module-6dc90d2d210b">Database Module</a></li><li><a href="https://zlaval.medium.com/terraform-aws-infrastructe-step-by-step-guide-6-6-instance-module-6385fa3cf178">Instance Module</a></li></ul><p>In this section we are going to create the Network module and provisioning it to AWS.</p><p>Before start, here is a quick reminder about the infrastructure state we would like to achieve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*b2iyjt-gmQKROWQf5d3VQA.jpeg" /><figcaption>Network Module</figcaption></figure><h4>Network</h4><p>AWS automatically creates default VPC for our account in every regions together with Internet Gateway, Routing Table, Network ACL and a Public Subnet in every Availibility Zones. <br>We are gonna use this VPC along with the afforomentioned resources except the subnets but we will also create new instances from most of them for the private subnets.</p><p>In the network folder we have to create three new files for the variables, outputs and resources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*KAK8kmO0Yz6Wq5a2MvlcHw.png" /><figcaption>modules/network</figcaption></figure><p>Two variables are defined in the variables.tf file.<br>The namespace and the project name whose will be used as prefix of the resources’ name.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05da7463048da34f6d407ad983fe670a/href">https://medium.com/media/05da7463048da34f6d407ad983fe670a/href</a></iframe><p>These variables come from the main module as parameters. Check main.tf in the root module:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/078c317a6496355bda3c3623e7fb7cf4/href">https://medium.com/media/078c317a6496355bda3c3623e7fb7cf4/href</a></iframe><p>Next we are working on the module/network/main.tf. This file contains the resources.</p><p>First we create 2 public and 2 private subnets in the default VPC. We are going to add EC2 instances into the public and Database into the private ones. The CIDR block of the default VPC is <em>172.31.0.0/16. </em>This means we can use 65536 ip addresses (minus the reserved ones) for our services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*7Tr7mbuaHVsnFyo1kC_BFA.png" /><figcaption>Default VPC</figcaption></figure><p>There has already been three subnets created by AWS automatically. Each contains 4096 ip addresses. We won’t use these so they stay untouched but new subnets will be created for our services</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rGMiCpH6FaE2ecQ1Oq2kOw.png" /><figcaption>Default Subnets</figcaption></figure><p>The last CIDR block of the default subnets is 172.31.32.0/20 which means the last used IP is 172.31.47.255. so we can start our subnets from 172.31.48.0. <br>As we dont want to create many EC2 instances, we are going to use /24 range which contains 256 ip addresses. <br>The /24 means how many digits (binary) will be used as network identifier. An IPv4 address is built from 32 bits (four octets: 00000000.00000000.00000000.00000000) we can calculate the number of hosts using the following method:</p><blockquote>host bit count = ipv4 bit count - network identifier length</blockquote><p>For example if we use /24 mask then 32–24 = 8, so we have 8 bits for the hosts. The biggest binary number we can represent on 8 bits is 11111111 which is 255 in decimal number system plus the 0. <br>This topic would worth another article and there is an easier way from IP range calculation, which is using <a href="https://www.ipaddressguide.com/cidr">ipaddressguide</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KBg6O00uU2rBFz6Y3bDpDA.png" /><figcaption>Last IP of the predefined subnet in the default VPC</figcaption></figure><p>As we saw our range has 256 IP, but we can use only 251 due to the AWS reservations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CdeheK-MDoAY2IT0BUOZ-w.png" /><figcaption>IP addresses for the first /24 subnet</figcaption></figure><p>Let’s create a local variable from the requested IP addresses. Local variables are the nice way for defining variables used only in the particular file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4b0a7769ef8944166a21ab5ad3ce89c/href">https://medium.com/media/f4b0a7769ef8944166a21ab5ad3ce89c/href</a></iframe><p>As we talked about previously the subnets are being created in the default VPC and we also would like to place each pair into separate AZs. For this we have to retrieve the VPC data and the current region. <br>The two type we use through this tutorial are</p><ul><li><em>resource: </em>creates the defined resources</li><li><em>data: </em>retrieves data from the provider</li></ul><p>Every resource has 2 properties, the type — like aws_default_vpc — and the name — like default .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*tWqCdER7MdYjLwwfex2Pwg.png" /></figure><p>The <a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs">documentation</a> contains all available types. The names is up to use but it will be used to reference to the given resource within the module.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3192743963004188573e04d7756183f/href">https://medium.com/media/f3192743963004188573e04d7756183f/href</a></iframe><ul><li><a href="https://registry.terraform.io/providers/hashicorp/aws/4.22.0/docs/resources/default_vpc">aws_default_vpc</a> is a special kind of resource as it does not create VPC but retrieves the default one. It also won’t delete the VPC on destroy.</li><li><a href="https://registry.terraform.io/providers/hashicorp/aws/4.22.0/docs/data-sources/region">aws_region</a> returns with the current region.</li></ul><p>Next the four subnets will be created. The AZ names come from the region name and we concatenate the zone id (mostly <em>a</em>, <em>b</em> and <em>c</em> but check the region you are using). Map a public IP on launch has to be true for the public subnets but not for the private ones. With the help of this public IP will be assigned to all the launched EC2 instances automatically so we can ssh into the these VMs.<br>Advanced Terraform structures — like loops — could be used here but I would like to keep this tutorial simple therefor let’s discuss these advanced features in a separate article.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6778a0275e2b76bd0ead20baa6efff3e/href">https://medium.com/media/6778a0275e2b76bd0ead20baa6efff3e/href</a></iframe><p>Next we have to associate the subnets with the corresponding routing table. For the public subnets we use the default routing table. We can retrieve it from the vpc resource using the aws_default_vpc.default.idexpression.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*8nc3FEfa46xhL7CLeMidRg.png" /></figure><p>We are also going to create a new routing table for private subnets so those cannot connect to the internet as there is no attached Internet Gateway on this one. For security reason it is always wise decision to place the applications into private subnets.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e377a99e363af555d8939622e9a8641b/href">https://medium.com/media/e377a99e363af555d8939622e9a8641b/href</a></iframe><p>We can provision the subnets. A quick reminder here about the necessary steps. Please make sure you are logged into the <em>aws-vault</em>. <br>Every modules have to be initialized before provisioning. Use the terraform init command in the root folder, this is required at the first time and for every new module added later on. Next we can validate the<em> </em><em>*.tf</em> files, it can be done by the terraform validate command. Then terraform plan does dry-run and print the results. If everything is fine we can do the provisioning using the terraform apply command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UdfDMu6Iq-EZBTxN07yGoQ.png" /></figure><p>After a few seconds we can check the result on the aws console. Under the <em>Subnets </em>section we should see the subnets…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4hE0XdHiV1xcEfXw0IWJZQ.png" /></figure><p>…and the routing tables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pKsn013uomKazRidp50NCQ.png" /></figure><p>The public routing table contains the<em> igw </em>target which is the Internet Gateway so from subnets connected to this RT resources have internet access.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qEk-ksj70lWJd944MKvrlg.png" /></figure><p>But in the private ones resources cannot access to the internet. If we want them to connect to the internet — for example our services need updates — we have to setup NAT gateway.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AJw4jmaZXtohkV2qGq-k3w.png" /></figure><p>At last, before we are moving towards the database setup section, let’s create the Application Load Balancer. We could also secure it with WAF which is advisable but it is out of free tier so I’ll write about it in a separate article.</p><p>ALB routes the traffic from the internet to our EC2 instances. Right now we just create the ALB resource and it’s security group and we are going to attach the application to it in the Instance module.</p><p>Security group acts like a firewall, we can restrict the incoming (ingress) and outgoing (egress) traffic. <br>Ingress accept traffic on the range start from <em>from_port </em>and end with <em>to_port.</em> Only the default http port will be used so set both of them to 80. The protocol is tcp and we set <em>cidr_blocks </em>to 0.0.0.0/0 , which means it accepts traffic from any IP. We could restrict the incoming traffic to specific IP ranges. In that case all requests out of the range would be rejected. The <em>self </em>property is false as we dont need to accept traffic from this the SG itself.<br>All egress rules are set to zero which permits all outgoing traffic (default).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/92db38038f0424fcbbf4997f2bebe1e3/href">https://medium.com/media/92db38038f0424fcbbf4997f2bebe1e3/href</a></iframe><p>We create load balancer resource as well. It’s <em>type </em>is application (<a href="https://www.wikiwand.com/en/OSI_model">OSI 7</a>) as we use http. ALB has to be public as we would like to access it from the internet so set <em>internal </em>to false and define the subnets for it. We have created two subnets for our application, let’s add these to the ALB as our EC2 instances will be created in the public subnets. <br>Finally we attach the security group to the load balancer.</p><p>We have to use some of the output data of this module in the Database and Instance modules thus we need to add them to the outputs.tf file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e30b859cbf3cbbb615e64be7d15db25/href">https://medium.com/media/3e30b859cbf3cbbb615e64be7d15db25/href</a></iframe><p>Outputs have <em>value </em>property. It can be a single one or a structure. We can assign value for a variable using the resource type and it’s name. Every resources provided by aws provider has output values. For example we could retrieve the id of the vpc using the aws_default_vpc.default.id expression as we will do it in the next chapter. All output values are well <a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/vpc#attributes-reference">documented</a>.</p><p>Let’s apply the current state using terraform apply command again and check the result on the aws console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QQ8H7_tmgV30927yek3K7g.png" /></figure><p>Go to the Load Balancers screen (use the search field on the top of the screen). There have been one load balancer and we can use it’s DNS name to access to it. We haven’t defined any listener until now so it will deny any attempt to connect but when we will have the installed applications we can send requests to those instances through this URL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7CFQ_ITvIK1QkW0LlcGNjA.png" /></figure><p>In the next article we are going to setup the database in the private subnet.</p><p><a href="https://github.com/zlaval/devops/tree/master/infra/terraform/aws-infra">Source Code</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59c4e453077" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/terraform-aws-infrastructe-step-by-step-guide-4-6-network-module-59c4e453077">Terraform AWS Infrastructe Step-by-Step Guide 4/6 - Network Module</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Terraform AWS Infrastructe Step-by-Step Guide 3/6 — Main Module]]></title>
            <link>https://awstip.com/terraform-aws-infrastructe-step-by-step-guide-3-6-main-module-3aabed3f0515?source=rss-8af538bf2181------2</link>
            <guid isPermaLink="false">https://medium.com/p/3aabed3f0515</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[infrastructure]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Zalán Tóth]]></dc:creator>
            <pubDate>Fri, 30 Sep 2022 22:18:13 GMT</pubDate>
            <atom:updated>2022-10-12T22:50:52.090Z</atom:updated>
            <content:encoded><![CDATA[<h3>Terraform AWS Infrastructe Step-by-Step Guide 3/6 — Main Module</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*qsrz6Ct-gmLgEjLpyyj2hw.png" /></figure><h3>Content</h3><ul><li><a href="https://medium.com/p/7c01e9fd4b14">Overview</a></li><li><a href="https://zlaval.medium.com/terraform-aws-infrastructe-step-by-step-guide-2-6-backend-4c05c2896d">Terraform Backend</a></li><li><strong>Main Module</strong></li><li><a href="https://zlaval.medium.com/terraform-aws-infrastructe-step-by-step-guide-4-6-network-module-59c4e453077">Network Module</a></li><li><a href="https://zlaval.medium.com/terraform-aws-infrastructe-step-by-step-guide-5-6-database-module-6dc90d2d210b">Database Module</a></li><li><a href="https://zlaval.medium.com/terraform-aws-infrastructe-step-by-step-guide-6-6-instance-module-6385fa3cf178">Instance Module</a></li></ul><p>In this article we are going to discuss the module system of Terraform and create the main module.</p><p>We can use modules for logical grouping of the resources as well as for extracting the repetative parts of the infrastructure.</p><p>Modules can accept input parameters and returns with output variables — like resource id, ip addresses and so on — which we can use in another modules. <br>For example, for database provisioning we have to pass the subnet from the network module to the database module. We use the root module to get the output variables from one module and pass them to another one as input variable. <br>Let’s see an example now and we will talk about it later in details.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c384b24208baba53fda93dbb17aaf04a/href">https://medium.com/media/c384b24208baba53fda93dbb17aaf04a/href</a></iframe><p>We can declare circular dependencies between modules — but not between individual resources — as Terraform is able to build up a dependency tree from the resources and deploy them in the right order.</p><p>Each module contains multiple resources connected to each other logically. The Network module contains the vpc, route table, subnet… definitions while the Instance module has target group, security group, launch template…</p><p>Let’s see how our modules are connected to each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*NQqbX0KsegFoUr5iWorSVA.png" /></figure><p>Database and Instance modules depend on the Network module as they have to be created in a specific subnet. Database module needs the security group from Instance module so it can add the SG of the EC2 instances to its own SG and accept traffic from those virtual machines. The application runs inside the EC2 instance also need the database configuration — <em>url, user, password </em>— from the Database module.</p><p>Now as we discussed the basics of the modules, let’s start to implement the Root module. <br>First we have to create the folder structure and 6 files as you can see it on the picture below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*dtbMR0W-sCrYEvKX2sCtPA.png" /><figcaption>Folder structure</figcaption></figure><p>The first one is the providers.ft . This file defines the used providers and common data — like tags — for every resources. We also declare the desired region here. The value comes from the variables file as we will see it later on. We only use the <em>aws </em>provider in this tutorial but for multicloud system further records can be added.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cbdb6f42837c630ee2c4987f4646ed2e/href">https://medium.com/media/cbdb6f42837c630ee2c4987f4646ed2e/href</a></iframe><p>The variables.tf file is a collection of data we would like to use to define … variables. We will use these values multiple time in this project. Terraform automatically set the values from the tfvars but we can also declare default value used in case of a missing properly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/786a6dab4b5bd4973d5b79df9a4c1fc8/href">https://medium.com/media/786a6dab4b5bd4973d5b79df9a4c1fc8/href</a></iframe><p>The <em>region </em>variable is used for defining the aws region. This is where we would like to provisioning our resources. The <em>namespace </em>is used for logical separation of the resources, like dev environment, qa and so on. The <em>ssh_key </em>is a private key — by default from the .ssh folder. We are going to copy it to the EC2 instances thus we can login to the virtual machines.</p><p>The terraform.tfvars defines the values of the variables. As a rule of thumb this file should not be under version control so we can use it for sensitive data. I recommend to create a template file from it under the version control, in that way individual developers can easily create their own version.<br>Please replace the ssh_key’s value with your own public ssh key.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a3723a2c72d9493389a63deb4da6004/href">https://medium.com/media/8a3723a2c72d9493389a63deb4da6004/href</a></iframe><p>In the versions.tffile we describe the required terraform version, the backend — DynamoDB table and S3 storage — we setup earlier and the necessery dependencies.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/19bf0aa257bfcb3820c3debab039947b/href">https://medium.com/media/19bf0aa257bfcb3820c3debab039947b/href</a></iframe><p>We are going to use <em>cloudinit </em>to deploy a very basic CRUD application to the EC2 instances and the <em>random </em>provider for generating random password to the database.</p><p>The next one is the output.tf. The main module will print these values for us when we apply the infrastucture. Let’s just add an output from Network module as that will be the first module we can provisioning.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43047f4230c0a9b5558e582fa46ffa4e/href">https://medium.com/media/43047f4230c0a9b5558e582fa46ffa4e/href</a></iframe><p>At last main.tf links the modules together. Pass the variables to them and holds their ourputs. We add the network module at this time and extend this file later as modules will have been created.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d60204688ec2f45e452907230473846/href">https://medium.com/media/9d60204688ec2f45e452907230473846/href</a></iframe><p>The <em>source </em>is the relative path of the module to the main.tf file and two variables are passed to this one. We are going to define these variables in the variables.tf file of the module.</p><p>In the next article we are going to create and deploy the Network module.</p><p><a href="https://github.com/zlaval/devops/tree/master/infra/terraform/aws-infra">Source Code</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3aabed3f0515" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/terraform-aws-infrastructe-step-by-step-guide-3-6-main-module-3aabed3f0515">Terraform AWS Infrastructe Step-by-Step Guide 3/6 — Main Module</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Terraform AWS Infrastructe Step-by-Step Guide 2/6 - Backend]]></title>
            <link>https://awstip.com/terraform-aws-infrastructe-step-by-step-guide-2-6-backend-4c05c2896d?source=rss-8af538bf2181------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c05c2896d</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Zalán Tóth]]></dc:creator>
            <pubDate>Wed, 28 Sep 2022 18:00:02 GMT</pubDate>
            <atom:updated>2022-10-12T22:50:36.264Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*qsrz6Ct-gmLgEjLpyyj2hw.png" /></figure><h4>Content</h4><ul><li><a href="https://medium.com/p/7c01e9fd4b14">Overview</a></li><li><strong>Terraform Backend</strong></li><li><a href="https://zlaval.medium.com/terraform-aws-infrastructe-step-by-step-guide-3-6-main-module-3aabed3f0515">Main Module</a></li><li><a href="https://zlaval.medium.com/terraform-aws-infrastructe-step-by-step-guide-4-6-network-module-59c4e453077">Network Module</a></li><li><a href="https://zlaval.medium.com/terraform-aws-infrastructe-step-by-step-guide-5-6-database-module-6dc90d2d210b">Database Module</a></li><li><a href="https://zlaval.medium.com/terraform-aws-infrastructe-step-by-step-guide-6-6-instance-module-6385fa3cf178">Instance Module</a></li></ul><p>In this article we are going to setup the Terraform backend for state management.</p><h4>Terraform Backend</h4><p>Terraform persists the current state of the infrastructure using the terraform.tfstate file. It is good practice to save this file into a shared storage so multiple team member can safetely work on the same terraform codebase.<br>We are going to setup S3 bucket and save this file there. DynamoDB table will also be created for locking the state file. Without locking, multiple developers could provision the infrastructure at the same time, which would result in invalid state and could do serious damage in the infrastructure. The DynamoDB table must contain a string field named LockID. Terraform writes this field to acquire the lock. While a process holds the lock, any other attemption to acquire it will fail thus only one person can apply the changes at the same time.</p><p>Worth to mention the <a href="https://cloud.hashicorp.com/products/terraform">Terraform Cloud</a> service which can handle this for us automatically.</p><p>Let’s create a folder for the backend and a file in it called main.tf. I’m using the <em>eu-central-1</em> AWS region but feel free to pick one fits you better.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0d7021b7605f21327a0961145cf07bd/href">https://medium.com/media/b0d7021b7605f21327a0961145cf07bd/href</a></iframe><p>First we have to define the <em>aws</em> provider. Terraform supports <a href="https://registry.terraform.io/browse/providers">multiple providers</a> for different type of infrastructures like Azure, GCP, Kubernetes and so on.</p><p>Then we add a private S3 bucket and set the <em>force destroy</em> option to true thus Terraform can delete the bucket on destroy even if it contains files. After this we enable bucket versioning for preserving the state history. Also block all public access for the S3 bucket for security reasons.</p><p>At last we create the aforementioned DynamoDB table. The hash key is <em>LockID </em>as we discussed it before. Its type is string and we set the read and write capacity as well. The table has two modes, <em>On-demand </em>and <em>Provisioned </em>(default). Provisioned is free-tier eligible but for this we have to set the capacity properties. In sloppy language one unit of read means 4Kb/s and write means 1Kb/s.</p><p>I’m trying to keep the infrastructure in the free tier so we won’t encrypt the state file, although in production environments it is strongly recommended. All the information for this is available in the <a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/s3_bucket_server_side_encryption_configuration">documentation</a>.</p><p>Let’s provision the backend. Open a terminal in the main file’s folder. Before the apply we have to login into the AWS account.</p><blockquote>aws-vault exec [username] --duration=12h</blockquote><p>or if you use Windows</p><blockquote>aws-vault exec [username] --duration=12h -- cmd.exe</blockquote><p>Terraform has to download the provider library so the next command is</p><blockquote>terraform init</blockquote><p>The output should be similar as you can see on the following picture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FUJu-UtyKuaWMvq5Dc9tcA.png" /><figcaption>terraform init</figcaption></figure><p>We can also validate the terraform maifest using the terraform validate command and dry-run it with the terraform plan command.</p><p>If everything is fine, let’s run the</p><blockquote>terraform apply</blockquote><p>command. This will provision the backend on AWS after we say yes to the plan.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n1HBL_qIvqgM1O6hjKm6Pw.png" /><figcaption>terraform apply</figcaption></figure><p>After the provisioning is finished, check the AWS dashboard.<br>On the S3 page we should see the provisioned bucket…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ECXKL2nh6SBJHbB-PlgzRw.png" /><figcaption>S3/Buckets</figcaption></figure><p>… and the table on the DynamoDB page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x4v1Okfq4Ga1jDWF_5SGDg.png" /><figcaption>DynamoDB/Tables</figcaption></figure><p>If you would like to remove the resources, you can use the following command.</p><blockquote>terraform destroy</blockquote><p>This will completely remove all provisioned resources although we are going to use them for the infrastructure automation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LOF-yN5_DRJoTSp54h9o8A.png" /><figcaption>terraform destroy</figcaption></figure><p>In the next article we are going to create the main module of the infrastructure.</p><p><a href="https://github.com/zlaval/devops/tree/master/infra/terraform/aws-backend">Source Code</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c05c2896d" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/terraform-aws-infrastructe-step-by-step-guide-2-6-backend-4c05c2896d">Terraform AWS Infrastructe Step-by-Step Guide 2/6 - Backend</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Terraform AWS Infrastructe Step-by-Step Guide 1/6 - Overview]]></title>
            <link>https://awstip.com/terraform-aws-infrastructe-step-by-step-guide-1-5-overview-7c01e9fd4b14?source=rss-8af538bf2181------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c01e9fd4b14</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Zalán Tóth]]></dc:creator>
            <pubDate>Sun, 25 Sep 2022 17:41:14 GMT</pubDate>
            <atom:updated>2022-10-12T22:50:22.679Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*qsrz6Ct-gmLgEjLpyyj2hw.png" /></figure><h4>Content</h4><ul><li><strong>Overview</strong></li><li><a href="https://zlaval.medium.com/terraform-aws-infrastructe-step-by-step-guide-2-6-backend-4c05c2896d">Terraform Backend</a></li><li><a href="https://zlaval.medium.com/terraform-aws-infrastructe-step-by-step-guide-3-6-main-module-3aabed3f0515">Main Module</a></li><li><a href="https://zlaval.medium.com/terraform-aws-infrastructe-step-by-step-guide-4-6-network-module-59c4e453077">Network Module</a></li><li><a href="https://zlaval.medium.com/terraform-aws-infrastructe-step-by-step-guide-5-6-database-module-6dc90d2d210b">Database Module</a></li><li><a href="https://zlaval.medium.com/terraform-aws-infrastructe-step-by-step-guide-6-6-instance-module-6385fa3cf178">Instance Module</a></li></ul><h4>Introduction</h4><p><a href="https://portal.aws.amazon.com/billing/signup?nc2=h_ct&amp;src=header_signup&amp;redirect_url=https%3A%2F%2Faws.amazon.com%2Fregistration-confirmation#/start/email">AWS</a> has many services and it is not easy to learn the whole concept off the top of ones head. In this article we are going to set up AWS infrastructure from scratch using Terraform infrastructure automation tool and we will deploy a simple CRUD application for testing purpose.</p><p><a href="https://www.terraform.io/">Terraform</a> is an infrastructure as code (IaC) tool. With the help of it we can managing, versioning and provisioning infrastructure though code. There are many other adventages like repetable (on other accounts or in different regions) and automatic provisioning (using ci/cd pipelines)</p><p>Most of the aws services we are using through this tutorial are available in the free-tier others will be signed so you can skip those.</p><p>Let’s take a look at the required resources we have to create.</p><ul><li>Virtual Private Cloud (VPC)</li><li>Internet Gateway</li><li>Public and Private Subnets</li><li>Routing Tables</li><li>Network ACL (NACL)</li><li>Security Groups (SG)</li><li>Database in the Private Subnet</li><li>Application Load Balancer (ALB)</li><li>Auto Scaling Group (ASG) for EC2</li><li>Launch Template for EC2</li><li>Target Group (TG) for the ALB</li><li>Web Application Firewall (WAF)</li><li>Simple Web Application</li></ul><p>We can use different AWS services to achieve the same or similar infrastructure, like Elastic Beanstalk, ECS, EKS. These services make the infrastructure setup easier but it is always good to know what happens in the background.</p><h4>Infrastructure overview</h4><p>Before we tear down the infrastructure apart and explain every resources and their connections in detail, let’s see the whole as one. We are gonna provision our EC2 instances into the public subnet for the sake of simplicity but real one should have been provisioned into the private subnet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*T8Qf1vai09S9a6vr_vWuag.jpeg" /><figcaption>Infrastructure</figcaption></figure><p><strong>Network module</strong></p><p>VPC is an isolated private virtual network hosted by the cloud provider (in this case by Amazon). All of our resources will be created within a VPC.</p><p>AWS hosts servers in multiple geographic locations - like us-east-1, eu-central-1 - called <a href="https://aws.amazon.com/about-aws/global-infrastructure/regions_az/">Region</a> and each Region is splitted up to multiple isolated locations, like eu-central-1a, eu-central-1b, called Availability Zone (AZ). In this article I’m using eu-central-1 but feel free to choose the closest one to you.</p><p>Subnet is a range of IP addresses in the VPC, we can create the necessary resources in subnets. Every subnet associated to an AZ and has route table (default if not defined explicitely), we are going to create one with internet connection for the public subnets and another one for our private network. Private network does not have internet access by default. Public network is going to route the outgoing traffic towards the Internet Gateway which connects the VPC to the Internet.<br>NACL provides a layer of security for the subnet. We can define inbound and outbound rules for the associated subnets.</p><p>ALB distributes the traffic across EC2 instances grouped by the defined TG.<br>The load balancer is guarded by a Security Group where we can define ingress and egress rules. We will also create WAF for filtering out the malicious incoming traffic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*b2iyjt-gmQKROWQf5d3VQA.jpeg" /><figcaption>Network Module</figcaption></figure><p><strong>Database module</strong></p><p>This layer contains PostgreSQL database protected by SG. The SG will accept traffic only from the Service Layer on the database’s port.</p><p>AWS supports MultiAZ databases and Read Replicas.<br>In the first case, RDS automatically creates synchronous standby replica(s) from the master DB in different AZs and in case of failure all call automatically goes towards one of the standby instance. This is done by DNS record update so the given domain name points to the working database.<br>Read Replicas are asynchronius read only databases. We can use these instances to distribute the loads and unburden the primary database. All write still goes to the master instance and the data is replicated through the read replicas after it, therefore there can be some latency while the data will be available on read replicas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*0Lk5HYbs_fgq7M5JDmUTcg.jpeg" /><figcaption>Database Module</figcaption></figure><p><strong>Server module</strong></p><p>In this module we are going to setup Launch Template and Auto Scaling Group. ASG will create EC2 instances using the afforementioned template. We’ll also create auto scaling policy for the ASG which monitoring the CPU usage of the EC2 instances and scale out or scale down depending on the given threshold. The instances will be protected by SG which accept traffic only from the ALB. All instances will be grouped into a TG and we are going to create a listener for ALB which routes the traffic to this TG.<br>At last we will deploy a simple CRUD application with the help of Cloud Init Terraform provider.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*MWeG2aI3E9nAHXU05ooMzQ.jpeg" /><figcaption>Server Module</figcaption></figure><h4>Setup AWS account and deployer IAM user</h4><p>First we have to create an <a href="https://portal.aws.amazon.com/billing/signup?nc2=h_ct&amp;src=header_signup&amp;redirect_url=https%3A%2F%2Faws.amazon.com%2Fregistration-confirmation#/start/email">AWS account</a> and add an IAM user which we can use for provisioning the infrastructure. We can do it on the <a href="https://us-east-1.console.aws.amazon.com/iamv2/home?region=us-east-1#/users">IAM page</a> using the Add user button, filling the name and selecting the Access key credential type (and also the password if you want to login with the user as well). Then Press the next button</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hoe5f6BE-_cNpBFN8z4HWg.png" /></figure><p>For the sake of simplicity we add Admin permission for this user and we won’t enable the Multi Factor Authentication at this time. Let’s click on the Create group button, type the name, for example Admin, and select the AdministratorAccess policy. After the group has been created, select it and go to the next page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JBKBKHG6bQOvbw5CPt5X4Q.png" /></figure><p>We do not need anything else right now, so click on the Next button and press the Create user on the next page. Save the Access key ID and the Secret access key, as we need those for authentication setup.</p><p>Next we have to setup the <a href="https://github.com/99designs/aws-vault">aws-vault</a> so terraform can use the credentials for accessing to aws services. After the installation, use the aws-vault add [username] command. It will ask for the access key id and secret access key.<br>When the setup is completed we can use the following command to login.</p><blockquote>aws-vault exec [username] --duration=12h</blockquote><p>You can read more about AWS provider and authentication on this <a href="https://spacelift.io/blog/terraform-aws-provider">link</a>.</p><p>Download <a href="https://www.terraform.io/downloads">Terraform </a>and we are ready for writing our terraform manifests.</p><p><a href="https://github.com/zlaval/devops/tree/master/infra/terraform/aws-infra">Source Code</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c01e9fd4b14" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/terraform-aws-infrastructe-step-by-step-guide-1-5-overview-7c01e9fd4b14">Terraform AWS Infrastructe Step-by-Step Guide 1/6 - Overview</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hitchhiker’s guide to Java Optional]]></title>
            <link>https://zlaval.medium.com/hitchhikers-guide-to-java-optional-c2f0d42be26a?source=rss-8af538bf2181------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2f0d42be26a</guid>
            <category><![CDATA[java8]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Zalán Tóth]]></dc:creator>
            <pubDate>Sun, 28 Aug 2022 19:33:29 GMT</pubDate>
            <atom:updated>2022-08-28T19:33:29.738Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SXPuPRXn50FK4QkfUB_63w.jpeg" /></figure><p>In software development the most frequent error is the null reference. Even its inventor, Tony Hoare called it a billion-dollar mistake. <br>Many modern languages are null safe by nature, but as Java is mature and backward compatibile is maintained, the language does not offer null safety at language level.</p><p>Besides this Java offers a workaround called <a href="https://docs.oracle.com/en/java/javase/17/docs/api//java.base/java/util/Optional.html">Optional</a>. We can achieve null safety using this wrapper class wisely. In this article we will get to know its capabilities and how to use it properly.</p><h4>Basic usage</h4><p>First we define a sample domain model We are going to use it through our examples.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b760889f68334053642ea4a757bd49e/href">https://medium.com/media/0b760889f68334053642ea4a757bd49e/href</a></iframe><p>Let’s look at a null reference error. Define a reference as null and call a getter method on that.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae1502ea4680c2c3c1186ed14c0442b9/href">https://medium.com/media/ae1502ea4680c2c3c1186ed14c0442b9/href</a></iframe><p>As <em>car </em>variable does not refer to any objects, when we call the year method on the variable we’ll get NullPointerException.</p><blockquote>Exception in thread “main” java.lang.NullPointerException: Cannot invoke “com.zlrx.article.optional.domain.Car.year()” because “car” is null<br> at com.zlrx.article.optional.NullPointerExceptionExample.main (NullPointerExceptionExample.java:10)</blockquote><p>Java 8 has brought us the Optional wrapper class which tries to handle this problem. It can either contain a value or signs us the lack of it. <br>Optional is immutable. Once it was instantiated, we cannot change it’s value</p><p>In the following example we are creating Optional from null value using the ofNullable factory method. It accepts either a value or null. This is the most used generator for Optional besides the Optional.empty() which produces the same result as null would have been passed to the ofNullable method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1df07be1c9f7646b985b0c45e7815afd/href">https://medium.com/media/1df07be1c9f7646b985b0c45e7815afd/href</a></iframe><p>There are multiple functions we can use for retrieving the wrapped value. For example the orElse returns with the value if exists or with the passed default if not. In the example above the result would be the default value as the original string was null .</p><p>Of course we can check if the value is missing or not. The isPresent method returns true when the value is not null inside the wrapper. <br>In case the value presents we can safetely call the get() for retrieving the value. This method throws NoSuchElementException if the value is missing.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e357e323f49f4b4fca243380d8dd9e9/href">https://medium.com/media/3e357e323f49f4b4fca243380d8dd9e9/href</a></iframe><p>We can also use the ifPresent high ordered function which accepts a function as input parameter and executes it when the value presents or skip it. The ifPresentOrElse method accepts an instance of the Runnable interface as second argument and executes it in case of missing value.</p><h4>When to use it and when not</h4><p>Use it mainly as the return value of the public methods of classes, when the value goes back can be null. In this way a missing null check by the client won’t ended in NullpointerException. Use null in private scope only and not in public methods.</p><p>There are many cases when Optional is not so effective and the overuse of it can cause unclean, overcomplicated source code. Let’s see some examples.</p><ul><li>Never use Optional as class variable. It isn’t serializable.</li><li>Never use it as input parameter of a method. There are multiple problems with it. The caller must wrap the value which is inconvinient. The Optional reference can also be null so we have to check it anyway.</li><li>Never use it for wrapping collections directly (Lists, Sets, Maps..). Use empty collection instead of null and Optional.</li><li>Don’t use it as the return value of a private method. It increases the complexity and most of the time the caller method should unwrap it anyway.</li></ul><p>Some examples for this bullet list. <strong>Never use Optional in this way.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/73dde8ddf31796fef1737915b3ebeb9f/href">https://medium.com/media/73dde8ddf31796fef1737915b3ebeb9f/href</a></iframe><p>Now let’s look at an example where it was used in the proper way.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0227bbde1e9daa7a49772734a3670094/href">https://medium.com/media/0227bbde1e9daa7a49772734a3670094/href</a></iframe><p>The database simulator class randomly retrieves a Car object or null. The private methods of the example use the plain Car object only as it would be both performance degradation to wrap in and out the object from Optional constantly for every operations. Also it would make the code less readable. But as the public method returns with Optional, the client of the API gets the result object wrapped so we force them towards null safety.</p><h4>Constructing Optional and Retrieving its value</h4><p>There are three factory methods we can use for creating Optional instance.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d2a276215b0ddf728f165ce9b1dc38f/href">https://medium.com/media/0d2a276215b0ddf728f165ce9b1dc38f/href</a></iframe><p>The ofNullablewas discussed earlier. We can indicate the lack of value using the empty method as well. The of function only accepts values different from null. When we try to pass null it throws NullpointerException.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5940ee8e448d417d06b70e454a030a6a/href">https://medium.com/media/5940ee8e448d417d06b70e454a030a6a/href</a></iframe><p>We’ve also discussed get() previously. The orElse method returns with the passed default in case of missing value. orElseGet is similar but we can use Supplier instance as input parameter, which produces default value on fly. At last orElseThrow - as its name indicates - throws predefined exception if the value is null.</p><h4>Transformation</h4><p>There are several useful methods we can use to ‘manipulate’ the Optional (actually these are creating new instances).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65b2cad179e4c19ff7d4bd347b7f6222/href">https://medium.com/media/65b2cad179e4c19ff7d4bd347b7f6222/href</a></iframe><p>filter accepts Predicate and return with the current object when it meets with the requirements or empty if not. <br>The value can be modified by the map method. In this example we transform the string value to an integer which represents the length of the aforementioned string.</p><p>flatMapaccepts mapper function which has Optional return type. If we used the map function we would get back Optional&lt;Optional&lt;T&gt;&gt;type as the result. flatMap extracts the value so the result will be simply an Optional&lt;T&gt; where T is a generic type. In this example the flatMap method calls the mapper function from another class (Mapper) ,which returns with an Optional value on its public method, as it is the best practices.</p><p>The last example shows how we can combine these operations. Filter the value if its length is greater then five, then write it twice after each other and then calculate its length. (=14)</p><h4>Null check chain</h4><p>Checking null on object deep inside object chains is painful. We have to test every objects in order to avoid NullpointerException. There are multiple approaches exist for this, like multiple embedded if statements or chaining null tests using &amp;&amp;. In the following example we would like to retrieve the piston of a car but as you may see, we have to do four null tests. These null checks would work just fine but they are complex and ugly. Let’s take a look how we can use the Optional wrapper class for chain null checks in a nice way.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e0d3385c676ef23f9714f47925d62266/href">https://medium.com/media/e0d3385c676ef23f9714f47925d62266/href</a></iframe><p>Optional’s map function will return as empty if any objects in the chain or the value itself is null. This prevents us to make mistakes on null check ordering and get NullpointerException. Also it is much more readable and easier to debug.</p><p>We can call the stream method on the Optional which converts it to a regular java stream. For detailed explanation please read the <a href="https://zlaval.medium.com/functional-interface-lambda-and-stream-in-java-3c16e8138edb">following article</a>.</p><p>Source code on <a href="https://github.com/zlaval/Optional">GitHub</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2f0d42be26a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Functional Interface, Lambda and Stream in Java]]></title>
            <link>https://zlaval.medium.com/functional-interface-lambda-and-stream-in-java-3c16e8138edb?source=rss-8af538bf2181------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c16e8138edb</guid>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Zalán Tóth]]></dc:creator>
            <pubDate>Wed, 29 Jun 2022 23:46:52 GMT</pubDate>
            <atom:updated>2022-06-29T23:46:52.746Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lXtqd4lv8Jeekwc9juRY8g.png" /></figure><p>Java 8 has brought functional programming into the language - or at least some parts of that. It is not perfect, verbose but still a nice and easy-to-use tool in our belt. In this article we will review this part of Java through many-many examples.</p><h4>Functional Interface</h4><p>Funcional interfaces are the basis of Lambda functions and Streams. <br>It must contain only one abstract method. The @FunctionalInterface annotation can be used for compile time checking of this constraint.</p><p>Let’s create an interface which converts an input object from type T to type U .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7702bdd71ac050d34faa94e78c7d1b3c/href">https://medium.com/media/7702bdd71ac050d34faa94e78c7d1b3c/href</a></iframe><p>Before Java 8 anonymous class had to be created from the interface. <br>In this example we implement <em>String </em>to <em>Integer </em>converter.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8394c0966c845db496b25b59608c4af1/href">https://medium.com/media/8394c0966c845db496b25b59608c4af1/href</a></iframe><h4>Lambda expression</h4><p>From Java 8 we can use <em>lambda expressions</em> (and <em>method references</em> in some specific cases). These are syntactic sugars over inner classes. Before the <em>arrow </em>the String input parameter is declared and after the <em>arrow </em>the method body. The following picture shows how the<em> anonymous class</em> was transformed into <em>lambda function</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ha0OoFiKc1sBgLiwfwU-8g.png" /><figcaption>Transform anonymous class into lambda function</figcaption></figure><p>As the function call in the body of the method (Integer.valueOf(from)) has the same input type as the input type of the lambda expression, we can shorten the expression even further by omiting the input parameter. This is what we call as <em>method reference</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/043e3aa676f1820540373fdae5b7443d/href">https://medium.com/media/043e3aa676f1820540373fdae5b7443d/href</a></iframe><p>Unfortunatelly the function name is still needed to the execution of the lambda expression thus there can be only one function on the interface so the language could omit that as well. The following expression would be nicer, maybe we will get this in the furute.</p><pre>var result = rfConverter(10)</pre><p>Another important thing is variables outside from the lambda’s context has to be at least effectively final. In the following example the count is incremented in the 5th line, therefore the variable is not effectively final so we will get compilation error. If we remove that line, the compilation will succeed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed748a9784fe1067652839835ae138fb/href">https://medium.com/media/ed748a9784fe1067652839835ae138fb/href</a></iframe><h4>Built-In Functional Interface</h4><p>There are multiple built-in functional interfaces in Java. The best practice is using them and only define custom ones if it’s really necessary.</p><ul><li><a href="https://cr.openjdk.java.net/~iris/se/17/latestSpec//api/java.base/java/util/function/Supplier.html"><strong>Supplier&lt;T&gt;</strong></a> has only return value. It is useful for object generation.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2dff6746b1522865fee2ef8806873be/href">https://medium.com/media/b2dff6746b1522865fee2ef8806873be/href</a></iframe><ul><li><a href="https://cr.openjdk.java.net/~iris/se/17/latestSpec//api/java.base/java/util/function/Predicate.html"><strong>Predicate&lt;T&gt;</strong></a> has an input parameter and returns with <em>boolean </em>value. We can use it for testing values. Predicate has many default methods. We can combine multiple Predicates using them.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e0a42c9a75bd5d2dbd0b0ecd81e429ed/href">https://medium.com/media/e0a42c9a75bd5d2dbd0b0ecd81e429ed/href</a></iframe><ul><li><a href="https://cr.openjdk.java.net/~iris/se/17/latestSpec//api/java.base/java/util/function/Function.html"><strong>Function&lt;T , R&gt;</strong></a> useful for convert elements from one type to another. It’s similar to the Converter interface we defined earlier but it contains <em>default </em>methods for composing functions. Composition has to be assembled in reverse order and the type of the preceding function’s output must be the same as the current function’s input type.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38b0bcb99f33b721e3fdf179d9995518/href">https://medium.com/media/38b0bcb99f33b721e3fdf179d9995518/href</a></iframe><ul><li><a href="https://cr.openjdk.java.net/~iris/se/17/latestSpec//api/java.base/java/util/function/Consumer.html"><strong>Consumer&lt;T&gt;</strong></a> has an input parameter and <em>void </em>return type. It is useful for processing values (save into database, write into file…).</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b907f2e1533c4dfc0969ff116391880/href">https://medium.com/media/4b907f2e1533c4dfc0969ff116391880/href</a></iframe><p>Here are the definitions of the discussed interfaces for reference.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9254d61bcb8bd2b599dde11a34d9364c/href">https://medium.com/media/9254d61bcb8bd2b599dde11a34d9364c/href</a></iframe><p>There are multiple useful interfaces in the java.util.function package like <a href="https://cr.openjdk.java.net/~iris/se/17/latestSpec//api/java.base/java/util/function/BiFunction.html"><em>BiFunction&lt;T, U, R&gt;</em></a><strong>, </strong><a href="https://cr.openjdk.java.net/~iris/se/17/latestSpec//api/java.base/java/util/function/BinaryOperator.html"><em>BinaryOperator&lt;T&gt;</em></a><em> </em>and so on<em>. <br></em>Feel free to discover all of them.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db3afedf2fd98100d7f7a0a5109c108f/href">https://medium.com/media/db3afedf2fd98100d7f7a0a5109c108f/href</a></iframe><p>Stream was the greatest novelty of Java 8. It can be used on various collections. We can define declarative pipelines using distinct operations. Each operations accept a lambda function and returns with the mutated view of the collection. The original collection won’t be modified though. Using stream is easier then using loops and also it is more secure.</p><p>There are two type of operations:</p><ul><li><strong>Intermediate</strong>: a pipeline can contains multiple intermediate operations.</li><li><strong>Terminal</strong>: produce the final value (or <em>void</em>). Stream can have only one at the end of the pipeline. After the terminal operation the stream becomes closed and cannot be reused anymore.</li></ul><p>Let’s jump into the available operations.</p><h4>Stream operators</h4><p><strong><em>forEach </em></strong>accepts a Consumer, executes the given function and returns with void.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed8252491cef821b311683050dd09425/href">https://medium.com/media/ed8252491cef821b311683050dd09425/href</a></iframe><p><strong><em>count </em></strong>is another terminal operation. As its name implies it returns with the number of the elements of the list.</p><pre>var size = words.stream().count();</pre><p><strong><em>filter </em></strong>accepts a Predicate and drop values not pass on it. This is an intermediate operation, so after it, a terminal operation must be used. The .toList terminal operation collects the remaining elements into a new list.</p><pre>var result=words.stream().filter(str -&gt; str.length() &lt; 4).toList();</pre><p>The result is<em> [foo, bar, car, sun]</em></p><p><strong><em>sort </em></strong>is an intermediate operator which sorts the list using the input Comparator or sorts into natural order if no comparator was provided.</p><pre>var result = words.stream().sorted((a,b)-&gt;a.compareTo(b)).toList();</pre><p>or</p><pre>var ordered = words.stream().sorted().toList();</pre><p>Result: <em>[animal, bar, car, foo, home, java, play, sun, sword, sword]</em></p><p>The natural order of strings are alphabet.</p><p><strong><em>map </em></strong>transforms all elements of the list using the passed Function. We are going to <em>map </em>the list of strings into a list of Word objects.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/39265fdfb80969aa6b554553cb50a290/href">https://medium.com/media/39265fdfb80969aa6b554553cb50a290/href</a></iframe><p>Result: <em>[word = foo, word = bar, word = home, word = sword, word = play, word = animal, word = sword, word = car, word = sun, word = java]</em></p><p>While <em>map </em>transforms an element into another one, <strong><em>flatMap </em></strong>transforms a list of lists into a list of elements. In this example the phone number list of each person will be flattened into a list of phone numbers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53eacc5706cbc4ec68c0c5dc0f5f80ae/href">https://medium.com/media/53eacc5706cbc4ec68c0c5dc0f5f80ae/href</a></iframe><p><strong><em>allMatch, anyMatch, noneMatch</em> </strong>terminal operations return with <em>boolean </em>value. The first one is true if the given Predicate is true for all elements, the second one is true if at least one element matches an the third one is only true if non of the elements match to the given Predicate.</p><pre>boolean anyWordLongerThenFiveCharacter = words.stream().anyMatch(it -&gt; it.length() &gt; 5);</pre><p><strong><em>distinct </em></strong>filters all duplicates from the list.</p><pre>var distinctList = words.stream().distinct().toList();</pre><p>Result: <em>[foo, bar, home, sword, play, animal, car, sun, java]</em></p><p><strong>reduce </strong>is a terminal operation. It takes an element from the list in every rounds and combines it with the <em>accumulator</em>. The final result will be the latest value of the accumulator property. For example we can use it for summarizing the values in an Integer list.</p><pre>var sum = IntStream.<em>range</em>(0, 100).reduce((accumulator, number) -&gt; accumulator += number); //4950</pre><p>Let’s see how it works inside.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f339e46c9f599b947fc9669f2f725704/href">https://medium.com/media/f339e46c9f599b947fc9669f2f725704/href</a></iframe><p>We can define the initial value of the accumulator field as well.</p><pre>IntStream.<em>range</em>(0, 100).reduce(100,(accumulator, number) -&gt; accumulator += number); //5050</pre><p>Using <strong>peek </strong>we can take a look into the stream. It is useful for logging and debugging. For example ‘log’ the elements of the stream after applying uppercase transformation on them.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a72ab258a2e8c342101f650df4234b62/href">https://medium.com/media/a72ab258a2e8c342101f650df4234b62/href</a></iframe><p>Result: <em>FOO BAR HOME SWORD PLAY ANIMAL SWORD CAR SUN JAVA</em></p><p>The real power of streams are the combination of the different operations. In this example we will filter duplicated elements, transform the words to uppercase letter, sort them into alphabetize order and transform the elements into Word objects and collect it into a collection of <em>List&lt;Word&gt;</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/864e569a655c0a38f68a4ec3e7f60194/href">https://medium.com/media/864e569a655c0a38f68a4ec3e7f60194/href</a></iframe><p>Building this logic using loop consumes more time, it would be also error prone and difficult to read .. and we are not even talked about parallelization.</p><h4>Order of execution.</h4><p>We have to talk about the order of execution as well. We are gonna create a list with 4 elements and in the first example we will sort the list, then apply a transformation and at last we are gonna filter the elements. In the second one, we will filter the elements, then transform and at the end sort it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb311f78b748c4bfbc5fb20a46064179/href">https://medium.com/media/bb311f78b748c4bfbc5fb20a46064179/href</a></iframe><p>So what was happening? First of all, as you may see the <strong>sort </strong>operation made the flow stop, sorted the whole list and after thatthe elements were pushed to the next stage of the pipeline. Order is a stateful operation so it was executed horizontally. After sort, the elements went through to the remaining steps of the pipeline one by one vertically as the rest of the operations are stateless. The whole pipeline has taken 14 steps.</p><p>Now let’s see the second version of the pipline.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa1fb3b4ebabc13934f5bc29b55a557c/href">https://medium.com/media/fa1fb3b4ebabc13934f5bc29b55a557c/href</a></iframe><p>It has only taken 8 steps because we filtered out the unnecessary elements before the map and filter steps. <br>The order of the pipeline has impact on the performance as well as the final result. Consider the case when we transform the words into longer words and then filtering the elements by length versus the reverse of this two steps.</p><h4>Numeric streams</h4><p>Primitive numeric values can be processed using this specific kind of streams. The main problem if the <em>Stream&lt;Number&gt;</em> is it can only handle <em>boxed </em>numbers. When we would like to apply operations on it, the value has to be outboxed which has high cost. Also for example an <em>Integer </em>object is 16 bytes while an <em>int </em>primitive is only 4 bytes. <em>IntStream</em>, <em>DoubleStream</em>.. solve this problem and also contain numerical value specific operations.</p><p><strong>SummaryStatistic </strong>generates stats from the elements of the collection.</p><pre>var stats = IntStream.<em>of</em>(1, 3, 5, 7, 9).summaryStatistics();</pre><p>Result: <em>IntSummaryStatistics{count=5, sum=25, min=1, average=5,000000, max=9}</em></p><p>We can also boxing the stream into <em>Stream&lt;Integer&gt;</em></p><pre>Stream&lt;Integer&gt; boxedStream = IntStream.<em>of</em>(1, 3, 5, 7, 9).boxed();</pre><h4>Collectors</h4><p>We have already seen the most used terminal collector (<em>.toList()</em>) but sometimes different type of results are needed. Let’s see other built-in collectors and write our own as well.</p><p><strong>groupingBy</strong> collects the elements into <em>map </em>by the given key. In this example we are gonna use <em>Student</em>’s birth year as key.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f39e99cc3dec9a1e28a290d964e2ca2/href">https://medium.com/media/9f39e99cc3dec9a1e28a290d964e2ca2/href</a></iframe><p><strong>averagingInt </strong>calculates the average of the given numeric properties. The average of the birth year for the afforementioned students is 2001.6</p><pre>Double averageBirthYear = students.stream().collect(Collectors.<em>averagingInt</em>(s -&gt; s.birth)); </pre><p><strong>partitioningBy </strong>divides the collection into two parts based on the given <em>Predicate</em>. The result will be a map which contains two keys, the records not match to the Predicate will be placed to the <em>false </em>key’s bucket while the others to the <em>true</em>’s<em> </em>bucket.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1c32af936a8312c2970d607f8622844/href">https://medium.com/media/d1c32af936a8312c2970d607f8622844/href</a></iframe><p>There are many other operations, here is some non-exhaustive examples.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed7d1aa3b1b4218e3c98b24be81dee0f/href">https://medium.com/media/ed7d1aa3b1b4218e3c98b24be81dee0f/href</a></iframe><h4>Parallel streams</h4><p>Concurrency is effective but difficult to do it in the right way. Fortunately we can handle it easily using the Stream API. We have to call parallelStream() function and that’s it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c3a1a447a813b438d01f4e05f5c36ab/href">https://medium.com/media/8c3a1a447a813b438d01f4e05f5c36ab/href</a></iframe><p>Let’s compare the execution time of a sequential and a parallel streams. Here we create a list from one million unique strings and sort it sequentially and then concurrently.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1191b2877393b9d46a357cbc75baef6/href">https://medium.com/media/a1191b2877393b9d46a357cbc75baef6/href</a></iframe><p>Parallel stream was almost two time faster than the sequential. <br>Before we instantly start to rewrite all streams to parallel, we have to ensure that the parallel version can be executed faster than the sequential one. Thread handling, context switches, merging the results of the threads add extra costs to the concurrent execution which makes it slower in many cases. Sequential pipelines over small collections are almost always faster. Splitting LinkedList for parallel processing has enormous cost compared to splitting an ArrayList. But the choice also depends on the number of CPU cores, the cost of the operations and so on.</p><p>Also worth to mention that every parallel stream use the common ForkJoinPool by default. The number of threads mimic to the number of CPU cores (or hyperthreads). We can check it using the following command:</p><pre>var cores=ForkJoinPool.<em>commonPool</em>().getParallelism();</pre><p>Pay attention to the slow stream operations as they can slow down other parts of the application whose are using the same common - on JVM level - ForkJoinPool. We can easily write application which runs out of threads quickly.</p><p>At last, let’s see how parallelStream splits the work and schedules them into threads.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4beaaa282f25269c0771497411098e49/href">https://medium.com/media/4beaaa282f25269c0771497411098e49/href</a></iframe><p>My ForkJoinPool has 24 threads so every element could have been processed in different threads.</p><h4>Custom collector</h4><p>Let’s take a look at the signatura of the Stream’s collect method. There are multiple overloads of it. Now we are gonna use one of the simplest signature.</p><pre>&lt;R&gt; R collect(Supplier&lt;R&gt; supplier,<br>              BiConsumer&lt;R, ? super T&gt; accumulator,<br>              BiConsumer&lt;R, R&gt; combiner);</pre><p>It waits three parameter. <em>Supplier </em>creates new instance(s) of the container for holding the result. Accumulator appends the actual element of the current iteration to the container. Combiner is only necessary for parallel streams, where every thread creates its own container and collect the data into it and in the end those collections are merged into one by the combiner.</p><p>We create a collector which collects the elements into <em>LinkedList</em>.</p><pre>students.stream().filter(s -&gt; s.birth &gt; 2005).collect(<br>        LinkedList::new,<br>        LinkedList::add,<br>        LinkedList::addAll<br>);</pre><p>In the background the <em>LinkedList::new</em> supplier creates a new LinkedList instance. Then on every iterations the <em>LinkedList::add</em> <em>BiConsumer </em>gets two parameters, a list and an object and put the object into the list <em>[(list, student)-&gt;list.add(student)]</em>. In case of parallel stream, every threads do this steps and at the end all result lists are combined together by <em>LinkedList::addAll</em> <em>[(leftList,rightList)-&gt;leftList.addAll(rightList)]</em></p><p>In the second example we are gonna simulate message receiving over network. The sender splits the message into byte chunks, wrap it into Message objects with the order and sends it over the network. The client receives the messages in random order, sort them and restores the original message from the chunks.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a83d814fbba9d546e41e1a0a082463f/href">https://medium.com/media/5a83d814fbba9d546e41e1a0a082463f/href</a></iframe><p>The collector creates new ByteArrayOutputStream(s) and writes the received messages’ data into it one-by-one. If parallel stream was used, then it combines the buffers from each threads. At last, the toByteArray method creates the final merged array which contains the original message.</p><h4>File handling</h4><p>We can use stream for file handling as well. In the following example we read the<em> name.txt</em> file line-by-line, skip the first 20 rows and filter the remaining names by length. Then we take the first 10 rows from the result and map it into lowercase format and collect them into a list.<br>The <a href="https://github.com/zlaval/article-java_stream/blob/master/src/main/resources/names.txt"><em>names.txt</em></a> contains 100 different names.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9eeec0b1fa5c7990f728500b020c16f3/href">https://medium.com/media/9eeec0b1fa5c7990f728500b020c16f3/href</a></iframe><h4>Reusing stream</h4><p>As we discussed earlier, when the terminal operation is called on a stream it becomes terminated and we cannot use it anymore. The next example shows the exception thrown by Java in this case.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/99c558f0e83d5e3ef5e6ead1d7799b1b/href">https://medium.com/media/99c558f0e83d5e3ef5e6ead1d7799b1b/href</a></iframe><p>If we would like to create reusable streams, <em>Supplier </em>interface can be used. It generates new stream every time its get method is called.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63d69cb0a8efe8396639275ec21b18fb/href">https://medium.com/media/63d69cb0a8efe8396639275ec21b18fb/href</a></iframe><h4>Stream debugger</h4><p>Debugging stream can be difficult but <a href="https://www.jetbrains.com/idea/">IntelliJ</a> contains the <a href="https://www.jetbrains.com/help/idea/analyze-java-stream-operations.html">Stream Trace</a> plugin by default, where we can visualize the execution of the pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8qjlAzteYG38jUBCQVn-FQ.png" /><figcaption>Stream Trace</figcaption></figure><p>As you may see, stream is a very powerful tool for data processing but sometimes it is not enough. <br>There are tools/extensions also worth to mention. <br>The first one is <a href="https://docs.vavr.io/">Vavr</a>. It is a complete funtional programming library for Java. It contains funtional interfaces, collections, extended stream operations and so on.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e36115ddcad1a9d78c88f5875a6231a8/href">https://medium.com/media/e36115ddcad1a9d78c88f5875a6231a8/href</a></iframe><p><a href="https://github.com/amaembo/streamex">StreamEx</a> and <a href="https://github.com/eclipse/eclipse-collections/blob/master/docs/guide.md">Eclipse collections</a> are another great tools and worth to check them.</p><p>The source code available on <a href="https://github.com/zlaval/article-java_stream">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c16e8138edb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>