<?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 Cesar Cordoba on Medium]]></title>
        <description><![CDATA[Stories by Cesar Cordoba on Medium]]></description>
        <link>https://medium.com/@cesar.cordoba?source=rss-7c3bc1fa46ce------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*6XaDeawNuxNZd4WqmKSNUQ.jpeg</url>
            <title>Stories by Cesar Cordoba on Medium</title>
            <link>https://medium.com/@cesar.cordoba?source=rss-7c3bc1fa46ce------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 11:49:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@cesar.cordoba/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[How to Deploy a Web App in AWS]]></title>
            <link>https://medium.com/@cesar.cordoba/how-to-deploy-a-web-app-in-aws-771ee7c15571?source=rss-7c3bc1fa46ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/771ee7c15571</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[full-stack]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Cesar Cordoba]]></dc:creator>
            <pubDate>Mon, 17 Feb 2025 19:11:37 GMT</pubDate>
            <atom:updated>2025-02-17T19:14:01.247Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Build Your Own Website in Just 10 Minutes</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v0EEuCD6f3Mdt5GCGg0PNQ.png" /></figure><p>As the title suggests, we’re building a static website with a functional backend — step by step, no deep expertise required.</p><p>Why this post? Because in tutorials, everything <em>magically</em> works. But in reality you might run into frustrating errors when deploying, and I’m here to help you dodge the most common ones: <strong>denied access</strong> and <strong>CORS authentication issues</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OsoPq_6EHq5bhAlcNDpq1Q.png" /><figcaption><strong>CORS authentication issues</strong></figcaption></figure><p>We’ll deploy everything manually to understand the infrastructure first. Once you get the hang of it, tools like AWS Amplify can make your life easier.</p><h3>Table of contents</h3><p><a href="#8cff">Step 1: Configure an S3 Bucket for the Website</a> (Avoiding CORS Error)</p><p><a href="#cb7e">Step 2: Build the website</a></p><p><a href="#bdd3">Step 3: Deploy the database</a></p><p><a href="#210e">Step 4: Deploy the lambda (Avoiding Access denied error)</a></p><p><a href="#a306">Step 5: Deploy the API Gateway (Avoiding CORS Error)</a></p><p>Bonus: How to test the Api</p><h4><strong>The Overall Architecture</strong></h4><figure><img alt="AWS Architecture" src="https://cdn-images-1.medium.com/max/519/1*xPIrtd_Fbe5WjLd2Tha7lw.png" /></figure><p>Here’s what we’re building:</p><ul><li><strong>Amazon S3: </strong>Hosts our static website.</li><li><strong>API Gateway: </strong>Manages backend requests.</li><li><strong>AWS Lambda: </strong>Runs backend logic and connects to other AWS services.</li><li><strong>DynamoDB: </strong>Stores transactions — simple, scalable, and efficient. (But you can swap it for any database that fits your needs.)</li></ul><p>Here’s a sneak peek of the final result:</p><p>We’re building a <strong>simple banking website</strong> that lets you check your account balance — fast, secure, and fully serverless. 🚀</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X2BCGfawCa78Y9ej_cJGiw.png" /></figure><h3>Step 1: <strong>Configure an S3 Bucket for the Website</strong></h3><p>First, we’ll set up an <strong>S3 bucket</strong> to host our website. This involves <strong>making the bucket publicly accessible</strong> so it can be accessed from the internet.</p><blockquote>Note: There are more secure ways to do this. For example, to use cloudfront to expose the website. But to keep things simple, we’ll open the bucket directly.</blockquote><h4><strong>Configure the S3 Bucket permissions:</strong></h4><ol><li>Navigate to the <strong>Permissions</strong> tab of your S3 bucket.</li><li>By default, public access is blocked. Click the <strong>Edit</strong> button in the <em>Block public access</em> section.</li></ol><figure><img alt="Permissions Tab in S3" src="https://cdn-images-1.medium.com/max/1024/1*NxE0t_V8UdDgrEWwlVYOtA.png" /><figcaption>Permission Tab inside S3 console</figcaption></figure><p>3. Uncheck the option for <strong>Block all public access</strong>.</p><p>4. Save your changes.</p><figure><img alt="Bucket settings panel" src="https://cdn-images-1.medium.com/max/1024/1*Ir7Z58pv6usTVmb40sIwzg.png" /><figcaption>Bucket settings</figcaption></figure><p>Now that public access is unblocked, we need to <strong>edit the Bucket Policy</strong> so users can retrieve objects from the bucket.</p><h4><strong>Steps to Add a Bucket Policy:</strong></h4><p>1. In the <strong>Permissions tab</strong>, scroll down to the <strong>Bucket Policy</strong> section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X8zRabU3hrgdrArYaYFexQ.png" /></figure><p>2. Click <strong>Edit</strong> to modify the policy</p><p>3. Add the following JSON policy, replacing your-bucket-name with your actual bucket name:</p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Sid&quot;: &quot;Statement1&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Principal&quot;: &quot;*&quot;,<br>            &quot;Action&quot;: &quot;s3:GetObject&quot;,<br>            &quot;Resource&quot;: &quot;arn:aws:s3:::your-bucket-name/*&quot;<br>        }<br>    ]<br>}</pre><p>4. Save the policy</p><p>This policy allows the s3:GetObject action, enabling users to retrieve objects (like your website files) from the bucket.</p><h4><strong>Modify the CORS Settings</strong></h4><p>To ensure your website can be accessed from anywhere, we need to configure <strong>CORS (Cross-Origin Resource Sharing)</strong>.</p><blockquote>What is CORS? <strong>Cross-Origin Resource Sharing</strong> is a security feature in web browsers that controls which domains can request resources from a server. By default, browsers block requests from different origins to prevent security risks.</blockquote><p>1. In the<strong> Permissions tab</strong>, scroll down to the <strong>CORS Configuration</strong> section.</p><figure><img alt="Cors subsection" src="https://cdn-images-1.medium.com/max/1024/1*kBVdK5VnFnh2N-ml492bRw.png" /><figcaption>CORS Subsection within Permissions Tab</figcaption></figure><p>2. Click <strong>Edit</strong> and replace the existing configuration with the following:</p><pre>[<br>    {<br>        &quot;AllowedHeaders&quot;: [<br>            &quot;*&quot;<br>        ],<br>        &quot;AllowedMethods&quot;: [<br>            &quot;GET&quot;,<br>            &quot;HEAD&quot;,<br>            &quot;POST&quot;<br>        ],<br>        &quot;AllowedOrigins&quot;: [<br>            &quot;*&quot;<br>        ],<br>        &quot;ExposeHeaders&quot;: []<br>    }<br>]</pre><blockquote><strong>We’re Allowing Everything (Not Ideal for Production). </strong>In our CORS settings, we set AllowedOrigin to *, meaning <strong>any website can access our resources</strong>. This is fine for learning and testing, but in production, it’s best to <strong>restrict access to specific domains</strong> to improve security. Instead of *, you should define trusted domains like: “AllowedOrigin”: [https://yourdomain.com]</blockquote><h4><strong>Enable Website Hosting</strong></h4><p>The last step is to enable <strong>static website hosting</strong> so your S3 bucket can serve web pages.</p><p>1. Go to the <strong>Properties tab</strong> of your S3 bucket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*azqkt_PaKBc6UWPapqeZfg.png" /></figure><p>2. Scroll down to the <strong>Static Website Hosting</strong> section and click <strong>Edit</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wnc71hwxqg0WjwIUrV1xCw.png" /></figure><p>3. Enable website hosting and specify the index.html file as the default document.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NKViPBDkBJWnCoUcKm3gsQ.png" /></figure><p>Your S3 bucket is now fully configured to host a static website! 🎉</p><h4>Step 2: Build the website</h4><p>Now that your S3 bucket is ready, it’s time to create the actual website.</p><p>At the very least, you’ll need an <strong>index.html</strong> file. But why stop there?</p><ol><li>You can include <strong>CSS files</strong> to style your website and give it a polished, professional appearance.</li><li>In more complex use cases, you can (and should) include <strong>JavaScript files to add more functionalities.</strong></li><li>Want to make your code more secure and dynamic?Store external parameters in a <strong>config folder</strong> instead of hardcoding them in your HTML or JavaScript. This makes your site more <strong>secure</strong> and <strong>easier to maintain</strong>.</li></ol><p>With these elements in place, your website can range from a simple static page to a dynamic, feature-rich application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7FYlNjqugiuv6ZaCJk6K_Q.png" /><figcaption>Example of an application using files to organize the code</figcaption></figure><h4><strong>Building the Basics: index.html and CSS</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X2BCGfawCa78Y9ej_cJGiw.png" /><figcaption>Index.html</figcaption></figure><ol><li>Create index.html: We’re keeping things simple for now. Our <strong>index.html</strong> will include a basic structure and a <strong>JavaScript</strong> function to handle some dynamic behavior -more complex code in <a href="https://github.com/cesar1226/web-development">GitHub</a>.</li></ol><p>Here’s a basic example:</p><blockquote><strong>Important</strong>: We wil come back to include our api endpoint for the balance: ‘my-api-endpoint/dev/get_balance’</blockquote><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>    &lt;title&gt;Balance Checker&lt;/title&gt;<br>    &lt;link rel=&quot;stylesheet&quot; href=&quot;style.css&quot;&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;div class=&quot;container&quot;&gt;<br>        &lt;h1&gt;Balance Checker&lt;/h1&gt;<br>        &lt;div class=&quot;input-group&quot;&gt;<br>            &lt;label for=&quot;accountIdForBalance&quot;&gt;Account ID:&lt;/label&gt;<br>            &lt;input type=&quot;text&quot; id=&quot;accountIdForBalance&quot; placeholder=&quot;Enter account ID&quot; required&gt;<br>            &lt;button type=&quot;button&quot; id=&quot;checkBalance&quot;&gt;Check Balance&lt;/button&gt;<br>        &lt;/div&gt;<br>        &lt;div id=&quot;balanceResult&quot; style=&quot;display: none;&quot;&gt;&lt;/div&gt;<br>    &lt;/div&gt;<br><br>    &lt;script&gt;<br>        // Configuration<br>        const API_ENDPOINTS = {<br>            balance: &#39;my-api-endpoint/dev/get_balance&#39;<br>        };<br><br>        // Elements<br>        const accountInput = document.getElementById(&#39;accountIdForBalance&#39;);<br>        const checkButton = document.getElementById(&#39;checkBalance&#39;);<br>        const balanceResult = document.getElementById(&#39;balanceResult&#39;);<br><br>        // Helper functions<br>        function showResult(message, type) {<br>            balanceResult.textContent = message;<br>            balanceResult.style.display = &#39;block&#39;;<br>            balanceResult.className = type;<br>        }<br><br>        function validateAccountId(accountId) {<br>            return accountId.trim().length &gt; 0;<br>        }<br><br>        // Event listeners<br>        checkButton.addEventListener(&#39;click&#39;, async function() {<br>            const accountId = accountInput.value;<br><br>            // Validation<br>            if (!validateAccountId(accountId)) {<br>                showResult(&#39;Please enter a valid Account ID&#39;, &#39;error&#39;);<br>                return;<br>            }<br><br>            // Disable button and show loading state<br>            checkButton.disabled = true;<br>            showResult(&#39;Fetching balance...&#39;, &#39;loading&#39;);<br><br>            try {<br>                const requestOptions = {<br>                    method: &#39;POST&#39;,<br>                    headers: {<br>                        &#39;Content-Type&#39;: &#39;application/json&#39;<br>                    },<br>                    body: JSON.stringify({ accountId })<br>                };<br><br>                const response = await fetch(API_ENDPOINTS.balance, requestOptions);<br>                <br>                if (!response.ok) {<br>                    throw new Error(`HTTP error! status: ${response.status}`);<br>                }<br><br>                const result = await response.json();<br>                const parsedBody = JSON.parse(result.body);<br>                showResult(`Current balance: $${parsedBody.balance.toFixed(2)}`, &#39;success&#39;);<br>            } catch (error) {<br>                console.error(&#39;Error:&#39;, error);<br>                showResult(<br>                    `Unable to retrieve balance. Please try again later. ${error.message}`,<br>                    &#39;error&#39;<br>                );<br>            } finally {<br>                checkButton.disabled = false;<br>            }<br>        });<br>    &lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>2. Create style.css file</p><pre>body {<br>    font-family: Arial, sans-serif;<br>    margin: 40px;<br>    text-align: center;<br>    background-color: #f5f5f5;<br>}<br>.container {<br>    max-width: 600px;<br>    margin: 0 auto;<br>    padding: 20px;<br>    background-color: white;<br>    border-radius: 10px;<br>    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);<br>}<br>h1 {<br>    color: #333;<br>    margin-bottom: 30px;<br>}<br>.input-group {<br>    margin-bottom: 20px;<br>}<br>label {<br>    display: block;<br>    margin-bottom: 8px;<br>    color: #555;<br>}<br>input {<br>    padding: 10px;<br>    width: 200px;<br>    border: 1px solid #ddd;<br>    border-radius: 4px;<br>    margin-right: 10px;<br>}<br>button {<br>    background-color: #007BFF;<br>    color: white;<br>    padding: 10px 20px;<br>    border: none;<br>    border-radius: 4px;<br>    cursor: pointer;<br>    transition: background-color 0.3s;<br>}<br>button:hover {<br>    background-color: #0056b3;<br>}<br>button:disabled {<br>    background-color: #cccccc;<br>    cursor: not-allowed;<br>}<br>#balanceResult {<br>    margin-top: 20px;<br>    padding: 15px;<br>    border-radius: 4px;<br>}<br>.error {<br>    background-color: #ffe6e6;<br>    color: #dc3545;<br>}<br>.success {<br>    background-color: #e6ffe6;<br>    color: #28a745;<br>}<br>.loading {<br>    background-color: #e6f3ff;<br>    color: #007BFF;<br>}</pre><p>3. Upload the code in your s3 bucket</p><h4>Step 3: Deploy the database</h4><p>For this simple banking website, we’ll start with a <strong>single table</strong> to store user balances. In a more complex setup, you might consider separating this into two tables — one for transactions and another for user balances.</p><h4><strong>Create the Accounts Table Schema</strong></h4><p>Here’s how we’ll configure the <strong>Accounts</strong> table:</p><ul><li>Table Name: accounts</li><li>Primary Key: account_id (String)</li><li>Attributes:</li><li>balance (Number)</li><li>user_address (String)</li><li>user_name (String)</li></ul><ol><li>Click on create table and put the following parameters:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YqcnpL1nh9kcC-Z7tYQl7w.png" /></figure><p>2. [Optional] Scroll down and customize the table settings: Since we’ll be making very few API calls, we can let it be Default Setting to use <strong>DynamoDB On-Demand</strong> mode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BbG3WxZma9XVNMUGpjdSiw.png" /><figcaption>Default table settings</figcaption></figure><p>3. Create an item</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SUwINy5dq6zbXH3cWJsTVQ.png" /><figcaption>Adding an item to the table</figcaption></figure><p>4. Add some atttributes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6oc4onIQqTnTOTDBDUzjtg.png" /></figure><p>5. Validate your users: Go to your table and click <em>Explore table items</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EGl1dF4mC2gst4zwh8NMHg.png" /><figcaption>Items stored in accounts table</figcaption></figure><h4>Step 4: Deploy the lambda</h4><p>We will deploy one lambda in python to get the balance from the database.</p><p>The process is straightforward:</p><ol><li>Go to the lambda service and click create lambda.</li><li>Choose python and once it is created, paste the following code:</li></ol><pre>import json<br>import boto3<br>from boto3.dynamodb.conditions import Key<br><br>dynamodb = boto3.resource(&#39;dynamodb&#39;)<br>table = dynamodb.Table(&#39;your-dynamoDB-table&#39;)<br><br>def lambda_handler(event, context):<br>    try:<br>        # Parse the account_id from the path parameters<br>        account_id = str(event[&#39;accountId&#39;])<br><br>        # Query the DynamoDB table for the account balance<br>        response = table.get_item(<br>            Key={&#39;account_id&#39;: account_id}<br>        )<br><br>        # Check if the account exists<br>        if &#39;Item&#39; not in response:<br>            return {<br>                &#39;statusCode&#39;: 404,<br>                &#39;body&#39;: json.dumps({&#39;error&#39;: &#39;Account not found&#39;})<br>            }<br><br>        # Extract the balance from the response<br>        balance = response[&#39;Item&#39;][&#39;balance&#39;]<br><br>        return {<br>            &#39;statusCode&#39;: 200,<br>            &#39;body&#39;: json.dumps({&#39;accountId&#39;: account_id, &#39;balance&#39;: float(balance)})<br>        }<br>    except Exception as e:<br>        return {<br>            &#39;statusCode&#39;: 400,<br>            &#39;body&#39;: json.dumps({&#39;error&#39;: str(e)})<br>        }</pre><p>3. Substitute the ‘your-dynamoDB-table’ for your actual table name (accounts if you are following the post)</p><p>4. Deploy the lambda. If you don’t do this step, you new code won’t work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pVYl0gENxsWKEcgBxDXA5g.png" /></figure><blockquote>This lambda will receive the accountId of the user and will look for the balance in the database. Notice it is receiving accountId from the post request (html) and not account_id. We do this operation in the code.</blockquote><p>5. Test it. Go to the test tab and create an event</p><pre>{&quot;accountId&quot;:&quot;1&quot;}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pExsRoiEJlWREQnMaTbVYg.png" /><figcaption>Test creation</figcaption></figure><p><strong>Important</strong>: You need to configure the permissions of your lamba to access the dynamoDB database, otherwise you will get the nasty error:</p><figure><img alt="Example of access denied error" src="https://cdn-images-1.medium.com/max/1024/1*gbslLcxLgdWEXndTiFXQpQ.png" /></figure><p>To avoid this:</p><ol><li>Find the permissions of the lambda inside the configuration tab.</li></ol><figure><img alt="Where to find the role for lambda" src="https://cdn-images-1.medium.com/max/1024/1*YCFUx29WDGYCvmpEgtmVjQ.png" /></figure><p>2. Modify the role by attaching or creating a new policy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UReSPZ4zP_TtL6B3KrAFDw.png" /></figure><p>3. Paste this policy to give the minimum privileges — <strong>Substitute the Resource parameter with your table arn</strong></p><pre>{<br>&quot;Version&quot;: &quot;2012-10-17&quot;,<br>&quot;Statement&quot;: [<br>    {<br>        &quot;Sid&quot;: &quot;VisualEditor0&quot;,<br>        &quot;Effect&quot;: &quot;Allow&quot;,<br>        &quot;Action&quot;: [<br>            &quot;dynamodb:PutItem&quot;,<br>            &quot;dynamodb:DeleteItem&quot;,<br>            &quot;dynamodb:GetItem&quot;,<br>            &quot;dynamodb:Scan&quot;,<br>            &quot;dynamodb:Query&quot;,<br>            &quot;dynamodb:UpdateItem&quot;<br>        ],<br>        &quot;Resource&quot;: &quot;YOUR-TABLE-ARN&quot;<br>    }<br>    ]<br>}</pre><blockquote>You can find the arn inside your table menu by displaying the additional info</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*HeMBv0NMu87GeIKzMTGX-A.png" /></figure><h3><strong>Step 5: Deploy the API Gateway</strong></h3><p>To connect your Lambda to the outside world and allow your website to interact with it, you need to deploy an <strong>API Gateway</strong>.</p><ol><li><strong>Go to the API Gateway service</strong> in the AWS Management Console.</li><li>Click <strong>Create API</strong> and choose <strong>REST API</strong>.</li><li>Click Create resource. Enable CORS</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TBn7dx7SCsTOcUFMirkeVg.png" /><figcaption>resource creation</figcaption></figure><p>4. Click on your new resource <em>get_balance</em> and clik on <strong>Create Method</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ImKYRTEKsT_HoOm4K1AeqA.png" /></figure><p>5. Choose POST method with lambda integration. Select the lambda you created in the previous step</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y5cYXPsjkh79W5iIw01JJw.png" /><figcaption>Post method creation</figcaption></figure><p>6. [Optional] In case you didn’t <strong>enabled CORS, you can enable it afterwards by c</strong>reating an <strong>OPTIONS method.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*db8HH5OVCqKAoeDwgyVPug.png" /></figure><p>7. Test the API Gateway: Go to the test tab and put the same json as with the lambda.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*USVfn5YrpMU8EiPpge4scw.png" /><figcaption>Test API Gateway</figcaption></figure><p>It should return you the value you have in your dataset</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DkhExHy4XhTfuySxfNdzEA.png" /><figcaption>Api response</figcaption></figure><p>8. Deploy the API. You will need to create a stage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MyKd1fcwOfoc12vqpf-nqQ.png" /><figcaption>API deployment</figcaption></figure><p>9. Put your endpoint inside the html. You can find it in stages -&gt;Invoke URL</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xFkHlD-4yOrftIImH_5WUA.png" /><figcaption>Invoke URL</figcaption></figure><h3>Troubleshooting:</h3><p>You can validate that you api gateway is actually working before placing it inside your html by running in the terminal:</p><pre>curl -X POST https://&lt;UNIQUE ID&gt;.execute-api.us-east-1.amazonaws.com/dev/get_balance \<br>-H &quot;Content-Type: application/json&quot; \<br>-d &#39;{&quot;accountId&quot;:&quot;1&quot;}&#39;</pre><p>If you haven’t configured properly the CORS, once you have updated the html, you might end up seeing this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2eO3PqnDNFAXGo9fA5ZH3g.png" /></figure><p>Test all the middle steps and be sure that the lambda and the api are fetching results.</p><p>I hope this post has helped you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=771ee7c15571" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use AWS Bedrock with Sagemaker]]></title>
            <link>https://aws.plainenglish.io/simplified-guide-how-to-use-aws-bedrock-with-sagemaker-39316980e8fe?source=rss-7c3bc1fa46ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/39316980e8fe</guid>
            <category><![CDATA[sagemaker]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[Cesar Cordoba]]></dc:creator>
            <pubDate>Tue, 03 Sep 2024 19:33:19 GMT</pubDate>
            <atom:updated>2024-11-22T12:35:54.280Z</atom:updated>
            <content:encoded><![CDATA[<h4>This guide is designed to be very straightforward so you can start testing LLMs using the Sagemaker ecosystem.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iW1BAlZVZwWaZgcS" /><figcaption>Photo by <a href="https://unsplash.com/@burntime?utm_source=medium&amp;utm_medium=referral">Alex Kulikov</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Important considerations:</h3><p>I won’t explain in much detail sagemaker as it is far from the intention of the blog. I’ll introduce you only on how to work there and launch the studio. I won’t go deeper in how you can use it to deploy models.</p><p>Let that be for another blog.</p><h4>INTRODUCTION</h4><p>If you are here, you either know what AWS Bedrock is or you want to learn more about it. Either way, I will do my best to satisfy that curiosity.</p><p>Let me introduce very briefly the service to you.</p><blockquote><strong>Warning</strong>: I’m a bit of a fanboy. The next few paragraphs might sound like I’m trying to sell you a miracle cure, but I swear it’s just genuine enthusiasm. If it feels too much, skip ahead to the tutorial section and let me know so I can adjust it (or not). The tutorial starts at “Getting started on bedrock”</blockquote><p><strong>Bedrock is a service by AWS designed to simplify the process of building and scaling generative AI applications</strong>. Think of it as a comprehensive platform where you can seamlessly access a wide variety of pre-trained AI models from AWS and its partners, including Anthropic, Mistral, and others. Models like Claude, Mistral 7, llama 3, etc.</p><p>These models are versatile, capable of generating text, images and code. Therefore, with this combination of properties, human imagination is the key factor.</p><p>Now, here’s something cool about Bedrock:<strong> it’s serverless</strong>. It removes the burden of setting up or managing any infrastructure so we as developers can focus on the code, the prompts and the integration between services.</p><p>Even though these AI models are pre-trained, they’re not set in stone.</p><p>Sometimes, you might want to <strong>fine-tune these models</strong> so they can better address specific use cases, ensuring more accurate and relevant responses.</p><p>However, in most cases, you may not require to go that far. Instead, you’ll likely implement a <strong>Retrieval-Augmented Generation (RAG) approach</strong>.</p><p>With the fine tuning you train again the model with your data and with RAG you tell the model “I have this data here, saved in this <strong>vector database</strong>. Check first if you can find the answer there, retrieve the specific knowledge and and then use your general knowledge”.</p><p>What makes Bedrock really powerful in this aspect is that you can create the RAG without leaving the console, from data that you have on your S3, from the web or some other third parties.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QcoJ17fV1Vo0s_viGdB5Iw.png" /><figcaption>Choose data sources to create RAGs in Bedrock</figcaption></figure><p>So in summary, AWS Bedrock allows you to implement new Gen AI applications using the model that best suits your needs while it also allows you to customize it with the data you consider.</p><h4>Potential Applications of AWS Bedrock</h4><p>There are many different models available, and it’s the user’s responsibility to choose the one that best suits their needs. This is important because opting for a more advanced model when unnecessary can lead to significant cost implications, potentially increasing expenses by up to 90%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*A7vn23eG8XcWx_l0.jpg" /><figcaption>Bedrock Logo</figcaption></figure><p>Below are several industry-specific applications that demonstrate the versatility and power of AWS Bedrock (or the use of LLMs actually):</p><ul><li><strong>Insurance Sector:</strong> Bedrock can be used to create a RAG system that quickly retrieves and organizes data from contracts and legal documents. This allows insurance professionals to access accurate information through natural language queries, reducing the need for manual file searches.</li><li><strong>Product Recommendation Systems:</strong> Bedrock can connect to external sources via scraping and interact with AWS services, making it ideal for setting up product recommendation engines using data stored in your databases and on the web.</li><li><strong>Document and Image Processing:</strong> Bedrock can analyze photos, emails, and documents to extract specific information. This can be applied to personal finance management, such as categorizing expenses by processing invoices and receipts, offering detailed breakdowns across various categories.</li><li><strong>Medical Assistance: </strong>In healthcare, Bedrock can assist practitioners by summarizing patient histories and highlighting critical information like allergies and past treatments. It can also support telemedicine by recommending medications based on specific conditions and directing physicians to relevant medical literature or guidelines.</li></ul><blockquote>Now that you have a context of what Bedrock is and different use cases, let’s begin with the tutorial.</blockquote><h3>Getting started on bedrock</h3><p>First thing first, you need to log in into the AWS console. Go to the service and select a couple of models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*afChT6-_ZKXdPM5V2QbjGg.png" /><figcaption>AWS Bedrock Console</figcaption></figure><p>You will notice that you can’t use any model out of the box:<strong> you need to indicate to Bedrock which ones you want to have access.</strong></p><blockquote><strong>Note</strong>: Bedrock is a layer of abstraction so when you request access to a model, bedrock actually goes to the marketplace and start a subscription. Unlike fixed monthly charges (20€ subscription), you’ll pay based on requests and tokens exchanged with model providers.</blockquote><p>So, for gaining access we need to go to the left side panel of the console: <strong>Bedrock configurations</strong> → <strong>Model access.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*wmHWvyE_lymEXrIaMw--Kg.png" /><figcaption>Model access in Bedrock Console</figcaption></figure><p>To follow this tutorial, choose the models from Amazon (Titan Embeddings and Titan Text G1 Express), Antrophic (claude 3.5) and Meta (Llama 3).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B8KxpTVuIlTxvby5QozT1g.png" /><figcaption>Meta models</figcaption></figure><p>There isn’t anything else much to do here. Let’s go with sagemaker now.</p><h4>AWS SAGEMAKER INTEGRATION</h4><p>As the title suggest, one of the easiest ways of start using bedrock is through another service: Sagemaker.</p><p>Both services work pretty well together. Nevertheless, it is not mandatory to use sagemaker to follow this tutorial.</p><p>In reality, you only need a role with enough permissions on bedrock so it can be called through <a href="https://boto3.amazonaws.com/v1/documentation/api/latest/index.html">boto3</a>.</p><p>This means that you can use a jupyter notebook on your computer if your credentials have the rights. If you prefer that, I recommend you to download the <a href="http://AWS Toolkit for Visual Studio">AWS Toolkit for Visual Studio</a> and configure it.</p><p>For the sake of simplicity and to teach you how to launch sagemaker, we will continue using this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HdjZzuPfEFPbYCDBb3RbsA.png" /><figcaption>Sagemaker in AWS console</figcaption></figure><p><strong>SageMaker is a fully managed machine learning platform provided by AWS</strong>. It provides tools for building, training, and deploying machine learning models quickly and at scale.</p><h4><strong>1 Initial Setup</strong>:</h4><ul><li>Navigate to the Amazon SageMaker home page in your AWS console.</li><li>Utilize the “Quick setup” option for a single user. This will automatically provision the necessary resources for your environment.</li></ul><h4><strong>2 IAM Role Configuration</strong>:</h4><ul><li>Once the setup is complete, locate the IAM role that SageMaker has generated for your instance. Amazon SageMaker -&gt; Domains -&gt; QuickSetupDomain-date -&gt; <strong>Default execution role</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wWSDFqVJ_YQTxzmH_VTt0g.png" /></figure><ul><li><strong>Go to IAM console</strong>, search for the role and attach to it the appropriate permissions for AWS Bedrock (we are giving full access but this is not good practice).</li></ul><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Sid&quot;: &quot;BedrockAll&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;bedrock:*&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;<br>        },<br>    ]<br>}</pre><h4>3 Launch the Studio:</h4><p>If you have followed the previous steps, you should have the studio ready: <strong>Domains</strong> -&gt; QuickSetupDomain-date -&gt; <strong>User profile</strong> -&gt; <strong>Launch studio</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HwRtFTrkq5nc3HgvvMmdew.png" /><figcaption>How to launch the sagemaker studio</figcaption></figure><p>Once the Sagemaker Studios is up, go to <strong>JupyterLab</strong> and create your session.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RHN5aj2RH96zEIovVfUfXQ.png" /><figcaption>Sagemaer Studio Console</figcaption></figure><p>Use the smallest machine available <strong>ml.t3.medium</strong>. Use the latest sagemkaer distribution (≥1.9).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*edDG2TUZqdsBwURJU0jCiA.png" /><figcaption>Jupyter Lab configuration</figcaption></figure><p>Everything is set up now. With this procedure, you can always create a space in sagemaker where you can test and play around with machine learning models.</p><h3>Deploying LLMs Models</h3><p>Now it’s time to get our hands dirty: Open the notebook and import some libraries:</p><pre>import json <br>import os<br>import sys<br>import boto3</pre><p>Let’s create a client that will allow us to call bedrock:</p><pre>boto3_bedrock = boto3.client(&#39;bedrock&#39;)</pre><p><strong>Boto 3 is a python library that allow us to interact with AWS services</strong>. We use clients to call each service independently and each client has its specific functions to work.</p><p>You can learn more about them in the documentation <a href="https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/bedrock.html">Bedrock — Boto3 1.34.161 documentation</a></p><p>From this client , you can list the models, get some information, create guardrails, jobs, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vtlpuCgEWq--erbr-5GCXQ.png" /><figcaption>Boto 3 documentation for bedrock client</figcaption></figure><p>Right now, what we want is to <strong>call some models</strong> and pass them a prompt. For this we need to use the <strong>bedrock runtime client </strong><a href="https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/bedrock-runtime.html">Bedrock-Runtime — Boto3 1.34.161 documentation</a>.</p><pre>bedrock_runtime = boto3.client(&#39;bedrock-runtime&#39;)</pre><p>Here with the <strong>method invoke_model()</strong> we can call the model of our preference.</p><h4>Constructing the boto3 call</h4><p>Here is the way to construct the function:</p><pre>response = client.invoke_model(<br>    body=b&#39;bytes&#39;|file,<br>    contentType=&#39;string&#39;,<br>    accept=&#39;string&#39;,<br>    modelId=&#39;string&#39;,<br>    trace=&#39;ENABLED&#39;|&#39;DISABLED&#39;,<br>    guardrailIdentifier=&#39;string&#39;,<br>    guardrailVersion=&#39;string&#39;<br>)</pre><p>The most important parameters here are:</p><ul><li><strong>body</strong>, which contains the prompt and some additional arguments. These will vary from one model to another (more on this later).</li><li><strong>modelId</strong>,<strong> </strong>which tells exactly which model we want to call.</li><li><strong>contenType</strong>,<strong> </strong>where<strong> </strong>we need to pass always “application/json” as we will format the <strong>body</strong> like this.</li></ul><p>You might be asking yourself, <em>How can I know the model ID?</em></p><p>I got you cover! Just check: <a href="https://docs.aws.amazon.com/bedrock/latest/userguide/model-ids.html#model-ids-arns">Amazon Bedrock model IDs — Amazon Bedrock</a></p><p>The response syntax of the function will be as simple as:</p><pre>{<br>    &#39;body&#39;: StreamingBody(),<br>    &#39;contentType&#39;: &#39;string&#39;<br>}</pre><p>Where in the “body” we will have the output of the model.</p><p>Once again, how we access the response is different from one model to another. Check <a href="https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters.html">Inference parameters for foundation models — Amazon Bedrock</a>.</p><p>To simplify the tutorial, we are going to use Claude from Anthropich and Titan from Amazon.</p><h4>Jupyter Notebook</h4><p>Your first cell should look like this:</p><pre>import json <br>import os<br>import sys<br>import boto3<br>import botocore<br>bedrock_runtime = boto3.client(&#39;bedrock-runtime&#39;)</pre><p>The prompt:</p><pre># If you&#39;d like to try your own prompt, edit this parameter!<br>prompt_data = &quot;&quot;&quot;Command: Write me a short poem about a data scientist reading a blog in medium.<br>Poem:<br>&quot;&quot;&quot;</pre><p>And the models:</p><h4>Titan</h4><pre># Amazon Titan parameters<br>body = json.dumps(<br>	{&quot;inputText&quot;: prompt_data, <br>	&quot;textGenerationConfig&quot; : {&quot;topP&quot;:0.95, &quot;temperature&quot;:0.2}}<br>)<br>modelId = &quot;amazon.titan-tg1-large&quot; <br>accept = &quot;application/json&quot;<br>contentType = &quot;application/json&quot;<br><br>titan_response = bedrock_runtime.invoke_model(<br>    body=body, <br>    modelId=modelId, <br>    accept=accept, <br>    contentType=contentType<br>)</pre><h4>Claude</h4><pre># Claude parameters<br>body = json.dumps(<br>       {&quot;prompt&quot;: prompt_data, <br>       &quot;max_tokens_to_sample&quot;: 500}<br>)<br>modelId = &quot;anthropic.claude-instant-v1&quot;  # change this to use another version from the model provider<br>accept = &quot;application/json&quot;<br>contentType = &quot;application/json&quot;<br><br>claude_response = bedrock_runtime.invoke_model(<br>    body=body, <br>    modelId=modelId, <br>    accept=accept, <br>    contentType=contentType<br>)</pre><p>Stop here for a moment. Please note how the main difference in the body isthat for Titan you pass a json with <strong><em>inputText</em></strong> as the prompt and some configuration within the <strong><em>textGenerationTopic</em></strong>.</p><p>In the case of Claude, you pass the prompt in the <strong><em>prompt key</em></strong> and the extra configuration in <strong><em>max_token_to_sample</em></strong>.</p><p>Let’s see how to display the response.</p><p><strong>Titan response:</strong></p><pre>titan_response_body = json.loads(titan_response.get(&quot;body&quot;).read())<br>print(titan_response_body.get(&quot;results&quot;)[0].get(&quot;outputText&quot;))</pre><p><strong>Claude response:</strong></p><pre>claude_response_body = json.loads(claude_response.get(&quot;body&quot;).read())<br>print(claude_response_body.get(&quot;completion&quot;))</pre><p>As I mentioned before, in both cases we get the answer in the body argument of the response. They differ in that within the body, we need to extract different keys depending on the model.</p><pre>titan_response_body.get(&quot;results&quot;)[0].get(&quot;outputText&quot;) for titan</pre><pre>claude_response_body.get(&quot;completion&quot;) for claude</pre><h4>Full code</h4><pre>import json <br>import os<br>import sys<br>import boto3<br>import botocore<br>bedrock_runtime = boto3.client(&#39;bedrock-runtime&#39;)<br><br># If you&#39;d like to try your own prompt, edit this parameter!<br>prompt_data = &quot;&quot;&quot;Command: Write me a short poem about a data scientist reading a blog in medium.<br>Poem:<br>&quot;&quot;&quot;<br><br># Amazon Titan parameters<br>body = json.dumps(<br> {&quot;inputText&quot;: prompt_data, <br> &quot;textGenerationConfig&quot; : {&quot;topP&quot;:0.95, &quot;temperature&quot;:0.2}}<br>)<br>modelId = &quot;amazon.titan-tg1-large&quot; <br>accept = &quot;application/json&quot;<br>contentType = &quot;application/json&quot;<br><br>titan_response = bedrock_runtime.invoke_model(<br>    body=body, <br>    modelId=modelId, <br>    accept=accept, <br>    contentType=contentType<br>)<br><br>titan_response_body = json.loads(titan_response.get(&quot;body&quot;).read())<br>print(titan_response_body.get(&quot;results&quot;)[0].get(&quot;outputText&quot;))</pre><p>I’m curious about what your output was ! You can play around with your own prompts, different models and check for the other parameters to see how your output vary.</p><p>Once you have finished, go to the domain in sagemaker and delete it. You will need to <strong>delete the user first</strong>, otherwise it won’t let you delete the domain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C9Mku3-5H-u8-vS0urJf7g.png" /><figcaption>delete domain option</figcaption></figure><h3>RECAP</h3><ul><li>Bedrock allows you to subscribe to different models that you can call via boto 3.</li><li>You can launch your Sagemaker Studio to play around in a JupyterLab environment.</li><li>Even though both the request and response are constructed with the same syntax, the arguments you pass vary from one model to another: <a href="https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters.html">https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters.html</a></li></ul><h3>BONUS</h3><h4>Generate images</h4><p>In bedrock you can use the models from stability too. The syntax is what you already know but in the body we use:</p><pre>{<br>    &quot;text_prompts&quot;: [{&quot;text&quot;: prompt_data}],<br>    &quot;cfg_scale&quot;: 10,<br>    &quot;seed&quot;: 20,<br>    &quot;steps&quot;: 50<br>}</pre><pre>prompt_data = &quot;Image of and elder tree with golden leafs&quot;<br>body = json.dumps({<br>    &quot;text_prompts&quot;: [{&quot;text&quot;: prompt_data}],<br>    &quot;cfg_scale&quot;: 10,<br>    &quot;seed&quot;: 20,<br>    &quot;steps&quot;: 50<br>})<br>modelId = &quot;stability.stable-diffusion-xl-v1&quot;<br>accept = &quot;application/json&quot;<br>contentType = &quot;application/json&quot;<br><br><br>response = bedrock_runtime.invoke_model(<br>    body=body, modelId=modelId, accept=accept, contentType=contentType<br>)<br>response_body = json.loads(response.get(&quot;body&quot;).read())<br><br>print(response_body[&quot;result&quot;])<br>print(f&#39;{response_body.get(&quot;artifacts&quot;)[0].get(&quot;base64&quot;)[0:80]}...&#39;)<br># output: iVBORw0KGgoAAAANSUhEUgAABAAAAAQACAIAAADwf7zUAAABjmVYSWZNTQAqAAAACAAGAQAABAAAAAEA...<br></pre><p>The output is a base64 encoded string data. You need to decode it:</p><pre>%pip install pillow<br>import base64<br>import io<br>from PIL import Image<br><br>base_64_img_str = response_body.get(&quot;artifacts&quot;)[0].get(&quot;base64&quot;)<br>image = Image.open(io.BytesIO(base64.decodebytes(bytes(base_64_img_str, &quot;utf-8&quot;))))<br>image</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pqk02UsvC1i0FxGyK8jUig.png" /></figure><p>I hope that this has ignited your interest in using bedrock and you have realized that it is not so complicated to start developing.</p><p>In future posts, I will talk about more complex scenarios and how you can use sagemaker to actually handle production deployments.</p><h3><strong>Bibliography</strong></h3><p>This post was motivated from the AWS workshop: <a href="https://catalog.us-east-1.prod.workshops.aws/workshops/a4bdb007-5600-4368-81c5-ff5b4154f518/en-US">https://catalog.us-east-1.prod.workshops.aws/workshops/a4bdb007-5600-4368-81c5-ff5b4154f518/en-US</a></p><p>I highly recommend to go and check it and do all the labs that are in there. I have tried to cover some aspects that the notebooks take from granted so you are better prepared.</p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39316980e8fe" width="1" height="1" alt=""><hr><p><a href="https://aws.plainenglish.io/simplified-guide-how-to-use-aws-bedrock-with-sagemaker-39316980e8fe">How to use AWS Bedrock with Sagemaker</a> was originally published in <a href="https://aws.plainenglish.io/">AWS in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Road to AWS Data Engineer certification]]></title>
            <link>https://aws.plainenglish.io/road-to-aws-data-engineer-certification-f61470ba9fc1?source=rss-7c3bc1fa46ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/f61470ba9fc1</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-certification]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[Cesar Cordoba]]></dc:creator>
            <pubDate>Tue, 25 Jun 2024 18:49:30 GMT</pubDate>
            <atom:updated>2025-01-06T03:17:26.486Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>During this series of posts, I will be covering all the aspects of AWS Data Engineer certification: What I’m studying and what I consider it’s important. Once I try the exam and pass or fail, this content might suffer some changes</blockquote><h3>Updates:</h3><p>As I promised, here is my feedback after passing the exam (oct-2024)</p><p>Time preparation: If you are consistent, 3–4 weeks are more than enough (8h per week)</p><p>Contents:</p><p>Basically everything I listed in the main article was in the exam. Nevertheless, some topics were more prominent.</p><p>- The exam do test about git concepts and CI/CD – review them.</p><p>- On compute/analytics, Glue, Athena &amp; Redshift were the preferred topics on my exam. EMR &amp; lambda also appeared but with less frequency.</p><p>- On storage, S3 was the king (partitioning for Big Data, data formats &amp; data lakes)</p><p>- On orchestration, step functions &amp; glue</p><p>- On databases: RDS for my SQL, two or three questions.</p><p><strong>Having worked with Data Mesh is a huge plus</strong>, Iceberg mentions appeared. Glue catalog and lake formation also were asked</p><p>My honest advice: do a course if you need to refresh concepts, the exam is not precisely cheap nor easy to go unprepared. <strong>And of course, do as many questions as you can before the exam.</strong></p><p>I let here the updated resources I used and the ones I keep recommending if you have time to do them.</p><p>Best of luck and let your comments if you pass!!🙌🙌</p><h3><strong>What is going to be tested?</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*kCAm_tRWbdI-Ti5PJ7LHPg.png" /></figure><p>The main objective of the test is to validate the ability to implement data pipelines and to monitor, troubleshoot, and optimize cost and performance issues in accordance with best practices (both of code and of AWS).</p><p>It does so by validating the following tasks:</p><ul><li>Ingest and transform data, and orchestrate data pipelines while applying programming concepts. -The very well know ETL/ELT processes-</li><li>Choose an optimal data store, design data models, catalog data schemas and manage data lifecycles.</li><li>Operationalize, maintain, and monitor data pipelines. Analyze data and ensure data quality.</li><li>Implement authentication, authorization, data encryption, privacy, and governance. Enable logging.</li></ul><h3><strong>Target candidate</strong></h3><ul><li>The candidate should have 2–3 years of experience in data engineering. 1 year with hands-on experience in AWS</li><li>The candidate should understand the effects of volume, variety and velocity on data ingestions (”the threes V’s)</li><li>The candidate should know about modeling, transformation, security, governance, privacy, and optimal data store design.</li></ul><h3><strong>Recommended knowledge:</strong></h3><h4>General:</h4><ul><li>How to use Apache Spark</li><li>File formats: Parquet, CSV, ORC</li><li>How to use git commands: Create, update, clone and branch repositories</li><li>Optimize Sql queries</li><li>CI/CD topics</li></ul><h4>AWS Specific:</h4><ul><li>Setup and maintenance of ETL pipelines (and how to do it in AWS): Amazon EventBridge, Step functions, Apache Airflow</li><li>Batch vs streaming: Glue Jobs, Kinesis, DynamoDb Streams</li><li>How to set up data lakes to store data: Lake Formation, Glue catalog, Crawlers</li><li>General knowledge about compute: Amazon Glue, EMR, EC2, lambdas</li><li>General knowledge about storage: Amazon S3, DynamoDB, Amazon Aurora</li><li>How to structure SQL queries and how to run them on AWS services: Athena, Redshift</li><li>How to use notification services to send alerts: Amazon S3 Event Notification, Amazon SNS, Amazon SQS</li></ul><h3><strong>Out of the Scope:</strong></h3><ul><li>Artificial Intelligence and machine learning tasks</li><li>Specific programming language syntax</li><li>Draw business conclusions based on data</li></ul><h3><strong>How do I know If I have passed the exam?</strong></h3><p>The minimum score is 720 out of 1000. There are different sections and each one has a specific weighting</p><p><strong>The exam has the following content domains and weightings:</strong></p><ul><li>Domain 1: Data Ingestion and Transformation (34% of scored content)</li><li>Domain 2: Data Store Management (26% of scored content)</li><li>Domain 3: Data Operations and Support (22% of scored content)</li><li>Domain 4: Data Security and Governance (18% of scored content)</li></ul><p>For more information on the exam (response types, scoring, content and results) check: <a href="https://d1.awsstatic.com/training-and-certification/docs-data-engineer-associate/AWS-Certified-Data-Engineer-Associate_Exam-Guide.pdf?trk=999c565d-69a8-4d73-b5a4-f7f966e205e0&amp;sc_channel=em&amp;mkt_tok=MTEyLVRaTS03NjYAAAGTd2gNJcAyv_z0RuYRy5ny7ptYiM65G4TqjJlhOX5ob1W9lZj7iP-7AqAgBwbYKMmA3NaBPRhLm1RtqiwJMTCi4HohFdcPIDIgkYb7Shg7Zwr48BYJdse5">AWS Certified Data Engineer — Associate (DEA-C01) Exam Guide</a></p><p><strong>To book your exam you can do it here:</strong></p><p><a href="https://aws.amazon.com/certification/certified-data-engineer-associate/">AWS Certified Data Engineer — Associate Certification | AWS Certification (amazon.com)</a></p><h3>Resources that guarantee 100% pass:</h3><h4>Free complementary videos</h4><p>I didn’t use them at all. Nevertheless, if you don’t want to pay anything, give them a look.</p><ul><li><a href="https://explore.skillbuilder.aws/learn/course/external/view/elearning/18440/fundamentals-of-analytics-on-aws-part-2"><strong>Fundamentals of Analytics on AWS — Part 2</strong></a></li><li><a href="https://explore.skillbuilder.aws/learn/course/external/view/elearning/15545/planning-large-scale-data-migrations-to-aws"><strong>Planning Large Scale Data Migrations to AWS</strong></a></li></ul><h4>Paid courses:</h4><p>I did 3/4 of the course. And on 2x speed.</p><p>Teachers are good but the course gets quite… difficult to follow. After a couple of hours, concentration completely desintegrates.</p><p>Of course, it doesn’t help that the topic has a lot of theory, and theory is not as sexy as building.</p><ul><li><a href="https://www.udemy.com/course/aws-data-engineer/">https://www.udemy.com/course/aws-data-engineer/</a></li></ul><h4>Free Exam Prep courses:</h4><p>If I haven’t had the paid course, I would have gone for the enhanced version(go straight to the module 4). It has labs.</p><ul><li>Standard (6h): <a href="https://explore.skillbuilder.aws/learn/course/external/view/elearning/18546/exam-prep-standard-course-aws-certified-data-engineer-associate-dea-c01">https://explore.skillbuilder.aws/learn/course/external/view/elearning/18546/exam-prep-standard-course-aws-certified-data-engineer-associate-dea-c01</a></li><li>Enhanced (13h) It is standard + labs + extra questions + additional resources to learn: <a href="https://explore.skillbuilder.aws/learn/course/external/view/elearning/18603/exam-prep-enhanced-course-aws-certified-data-engineer-associate-dea-c01-english">https://explore.skillbuilder.aws/learn/course/external/view/elearning/18603/exam-prep-enhanced-course-aws-certified-data-engineer-associate-dea-c01-english</a></li></ul><h4>Twitch videos by AWS Employees</h4><p><a href="https://pages.awscloud.com/GLOBAL-other-T2-Traincert-AWS-Power-Hour-Data-Engineer-Associate-Season1-2024-reg.html">https://pages.awscloud.com/GLOBAL-other-T2-Traincert-AWS-Power-Hour-Data-Engineer-Associate-Season1-2024-reg.html</a></p><h4>Official practice tests:</h4><p>Do them if you don’t want to spend time in examtopics.</p><p><a href="https://explore.skillbuilder.aws/learn/course/external/view/elearning/16985/aws-certified-data-engineer-associate-official-practice-question-set-dea-c01-english?trk=999c565d-69a8-4d73-b5a4-f7f966e205e0&amp;sc_channel=em&amp;mkt_tok=MTEyLVRaTS03NjYAAAGTd2gNJvcPVApVe8ZorSVwAmiRkQ_bS-cBA0JBvwOAMVmlOWs-HGxDuG8ZyBWcB8bBIrpOjCmTzjTVmpBn0pd_mxi-sdNZVvsAcmt-JWEtIf6f-f0G0qi1"><strong>Exam Prep Official Practice Question Set: AWS Certified Data</strong></a></p><p><a href="https://explore.skillbuilder.aws/learn/course/external/view/elearning/18609/exam-prep-official-pretest-aws-certified-data-engineer-associate-dea-c01-english"><strong>Exam Prep Official Pretest: AWS Certified Data Engineer — Associate</strong></a></p><h4>Non-official practice tests:</h4><p>Whatever you find on ExamTopics, do all the questions before going to any video practice test (at least 40).</p><p>For the questions you fail, go and read the documentation thoroughly.</p><p>You want to pass the exam, but also learn something.</p><h4><strong>Video Practice test:</strong></h4><p>I did the first and second video. 1.5x speed.</p><p>I do think I should have done more tests but I was on a hurry. Nevertheless, this guy helped me a lot</p><p><a href="https://youtu.be/O2cbN1MNPMQ?si=Ksi4lCkEVRXEbZm8">AWS Certified Data Engineer Associate Exam questions – sthithapragna</a></p><h3>Closing Comments</h3><p>I truly hope this content helps you.</p><p>Please let me know in comments if you encounter anything different on your exam so I can update the post and help more people.</p><p>Also, if you want to connect and share your experience, you can find me here: <a href="https://www.linkedin.com/in/cesar-restrepo-cordoba">https://www.linkedin.com/in/cesar-restrepo-cordoba</a></p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://cofeed.app/"><strong>Check out CoFeed, the smart way to stay up-to-date with the latest in tech</strong></a> <strong>🧪</strong></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f61470ba9fc1" width="1" height="1" alt=""><hr><p><a href="https://aws.plainenglish.io/road-to-aws-data-engineer-certification-f61470ba9fc1">Road to AWS Data Engineer certification</a> was originally published in <a href="https://aws.plainenglish.io/">AWS in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[S3 Lifecycle Rules: Optimized Storage Costs and Enhanced Data Compliance]]></title>
            <link>https://medium.com/@cesar.cordoba/unlock-the-power-of-s3-lifecycle-rules-optimized-storage-costs-and-enhanced-data-compliance-0383b51b7ebd?source=rss-7c3bc1fa46ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/0383b51b7ebd</guid>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Cesar Cordoba]]></dc:creator>
            <pubDate>Mon, 05 Feb 2024 19:48:11 GMT</pubDate>
            <atom:updated>2024-03-17T15:29:41.232Z</atom:updated>
            <content:encoded><![CDATA[<h4>Data Engineer | Cloud Optimization</h4><blockquote>In this post, we will explore the significant economic and legal advantages of using lifecycle rules, demonstrating how well-defined rules can streamline data management, reduce storage costs and protect data throughout its lifecycle.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HDdD1QV44sQbMQCm.png" /><figcaption>AWS S3. Source: <a href="https://aws.amazon.com/es/s3/">https://aws.amazon.com/es/s3/</a></figcaption></figure><p>As companies migrate to the cloud, automated data management becomes crucial. Therefore, <strong>before your data project expands, prioritize setting up the s3 buckets:</strong></p><ol><li><strong>Enable versioning</strong>: This safeguards critical data and allows fast rollbacks if needed.</li><li><strong>Define lifecycle rules</strong>: Determine deletion or archiving timelines based on data type, compliance requirements, and cost optimization goals.</li><li><strong>Fine-tune later:</strong> Flexibility lets you adjust rules as your needs evolve</li></ol><h4>What is versioning?</h4><p>Before we go further on lifecycle rules, I would like to discuss briefly versioning. This is crucial to understand the impact of the lifecycle rules.</p><p>As its name suggests, versioning is a feature that allows you to keep multiple variants of an object within the same bucket. When enabled, every object stored in the bucket is assigned an <strong>unique version ID. </strong>This means that every time you modify an object, a new version of it is created.</p><figure><img alt="Example of s3 bucket with severa versions of a file in it" src="https://cdn-images-1.medium.com/max/1024/1*U1-0OMyb0sOQN-QAhJQ1cA.png" /><figcaption>Example of a file with 4 versions</figcaption></figure><p>On a similar way, this happens when we delete a file. While seemingly deleted, files with versioning enabled actually receive a “delete marker” instead of being permanently deleted: We won’t be able to see them or use them (unless we specifically check for the versions) but they <strong>still incur storage costs.</strong></p><figure><img alt="Example of deleted file with versioning enabled" src="https://cdn-images-1.medium.com/max/1024/1*MznNQfbo9skkv47bDsWiNg.png" /><figcaption>Example of a file with a “deleted” version</figcaption></figure><p>Versioning is crucial as it simplifies accidental deletion recovery. However, it’s necessary to grasp the impact on “deletion” for optimal storage management and compliance:</p><p>Imagine you need to write 100GB of temporary files once a day (<a href="https://docs.aws.amazon.com/glue/latest/dg/monitor-spark-shuffle-manager.html">some shuffle using s3 — Glue</a>). Doing some maths, by the end of a month you can expect to have 300 TB of “deleted” data and still pay for that: 300 TB * $0.0095/GB/month ≈ $2,850/month.</p><p>In this post, however, I will present you some ways to keep your environment clean and costs under control.</p><h4>What are lifecycle rules?</h4><p>S3 lifecycle rules are a feature of Amazon Simple Storage Service (S3) that, by defining a set of actions, allows you to automatically manage the storage of your objects over time. These rules are highly customizable so they can meet any specific needs: you just need to specify the conditions that an object must meet to trigger a particular action.</p><h4>Types of S3 lifecycle rules</h4><p>There are two types of S3 lifecycle rules:</p><ul><li><strong>Transition action rules</strong>: These rules move objects to a different storage class at pre-defined time intervals. For example, you could create a rule that moves objects to S3 Glacier Deep Archive storage after 1 year.</li><li><strong>Expiration action rules</strong>: These rules are in charge of deleting <strong><em>permanently</em></strong><em> </em>objects after a specified period of time. For example, you could create a rule that deletes objects that have not been modified in 3 years or a rule to keep only the last three versions of a file.</li></ul><h4>Benefits of using S3 lifecycle rules:</h4><ul><li><strong>Simplify data management</strong>: You can automate the management of your data lifecycle, which can save you time and effort.</li><li><strong>Compliance</strong>: GDPR rules demand responsible data handling, including defined retention periods. If this is the case for you, you can implement automated deletion for outdated data to simplify compliance and safeguard your users. <br><strong><em>Word of Caution</em></strong><em>: Data lakes in S3 require special attention. Their dynamic nature allows continuous modification, blurring the lines of “data age”</em></li><li><strong>Reduce storage costs</strong>: You can move objects to lower-cost storage classes as they become less frequently accessed. For example, you can move objects to S3 Glacier Deep Archive storage after 3 years, which can save you up to 95% of the storage cost.</li></ul><blockquote><strong>Changes in billing</strong></blockquote><blockquote>There may be a lag between when the Lifecycle configuration rules are satisfied and when the action triggered by satisfying the rule is taken. However, changes in billing happen <strong>as soon as the Lifecycle configuration rule is satisfied</strong>, even if the action is not yet taken: <strong>after the object expiration time, you are not charged for storage, even if the object is not deleted immediately</strong>.</blockquote><blockquote>Nevertheless, transitions have particular rules. In the case of a transition from one class to S3 Glacier, once the condition is met, you will be charged S3 Glacier Flexible Retriever storage rates if you access the information. <strong>Even if the object is not immediately transitioned to the corresponding storage</strong>. For more information on other transitions, please check [<a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/how-to-set-lifecycle-configuration-intro.html">Source</a>].</blockquote><h3>How to configure lifecycle rules</h3><h4>Defining policies in S3 console</h4><ol><li>Go to the S3 service inside your account</li><li>Go to the bucket you want to configure. In this case, “test-bucket”</li><li>Make sure that bucket versioning is enabled</li><li>Go to the “management” tab</li><li>Create lifecycle rule</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*55jAlmngPTRwtz9-wAFYbw.png" /></figure><p>6. Give the rule a name and scope: To all the objects in a bucket or to objects that match a certain prefix or tag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H3OIxCDImgHjqQK2gariKQ.png" /></figure><p>Let’s see this in more detail. Here we have inside our bucket, four different folders.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ujmwnh0bjHoJKSnSasl-XQ.png" /></figure><p>If we define a prefix like <strong>temp_folder</strong>, this prefix will trigger a regex that will match the four folders inside our bucket. Therefore, if we would want to delete only “temp_folder” then the prefix must be defined as <strong>temp_folder/.</strong></p><p>Please, remember to use always the backslash(/) to define more precisely the scope of your rules.</p><p>7. Specify the action</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-NM68HmXwzPJ8B6bU4blIw.png" /></figure><p>Although 5 different options are presented we will focus on the last 3 as the others are more straightforward.</p><ul><li><strong>Expire current versions of objects</strong>: to delete the files inside the folder after an x amount of days.</li><li><strong>Permanently delete noncurrent versions of objects</strong>: once a file has been deleted (or overwritten), it becomes noncurrent. With this action, we decide that after x days we want its versions to be deleted. Also, we can decide how many versions we want to keep.</li><li><strong>Delete expired object delete markers or incomplete uploads</strong>: remove the delete markers.</li></ul><p>And this is it. With lifecycle rules in place, you won’t longer need to worry of hidden cost for old versions and you can be sure that what you deleted is actually deleted after the days you have specified.</p><p>Take into account that lifecycle rules are executed once a day. After the first time that Amazon S3 runs the rules, all objects that are eligible for expiration are marked for deletion.</p><p>Amazon S3 asynchronously expires object versions and removes delete markers. It might take the rules a few days before the bucket is empty. Nevertheless, once triggered remember <strong>you’re no longer charged for objects that are marked for deletion. </strong>For more information about asynchronous object removal in Amazon S3, see <a href="https://docs.aws.amazon.com/AmazonS3/latest/dev/lifecycle-expire-general-considerations.html">Expiring objects</a>.</p><blockquote>It’s important to carefully plan and test your lifecycle rules to ensure they align with your data management requirements and budget constraints.</blockquote><h4>Others</h4><ul><li>One alternative to the previous option is to use the command shell in AWS to indicate the bucket and prefix to permanently delete. Check <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/how-to-set-lifecycle-configuration-intro.html"><strong>Using the AWS CLI</strong></a><strong>.</strong></li><li>Also, if you are using infrastructure as a code, when deploying a bucket you can configure the policies right away using <a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/s3_bucket_lifecycle_configuration">terraform</a> or <a href="https://www.pulumi.com/registry/packages/aws/api-docs/s3/bucketlifecycleconfigurationv2/">pulumi</a>.</li></ul><h3>BONUS: Permanently delete files via python script</h3><p>In case you need to write that temporary parquet file in a folder and don’t want to mess with specific lifecycle rules you can still permanently delete it. For this, you will need to use boto3, the AWS SDK for python</p><h4>Using this code you can permanently delete a folder.</h4><pre>import boto3<br><br># Initialize Boto3 S3 client<br>s3_client = boto3.client(&#39;s3&#39;, <br>                        aws_access_key_id=&#39;YOUR_ACCESS_KEY&#39;, <br>                        aws_secret_access_key=&#39;YOUR_SECRET_KEY&#39;<br>)<br><br># Specify the bucket name and object key<br>bucket_name = &#39;test-bucket-policy&#39;<br>object_key = &#39;temporary-folder/temporary-file&#39;<br><br># To delete all versions of an object (including delete markers):<br>s3_client.delete_object(Bucket=bucket_name, Key=object_key)<br><br>print(f&quot;Folder deleted successfully.&quot;)</pre><h3>References</h3><p>If you want to learn more, please consider reading too:</p><ul><li><a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/Versioning.html">Using versioning in S3 buckets</a></li><li><a href="https://repost.aws/knowledge-center/s3-empty-bucket-lifecycle-rule">Empty an Amazon S3 bucket with a lifecycle configuration rule</a></li><li><a href="https://repost.aws/knowledge-center/s3-lifecycle-rule-non-current-version">Create S3 lifecycle rules for non-current object versions</a></li><li><a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/how-to-set-lifecycle-configuration-intro.html">Setting lifecycle configuration on a bucket</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0383b51b7ebd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to work with Iceberg format in AWS-Glue.]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@cesar.cordoba/how-to-work-with-iceberg-format-in-aws-glue-258bbcec52d7?source=rss-7c3bc1fa46ce------2"><img src="https://cdn-images-1.medium.com/max/800/1*GYn0UEm98R-muw3CYBb8fw.png" width="800"></a></p><p class="medium-feed-snippet">As the official guide might be overwhelming some times, this post has been designed to cover all the main operations that one would want&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@cesar.cordoba/how-to-work-with-iceberg-format-in-aws-glue-258bbcec52d7?source=rss-7c3bc1fa46ce------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@cesar.cordoba/how-to-work-with-iceberg-format-in-aws-glue-258bbcec52d7?source=rss-7c3bc1fa46ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/258bbcec52d7</guid>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[apache-iceberg]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Cesar Cordoba]]></dc:creator>
            <pubDate>Wed, 06 Sep 2023 12:54:10 GMT</pubDate>
            <atom:updated>2024-05-20T15:38:25.803Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Iceberg format: a short introduction]]></title>
            <link>https://medium.com/@cesar.cordoba/iceberg-format-a-short-introduction-6cca39e48ac?source=rss-7c3bc1fa46ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/6cca39e48ac</guid>
            <category><![CDATA[apache-iceberg]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[Cesar Cordoba]]></dc:creator>
            <pubDate>Wed, 06 Sep 2023 12:46:51 GMT</pubDate>
            <atom:updated>2023-09-06T12:46:51.238Z</atom:updated>
            <content:encoded><![CDATA[<h4>Data engineering | Big Data</h4><blockquote>Whether you choose a data mesh or a data lake strategy, finding the right format is crucial in the long term. Let’s look first at the current “panorama” of data lakes and understand the major benefits of using a table format like Iceberg.</blockquote><h3>Table formats: Iceberg</h3><p>Chances are that if you are into the data engineering field, you might be working with some <strong>table format</strong>. In particular, three are the leaders on this field: <a href="https://delta.io/">delta lake</a>, <a href="https://hudi.apache.org/">apache hudi</a> and <a href="https://iceberg.apache.org/">apache iceberg</a>. These formats enhance other popular <strong>data formats</strong> like <em>parquet</em> or <em>avro</em> by adding an extra layer of metadata that enables transactional capabilities.</p><p>In the case of Iceberg, its metadata is made up of:</p><ul><li>A <strong>snapshot log.</strong> Every snapshot (s0 -&gt; s1) represents the state of the table at some time, i.e, list all the data files that make up the table.</li><li><strong>A manifest list. </strong>This file<strong> </strong>is made up of several manifest files with some information associated of them, that is <strong>used to speed up metadata operations.</strong></li><li><strong>Manifest files. </strong>A manifest file lists a subset of data files that make up the snapshot. Each data file in a manifest is stored with some column-level statistics used to prune splits during <a href="https://iceberg.apache.org/performance#scan-planning">scan planning</a>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*B6qr44le50ancXPg3cYq7A.png" /><figcaption>Schema of iceberg format: <a href="https://iceberg.apache.org/spec/">https://iceberg.apache.org/spec/</a></figcaption></figure><h3>Data lake vs transactional data lake</h3><p>A typical data lake in the cloud consist of a blob storage system where the data is stored and a catalog where the tables are kept.</p><p>This catalog normally tracks the files at folder level, so you need to use precise <em>where</em> clauses for querying, otherwise it will list all the files.</p><p>Table formats are a powerful solution for this problem. They explicitly define a table on their own, so now the catalog only has to track the metadata file that tells the query engine where to find the data.</p><p>It doesn’t stop there, by adding this extra layer we get some other enhancements :</p><ul><li><strong>Schema evolution</strong>. Because of the metadata, instead of applying a schema when the data is read, clients already know the schema before the query is run. It also facilitates tracking the changes of a table over time.</li><li><strong>Time travel</strong>. As the metadata contains the mapping to previous version of the data, it’s possible to rollback or query old versions if required.</li><li><strong>Speed</strong>. The metadata has statistics which allow to speed up queries by prunning files that aren’t needed.</li></ul><h3>What is iceberg and why you want to use it?</h3><figure><img alt="apache iceberg logo" src="https://cdn-images-1.medium.com/max/800/1*GYn0UEm98R-muw3CYBb8fw.png" /></figure><p>Apache Iceberg is an open-source <strong>table format, </strong>originally developed by Netflix<strong>, </strong>for data processing on large datasets stored in data lakes (up to petabytes). It offers speed, efficiency and reliability at any scale, as well as ACID features. It also supports time travel, version rollback, schema evolution and data compaction by default.</p><p>We have said that there are three major projects so what makes Iceberg different? Focusing on what, in my opinion, makes iceberg shine is:</p><ul><li><strong>Iceberg is agnostic to processing engine and file format</strong>. You can use it on top of AVRO, ORC and Parquet. Also, many engines will benefit from it: Spark, Flink, Hive, Athena and more. In contrast, consider delta lake, which is excellent, but currently only runs on top of parquet and is mainly used with spark.</li><li><strong>Fully Open source project</strong>. You have many businesses interested in this and contributing actively.</li><li>Have <strong>concurrent writes</strong> with <a href="https://iceberg.apache.org/docs/latest/reliability/">optimistic locking</a>.</li></ul><h3>References</h3><p>If you want to learn more of iceberg or table formats, please consider reading too:</p><ul><li><a href="https://iceberg.apache.org/docs/latest/">Introduction - Apache Iceberg™</a></li><li><a href="https://www.dremio.com/resources/guides/apache-iceberg/">What Is Apache Iceberg? Features &amp; Benefits</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6cca39e48ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Step Functions: How to use variables]]></title>
            <link>https://aws.plainenglish.io/step-functions-how-to-use-variables-1c77f6133e87?source=rss-7c3bc1fa46ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c77f6133e87</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[step-functions]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Cesar Cordoba]]></dc:creator>
            <pubDate>Wed, 07 Jun 2023 16:24:23 GMT</pubDate>
            <atom:updated>2024-11-22T12:36:13.853Z</atom:updated>
            <content:encoded><![CDATA[<h4>Cloud | AWS</h4><h4>In this post, we will look through many examples, how to create AWS Step Functions using some JSON as input.</h4><p>Here I assume you have basic knowledge of what a step function is and you are familiar with the AWS State Language (<a href="https://medium.com/@cesar.cordoba/step-functions-state-language-d60620f44d67">Step Functions: State Language</a>).</p><h3>Step functions + parameters</h3><p>In AWS, it is very common to use Lambda functions and Spark jobs to process the information. Let’s imagine we have a simple process where we start with a Lambda to fetch some data and then proceed with a Glue job.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*OuUku6X539tjUU-NsbVXuQ.png" /><figcaption>Simple workflow to invoke a lambda and then a glue job</figcaption></figure><p>Let’s say too that in our use case, we want our Step Function to <strong>work in two or more ways</strong> depending on a variable. We also want the Step to be able to react to it at the execution’s start.</p><p>As an example, this might be a regular ETL that runs on a daily basis. This process fetches some data from a server, performs some operations on it, and then saves the data in two different S3 buckets: one for the archive and another for the refined data.</p><p>Imagine we have been working on the ETL and we have made some changes in the logic for extracting the information. Now, we need to reprocess some files from the archive. We can make use of two variables “from” and “to” that, if set as “2023–01–01” and “2023–01–05” accordingly, instead of trying to retrieve files from the server, it will look for them in the archive.</p><p>One way to achieve this is by defining <strong>environment variables</strong> for the lambda functions and <strong>job parameters</strong> for the glue job.</p><figure><img alt="AWS console for setting environment variables" src="https://cdn-images-1.medium.com/max/1024/1*IikonwBhAqTr2mbzglIbQw.png" /><figcaption>Defining Environment Variables for lambda</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AjloAf-O76hHiR-bmySEAg.png" /><figcaption>Defining Parameters for glue</figcaption></figure><p>Nevertheless, these variables are defined independently in each service and we can’t modify them on the fly once they are set. To do so, we need to go to each service, make the changes, and save them.</p><p>It’s not a complicated operation but it takes time… and if we add more services to the equation, we might end up forgetting to modify one.</p><p>We need a new approach.</p><h4>Input and Output Processing</h4><p>To start with the explanation, we need to understand how the information flows between the different states in our step function.</p><p>Imagine we have in our step function a single lambda task and its <strong>State Input</strong> is a Json containing some information (See the image below).</p><p>After using this information and doing all the required work, the lambda will return an output, the <strong>Task Result</strong>. In this particular example, it will return back “Hello, AWS Step Functions!”</p><p>To keep it simple, we face two options, should we append the result into the input Json or should we only retrieve the task result?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*n2imbd-ABTbbnybxJ868Tw.png" /><figcaption><a href="https://docs.aws.amazon.com/step-functions/latest/dg/input-output-resultpath.html">AWS Step Functions — Developer Guide — ResultPath</a></figcaption></figure><p>On the image we can see the default behavior of the step function which is to <strong>overwrite</strong> the input with <strong>“ResultPath”:”$”</strong>.</p><p>If we had wanted to <strong>keep the input while adding the result</strong>, then we should have used <strong>“ResultPath”: “$.taskresult”</strong>. This would have lead to the following State Output:</p><pre>{<br>  &quot;comment&quot;: &quot;This is a test of input and output of a Task state.&quot;,<br>  &quot;details&quot;: &quot;Default behavior example&quot;,<br>  &quot;who&quot;: &quot;AWS Step Functions&quot;,<br>  &quot;taskresult&quot;: &quot;Hello, AWS Step Functions!&quot;<br>}</pre><blockquote>Take into consideration that we can do much more than append the data. We can also overwrite a specific part of the state input with the task output by using <strong>“ResultPath”: “$.comment”</strong> or discard the task output by using <strong>“ResultPath”: null</strong>.</blockquote><h4>Paths</h4><p>In Amazon States Language, we use <em>paths</em> to identify a component within a Json. <strong>These paths are strings that always begin with with </strong><strong>$</strong>.</p><p>For key-value pairs where the value is selected using a <em>path</em>, the key name must end also in .$. Let’s see this with examples.</p><p>We have now as an State Input the following Json:</p><pre>{<br>  &quot;comment&quot;: &quot;Example for Parameters.&quot;,<br>  &quot;product&quot;: {<br>    &quot;details&quot;: {<br>       &quot;color&quot;: &quot;blue&quot;,<br>       &quot;size&quot;: &quot;small&quot;,<br>       &quot;material&quot;: &quot;cotton&quot;<br>    },<br>    &quot;availability&quot;: &quot;in stock&quot;,<br>    &quot;sku&quot;: &quot;2317&quot;,<br>    &quot;cost&quot;: &quot;$23&quot;<br>  }<br>}</pre><p>To select some of the information, you could specify which of these parameters you are going to use, like in this example:</p><pre>&quot;Parameters&quot;: {<br>        &quot;comment&quot;: &quot;Selecting what I care about.&quot;,<br>        &quot;MyDetails&quot;: {<br>          &quot;size.$&quot;: &quot;$.product.details.size&quot;,<br>          &quot;exists.$&quot;: &quot;$.product.availability&quot;,<br>          &quot;StaticValue&quot;: &quot;foo&quot;<br>        }<br>      }</pre><p>Notice how we declare the variable <em>size</em> with .$ in the end as we are getting the information from the Json. Notice also how every dot indicates one level deeper inside the key-value pairs.</p><h4>InputPath, ResultPath &amp; OutputPath</h4><p>With our previous example of the lamba, let’s see now how we can play with the information.</p><p>First, let’s take into consideration this four variables:</p><ul><li><em>InputPath</em>: <strong>Limits the input</strong> that is passed to the state by filtering the Json.</li><li><em>ResultSelector</em>: Allows you to <strong>filter the State Output</strong> (task result) by creating a collection of key-value pairs. Using this field, we can choose what we actually want to pass to the next field, <em>ResultPath</em>.</li><li><em>ResultPath</em><strong>: </strong>Allows you to overwrite, append or <strong>modify the State Input </strong>with the result of the task<strong>.</strong></li><li><em>OutputPath</em>: The final result of the state or in other words, what is going to be the input for the next state. If no OutputPath is defined, after the task has finished, the <em>ResultPath </em>will control the State Input for the next task.</li></ul><blockquote>We don’t need to use them all at once. Just remember that ResultPath is always working even if you don’t define it.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*D0sj6aGo_3zDM8vGCKbVew.png" /><figcaption><a href="https://docs.aws.amazon.com/step-functions/latest/dg/concepts-input-output-filtering.html">AWS Developer guide — Step Functions — Input and Output processing</a></figcaption></figure><p>For this new example, we start the execution with the following State Input:</p><pre>{<br>  &quot;comment&quot;: &quot;An input comment.&quot;,<br>  &quot;data&quot;: {<br>    &quot;val1&quot;: 23,<br>   },<br>  &quot;extra&quot;: &quot;foo&quot;,<br>  &quot;lambda&quot;: {<br>    &quot;who&quot;: &quot;AWS Step Functions&quot;,<br>  }<br>}</pre><p>And we define the following Step Function:</p><pre>{<br>  &quot;Comment&quot;: &quot;A simple Lambda function&quot;,<br>  &quot;StartAt&quot;: &quot;HelloWorld&quot;,<br>  &quot;States&quot;: {<br>    &quot;HelloWorld&quot;: {<br>      &quot;Type&quot;: &quot;Task&quot;,<br>      &quot;Resource&quot;: &quot;arn:aws:lambda:us-east-1:123456789012:function:HelloFunction&quot;,<br>      &quot;Parameters&quot;: {<br>        &quot;PayLoad&quot;:{<br>          &quot;DynamicValue.$&quot;: &quot;$.who&quot;,<br>          &quot;StaticValue&quot;: &quot;foo&quot;<br>          }<br>       },<br>      &quot;InputPath&quot;: &quot;$.lambda&quot;,<br>      &quot;ResultSelector&quot;: {<br>          &quot;lambdaTime.$&quot;: &quot;$.SdkHttpMetadata.HttpHeaders.Date&quot;,  <br>          &quot;ContentType.$&quot;: &quot;$.SdkHttpMetadata.HttpHeaders.Content-Type&quot;<br>        },<br>      &quot;ResultPath&quot;: &quot;$.data.lambdaresult&quot;,<br>      &quot;OutputPath&quot;: &quot;$.data&quot;,<br>      &quot;End&quot;: true<br>    }<br>  }<br>}</pre><p>In this case, we will filter first the full Json by keeping only the value of $.lamba. Notice that this is not a single variable but a dictionary.</p><p>For sake of completeness, we have added the <strong><em>PayLoad</em></strong> variable inside <strong><em>Parameters</em></strong><em>. T</em>his one is special from lambda as it actually creates key-value pairs that we can call inside the lambda. Just like if they were environment variables.</p><p>Once the computation is done, we are going to filter the task result with the <em>ResultSelector</em> so we only keep the date and the content-type<em>.</em></p><p>Here is an example of the output of a generic lambda function:</p><pre>{<br><br>   &quot;ExecutedVersion&quot;:&quot;$LATEST&quot;,<br>   &quot;Payload&quot;:&quot;FUNCTION OUTPUT&quot;,<br>   &quot;SdkHttpMetadata&quot;:{<br>      &quot;HttpHeaders&quot;:{<br>         &quot;Connection&quot;:&quot;keep-alive&quot;,<br>         &quot;Content-Length&quot;:&quot;4&quot;,<br>         &quot;Content-Type&quot;:&quot;application/json&quot;,<br>         &quot;Date&quot;:&quot;Fri, 26 Mar 2021 07:42:02 GMT&quot;,<br>         (...)<br>      },<br>      &quot;HttpStatusCode&quot;:200<br>   },<br>   &quot;SdkResponseMetadata&quot;:{<br>      &quot;RequestId&quot;:&quot;6b3bebdb-9251-453a-ae45-512d9e2bf4d3&quot;<br>   },<br>   &quot;StatusCode&quot;:200<br>}</pre><blockquote><a href="https://docs.aws.amazon.com/step-functions/latest/dg/connect-lambda.html"><em>Check how the invoke syntax of lambda looks like</em></a></blockquote><p>To finish, with <em>ResultPath</em> we are going to insert the filtered result as a child of the data node in the original input so the Json in this stage is something like:</p><pre>{<br>  &quot;comment&quot;: &quot;An input comment.&quot;,<br>  &quot;data&quot;: {<br>    &quot;val1&quot;: 23,<br>    &quot;lambdaresult&quot;:{<br>          &quot;lambdaTime&quot;: &quot;Fri, 26 Mar 2021 07:42:02 GMT&quot;, <br>          &quot;ContentType&quot;: &quot;application/json&quot;<br>     }<br>  },<br>  &quot;extra&quot;: &quot;foo&quot;,<br>  &quot;lambda&quot;: {<br>    &quot;who&quot;: &quot;AWS Step Functions&quot;,<br>  }<br>}</pre><p>After appending the data into the State Input, we declare with <em>OutputPath</em> that the final result will be only the data block <strong>“OutputPath”: “$.data”.</strong></p><p>This Json we have here is what is going to be passed to the next state:</p><pre>{<br>&quot;data&quot;: {<br>    &quot;val1&quot;: 23,<br>    &quot;val2&quot;: 17,<br>    &quot;lambdaresult&quot;:{<br>          &quot;lambdaTime&quot;: &quot;Fri, 26 Mar 2021 07:42:02 GMT&quot;, <br>          &quot;ContentType&quot;: &quot;application/json&quot;<br>     }<br>  }<br>}</pre><h3>Final example &amp; Conclusions</h3><p>In this final scenario, we define a lambda to do some operations based on a certain input. Here, we don’t care much about the return of the lambda after it has finished processing.</p><p>Instead, we discard the result and keep only the initial input, which is then forwarded to the glue job. In this way, we are able to synchronize the behavior of the glue job with what the lambda has done.</p><figure><img alt="AWS Console for Step Function definition" src="https://cdn-images-1.medium.com/max/800/1*-Rl-zDZ9gOJfTVVE5OS5uQ.png" /><figcaption>AWS Console: Generating the step function</figcaption></figure><pre>{<br>  &quot;StartAt&quot;: &quot;lambda-process&quot;,<br>  &quot;States&quot;: {<br>    &quot;Email Alert&quot;: {<br>      &quot;Type&quot;: &quot;Task&quot;,<br>      &quot;Resource&quot;: &quot;arn:aws:states:::sns:publish&quot;,<br>      &quot;Parameters&quot;: {<br>        &quot;TopicArn&quot;: &quot;arn:aws:sns:us-east-1:123456789012:topic&quot;,<br>        &quot;Message.$&quot;: &quot;$&quot;<br>      },<br>      &quot;End&quot;: true<br>    },<br>    &quot;lambda-process&quot;: <br>    {<br>      &quot;Type&quot;: &quot;Task&quot;,<br>      &quot;Resource&quot;:&quot;arn:aws:states:::lambda:invoke&quot;,<br>      &quot;Parameters&quot;:{<br>        &quot;FunctionName&quot;: &quot;arn:aws:lambda:us-east-1:123456789012:function:lambda-nm:$LATEST&quot;,<br>        &quot;Payload&quot;:{<br>          &quot;user_defined_variable.$&quot;: &quot;$.user_defined_variable&quot;,<br>          &quot;FROM.$&quot;:&quot;$.FROM&quot;,<br>          &quot;TO.$&quot;:&quot;$.TO&quot;<br>        }<br>      },<br>      &quot;ResultPath&quot;: null,<br>      &quot;Next&quot;: &quot;glue-job-process&quot;<br>    },<br>    &quot;glue-job-process&quot;: <br>    {<br>      &quot;Type&quot;: &quot;Task&quot;,<br>      &quot;Resource&quot;:&quot;arn:aws:states:::glue:startJobRun.sync&quot;,<br>      &quot;Parameters&quot;:{<br>        &quot;JobName&quot;: &quot;glue-job-process&quot;,<br>        &quot;Arguments&quot;:{<br>          &quot;--user_defined_variable.$&quot;: &quot;$.user_defined_variable&quot;<br>        }<br>      },<br>      &quot;Next&quot;: &quot;glue-job-process-2&quot;,<br>      &quot;Catch&quot;: [ {<br>          &quot;ErrorEquals&quot;: [ &quot;States.ALL&quot; ],<br>          &quot;Next&quot;: &quot;Email Alert&quot;<br>        }],<br>      &quot;Retry&quot;: [ {<br>          &quot;ErrorEquals&quot;: [ &quot;States.ALL&quot; ],<br>          &quot;IntervalSeconds&quot;: 3,<br>          &quot;MaxAttempts&quot;: 1<br>        }]<br>    },<br>    &quot;glue-job-process-2&quot;: <br>    {<br>      &quot;Type&quot;: &quot;Task&quot;,<br>      &quot;Resource&quot;:&quot;arn:aws:states:::glue:startJobRun.sync&quot;,<br>      &quot;Parameters&quot;:{<br>        &quot;JobName&quot;:&quot;glue-job-process-2&quot;<br>      },<br>      &quot;End&quot;: true<br>    }<br>  }<br>}</pre><p>Recalling what we talk at the beginning of the post, with this approach, we are able to control our step function just at the moment we launch it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/981/1*FS1uW9QfkwNeWwt49Uo9kA.png" /></figure><p>To conclude, to control the flow of information inside the Step Function, we need to pay extra attention to:</p><ul><li>Some special variables such as the InputPath, ResultPaht and the OutputPath.</li><li>By default, the input for the next task will be overwritten with the result of the previous one (<strong>ResultPath”:”$”)</strong>. We need to play with this variable to forward the information we really care about.</li><li>Every service has it’s way to select and define variables. Although they are defined on the <em>Parameter </em>node, in the case of lambda they are defined in “Parameter.Payload” and for glue jobs they are in “Parameter.Arguments”.</li></ul><p>That’s all I wanted to share with you in this post. Thank you for reading and I hope you learnt something new about steps functions! Here you can connect with me <a href="http://www.linkedin.com/in/cesar-antonio-restrepo-cordoba">www.linkedin.com/in/cesar-antonio-restrepo-cordoba</a>.</p><p>Also, if you are interested in this topic, I highly recommend you to check this <a href="https://aws.amazon.com/blogs/compute/modeling-workflow-input-output-path-processing-with-data-flow-simulator/">simulator</a> to understand better how the flow of information works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BLqRkGguJ6LIhZIUmxYL4A.png" /><figcaption>View of the Data Flow simulator from AWS</figcaption></figure><h3>Resources:</h3><ul><li><a href="https://catalog.workshops.aws/stepfunctions/en-US/">https://catalog.workshops.aws/stepfunctions/en-US/</a></li><li><a href="https://states-language.net/spec.html">https://states-language.net/spec.html</a></li><li><a href="https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html">https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html</a></li><li><a href="https://www.datadoghq.com/knowledge-center/aws-step-functions/">https://www.datadoghq.com/knowledge-center/aws-step-functions/</a></li><li><a href="https://aws.amazon.com/blogs/compute/prototyping-at-speed-with-aws-step-functions-new-workflow-studio/">https://aws.amazon.com/blogs/compute/prototyping-at-speed-with-aws-step-functions-new-workflow-studio/</a></li></ul><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c77f6133e87" width="1" height="1" alt=""><hr><p><a href="https://aws.plainenglish.io/step-functions-how-to-use-variables-1c77f6133e87">Step Functions: How to use variables</a> was originally published in <a href="https://aws.plainenglish.io/">AWS in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Step Functions: State Language]]></title>
            <link>https://medium.com/@cesar.cordoba/step-functions-state-language-d60620f44d67?source=rss-7c3bc1fa46ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/d60620f44d67</guid>
            <category><![CDATA[step-functions]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[data-engineer]]></category>
            <dc:creator><![CDATA[Cesar Cordoba]]></dc:creator>
            <pubDate>Tue, 06 Jun 2023 18:48:37 GMT</pubDate>
            <atom:updated>2023-06-06T18:48:37.586Z</atom:updated>
            <content:encoded><![CDATA[<h4>Cloud | AWS</h4><h4>In this post, we will look into how the code of a step function it’s built.</h4><p>So, just in case you are starting with step functions, it may be a good idea to take a look on <strong>what is and how a Step Function works</strong>. If you are already familiar with this service and want to learn how to use dynamic variables, please go to <a href="https://medium.com/p/1c77f6133e87/edit?source=your_stories_page-------------------------------------">Step Functions: How to use variables</a></p><h3>Crash course on Step Functions</h3><h4>What is and why do you want to use this service?</h4><p>We can define this service (more or less) as follows: “<em>AWS Step Functions is a serverless orchestration service that allows developers to create workflows of business-critical processes with a drag-and-drop visual console. It is designed to help organizations integrate multiple AWS services while allowing them to manage each service independently</em>”</p><p>In other words, it allows us to create a <strong>workflow</strong> by defining a series of steps or “blocks of code”, called <strong>states. </strong>This states can be of many types, but we will focus mainly on “tasks” and “choices”. We can define a state of the type <strong><em>task</em></strong> as a single unit of work done by an AWS service. Similarly, we can define a <strong><em>choice</em></strong> as an unit of control.</p><blockquote><strong>Note: </strong>There are many more states-types (pass, fail, etc) but to keep it simple for now, let’s think we only have two.</blockquote><p>For example, we can use the Step Functions to integrate several Lambda functions with other AWS services such as Glue Jobs, DynamoDb, etc. All of this while being able to define some clauses to manage the behavior of the workflow based on whether a state finished okay or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_xUQVBxpkkif5ZU7EvPdEQ.png" /><figcaption>Aws blog “<a href="https://aws.amazon.com/blogs/compute/prototyping-at-speed-with-aws-step-functions-new-workflow-studio/">Prototyping at speed with AWS Step Functions new Workflow Studio</a>”</figcaption></figure><p>The main benefit os this service and why you should be using it, is the ability to build complex and resilient pipelines in a short amount of time:</p><ul><li>Developers can use the visual interface to develope a template with all the required functionalities and then tune it</li><li>It allows to have a finer control on all the processes by breaking the code into several microservices. I.e, instead of one huge lambda, we can have two and coordinate them</li><li>The workflow can be exported as a template so it can be used for different deployments (<a href="https://developer.hashicorp.com/terraform/tutorials/aws-get-started/infrastructure-as-code">infrastructure as a code</a>)</li><li>Easy integration for over 200 Aws Services</li><li>The step can be launched by events or periodically on a custom schedule</li><li>Automatic error and exception handling are provided through built-in try/catch and retry capabilities</li></ul><h4>AWS State Language</h4><p>On a first glance, you can do everything just by clicking on the console. Nevertheless, under the hood, what we have been doing is defining a json template in <strong>AWS State language</strong> (ASL)</p><p><em>AWS State Language is a json-based language used to define the state machine through a collection of states. This states can make decisions based on their input, perform actions or just pass an output to other states.</em></p><p><strong>Each state is defined with an unique name inside the template so they can be referenced.</strong></p><p>Some examples of states are:</p><ul><li>Do some work in your state machine (a <a href="https://docs.aws.amazon.com/step-functions/latest/dg/amazon-states-language-task-state.html">Task</a> state)</li><li>Make a choice between branches of execution (a <a href="https://docs.aws.amazon.com/step-functions/latest/dg/amazon-states-language-choice-state.html">Choice</a> state)</li><li>Stop an execution with a failure or success (a <a href="https://docs.aws.amazon.com/step-functions/latest/dg/amazon-states-language-fail-state.html">Fail</a> or <a href="https://docs.aws.amazon.com/step-functions/latest/dg/amazon-states-language-succeed-state.html">Succeed</a> state)</li><li>Pass its input to its output, or inject some fixed data into the workflow (a <a href="https://docs.aws.amazon.com/step-functions/latest/dg/amazon-states-language-pass-state.html">Pass</a> state)</li><li>Provide a delay for a certain amount of time, or until a specified date and time (a <a href="https://docs.aws.amazon.com/step-functions/latest/dg/amazon-states-language-wait-state.html">Wait</a> state)</li><li>Begin parallel branches of execution (a <a href="https://docs.aws.amazon.com/step-functions/latest/dg/amazon-states-language-parallel-state.html">Parallel</a> state)</li><li>Dynamically iterate steps (a <a href="https://docs.aws.amazon.com/step-functions/latest/dg/amazon-states-language-map-state.html">Map</a> state)</li></ul><p>By now, we already know that a Step Function is a Json file… So the next logical question is, what does this file look like?</p><pre>{<br>  &quot;Comment&quot;: &quot;An example of the Amazon States Language using a choice state.&quot;,<br>  &quot;StartAt&quot;: &quot;TaskState&quot;,<br>  &quot;States&quot;: {<br>    &quot;TaskState&quot;: {<br>      &quot;Type&quot;: &quot;Task&quot;,<br>      &quot;Resource&quot;: &quot;arn:aws:lambda:us-east-1:123456789012:function:FUNCTION_NAME&quot;,<br>      &quot;Next&quot;: &quot;ChoiceState&quot;<br>    },<br>    &quot;ChoiceState&quot;: {<br>      &quot;Type&quot;: &quot;Choice&quot;,<br>      &quot;Choices&quot;: [<br>        {<br>          &quot;Variable&quot;: &quot;$.foo&quot;,<br>          &quot;NumericEquals&quot;: 1,<br>          &quot;Next&quot;: &quot;MatchState&quot;<br>        }<br>      ],<br>      &quot;Default&quot;: &quot;DefaultState&quot;<br>    },<br>    &quot;MatchState&quot;: {<br>      &quot;Comment&quot;: &quot;Launch lambda if variable was 1 to process x&quot;,<br>      &quot;Type&quot;: &quot;Task&quot;,<br>      &quot;Resource&quot;: &quot;arn:aws:lambda:us-east-1:123456789012:function:OnFirstMatch&quot;,<br>      &quot;End&quot;: true<br>    },<br>    &quot;DefaultState&quot;: {<br>      &quot;Type&quot;: &quot;Fail&quot;,<br>      &quot;Cause&quot;: &quot;No Matches!&quot;<br>    }<br>  }<br>}</pre><p>In this sample:</p><ul><li>We start with the state called <em>TaskState</em> which invokes a lambda to do some work (state of type Task).</li><li>Next, we face the <em>ChoiceState</em> where based on the lambda results, two things could happen. We might continue with the MatchState (invoke another lambda) or we might finish with DefaultState (state of type Fail )</li></ul><blockquote>All states can have a special variable “comment” to explain what is the expected behavior of the state. Although it’s not mandatory, it’s a best practice to include it</blockquote><p>Pay attention on how each state is named differently and they are constructed as a key-value pair where <strong>we define always the type of the state</strong>, and then assign some specific values of the state-type we are defining.</p><h3>Conclusions on Step Functions — AWS State Language</h3><p>I hope this has helped as a short introduction to the service and the template behind it. The main considerations to take from here are:</p><ul><li>The Step Functions allow us to build complex workflows, integrate several AWS services and trigger themas pleased (with events or schedule).</li><li>They are written in AWS State Language.</li><li>The template is composed of several states and they can be of many different types.</li><li>Each State is named individually and their names must be unique. They also have some parameters that can change from one state type to another.</li></ul><p>Simple right? If you want to know more about Steps Functions, in this second post we do a deep dive into how to manipulate the information as it goes through each state!</p><blockquote>In case of doubts, I highly recommend you to check the <a href="https://states-language.net/spec.html">Amazon States Language Specification</a>.</blockquote><h3>Resources</h3><ul><li><a href="https://catalog.workshops.aws/stepfunctions/en-US/">https://catalog.workshops.aws/stepfunctions/en-US/</a></li><li><a href="https://states-language.net/spec.html">https://states-language.net/spec.html</a></li><li><a href="https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html">https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html</a></li><li><a href="https://www.datadoghq.com/knowledge-center/aws-step-functions/">https://www.datadoghq.com/knowledge-center/aws-step-functions/</a></li><li><a href="https://aws.amazon.com/blogs/compute/prototyping-at-speed-with-aws-step-functions-new-workflow-studio/">https://aws.amazon.com/blogs/compute/prototyping-at-speed-with-aws-step-functions-new-workflow-studio/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d60620f44d67" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>