<?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 Mattiamazzari on Medium]]></title>
        <description><![CDATA[Stories by Mattiamazzari on Medium]]></description>
        <link>https://medium.com/@mattiamazzari?source=rss-e9f146485d51------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Roa-YuRcil2W7WweXk-eWA.jpeg</url>
            <title>Stories by Mattiamazzari on Medium</title>
            <link>https://medium.com/@mattiamazzari?source=rss-e9f146485d51------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 20:13:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mattiamazzari/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[Integrate an Amazon Lex  bot (V2), a Lambda function and DynamoDB with WhatsApp]]></title>
            <link>https://medium.com/@mattiamazzari/integrate-an-amazon-lex-bot-v2-a-lambda-function-and-dynamodb-with-whatsapp-d93187e596d5?source=rss-e9f146485d51------2</link>
            <guid isPermaLink="false">https://medium.com/p/d93187e596d5</guid>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[lambda-function]]></category>
            <category><![CDATA[amazon-lex]]></category>
            <dc:creator><![CDATA[Mattiamazzari]]></dc:creator>
            <pubDate>Fri, 27 Sep 2024 11:18:54 GMT</pubDate>
            <atom:updated>2024-09-27T11:20:46.066Z</atom:updated>
            <content:encoded><![CDATA[<h3>Integrate an Amazon Lex bot (V2), Lambda and DynamoDB with WhatsApp</h3><p>In this guide we will see how to integrate an Amazon Lex chatbot with WhatsApp by using Twilio to have the following demo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YEkSelrhaQxKWqubmf_Xhg.png" /></figure><h3>Step 1: setup Twilio</h3><p>First of all we need to signup in Twilio:</p><p><a href="https://twilio.com/try-twilio">Twilio Cloud Communications | Web Service API for building Voice and SMS Applications</a></p><p>After verifying the email, Twilio will ask you some questions, in the last question select that you want to integrate WhatsApp and you will be redirected to the page to connect to the WhatApp sandbox:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aYkywi_2Pzwsuze3Cqgq0Q.png" /></figure><p>Follow the instructions from Twilio: send the specific message from your device to the phone number displayed on the screen.</p><p>After you have done it, you can test it by sending the template message already prepared for you, so click on “Send template message”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2oR5Knzt2eYYomQgWTUk2w.png" /></figure><p>To see what is happening in the background, select “Python” to display the Python code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iGyrkjt2s0qdh3u2b0te4Q.png" /></figure><p>Now click on “Show auth token” to display your Authentication token and copy all the generated code somewhere in your PC, we will need it later on Step 6.</p><p>Then click on “Next step” in the top right corner:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PRWnM_tCdu7uc9mx8jahvQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zSGxb6FbvAzdbRGOHFo_wg.png" /></figure><p>Now Twilio will wait for a message from you. You can send whatever you want, I will send “hello”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5ULyuyuTGsAikdj_LzUFhA.png" /></figure><p>From Twilio we now prepare a reply: write a message in the body and click on “Send your reply”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ELV9oJumYmZxsnS-rjydHw.png" /></figure><p>Again, click on “Next step” above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_h3H9cGW2CJdJsI3arznXw.png" /></figure><p>Select the “Sandbox settings” tab and it will asks you a status callback URL (the empty field). For now we leave this page open.</p><h3>Step 2: setup Amazon Lex</h3><p>Go to the AWS management console in Amazon Lex and click on “Create bot”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rSsgjZved5QANuesTWOokg.png" /></figure><p>I will call it “AccountBalance”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oQkTRO-Y11CwgZld3ZC2tQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*I9rsWiIhFwfrSskIr3L7bg.png" /></figure><p>Then click on “Next”. Then select the language of the bot, I chose English and click on “Done”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6_fbjiYG__wyVmFpDJcNbg.png" /></figure><p>Then create an intent called “AccountBalanceEnquiry”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*XtMwa22WnPcuYz4UuCBlWA.png" /></figure><p>I provide to you some sample utterances:</p><pre>I want to know my account balance.<br>Get me my account balance.<br>Account balance.<br>Balance.</pre><p>Add them one at a time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*ZPMAW3J7XViQE59Igk4N1A.png" /></figure><p>Then we add a new slot because we want to know the account number of the client, so click on “Add slot” and then in the opened modal configure it as this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*3Rd0KCkn1YVePFImeI4-hw.png" /></figure><p>Then click on “Add”.</p><p>Now make sure that the “Fulfillment” phase of the bot is active.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*Q0At_rlpXKYPlC4AcVZjgg.png" /></figure><p>Then click on the arrow and select “Advanced options”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*LA06ZLmwuIP4zZ9B0OtlBw.png" /></figure><p>Make sure that “Use a Lambda function for fulfillment” is ticked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*ZFW9vCXy-PExjKwhyhAVRw.png" /></figure><p>Then save the intent.</p><p>Next, create a new empty intent called “Greetings”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*P8IQTOU6n6mQam5awhoAPg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*Z461xWo5SqHm9HLyBHG0bA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*Ks4wkmT9RzQ1rnzb_zhlIQ.png" /></figure><p>This intent is used to give a welcome to the client as it writes its first message to us.</p><p>Finally, save the intent and click on “Build” to build the bot for the specific language we selected before.</p><h3>Step 2: setup DynamoDB</h3><p>Then go to DynamoDB and create a new table. We will call it “customers” and define a partition key “account_number” which will be a string.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*gGSk4g10iVooL_nzuPcBnA.png" /></figure><p>Leave all the rest by default. Then click on “Create table”. If you select the table and go to “Explore table items”, on the bottom of the page you will be able to create new items. In particular we will create two items. The first one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tUXcDXDAonBkt7G25l9TOQ.png" /></figure><p>Then the second one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ontraonMwRT43tv67OCokw.png" /></figure><h3>Step 3: setup a Lambda function</h3><p>Now in a new page go to Amazon Lambda and create a new Lambda function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U393_n4nfy4CGmurRemc1Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hHBy5ocG5Lsb1scPO7yhYA.png" /></figure><p>Choose a name and select “Python 3.12” as Runtime. Then click on “Create function”. In the editor, paste the following code (Suggestion: write it line by line instead, as you would understand and memorize much better what it does):</p><pre>import json<br>import boto3<br>import logging<br><br># For detailed debugging<br>logger = logging.getLogger()<br>logger.setLevel(logging.INFO)<br><br>client = boto3.client(&#39;dynamodb&#39;)<br><br>def lambda_handler(event, context):<br>    logger.info(&#39;Received event: &#39; + json.dumps(event))<br>    <br>    intent = event[&#39;sessionState&#39;][&#39;intent&#39;][&#39;name&#39;]<br>    logger.info(f&#39;The intent is: {intent}&#39;)<br>    <br>    if intent == &#39;AccountBalanceEnquiry&#39;:<br>        account_number = event[&#39;sessionState&#39;][&#39;intent&#39;][&#39;slots&#39;][&#39;AccountNumber&#39;][&#39;value&#39;][&#39;interpretedValue&#39;]<br>        logger.info(f&#39;Account number is: {account_number}&#39;)<br>        account_number = str(account_number)<br>        return balance_enquiry(account_number)<br>    else:<br>        return {<br>            &quot;sessionState&quot;: {<br>                &quot;dialogAction&quot;: {<br>                    &quot;type&quot;: &quot;Close&quot;<br>                },<br>                &quot;intent&quot;: {<br>                    &quot;name&quot;: intent,<br>                    &quot;state&quot;: &quot;Fulfilled&quot;<br>                }<br>            },<br>            &quot;messages&quot;: [<br>                {<br>                    &quot;contentType&quot;: &quot;PlainText&quot;,<br>                    &quot;content&quot;: &quot;I&#39;m sorry, I couldn&#39;t process that request.&quot;<br>                }<br>            ]<br>        }<br><br>def balance_enquiry(account_number):<br>    response = client.get_item(<br>        TableName=&#39;customers&#39;,<br>        Key={<br>            &#39;account_number&#39;: {<br>                &#39;S&#39;: account_number,<br>            }<br>        }<br>    )<br>    logger.info(f&#39;DynamoDB response: {response}&#39;)<br><br>    if &#39;Item&#39; in response:<br>        name = response[&#39;Item&#39;][&#39;name&#39;][&#39;S&#39;]<br>        balance = response[&#39;Item&#39;][&#39;balance&#39;][&#39;N&#39;]<br>        message = f&#39;Hello {name}, You have ${balance} in your account&#39;<br>    else:<br>        logger.info(&quot;Account not found&quot;)<br>        message = &quot;Sorry, I can&#39;t find your details in our records. Please contact our support center on 8083829227&quot;<br><br>    return {<br>        &quot;sessionState&quot;: {<br>            &quot;dialogAction&quot;: {<br>                &quot;type&quot;: &quot;Close&quot;<br>            },<br>            &quot;intent&quot;: {<br>                &quot;name&quot;: &quot;AccountBalanceEnquiry&quot;,<br>                &quot;state&quot;: &quot;Fulfilled&quot;<br>            }<br>        },<br>        &quot;messages&quot;: [<br>            {<br>                &quot;contentType&quot;: &quot;PlainText&quot;,<br>                &quot;content&quot;: message<br>            }<br>        ]<br>    }</pre><p>Deploy your changes.</p><p>Next, we need to grant to this Lambda function full read access to our DynamoDB table. So, go to “Configuration”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LqM6Mwk7BvB3YN6AHyOcOw.png" /></figure><p>Then, click on “Permissions”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fKuUejWus5jCHRdzUqYQXw.png" /></figure><p>Then click on the “Role name”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*KzvxI5MqNayqMGrZU3tD_Q.png" /></figure><p>Then select “Add permissions” &gt; “Attach policies”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bcAagOE30822GoE5pjBTdQ.png" /></figure><p>Search “dynamodb” in the search bar and select “AmazonDynamoDBReadOnlyAccess”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*aciZgbBGJAQx7vJbq0Uf5Q.png" /></figure><p>Finally click on “Add permissions”.</p><p>Now go back to Amazon Lex, select the bot and click on “Test”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-SyxepPPz6KSEnqbYg5Liw.png" /></figure><p>Now click on the settings icon on the top and it will allow you to connect the Lambda function to the Amazon Lex bot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*OLgcI8ed4cGGZJZcEIKdVw.png" /></figure><p>Then click on “Save”.</p><p>Now test it out writing “Balance” and then the account number:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*Gqs2wWzV74TVmy_i2tp9OA.png" /></figure><h3>Step 4: Debugging Lambda (you can skip this step)</h3><p>If something goes wrong and it does not work as expected, go back to the Lambda function and select “Monitor”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*tNdjTfIBVioOs_XmQ8J8rg.png" /></figure><p>First, in CloudWatch metrics you have some metrics to see if the Lambda function is invoked or not, its duration and so on, for example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*Obrgf7_jUMgMIy91jAM5wQ.png" /></figure><p>Then, select “View CloudWatch logs”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C_E4nOGXyPxo7JHE-aoMDA.png" /></figure><p>Each log stream corresponds to an invocation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/1*BZKGoQIjRt-vmfdQNvfjvg.png" /></figure><p>If you click on the log stream you have a detailed explanation of what is happening in the background, along with all the prints that you can add in the code to verify that everything is working properly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eMPsHsxvoH61k1EiBx_BpA.png" /></figure><p>Then if you want to restart the conversation in Amazon Lex you can simply click on this icon:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*a__cVCZSN-ty5Qma4gn9Ug.png" /></figure><h3>Step 5: Create a bot version and an alias</h3><p>Up to now, we have worked with a draft version of our bot, but we need to create a new official version of it. So go to “Bot versions” in Amazon Lex:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_h7Y1V2zJtB-5IKvu3au4w.png" /></figure><p>Then click on “Create version”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CE8mLKAfbaPm1b1SBIuL0Q.png" /></figure><p>Then leave everything as it is and click on “Create”. Now you have Version 1:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AGBk6LP-mlgcl_8IvGrGyg.png" /></figure><p>Now go to “Aliases” on the left:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fyW8vgZ5wa_45I8tpxXxHA.png" /></figure><p>Then click on “Create alias”, choose an alias name and then select the Version of the bot to the alias:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/1*laOWMSoXIS5cVJAZEf8ODA.png" /></figure><p>I had to create a second version “Version 2”. However, in your case select “Version 1”. Then, click on “Create” at the bottom of the page.</p><p>Next, we need to attach the Lambda function to the bot through the alias. So, select the alias by clicking on its name and click on the language, in my case “English (US)”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*ZtnKJ0_ejEBsecIYCCWeQA.png" /></figure><p>Then select the Lambda function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*M5q8Jl_DhkvB4vKCLlGyrg.png" /></figure><p>Finally, click on “Save”.</p><h3>Step 6: Setup channel for Twilio</h3><p>In Amazon Lex go to “Channel integrations” and click on “Add channel”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ikJCgXV3fzZgUn2RJ5qDMA.png" /></figure><p>Select “Twilio SMS”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*wibL1I1kpue8xppTrP1l5A.png" /></figure><p>Then choose a name for this channel integration and a description. Select the alias we have created and the language. Then specify the Account SID and Authentication token provided by Twilio:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*hkay6TTlpCUOgaEYVohc-A.png" /></figure><p>Account SID and Authentication token were provided in the Python script generated by Twilio:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*oBpNOeeNl7lRLMV0R0dndQ.png" /></figure><p>Finally, click on “Add” and you have now a new channel integration with Twilio:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P-p66dGFCkYSRt_acnfcNA.png" /></figure><p>Then click on the channel name “Test” and then copy the Callback URL:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*uMadNrkdjbuuboLBEMBYng.png" /></figure><p>Back to Twilio, paste it in “When a message comes in” and click on “Save”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jmdYVMQqSYlGaJNZj9ed9Q.png" /></figure><p>Let’s test it out:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YEkSelrhaQxKWqubmf_Xhg.png" /></figure><p>It works! Amazing!</p><p>That’s it, I hope you liked this guide and I will see you in the next project!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d93187e596d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Track contact activities in Amazon Connect using CloudWatch Logs Insights]]></title>
            <link>https://medium.com/@mattiamazzari/track-contact-activities-in-amazon-connect-using-cloudwatch-logs-insights-117702bcb56c?source=rss-e9f146485d51------2</link>
            <guid isPermaLink="false">https://medium.com/p/117702bcb56c</guid>
            <category><![CDATA[amazon-connect]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cloudwatch]]></category>
            <category><![CDATA[cloudwatch-logs]]></category>
            <category><![CDATA[cloudwatch-logs-insights]]></category>
            <dc:creator><![CDATA[Mattiamazzari]]></dc:creator>
            <pubDate>Thu, 26 Sep 2024 14:35:09 GMT</pubDate>
            <atom:updated>2024-09-26T14:37:46.752Z</atom:updated>
            <content:encoded><![CDATA[<p>In this guide you will learn how to use Amazon CloudWatch Logs Insights to track the activities for a single contact or get the statistical overview about how many contacts from which channel voice/chat/task was initiated, queued, connected to agents or disconnected in a time range.</p><p>So we will focus in increasing the visibility of a contact center workload and improving supporting processes by subscribing and analyzing Amazon Connect contact events. You will get to know what Amazon Connect contact events are and understand why you need to gain insights about them.</p><p>Once the initial setup is complete you can continue to review it over time in Amazon CloudWatch, we can get the live data (or close to) by choosing the time range from the dashboard.</p><h3>Step 1: understand Amazon Connect contact events</h3><p>First of all, a contact can be a voice call, a chat interaction or a task in Amazon Connect. A lifecycle of a contact spans over the event types from <em>INITIATED</em> to <em>DISCONNECTED</em>. Between them, there is an ordered sequence of event types (<em>QUEUED, CONNECTED_TO_AGENT, ..</em>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*WgiWI71D5EatH1mpEKRi5g.png" /></figure><p>Not all those event types will occur in a contact, that depends on when a contact is disconnected and how a contact flow is designed.</p><p>Let us take an inbound voice call as an example, as shown above on the right. Note that all events are referenced by a unique contact ID which can be used for searching all events related to that contact. So:</p><ol><li>The contact is initiated by a caller, which starts the conversation. Thus, the event <em>INITIATED </em>is released</li><li>She was connected to an interactive voice response specified in the contact flow and it is mapped to the contact center number she talked, so she goes through IVR, so the event <em>CONNECTED_TO_SYSTEM </em>is released</li><li>She is being transferred to a queue, so the event <em>QUEUED </em>is released</li><li>A voice connection was established between the caller and an agent as soon as the agent got available and accepted the contact</li><li>After their conversation, the call was hung up. The event <em>DISCONNECTED </em>got released for the contact.</li></ol><p>A contact can be initiated not only through inbound call by a customer, but also through outbound call by an agent. An outbound call has no <em>QUEUED </em>event type because an agent dialed an external number directly, therefore there is no queue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*uoIUIZbG8DILfJPii9UjAw.png" /></figure><blockquote><em>If one or more contact attributes are added or updated, an additional event </em>CONTACT_DATA_UPDATED<em> is then released throughout the contact.</em></blockquote><p>Let’s see an example on how a <em>DISCONNECTED </em>event looks like as raw data:</p><pre>{<br>  &quot;eventType&quot;: &quot;DISCONNECTED&quot;,<br>  &quot;contactId&quot;: &quot;11111111-2222-3333-4444-555555555555&quot;,<br>  &quot;channel&quot;: &quot;VOICE&quot;,<br>  &quot;instanceARN&quot;: &quot;arn:aws:connect:us-west-2:123456789012:instance/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee&quot;,<br>  &quot;initiationMethod&quot;: &quot;INBOUND&quot;,<br>  &quot;queueInfo&quot;: {<br>    &quot;queueArn&quot;: &quot;arn:aws:connect:us-west-2:123456789012:instance/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee/queue/fffff-gggg-hhhh-iiii-jjjjjjjjjjjj&quot;,<br>    &quot;enqueueTimestamp&quot;: &quot;2023-09-26T10:15:35.000Z&quot;,<br>    &quot;queueType&quot;: &quot;STANDARD&quot;<br>  },<br>  &quot;agentInfo&quot;: {<br>    &quot;agentArn&quot;: &quot;arn:aws:connect:us-west-2:123456789012:instance/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee/agent/kkkkkk-llll-mmmm-nnnn-oooooooooooo&quot;,<br>    &quot;connectedToAgentTimestamp&quot;: &quot;2023-09-26T10:15:55.123Z&quot;,<br>    &quot;hierarchyGroups&quot;: {<br>      &quot;level1&quot;: {<br>        &quot;arn&quot;: &quot;arn:aws:connect:us-west-2:123456789012:instance/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee/agent-group/ppppp-qqqq-rrrr-ssss-tttttttttttt&quot;,<br>      },<br>      &quot;level2&quot;: {<br>        &quot;arn&quot;: &quot;arn:aws:connect:us-west-2:123456789012:instance/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee/agent-group/ppppp-qqqq-rrrr-ssss-tttttttttttt&quot;,<br>      },<br>    },<br>  }<br>  &quot;disconnectTimestamp&quot;: &quot;2023-09-26T10:20:45.678Z&quot;,<br>  &quot;initiationTimestamp&quot;: &quot;2023-09-26T10:15:00.000Z&quot;,<br>}</pre><p>The event type DISCONNECTED is an accumulation of all the information from the previous events for a contact with an unique contactID and channel information. The event describes information such as how the contact is initiated, which queue the caller was popped and which agent is connected to the caller.</p><p>In this guide I will show you how to use those key-value pairs to search, filter and aggregate contact events.</p><h3>Step 2: setup an Amazon EventBridge rule</h3><p>The next step is to get our hands on subscribing those contact events by creating a rule in Amazon EventBridge.</p><p>So search for Amazon EventBridge in the AWS management console and create a rule. Start by choosing a name and leaving everything else as default in the first step:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lFHtUS74l9NQ3WLiGfkuXQ.png" /></figure><p>Then click on “Next”.</p><p>In Step 2 (Build event pattern) scroll all the way down to the bottom, until you reach the section Event pattern. Choose <strong>Amazon Connect</strong> as AWS service and then <strong>Amazon Connect Contact Event</strong> as Event type:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*zb5J-bH3A7OdeQhNyFSsvw.png" /></figure><p>The pattern is generated automatically.</p><p>If you only want to subscribe contact events for a single Amazon Connect instance, select “Edit pattern” and specify the ARN of your Amazon Connect instance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/929/1*ACafZHE7_wZwGnZjxNpwYw.png" /></figure><p>If you don’t want to import all the event types, you may select or fill out some type such as <em>CONTACT_DATA_UPDATED</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*_SFs3sNsVac2Gr4rE82NkQ.png" /></figure><p>For demo purpose, we do want to import all the events, so the “details” property will be removed, returning back to having:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*itISLn9wml09nSIAmkCqPA.png" /></figure><p>Click on “Next”.</p><p>Here we select a target. You can decide to send the events within an AWS environment by using an API destination. In this guide we will see how to send the events to a CloudWatch log group, so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uxqJgLn95CY19jTHgcDoRg.png" /></figure><p>You have the choice to create a new log group with the name you prefer (/aws/events/<strong> &lt;&lt;name&gt;&gt;</strong>) or select an existing one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*cY79VUfxhN6h-bw3-CZCNw.png" /></figure><p>Then click on “Next”.</p><p>Skip the configuration of tags, thus click on “Next”.</p><p>Review the settings and then confirm by clicking on “Create rule”.</p><p>So you should have the rule displayed in the dashboard of rules of Amazon EventBridge:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YZVHZzG6CYjFa0-i7NKEVg.png" /></figure><p>Now feel free to make some inbound and outbound voice calls, chats, tasks and even outbound campaign calls to generate some events and come back to this guide when you have finished. If you have not created a contact center, I leave the link to another article I have made where I explain step-by-step how to create a simple AI Italian Chatbot/Voicebot or Assistant using Amazon Connect and Amazon Lex:</p><p><a href="https://medium.com/@mattiamazzari/ai-italian-booking-chatbot-voicebot-using-amazon-connect-and-lex-7590079fe67b">AI Italian Booking Chatbot/Voicebot using Amazon Connect and Lex</a></p><p>If you go to CloudWatch and select Log groups:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*EpzUOGs3teGQYb2hTPKv8A.png" /></figure><p>Select the log group which was created before by the Amazon EventBridge rule as target:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c9ZBFaGwR07LV395TXDcNw.png" /></figure><p>We can see that contact events are saved as log streams in a log group:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F3N8Fk3CZgyV67fFcuqp3A.png" /></figure><p>We can open one of them and see the event log in JSON format:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*APekUXD2LGl5f_UCXTfZJQ.png" /></figure><p>However, there is a better method than reading log streams line by line. There is a tool called Log Insights in Amazon CloudWatch which is used to query, filter, aggregate and visualize the log data in CloudWatch log groups. We will see how to query contact events.</p><p>Select “Logs Insights” on the left:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*a5aXnAfcQKtzgQScjMwzCw.png" /></figure><p>Then, to query the contact events, you need to select the log group where the contact events are saved from the dropdown list:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X1d72ljK2teVMwPdnOSqaA.png" /></figure><p>Before we create a new query, we can test it with the default query by specifying the time range contacts were made on your Amazon Connect instance, so click on “1h”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HTniOICYHk5JkH6MOTbFrw.png" /></figure><p>Then select “Run query”.</p><p>Each item with its timestamp is an event.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P5ym4CarjKIJE5T9QQ0nhQ.png" /></figure><p>Now we will try the following query: we want to define a filter to find out all <em>DISCONNECTED</em> events for and highlight key-value pair of event type, contactId, channel, initiation method by replacing the default query with this one:</p><pre>fields @timestamp, detail.eventType, detail.contactId, detail.channel, detail.initiationMethod, @message, @logStream<br>| filter detail.eventType = &quot;DISCONNECTED&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CQhNpm4yxfEojS5lYoACcA.png" /></figure><p>Here is the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YhMy7HfjUADSjxd3lsdNzg.png" /></figure><p>In general this allows us to track how a contact was going on and we can get even more details if we expand each of these event logs.</p><p>We might also consider another use case where the call is transferred to another agent. In this case there is no <em>CONNECTED_TO_SYSTEM </em>as the caller has already established a connection. A new contactId is used in this case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*ERbHt03UmiNrft9bQjetXw.png" /></figure><p>So for example we might want to modify the query to filter event logs setting “detail.initiationMethod = TRANSFER” and the two contactIds:</p><pre>fields @timestamp, detail.contactId, detail.initiationMethod, detail.otherField1, detail.otherField2<br>| filter detail.initiationMethod = &quot;TRANSFER&quot;<br>| filter detail.contactId = &quot;originalContactId&quot; or detail.contactId = &quot;newContactId&quot;<br>| sort @timestamp asc</pre><p>That’s it for this project! I hope you enjoyed it and see you in another one!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=117702bcb56c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI Italian Booking Chatbot/Voicebot using Amazon Connect and Lex]]></title>
            <link>https://medium.com/@mattiamazzari/ai-italian-booking-chatbot-voicebot-using-amazon-connect-and-lex-7590079fe67b?source=rss-e9f146485d51------2</link>
            <guid isPermaLink="false">https://medium.com/p/7590079fe67b</guid>
            <category><![CDATA[amazon-lex]]></category>
            <category><![CDATA[cloudfront]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[amazon-connect]]></category>
            <dc:creator><![CDATA[Mattiamazzari]]></dc:creator>
            <pubDate>Thu, 26 Sep 2024 09:10:05 GMT</pubDate>
            <atom:updated>2024-09-26T09:10:05.663Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi there! In this guide we will build an AI chatbot for automated travel booking service. Our fictious travel company offers car and hotel bookings and it wants to completely automate its travel booking service, which means that customers can book a car or make hotel reservations by talking to a chatbot or with a phone call or with text conversation. We will end up with a customer service widget. For example we want to book a car and it asks to us the city where we want to book it and what day we want to start our rental. We might also want to start a phone call with an AI assistant asking the same information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7QL28DsenzWTH9_LFKjbpA.png" /></figure><h3>Step 1: Setup an Amazon Lex Bot</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ypaR1WDyG26QeF5MwNTTA.png" /></figure><p>Click on “Create bot”, then select “Traditional” &gt; “Start with an example” and then choose BookTrip. Define a bot name and for the role select the option “Create a role with basic Amazon Lex permissions”. For the COPPA section, select No. Then click “Next”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rNemrZ-UzAZg_xejZut9Ow.png" /></figure><p>In the next window, we select “Italian” as language of the bot, then click on “Done”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jjl3wM7TfCbXF8XaXfIypw.png" /></figure><p>So the bot has been created with some intents:</p><ul><li>BookCar</li><li>BookHotel</li><li>FallbackIntent</li></ul><p>Let’s analyze what are the configuration options inside an intent, select the first one (BookCar) on the navbar on the left. An intent will be invoked based on sample utterances. If no intent is invoked, the FallbackIntent will be triggered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jBY9bIv4I7LNOE6O7fel3w.png" /></figure><p>You are free to add new samples utterances that will trigger each of these intents.</p><p>Slots instead are the information that the bot needs to fulfill the intent, therefore a user is asked for these information like PickUpCity, PickUpDate, ReturnDate, CarType and so on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7kGi-evf3Kk29ADfQi_HqQ.png" /></figure><p>Then there is a confirmation message to define, it usually recaps all the information that the user has given (the slots that were defined).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v0bcqNrNE2koA5OVlpK-Yg.png" /></figure><p>If the user says yes, it proceeds to the Fulfillment step:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zs2dbs7ptDYmjpUTTetw0w.png" /></figure><p>Please note that under Fullfillment, if you click on “Advanced options” there is a checkbox “Use a Lambda function for fulfillment” which allows you to attach a Lambda function code hook that allows you to run any custom code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UyUdF-IKXSEpdqtwfCul3A.png" /></figure><p>For this demo we will not use any Lambda function, so we untick this option and click on Cancel.</p><p>Now we can first build (to save the changes) and then test our bot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aRddB9BvSvAhYAXlzPofPQ.png" /></figure><p>Here is an example of the conversation with the chatbot, in Italian:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g-ngO-dxfTKtTlf12vzQ2g.png" /></figure><p>Up to now we have created a draft version. Now we will create a new version, so click on “Bot versions” on the left in the navbar. A version is simply a snapshot of the bot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PrB3TX_WRhHT0D_l1Roj2g.png" /></figure><p>Then click on “Create version”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qmrFVQY3N3SaEFhEWSnipg.png" /></figure><p>Leave everything as it is in the options, create the version and it will appear “Version 1” in the dashboard above.</p><p>Now we will create an alias by going to “Aliases” under “Deployment” on the left in the navbar. Choose a name for this alias and associate it with the version we have just created (Version 1):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MSEVULj_kF6Bky1DMYvSnQ.png" /></figure><h3>Step 2: Setup an Amazon Connect Instance</h3><p>In the console search for the Amazon Connect service and click on “Add an instance”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NP_oXxzH0Y2Kfn5FOMIqkQ.png" /></figure><p>For Identity management, leave it b as default (Store users in Amazon Connect) and provide an instance alias name, for example “travelnow”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hilwja4RsKEyjAg9vGSo7w.png" /></figure><p>Then specify an administrator and fill in the requested fields. Make sure to type a password with at least one capital letter, one number and at least 8 characters long. Take note of the username and of the password you chose, we will need them later:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RRGNjesDPr95glYJkA0yXg.png" /></figure><p>For the next steps leave everything as it is by default and finally create the instance. It will take some time. When it will be finished, select the new instance and go to “Flows” on the left. Under the “Amazon Lex” section choose the bot we have created and its alias. Then click on “+ Add Amazon Lex Bot”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4y4VdjMS-TneULvGVbkOhQ.png" /></figure><p>And we are all set! Now go back to the Amazon Connect instances page and click on the Access URL:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nSUFsn3j4ktT1uT12GeGCw.png" /></figure><p>You will be redirected to this login page, you should put the username and password of the administrator we specified before:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cqAf1I244g73b5OF1ksQpg.png" /></figure><p>We will be redirected to the homepage of the Amazon Connect instance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YFqNnus379UCAumrEL67xQ.png" /></figure><p>Then go to the third (from the top) icon on the navbar on the left which corresponds to Routing and select “Flows”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*chK4WUEnfD-L36YmilA3Og.png" /></figure><p>Then hit “Create flow” on the right:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fnZEBGO-KSWCJ7P--2nDXg.png" /></figure><p>First choose a name for this flow on the top left, I called it “TravelNowMainFlow”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CjuY8zFETrmA7ylmv9hRGg.png" /></figure><p>Then under “INTERACT” select the “Play prompt” block and place it in the flow, click on the three horizontal dots and then select “Edit settings”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SnuoYzHT_qWegbS1jvCoqw.png" /></figure><p>Choose “Text-to-speech or chat text” and write an Italian welcome message like:</p><pre>Benvenuto alla Travel Now.<br>Offriamo servizi di prenotazione auto e hotel.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0bL_LSi_c0g9vfopww3rtA.png" /></figure><p>Then click on “Save”.</p><p>Next, connect the Entry block to the new block like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YDCdonsaGOJTxfTfVYW2KQ.png" /></figure><p>Next, place the “Get customer input” block into the flow and go to its settings. Like before, select “Text-to-speech or chat text” and write something like:</p><pre>Come possiamo aiutarti oggi?</pre><p>Then in the same settings, if you scroll down, you should choose the tab named “Amazon Lex” and select the Lex bot and its corresponding alias:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2sUSANCcH3R_LFbRWFm_2A.png" /></figure><p>Continue then to scroll down and click on “Add an intent”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aF8xrZyHMakWM3kgRUxxWQ.png" /></figure><p>Write the name of the intent “BookCar”. Then click again on “Add an intent” and add the other one which is called “BookHotel” like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xppJS5WhS1QZt6Ks9VNDyg.png" /></figure><p>Then click on “Save”.</p><p>Note that under “INTEGRATE” there is a block “Invoke AWS Lambda Function” which already tells what it does by its name. We won’t use it, but it’s good to know that there is this option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TFjrFv8elgg5Gn9DjPbjEw.png" /></figure><p>Instead we will add another “Play prompt” block to add another message:</p><pre>Grazie.<br>Buona giornata.</pre><p>Finally, from “TERMINATE” we add a Disconnect block:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qvESi3Bnsr2bGpZieBMmbQ.png" /></figure><p>Then connect all the blocks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sd9L7MspW65BqzdRT-tPNg.png" /></figure><p>Once you have finished, click “Save” on the top right corner and then “Publish” to publish the flow.</p><p>Next, from the homepage select “View communication widgets”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MuIOA5ZXqJx1x177yGrwIA.png" /></figure><p>Then click on “Add widget”, give it a name and under Chat &gt; Chat concact flow you have to select the flow we have just published. Same for the Web calling section:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*DP0uAIzVzZxn8p681Ba7sg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*J6kwKvAiypUxEayrOKgBoQ.png" /></figure><p>Then hit “Save and continue”.</p><p>In the next step, you can customize the widget. For this demo we leave everything as it is, feel free to make changes to the style of the widget. For this demo I will simply click again on “Save and continue”.</p><p>Then for Domain &amp; Security you need to add the website domain where the communication widget would display.</p><p>So we open another tab in our browser and create a bucket in Amazon S3 (give it a unique name) and uncheck the “Block all public access” option while creating the bucket. Then check the “I acknowledge [..]” option:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PM-9QceTZOv59OJo386Brw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rsyYA-5QiGjLls6PqjWRiQ.png" /></figure><p>Then hit “Create bucket”.</p><p>Now select the bucket and go to Properties:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a4KALnnHS53QKwZYATzolw.png" /></figure><p>Then scroll down and hit “Edit” under Static website hosting:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fAkN-fmJ7nDz0nKEn7J5EA.png" /></figure><p>Select “Enable”, specify “index.html” as Index document and then hit “Save changes” on the bottom of the page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FU3wltmvx6GQrgkuzyovZA.png" /></figure><p>Then go to Permissions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*odpcFouLXSmm_fXVASQkdQ.png" /></figure><p>Next to Bucket policy, click on the Edit button:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*epP7kjNHvLhcXccLh2GKtw.png" /></figure><p>Copy the Bucket ARN and then open the Policy generator:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VQuBtWEaTtgEViot4k8ixA.png" /></figure><p>We want to create an S3 bucket policy to allow public read access to objects in the new S3 bucket, so we configure it as the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KRD_sw5uvruqhC7w-_cpnQ.png" /></figure><p>The selected action is “GetObject”. Paste the bucket ARN and add at the end of the string “/*” to specify that the policy is applied to all the objects inside the bucket, in my case it is:</p><pre>arn:aws:s3:::travelnowwebsite/*</pre><p>Finally click on “Add Statement” and then “Generate policy”. Copy and paste the code that it has generated to the previous page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Yg3fK4NXs0GZBVtJun2NA.png" /></figure><p>Then hit “Save changes”.</p><p>If you go back on “Properties” copy the Static website hosting URL:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MiOtkGsVPVAxDKfm4t40fA.png" /></figure><p>Now go to the CloudFront service and click on “Create distribution”. The reason why we create a CloudFront distribution is to have secure HTTPS access to the website hosted in S3.</p><ul><li>In Origin domain paste the website URL and remove “http://”.</li><li>Under “View protocol policy” select “HTTPS only”</li><li>Under “Allowed HTTP methods” select “GET, HEAD, OPTIONS, PUT, POST, PATCH, DELETE”.</li><li>Under “Web Application Firewall (WAF)” select “Do not enable security protections”</li><li>Choose an appropriate Price class, I will select “Use North America, Europe, Asia, Middle East, and Africa”.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*8P30FElvgu8ljPp-JJPPmA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*749QLbe0OT9nw76VDWyGOQ.png" /></figure><p>Then hit “Create distribution”. Now wait until it’s deployed. When it will be finished, you will se the current date and time under Last modified.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SvGejlQxudX0KwJJt9tJzg.png" /></figure><p>Next, copy the Distribution domain name. Then return to the communication widget in Amazon Connect and paste it as a new domain:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kYv0L_0mSSLpIHBVB3w1TQ.png" /></figure><p>Now the widget is succesfully created! If you scroll down, under “Widget script” copy the generated code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*--Kx5riYn0cx0SuScZji1g.png" /></figure><p>This is our sample HTML code for index.html. Replace the widget script with yours:</p><pre>&lt;html lang=&quot;it&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;Travel Now - Prenotazioni Auto e Hotel&lt;/title&gt;<br>    &lt;style&gt;<br>        body {<br>            font-family: Arial, sans-serif;<br>            background-color: #f4f4f4;<br>            margin: 0;<br>            padding: 20px;<br>            text-align: center;<br>        }<br>        h1 {<br>            color: #123456;<br>        }<br>        p {<br>            font-size: 18px;<br>        }<br>        .widget-invitation {<br>            margin-top: 20px;<br>            padding: 10px;<br>            background-color: #e0e0e0;<br>            border-radius: 5px;<br>        }<br>    &lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;h1&gt;Benvenuti su Travel Now!&lt;/h1&gt;<br>    &lt;p&gt;Il tuo punto di riferimento per prenotazioni di auto e hotel.&lt;/p&gt;<br>    &lt;div class=&quot;widget-invitation&quot;&gt;<br>        &lt;p&gt;Hai bisogno di aiuto per prenotare il tuo viaggio? Utilizza il nostro Custom Support Widget qui sotto!&lt;/p&gt;<br>    &lt;/div&gt;<br><br>    &lt;!-- Replace the widget script here --&gt;<br>    &lt;script type=&quot;text/javascript&quot;&gt;<br>        (function(w, d, x, id){<br>            s=d.createElement(&#39;script&#39;);<br>            s.src=&#39;https://d1ddlw7p7j6hta.cloudfront.net/amazon-connect-chat-interface-client.js&#39;;<br>            s.async=1;<br>            s.id=id;<br>            d.getElementsByTagName(&#39;head&#39;)[0].appendChild(s);<br>            w[x] =  w[x] || function() { (w[x].ac = w[x].ac || []).push(arguments) };<br>        })(window, document, &#39;amazon_connect&#39;, &#39;534cca15-4df7-4414-b90b-7e4a53f48dfc&#39;);<br>        amazon_connect(&#39;styles&#39;, { iconType: &#39;CHAT_VOICE&#39;, openChat: { color: &#39;#ffffff&#39;, backgroundColor: &#39;#123456&#39; }, closeChat: { color: &#39;#ffffff&#39;, backgroundColor: &#39;#123456&#39;} });<br>        amazon_connect(&#39;snippetId&#39;, &#39;QVFJREFIZ2ZySXd1eE1EWFNRRkRQSWFXZjRvaGxjT0xmd1pOWWViVU4vd0hnZnByS1FHMzhYLzc3TXZIQnh2MlhSQ2hmUkJHQUFBQWJqQnNCZ2txaGtpRzl3MEJCd2FnWHpCZEFnRUFNRmdHQ1NxR1NJYjNEUUVIQVRBZUJnbGdoa2dCWlFNRUFTNHdFUVFNZ2RsSFNNWUxmU2dRb25MZkFnRVFnQ3NnaVU3UzdGanNNOWVRdWJ5Rit5TkN2YVAxUjdyOHIyVlp0N0cxc3dVOGNOVFlxa3dSb3ZKSko4enY6OlNtemtsK3V1SmVTUElXd3RmeDZLN1NpMUZuMXJOTWQvN1hlaVdEVXFUYmpKNUlaZmtjamNvWHNXL0ZUazlNNWFsL0FEODFjY25qTmpMUFVaenhJVUZUQklXdXZtRHM3TDc0WW9nalI1RnZjajhyNCtkOVBCTElIelRWNWc2VmJMYzlqK012eHg5eHhSOEhrVGxxT21zc1N2S1N5RnVUMD0=&#39;);<br>        amazon_connect(&#39;supportedMessagingContentTypes&#39;, [ &#39;text/plain&#39;, &#39;text/markdown&#39;, &#39;application/vnd.amazonaws.connect.message.interactive&#39;, &#39;application/vnd.amazonaws.connect.message.interactive.response&#39; ]);<br>    &lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Save this code in a index.html file and in S3 go to our bucket and upload it.</p><p>Then in Amazon Connect go to Channels &gt; Phone Numbers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z1wdp-wQCWM7I_pwYSfGlQ.png" /></figure><p>Then hit “Claim a number”. Select a Country (for example United States) and choose a number. Then click on “Save”.</p><p>Now if you paste your CloudFront distribution name in the browser, you can see our page with our widget:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_MZB8knmlOa3JkDDv67h1g.png" /></figure><p>That’s it! Hope you enjoyed this lecture and I will see you in another project!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7590079fe67b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Step-by-Step Guide On Deploying REST API using API Gateway, Lambda, Cognito — Terraform]]></title>
            <link>https://awstip.com/a-step-by-step-guide-on-deploying-rest-api-using-api-gateway-lambda-cognito-terraform-f277814d048e?source=rss-e9f146485d51------2</link>
            <guid isPermaLink="false">https://medium.com/p/f277814d048e</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[api-gateway]]></category>
            <dc:creator><![CDATA[Mattiamazzari]]></dc:creator>
            <pubDate>Wed, 01 May 2024 17:24:39 GMT</pubDate>
            <atom:updated>2024-05-06T16:20:14.118Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Step-by-Step Guide On Deploying REST API using API Gateway, Lambda, DynamoDB, Cognito — Terraform</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OPd5dFStECWJoWbOfSvB7g.png" /></figure><h3>Introduction</h3><p>We want to build an hands-on project which can be used on different kind of situations and which is very common in the real world, in which almost all the applications are based on microservices in modular lego blocks.</p><p>In particular, the goal is to create an API hosted in an API gateway with the backend on Lambda and a database on DynamoDB. The Lambda Function will contain the logic to perform CRUD operations (CREATE, READ, UPDATE, DELETE) on the DynamoDB table. Then additionally we will restrict public access to some routes by adding authentication using Amazon Cognito because writing operations are dangerous for the database.</p><p>Since I was born in Sicily, a beautiful island in Italy, we will create a simple API for managing a list of traditional Sicilian dishes.</p><p>Here you can find all the source code:</p><p><a href="https://github.com/mattiamazzari/restapi-aws/">GitHub - mattiamazzari/restapi-aws</a></p><h3>Step 1: setup provider, AWS region, S3 backend</h3><p>The first step is to specify we’re using AWS as provider:</p><pre># provider.tf<br><br>provider &quot;aws&quot; {<br>  region = var.aws_region<br>}</pre><p>We are defining just one variable.</p><pre># variables.tf<br><br>variable &quot;aws_region&quot; {<br>  default   = &quot;eu-west-3&quot;<br>  type      = string<br>}</pre><p>Then go the AWS management console, go to the “S3” AWS service and create an S3 bucket that will store our Terraform state file later on in a path specified by a “key” attribute. I call it “my-api-gateway-lambda-terraform-state”, leave all the options as default.</p><p>After having created it, I will specify it in my Terraform configuration:</p><pre># backend.tf<br><br>terraform {<br>  backend &quot;s3&quot; {<br>    bucket = &quot;my-api-gateway-lambda-terraform-state&quot;<br>    region = var.aws_region<br>    key    = &quot;API-Gateway/terraform.tfstate&quot;<br>  }<br>  required_version = &quot;&gt;= 0.13.0&quot;<br>  required_providers {<br>    aws = {<br>      source  = &quot;hashicorp/aws&quot;<br>      version = &quot;&gt;= 2.7.0&quot;<br>    }<br>  }<br>}</pre><h3>Step 2: create Lambda IAM Role</h3><p>If the Lambda Function wants to perform some operations on the DynamoDB table, it must have the permissions to do it and so we have to create an IAM Role.</p><p>First of all we need to explictly indicate an IAM Role’s Assume Role policy (also called Trust Relationship), that indicates which resource / service can assume the role that we want to define, in our case the Lambda Function. This is always a mandatory step when giving permissions to an AWS service. The format for this policy is the following:</p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [{<br>        &quot;Effect&quot;: &quot;Allow&quot;,<br>        &quot;Principal&quot;: {<br>            &quot;Service&quot;: &quot;lambda.amazonaws.com&quot; # name of the AWS service<br>        },<br>        &quot;Action&quot;: &quot;sts:AssumeRole&quot;<br>    }]<br>}</pre><p>Basically we are saying “All Lambda Functions in my account can assume this role”.</p><p>Also we have to grant to the Lambda some minimal permissions required for writing logs associated to the execution of the function itself, and they are already defined in a IAM Service Role called AWSLambdaBasicExecutionRole, provided by AWS. So we associate this service role to the new IAM Role that we will assign to the Lambda.</p><p>So create a file “iam.tf” and paste this code:</p><pre># iam.tf<br><br># Assume Role policy<br>data &quot;aws_iam_policy_document&quot; &quot;AWSLambdaTrustPolicy&quot; {<br>  statement {<br>    actions    = [&quot;sts:AssumeRole&quot;]<br>    effect     = &quot;Allow&quot;<br>    principals {<br>      type        = &quot;Service&quot;<br>      identifiers = [&quot;lambda.amazonaws.com&quot;]<br>    }<br>  }<br>}<br><br># Define IAM role and attach the Assume Role Policy<br>resource &quot;aws_iam_role&quot; &quot;terraform_function_role&quot; {<br>  name               = &quot;terraform_function_role&quot;<br>  assume_role_policy = data.aws_iam_policy_document.AWSLambdaTrustPolicy.json<br>}<br><br># Attach a IAM Service Role to the IAM role we just defined<br># AWSLambdaBasicExecutionRole grants minimal permissions to the Lambda Function<br># (write logs about execution, errors, debug, ...)<br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;terraform_lambda_policy&quot; {<br>  role       = aws_iam_role.terraform_function_role.name<br>  policy_arn = &quot;arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole&quot;<br>}</pre><p>In addition to this, as we said, the Lambda Function must access to the DynamoDB table that we will create. So we create a JSON policy document in which all the actions on the DynamoDB table are explictly allowed:</p><pre>// lambda_dynamodb_policy.json<br><br>{<br>  &quot;Version&quot;: &quot;2012-10-17&quot;,<br>  &quot;Statement&quot;: [<br>      {<br>          &quot;Sid&quot;: &quot;ListAndDescribe&quot;,<br>          &quot;Effect&quot;: &quot;Allow&quot;,<br>          &quot;Action&quot;: [<br>              &quot;dynamodb:List*&quot;,<br>              &quot;dynamodb:DescribeReservedCapacity*&quot;,<br>              &quot;dynamodb:DescribeLimits&quot;,<br>              &quot;dynamodb:DescribeTimeToLive&quot;<br>          ],<br>          &quot;Resource&quot;: &quot;*&quot;<br>      },<br>      {<br>          &quot;Sid&quot;: &quot;SpecificTable&quot;,<br>          &quot;Effect&quot;: &quot;Allow&quot;,<br>          &quot;Action&quot;: [<br>              &quot;dynamodb:BatchGet*&quot;,<br>              &quot;dynamodb:DescribeStream&quot;,<br>              &quot;dynamodb:DescribeTable&quot;,<br>              &quot;dynamodb:Get*&quot;,<br>              &quot;dynamodb:Query&quot;,<br>              &quot;dynamodb:Scan&quot;,<br>              &quot;dynamodb:BatchWrite*&quot;,<br>              &quot;dynamodb:CreateTable&quot;,<br>              &quot;dynamodb:Delete*&quot;,<br>              &quot;dynamodb:Update*&quot;,<br>              &quot;dynamodb:PutItem&quot;<br>          ],<br>          &quot;Resource&quot;: &quot;arn:aws:dynamodb:*:*:table/dishes&quot; // DynamoDB table<br>      }<br>  ]<br>}</pre><p>So we are defining a policy that allows the Lambda function to perform CRUD operations (Get, Put, Update, Delete, Scan, Query and other operations) on the DynamoDB table, that we will call “dishes”.</p><p>In “iam.tf” instead we write this to attach the policy defined in the JSON document to the IAM role:</p><pre># iam.tf<br><br># Attach a custom policy to the IAM role for accessing DynamoDB<br>resource &quot;aws_iam_role_policy&quot; &quot;lambda_dynamodb_policy&quot; {<br>  name   = &quot;lambda_dynamodb_policy&quot;<br>  role   = aws_iam_role.lambda-iam-role.name<br>  policy = file(&quot;${path.module}/lambda_dynamodb_policy.json&quot;)<br>}</pre><h3>Step 3: setup Lambda code</h3><p>Next we want to setup the Lambda Function that will interact with the DynamoDB table. We will write it in Python.</p><p>Inside the Lambda we might want to define a method for each operation and return a response to the API Gateway, with different status codes. We will write the code of the function in Python.</p><p>First of all we setup the logger to see what is going on when we test the Lambda. Then inside the lambda_handler() we declare the DynamoDB client leveraging the library boto3, used to interact with AWS services. The event that triggers the Lambda is the HTTP request from the API Gateway. We can read the HTTP method from it and distinguish the operation that the Lambda should perform on the DynamoDB table accordingly.</p><p>REST API are structured like a tree, we want to structure it like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*diiEEw5gleYIlRkVephsRg.jpeg" /></figure><p>We want to be able to:</p><ul><li><strong>GET dishes/</strong> : retrieve all the dishes</li><li><strong>GET dish/{dishId}</strong> : retrieve one specific dish by ID</li><li><strong>POST dish/</strong> : save a new dish inside the table</li><li><strong>PATCH dish/</strong> : update a specific attribute of a dish</li><li><strong>DELETE dish/ </strong>: delete a dish from the table</li></ul><p>To get all the items of the table we leverage a recursive function recursive_scan, which is used to scan records from a DynamoDB table in an efficient way.</p><p>The standard DynamoDB’s scan operation is the standard approach to read all items in a table. However, due to the distributed nature of DynamoDB and its scalability, a single scan operation may not retrieve all items in one go, especially if the table is large. DynamoDB paginates the results, returning a subset of items with a token (LastEvaluatedKey) that indicates where the next page of results begins.</p><p>The recursive_scan method optimizes the scanning process by recursively fetching all pages of results until there are no more pages left (LastEvaluatedKey is not present in the response). This ensures that all items in the DynamoDB table are retrieved efficiently, regardless of the number of pages.</p><pre>def recursive_scan(scan_params, items):<br>    response = table.scan(**scan_params)<br>    items += response[&#39;Items&#39;]<br>    if &#39;LastEvaluatedKey&#39; in response:<br>        scan_params[&#39;ExclusiveStartKey&#39;] = response[&#39;LastEvaluatedKey&#39;]<br>        recursive_scan(scan_params, items)<br>    return items</pre><p>Here is the full code of the Lambda function:</p><pre># lambda_code.py<br><br>import json<br>import logging<br>import boto3<br>from decimal import Decimal<br>from botocore.exceptions import ClientError<br><br>logger = logging.getLogger()<br>logger.setLevel(logging.INFO)<br><br>dynamodb = boto3.resource(&#39;dynamodb&#39;)<br>table = dynamodb.Table(&#39;dishes&#39;)<br><br>dish_path = &#39;/dish&#39;<br>dishes_path = &#39;/dishes&#39;<br><br>def lambda_handler(event, context):<br>        <br>    logger.info(&#39;API event: {}&#39;.format(event))<br>    <br>    response = None<br>    <br>    try: <br>        http_method = event.get(&#39;httpMethod&#39;)<br>        path = event.get(&#39;path&#39;)<br>        <br>        if http_method == &#39;GET&#39; and path == dishes_path:<br>            response = get_all_dishes()<br>            <br>        elif http_method == &#39;GET&#39; and path == dish_path:<br>            dish_id = event[&#39;queryStringParameters&#39;][&#39;dish_id&#39;]<br>            response = get_dish(dish_id)<br>            <br>        elif http_method == &#39;POST&#39; and path == dish_path:<br>            body = json.loads(event[&#39;body&#39;])<br>            response = save_dish(body)<br>            <br>        elif http_method == &#39;PATCH&#39; and path == dish_path:<br>            body = json.loads(event[&#39;body&#39;])<br>            response = update_dish(body[&#39;dish_id&#39;], body[&#39;update_key&#39;], body[&#39;update_value&#39;])<br>            <br>        elif http_method == &#39;DELETE&#39;:<br>            body = json.loads(event[&#39;body&#39;])<br>            response = delete_dish(body[&#39;dish_id&#39;])<br>            <br>        else:<br>            response = generate_response(404, &#39;Resource Not Found&#39;)<br>            <br>    except ClientError as e:<br>        logger.error(&#39;Error: {}&#39;.format(e))<br>        response = generate_response(404, e.response[&#39;Error&#39;][&#39;Message&#39;])<br>        <br>    return response<br>        <br>def get_dish(dish_id):<br>    try:<br>        response = table.get_item(Key={&#39;dish_id&#39;: dish_id})<br>        item = response[&#39;Item&#39;]<br>        logger.info(&#39;GET item: {}&#39;.format(item))<br>        return generate_response(200, item)<br>    except ClientError as e:<br>        logger.error(&#39;Error: {}&#39;.format(e))<br>        return generate_response(404, e.response[&#39;Error&#39;][&#39;Message&#39;])<br>    <br>def get_all_dishes():<br>    try:<br>        scan_params = {<br>            &#39;TableName&#39;: table.name<br>        }<br>        items = recursive_scan(scan_params, [])<br>        logger.info(&#39;GET ALL items: {}&#39;.format(items))<br>        return generate_response(200, items)<br>    except ClientError as e:<br>        logger.error(&#39;Error: {}&#39;.format(e))<br>        return generate_response(404, e.response[&#39;Error&#39;][&#39;Message&#39;])<br>    <br>def recursive_scan(scan_params, items):<br>    response = table.scan(**scan_params)<br>    items += response[&#39;Items&#39;]<br>    if &#39;LastEvaluatedKey&#39; in response:<br>        scan_params[&#39;ExclusiveStartKey&#39;] = response[&#39;LastEvaluatedKey&#39;]<br>        recursive_scan(scan_params, items)<br>    return items<br><br>def save_dish(item):<br>    try:<br>        table.put_item(Item=item)<br>        logger.info(&#39;POST item: {}&#39;.format(item))<br>        body = {<br>            &#39;Operation&#39;: &#39;SAVE&#39;,<br>            &#39;Message&#39;: &#39;SUCCESS&#39;,<br>            &#39;Item&#39;: item<br>        }<br>        return generate_response(200, body)<br>    except ClientError as e:<br>        logger.error(&#39;Error: {}&#39;.format(e))<br>        return generate_response(404, e.response[&#39;Error&#39;][&#39;Message&#39;])<br>    <br>def update_dish(dish_id, update_key, update_value):<br>    try:<br>        response = table.update_item(<br>            Key={&#39;dish_id&#39;: dish_id},<br>            UpdateExpression=f&#39;SET {update_key} = :value&#39;,<br>            ExpressionAttributeValues={&#39;:value&#39;: update_value},<br>            ReturnValues=&#39;UPDATED_NEW&#39;<br>        )<br>        logger.info(&#39;UPDATE item: {}&#39;.format(response))<br>        body = {<br>            &#39;Operation&#39;: &#39;UPDATE&#39;,<br>            &#39;Message&#39;: &#39;SUCCESS&#39;,<br>            &#39;Item&#39;: response<br>        }<br>        return generate_response(200, response)<br>    except ClientError as e:<br>        logger.error(&#39;Error: {}&#39;.format(e))<br>        return generate_response(404, e.response[&#39;Error&#39;][&#39;Message&#39;])<br>    <br>def delete_dish(dish_id):<br>    try:<br>        response = table.delete_item(<br>            Key={&#39;dish_id&#39;: dish_id},<br>            ReturnValues=&#39;ALL_OLD&#39;<br>        )<br>        logger.info(&#39;DELETE item: {}&#39;.format(response))<br>        body = {<br>            &#39;Operation&#39;: &#39;DELETE&#39;,<br>            &#39;Message&#39;: &#39;SUCCESS&#39;,<br>            &#39;Item&#39;: response<br>        }<br>        return generate_response(200, body)<br>    except ClientError as e:<br>        logger.error(&#39;Error: {}&#39;.format(e))<br>        return generate_response(404, e.response[&#39;Error&#39;][&#39;Message&#39;])<br><br>class DecimalEncoder(json.JSONEncoder):<br>    def default(self, obj):<br>        if isinstance(obj, Decimal):<br>            # Check if it&#39;s an int or a float<br>            if obj % 1 == 0:<br>                return int(obj)<br>            else:<br>                return float(obj)<br>        # Let the base class default method raise the TypeError<br>        return super(DecimalEncoder, self).default(obj)<br>        <br>def generate_response(status_code, body):<br>    return {<br>        &#39;statusCode&#39;: status_code,<br>        &#39;headers&#39;: {<br>            &#39;Content-Type&#39;: &#39;application/json&#39;,<br>        },<br>        &#39;body&#39;: json.dumps(body, cls=DecimalEncoder)<br>    }</pre><p>Then, in a “lambda.tf” Terraform file we define a data block to zip the code of the Lambda and then we have a resource block for the Lambda itself:</p><pre>data &quot;archive_file&quot; &quot;lambda_code&quot; {<br>  type        = &quot;zip&quot;<br>  source_file = &quot;${path.module}/lambda_code.py&quot;<br>  output_path = &quot;${path.module}/lambda_code.zip&quot;<br>}<br><br>resource &quot;aws_lambda_function&quot; &quot;my-lambda-function&quot; {<br>  filename      = &quot;${path.module}/lambda_code.zip&quot;<br>  function_name = &quot;api-gateway-lambda&quot;<br>  role          = aws_iam_role.lambda-iam-role.arn<br>  handler       = &quot;lambda_code.lambda_handler&quot;<br>  runtime       = &quot;python3.12&quot;<br><br>  source_code_hash = data.archive_file.lambda_code.output_base64sha256<br>}</pre><h3>Step 3: setup DynamoDB</h3><p>It is time to create our delicious table of Sicilian dishes!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*WMK7Qze__kL4gO7lXQ5LKg.gif" /><figcaption>“Mangia ca crisci” means “Eat, because you have to grow!”</figcaption></figure><p>Create a file “database.tf” and paste this code:</p><pre># Define the DynamoDB table<br>resource &quot;aws_dynamodb_table&quot; &quot;my_dynamodb_table&quot; {<br>  name         = &quot;dishes&quot;<br>  billing_mode = &quot;PAY_PER_REQUEST&quot;<br>  hash_key     = &quot;dish_id&quot;<br><br>  attribute {<br>    name = &quot;dish_id&quot;<br>    type = &quot;S&quot;<br>  }<br><br>  tags = {<br>    Name = &quot;dishes-table&quot;<br>  }<br>}<br><br>locals {<br>  json_data = file(&quot;${path.module}/dishes.json&quot;)<br>  dishes    = jsondecode(local.json_data)<br>}<br><br># Create a new item in the DynamoDB table for each dish<br>resource &quot;aws_dynamodb_table_item&quot; &quot;dishes&quot; {<br>  for_each   = local.dishes<br>  table_name = aws_dynamodb_table.my_dynamodb_table.name<br>  hash_key   = aws_dynamodb_table.my_dynamodb_table.hash_key<br>  item       = jsonencode(each.value)<br>}</pre><p>We take the data from a JSON document, so create a file “dishes.json”. For each attribute we specify the type (S = String, N = Number, L = List).</p><pre>// dishes.json<br><br>{<br>    &quot;Item1&quot;: {<br>        &quot;dish_id&quot;: {<br>            &quot;S&quot;: &quot;1&quot;<br>        },<br>        &quot;name&quot;: {<br>            &quot;S&quot;: &quot;Arancini&quot;<br>        },<br>        &quot;description&quot;: {<br>            &quot;S&quot;: &quot;Fried rice balls stuffed with cheese, peas, and meat&quot;<br>        },<br>        &quot;price&quot;: {<br>            &quot;N&quot;: &quot;8.99&quot;<br>        },<br>        &quot;ingredients&quot;: {<br>            &quot;L&quot;: [<br>                {&quot;S&quot;: &quot;rice&quot;},<br>                {&quot;S&quot;: &quot;cheese&quot;},<br>                {&quot;S&quot;: &quot;peas&quot;},<br>                {&quot;S&quot;: &quot;meat&quot;},<br>                {&quot;S&quot;: &quot;breadcrumbs&quot;}<br>            ]<br>        }<br>    },<br>    &quot;Item2&quot;: {<br>        &quot;dish_id&quot;: {<br>            &quot;S&quot;: &quot;2&quot;<br>        },<br>        &quot;name&quot;: {<br>            &quot;S&quot;: &quot;Cannoli&quot;<br>        },<br>        &quot;description&quot;: {<br>            &quot;S&quot;: &quot;Sicilian pastry dessert consisting of tube-shaped shells of fried pastry dough, filled with a sweet, creamy filling&quot;<br>        },<br>        &quot;price&quot;: {<br>            &quot;N&quot;: &quot;5.99&quot;<br>        },<br>        &quot;ingredients&quot;: {<br>            &quot;L&quot;: [<br>                {&quot;S&quot;: &quot;flour&quot;},<br>                {&quot;S&quot;: &quot;ricotta cheese&quot;},<br>                {&quot;S&quot;: &quot;sugar&quot;},<br>                {&quot;S&quot;: &quot;chocolate chips&quot;}<br>            ]<br>        }<br>    },<br>    &quot;Item3&quot;: {<br>        &quot;dish_id&quot;: {<br>            &quot;S&quot;: &quot;3&quot;<br>        },<br>        &quot;name&quot;: {<br>            &quot;S&quot;: &quot;Pasta alla Norma&quot;<br>        },<br>        &quot;description&quot;: {<br>            &quot;S&quot;: &quot;Pasta with tomato sauce, fried eggplant, grated ricotta salata cheese, and basil&quot;<br>        },<br>        &quot;price&quot;: {<br>            &quot;N&quot;: &quot;12.99&quot;<br>        },<br>        &quot;ingredients&quot;: {<br>            &quot;L&quot;: [<br>                {&quot;S&quot;: &quot;pasta&quot;},<br>                {&quot;S&quot;: &quot;tomato sauce&quot;},<br>                {&quot;S&quot;: &quot;eggplant&quot;},<br>                {&quot;S&quot;: &quot;ricotta cheese&quot;},<br>                {&quot;S&quot;: &quot;basil&quot;}<br>            ]<br>        }<br>    },<br>    &quot;Item4&quot;: {<br>        &quot;dish_id&quot;: {<br>            &quot;S&quot;: &quot;4&quot;<br>        },<br>        &quot;name&quot;: {<br>            &quot;S&quot;: &quot;Cassata&quot;<br>        },<br>        &quot;description&quot;: {<br>            &quot;S&quot;: &quot;Sicilian cake consisting of round sponge cake moistened with fruit juices or liqueur and layered with ricotta cheese, candied peel, and a chocolate or vanilla filling similar to cannoli cream&quot;<br>        },<br>        &quot;price&quot;: {<br>            &quot;N&quot;: &quot;15.99&quot;<br>        },<br>        &quot;ingredients&quot;: {<br>            &quot;L&quot;: [<br>                {&quot;S&quot;: &quot;sponge cake&quot;},<br>                {&quot;S&quot;: &quot;fruit juices&quot;},<br>                {&quot;S&quot;: &quot;liqueur&quot;},<br>                {&quot;S&quot;: &quot;ricotta cheese&quot;},<br>                {&quot;S&quot;: &quot;candied peel&quot;},<br>                {&quot;S&quot;: &quot;chocolate&quot;},<br>                {&quot;S&quot;: &quot;vanilla&quot;}<br>            ]<br>        }<br>    }<br>}</pre><h3>Step 4: setup API Gateway</h3><p>Now it is time to setup our API gateway. The API Gateway acts as a proxy: it forwards the HTTP requests coming from the client to the Lambda Function (through a POST request) and with this “trick” the original HTTP request is sent (GET, POST, … )</p><p>First we setup the API gateway REST API and create two API resources, one for each path (/dishes and /dish):</p><pre># api_gateway.tf<br><br># API gateway<br>resource &quot;aws_api_gateway_rest_api&quot; &quot;API-gw&quot; {<br>  name        = &quot;lambda_rest_api&quot;<br>  description = &quot;This is the REST API for Sicilian Dishes&quot;<br>  endpoint_configuration {<br>    types = [&quot;REGIONAL&quot;]<br>  }<br>}<br><br># API resource for the path &quot;/dishes&quot;<br>resource &quot;aws_api_gateway_resource&quot; &quot;API-resource-dishes&quot; {<br>  rest_api_id = aws_api_gateway_rest_api.API-gw.id<br>  parent_id   = aws_api_gateway_rest_api.API-gw.root_resource_id<br>  path_part   = &quot;dishes&quot;<br>}<br><br># API resource for the path &quot;/dish&quot;<br>resource &quot;aws_api_gateway_resource&quot; &quot;API-resource-dish&quot; {<br>  rest_api_id = aws_api_gateway_rest_api.API-gw.id<br>  parent_id   = aws_api_gateway_rest_api.API-gw.root_resource_id<br>  path_part   = &quot;dishes&quot;<br>}</pre><p>As we said, we want the following API endpoints:</p><ul><li><strong>GET /dishes</strong>: Retrieve the list of all Sicilian dishes.</li><li><strong>GET /dishes/{dishId}</strong>: Retrieve details of a specific dish by its ID.</li><li><strong>POST /dishes</strong>: Add a new Sicilian dish to the database.</li><li><strong>PATCH /dishes/{dishId}</strong>: Update the details of a specific dish.</li><li><strong>DELETE /dishes/{dishId}</strong>: Delete a Sicilian dish from the database.</li></ul><p>Then for each HTTP method we define some blocks:</p><ul><li>Method (to specify the HTTP method)</li><li>Integration (to integrate with Lambda)</li><li>Method response</li><li>Integration response</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*h-2cDmHxFShN9qhrpT_kyw.png" /></figure><p>The “REST API” is the container for all of the other API Gateway objects we will create.</p><p>All incoming requests to API Gateway must match with:</p><ul><li>a configured resource (the one defined for /dish or the other for /dishes)</li><li>an HTTP method</li></ul><p>Each method on an API gateway resource has an integration which specifies to which Lambda function incoming requests are sent. The “AWS_PROXY” integration type causes API gateway to call the AWS Lambda API to create an “invocation” of the Lambda function. Then we configure method response (with associated status code) and integration response.</p><pre># . . .<br><br># Define an API gateway that triggers the Lambda function<br>resource &quot;aws_api_gateway_rest_api&quot; &quot;API-gw&quot; {<br>  name        = &quot;lambda_rest_api&quot;<br>  description = &quot;This is the REST API for Sicilian Dishes&quot;<br>  endpoint_configuration {<br>    types = [&quot;REGIONAL&quot;]<br>  }<br>}<br><br>resource &quot;aws_api_gateway_resource&quot; &quot;API-resource-dish&quot; {<br>  rest_api_id = aws_api_gateway_rest_api.API-gw.id<br>  parent_id   = aws_api_gateway_rest_api.API-gw.root_resource_id<br>  path_part   = &quot;dish&quot;<br>}<br><br>resource &quot;aws_api_gateway_resource&quot; &quot;API-resource-dishes&quot; {<br>  rest_api_id = aws_api_gateway_rest_api.API-gw.id<br>  parent_id   = aws_api_gateway_rest_api.API-gw.root_resource_id<br>  path_part   = &quot;dishes&quot;<br>}<br><br>#####################################################################################################<br>########################### GET ALL /dishes #########################################################<br>#####################################################################################################<br><br>resource &quot;aws_api_gateway_method&quot; &quot;GET_all_method&quot; {<br>  rest_api_id   = aws_api_gateway_rest_api.API-gw.id<br>  resource_id   = aws_api_gateway_resource.API-resource-dishes.id<br>  http_method   = &quot;GET&quot;<br>  authorization = &quot;NONE&quot;<br>}<br><br>resource &quot;aws_api_gateway_integration&quot; &quot;GET_all_lambda_integration&quot; {<br>  rest_api_id             = aws_api_gateway_rest_api.API-gw.id<br>  resource_id             = aws_api_gateway_resource.API-resource-dishes.id<br>  http_method             = aws_api_gateway_method.GET_all_method.http_method<br>  type                    = &quot;AWS_PROXY&quot;<br>  integration_http_method = &quot;POST&quot;<br>  uri                     = aws_lambda_function.my-lambda-function.invoke_arn<br>}<br><br>resource &quot;aws_api_gateway_method_response&quot; &quot;GET_all_method_response_200&quot; {<br>  rest_api_id = aws_api_gateway_rest_api.API-gw.id<br>  resource_id = aws_api_gateway_resource.API-resource-dishes.id<br>  http_method = aws_api_gateway_method.GET_all_method.http_method<br>  status_code = &quot;200&quot;<br><br>  response_parameters = {<br>    &quot;method.response.header.Access-Control-Allow-Headers&quot;     = true,<br>    &quot;method.response.header.Access-Control-Allow-Methods&quot;     = true,<br>    &quot;method.response.header.Access-Control-Allow-Origin&quot;      = true,<br>    &quot;method.response.header.Access-Control-Allow-Credentials&quot; = true<br>  }<br>}<br><br>resource &quot;aws_api_gateway_integration_response&quot; &quot;GET_all_integration_response_200&quot; {<br>  rest_api_id = aws_api_gateway_rest_api.API-gw.id<br>  resource_id = aws_api_gateway_resource.API-resource-dishes.id<br>  http_method = aws_api_gateway_method.GET_all_method.http_method<br>  status_code = aws_api_gateway_method_response.GET_all_method_response_200.status_code<br><br>  depends_on = [aws_api_gateway_integration.GET_all_lambda_integration]<br><br>  response_templates = {<br>    &quot;application/json&quot; = &lt;&lt;EOF<br>    #set($inputRoot = $input.path(&#39;$.body&#39;))<br>    {<br>      \&quot;statusCode\&quot;: 200,<br>      \&quot;body\&quot;: $inputRoot,<br>      \&quot;headers\&quot;: {<br>        \&quot;Content-Type\&quot;: \&quot;application/json\&quot;<br>      }<br>    }<br>    EOF<br>  }<br>}<br><br>#####################################################################################################<br>########################### GET /dish/{dishId} #########################################################<br>#####################################################################################################<br><br>resource &quot;aws_api_gateway_method&quot; &quot;GET_one_method&quot; {<br>  rest_api_id   = aws_api_gateway_rest_api.API-gw.id<br>  resource_id   = aws_api_gateway_resource.API-resource-dish.id<br>  http_method   = &quot;GET&quot;<br>  authorization = &quot;NONE&quot;<br>}<br><br>resource &quot;aws_api_gateway_integration&quot; &quot;GET_one_lambda_integration&quot; {<br>  rest_api_id             = aws_api_gateway_rest_api.API-gw.id<br>  resource_id             = aws_api_gateway_resource.API-resource-dish.id<br>  http_method             = aws_api_gateway_method.GET_one_method.http_method<br>  type                    = &quot;AWS_PROXY&quot;<br>  integration_http_method = &quot;POST&quot;<br>  uri                     = aws_lambda_function.my-lambda-function.invoke_arn<br>}<br><br>resource &quot;aws_api_gateway_method_response&quot; &quot;GET_one_method_response_200&quot; {<br>  rest_api_id = aws_api_gateway_rest_api.API-gw.id<br>  resource_id = aws_api_gateway_resource.API-resource-dish.id<br>  http_method = aws_api_gateway_method.GET_one_method.http_method<br>  status_code = &quot;200&quot;<br><br>  response_parameters = {<br>    &quot;method.response.header.Access-Control-Allow-Headers&quot;     = true,<br>    &quot;method.response.header.Access-Control-Allow-Methods&quot;     = true,<br>    &quot;method.response.header.Access-Control-Allow-Origin&quot;      = true,<br>    &quot;method.response.header.Access-Control-Allow-Credentials&quot; = true<br>  }<br>}<br><br>resource &quot;aws_api_gateway_integration_response&quot; &quot;GET_one_integration_response_200&quot; {<br>  rest_api_id = aws_api_gateway_rest_api.API-gw.id<br>  resource_id = aws_api_gateway_resource.API-resource-dish.id<br>  http_method = aws_api_gateway_method.GET_one_method.http_method<br>  status_code = aws_api_gateway_method_response.GET_one_method_response_200.status_code<br><br>  depends_on = [aws_api_gateway_integration.GET_one_lambda_integration]<br><br>  response_templates = {<br>    &quot;application/json&quot; = &lt;&lt;EOF<br>    #set($inputRoot = $input.path(&#39;$.body&#39;))<br>    {<br>      \&quot;statusCode\&quot;: 200,<br>      \&quot;body\&quot;: $inputRoot,<br>      \&quot;headers\&quot;: {<br>        \&quot;Content-Type\&quot;: \&quot;application/json\&quot;<br>      }<br>    }<br>    EOF<br>  }<br>}<br><br>#####################################################################################################<br>########################### POST /dish #########################################################<br>#####################################################################################################<br><br>resource &quot;aws_api_gateway_method&quot; &quot;POST_method&quot; {<br>  rest_api_id   = aws_api_gateway_rest_api.API-gw.id<br>  resource_id   = aws_api_gateway_resource.API-resource-dish.id<br>  http_method   = &quot;POST&quot;<br>  authorization = &quot;NONE&quot;<br>}<br><br>resource &quot;aws_api_gateway_integration&quot; &quot;POST_lambda_integration&quot; {<br>  rest_api_id             = aws_api_gateway_rest_api.API-gw.id<br>  resource_id             = aws_api_gateway_resource.API-resource-dish.id<br>  http_method             = aws_api_gateway_method.POST_method.http_method<br>  type                    = &quot;AWS_PROXY&quot;<br>  integration_http_method = &quot;POST&quot;<br>  uri                     = aws_lambda_function.my-lambda-function.invoke_arn<br>}<br><br>resource &quot;aws_api_gateway_method_response&quot; &quot;POST_method_response_200&quot; {<br>  rest_api_id = aws_api_gateway_rest_api.API-gw.id<br>  resource_id = aws_api_gateway_resource.API-resource-dish.id<br>  http_method = aws_api_gateway_method.POST_method.http_method<br>  status_code = &quot;200&quot;<br><br>  response_parameters = {<br>    &quot;method.response.header.Access-Control-Allow-Headers&quot;     = true,<br>    &quot;method.response.header.Access-Control-Allow-Methods&quot;     = true,<br>    &quot;method.response.header.Access-Control-Allow-Origin&quot;      = true,<br>    &quot;method.response.header.Access-Control-Allow-Credentials&quot; = true<br>  }<br>}<br><br>resource &quot;aws_api_gateway_integration_response&quot; &quot;POST_integration_response_200&quot; {<br>  rest_api_id = aws_api_gateway_rest_api.API-gw.id<br>  resource_id = aws_api_gateway_resource.API-resource-dish.id<br>  http_method = aws_api_gateway_method.POST_method.http_method<br>  status_code = aws_api_gateway_method_response.POST_method_response_200.status_code<br><br>  depends_on = [aws_api_gateway_integration.POST_lambda_integration]<br><br>  response_templates = {<br>    &quot;application/json&quot; = &lt;&lt;EOF<br>    #set($inputRoot = $input.path(&#39;$.body&#39;))<br>    {<br>      \&quot;statusCode\&quot;: 200,<br>      \&quot;body\&quot;: $inputRoot,<br>      \&quot;headers\&quot;: {<br>        \&quot;Content-Type\&quot;: \&quot;application/json\&quot;<br>      }<br>    }<br>    EOF<br>  }<br>}<br><br>#####################################################################################################<br>########################### PATCH /dish #########################################################<br>#####################################################################################################<br><br>resource &quot;aws_api_gateway_method&quot; &quot;PATCH_method&quot; {<br>  rest_api_id   = aws_api_gateway_rest_api.API-gw.id<br>  resource_id   = aws_api_gateway_resource.API-resource-dish.id<br>  http_method   = &quot;PATCH&quot;<br>  authorization = &quot;NONE&quot;<br>}<br><br>resource &quot;aws_api_gateway_integration&quot; &quot;PATCH_lambda_integration&quot; {<br>  rest_api_id             = aws_api_gateway_rest_api.API-gw.id<br>  resource_id             = aws_api_gateway_resource.API-resource-dish.id<br>  http_method             = aws_api_gateway_method.PATCH_method.http_method<br>  type                    = &quot;AWS_PROXY&quot;<br>  integration_http_method = &quot;POST&quot;<br>  uri                     = aws_lambda_function.my-lambda-function.invoke_arn<br>}<br><br>resource &quot;aws_api_gateway_method_response&quot; &quot;PATCH_method_response_200&quot; {<br>  rest_api_id = aws_api_gateway_rest_api.API-gw.id<br>  resource_id = aws_api_gateway_resource.API-resource-dish.id<br>  http_method = aws_api_gateway_method.PATCH_method.http_method<br>  status_code = &quot;200&quot;<br>}<br><br>resource &quot;aws_api_gateway_integration_response&quot; &quot;PATCH_integration_response_200&quot; {<br>  rest_api_id = aws_api_gateway_rest_api.API-gw.id<br>  resource_id = aws_api_gateway_resource.API-resource-dish.id<br>  http_method = aws_api_gateway_method.PATCH_method.http_method<br>  status_code = aws_api_gateway_method_response.PATCH_method_response_200.status_code<br><br>  depends_on = [aws_api_gateway_integration.PATCH_lambda_integration]<br><br>  response_templates = {<br>    &quot;application/json&quot; = &lt;&lt;EOF<br>    #set($inputRoot = $input.path(&#39;$.body&#39;))<br>    {<br>      \&quot;statusCode\&quot;: 200,<br>      \&quot;body\&quot;: $inputRoot,<br>      \&quot;headers\&quot;: {<br>        \&quot;Content-Type\&quot;: \&quot;application/json\&quot;<br>      }<br>    }<br>    EOF<br>  }<br>}<br><br>#####################################################################################################<br>########################### DELETE /dish #########################################################<br>#####################################################################################################<br><br>resource &quot;aws_api_gateway_method&quot; &quot;DELETE_method&quot; {<br>  rest_api_id   = aws_api_gateway_rest_api.API-gw.id<br>  resource_id   = aws_api_gateway_resource.API-resource-dish.id<br>  http_method   = &quot;DELETE&quot;<br>  authorization = &quot;NONE&quot;<br>}<br><br>resource &quot;aws_api_gateway_integration&quot; &quot;DELETE_lambda_integration&quot; {<br>  rest_api_id             = aws_api_gateway_rest_api.API-gw.id<br>  resource_id             = aws_api_gateway_resource.API-resource-dish.id<br>  http_method             = aws_api_gateway_method.DELETE_method.http_method<br>  type                    = &quot;AWS_PROXY&quot;<br>  integration_http_method = &quot;POST&quot;<br>  uri                     = aws_lambda_function.my-lambda-function.invoke_arn<br>}<br><br>resource &quot;aws_api_gateway_method_response&quot; &quot;DELETE_method_response_200&quot; {<br>  rest_api_id = aws_api_gateway_rest_api.API-gw.id<br>  resource_id = aws_api_gateway_resource.API-resource-dish.id<br>  http_method = aws_api_gateway_method.DELETE_method.http_method<br>  status_code = &quot;200&quot;<br>}<br><br>resource &quot;aws_api_gateway_integration_response&quot; &quot;DELETE_integration_response_200&quot; {<br>  rest_api_id = aws_api_gateway_rest_api.API-gw.id<br>  resource_id = aws_api_gateway_resource.API-resource-dish.id<br>  http_method = aws_api_gateway_method.DELETE_method.http_method<br>  status_code = aws_api_gateway_method_response.DELETE_method_response_200.status_code<br><br>  depends_on = [aws_api_gateway_integration.DELETE_lambda_integration]<br><br>  response_templates = {<br>    &quot;application/json&quot; = &lt;&lt;EOF<br>    #set($inputRoot = $input.path(&#39;$.body&#39;))<br>    {<br>      \&quot;statusCode\&quot;: 200,<br>      \&quot;body\&quot;: $inputRoot,<br>      \&quot;headers\&quot;: {<br>        \&quot;Content-Type\&quot;: \&quot;application/json\&quot;<br>      }<br>    }<br>    EOF<br>  }<br>}<br><br>#####################################################################################################<br>#####################################################################################################<br>#####################################################################################################<br><br><br>module &quot;cors&quot; {<br>  source = &quot;./modules/cors&quot;<br><br>  api_id            = aws_api_gateway_rest_api.API-gw.id<br>  api_resource_id   = aws_api_gateway_resource.API-resource-dish.id<br>  allow_credentials = true<br>}</pre><p>Next we need to allow the API gateway to invoke the Lambda Function:</p><pre># . . .<br><br># Allowing API Gateway to Access Lambda<br>resource &quot;aws_lambda_permission&quot; &quot;apigw&quot; {<br>  statement_id  = &quot;AllowAPIGatewayInvoke&quot;<br>  action        = &quot;lambda:InvokeFunction&quot;<br>  function_name = aws_lambda_function.my-lambda-function.function_name<br>  principal     = &quot;apigateway.amazonaws.com&quot;<br><br>  # The /*/* portion grants access from any method on any resource<br>  # within the API Gateway &quot;REST API&quot;.<br>  source_arn = &quot;${aws_api_gateway_rest_api.API-gw.execution_arn}/*/*&quot;<br>}</pre><p>Then we configure the API deployment and create a stage called “prod”, so the API Gateway URL will be something like “/prod/dishes”:</p><pre># . . .<br><br># Deployment<br>resource &quot;aws_api_gateway_deployment&quot; &quot;example&quot; {<br><br>  depends_on = [<br>    aws_api_gateway_integration.GET_one_lambda_integration,<br>    aws_api_gateway_integration.GET_all_lambda_integration,<br>    aws_api_gateway_integration.PATCH_lambda_integration,<br>    aws_api_gateway_integration.POST_lambda_integration,<br>    aws_api_gateway_integration.DELETE_lambda_integration<br>  ]<br><br>  triggers = {<br>    redeployment = sha1(jsonencode([<br>      aws_api_gateway_resource.API-resource-dish,<br>      aws_api_gateway_method.GET_one_method,<br>      aws_api_gateway_integration.GET_one_lambda_integration,<br>      aws_api_gateway_method.GET_all_method,<br>      aws_api_gateway_integration.GET_all_lambda_integration,<br>      aws_api_gateway_method.POST_method,<br>      aws_api_gateway_integration.POST_lambda_integration,<br>      aws_api_gateway_method.PATCH_method,<br>      aws_api_gateway_integration.PATCH_lambda_integration,<br>      aws_api_gateway_method.DELETE_method,<br>      aws_api_gateway_integration.DELETE_lambda_integration<br>    ]))<br>  }<br><br>  rest_api_id = aws_api_gateway_rest_api.API-gw.id<br>}<br><br># Deployment stage<br>resource &quot;aws_api_gateway_stage&quot; &quot;my-prod-stage&quot; {<br>  deployment_id = aws_api_gateway_deployment.example.id<br>  rest_api_id   = aws_api_gateway_rest_api.API-gw.id<br>  stage_name    = &quot;prod&quot;<br><br>  depends_on = [aws_cloudwatch_log_group.rest-api-logs]<br>}</pre><p>We are also defining a CloudWatch Log Group to log what is happening in the background when we send a request. The CloudWatch LogGroup should look like API-Gateway-Execution-Logs_{YOU_API_ID}/{YOU_STAGENAME} .</p><p>Then we use a resource “method_settings” to setup API Gateway stage level execution logging.</p><pre># . . .<br><br># CloudWatch Log Group, for debug purposes<br>resource &quot;aws_cloudwatch_log_group&quot; &quot;rest-api-logs&quot; {<br>  name              = &quot;API-Gateway-Execution-Logs_${aws_api_gateway_rest_api.API-gw.id}/prod&quot;<br>  retention_in_days = 7<br>}<br><br># Method settings<br>resource &quot;aws_api_gateway_method_settings&quot; &quot;my_settings&quot; {<br>  rest_api_id = aws_api_gateway_rest_api.API-gw.id<br>  stage_name  = aws_api_gateway_stage.my-prod-stage.stage_name<br>  method_path = &quot;*/*&quot;<br>  settings {<br>    logging_level = &quot;INFO&quot;<br>    data_trace_enabled = true<br>    metrics_enabled = true<br>  }<br>}</pre><p>Next we define a CORS module. The AWS documentation does a pretty good job of explaining CORS and all the nuances with integrations and integration responses on so I’ll just include a link to it <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html">here</a>.</p><pre># . . .<br><br>module &quot;cors&quot; {<br>  source = &quot;./modules/cors&quot;<br><br>  api_id            = aws_api_gateway_rest_api.API-gw.id<br>  api_resource_id   = aws_api_gateway_resource.API-resource-dish.id<br>  allow_credentials = true<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*Ynf_N8fwlaoQWGdix8seQw.png" /></figure><p>Follow this structure and paste the following code for each file.</p><p><em>cors.tf:</em></p><pre># cors.tf<br><br>resource &quot;aws_api_gateway_method&quot; &quot;_&quot; {<br>  rest_api_id   = var.api_id<br>  resource_id   = var.api_resource_id<br>  http_method   = &quot;OPTIONS&quot;<br>  authorization = &quot;NONE&quot;<br>}<br><br># aws_api_gateway_integration._<br>resource &quot;aws_api_gateway_integration&quot; &quot;_&quot; {<br>  rest_api_id = var.api_id<br>  resource_id = var.api_resource_id<br>  http_method = aws_api_gateway_method._.http_method<br><br>  type = &quot;MOCK&quot;<br><br>  request_templates = {<br>    &quot;application/json&quot; = &quot;{ \&quot;statusCode\&quot;: 200 }&quot;<br>  }<br>}<br><br># aws_api_gateway_integration_response._<br>resource &quot;aws_api_gateway_integration_response&quot; &quot;_&quot; {<br>  rest_api_id = var.api_id<br>  resource_id = var.api_resource_id<br>  http_method = aws_api_gateway_method._.http_method<br>  status_code = 200<br><br>  response_parameters = local.integration_response_parameters<br><br>  depends_on = [<br>    aws_api_gateway_integration._,<br>    aws_api_gateway_method_response._,<br>  ]<br>}<br><br># aws_api_gateway_method_response._<br>resource &quot;aws_api_gateway_method_response&quot; &quot;_&quot; {<br>  rest_api_id = var.api_id<br>  resource_id = var.api_resource_id<br>  http_method = aws_api_gateway_method._.http_method<br>  status_code = 200<br><br>  response_parameters = local.method_response_parameters<br><br>  response_models = {<br>    &quot;application/json&quot; = &quot;Empty&quot;<br>  }<br><br>  depends_on = [<br>    aws_api_gateway_method._,<br>  ]<br>}</pre><p><em>headers.tf:</em></p><pre># headers.tf<br><br>locals {<br>  headers = tomap({<br>     &quot;Access-Control-Allow-Headers&quot;= &quot;&#39;${join(&quot;,&quot;, var.allow_headers)}&#39;&quot;,<br>    &quot;Access-Control-Allow-Methods&quot;= &quot;&#39;${join(&quot;,&quot;, var.allow_methods)}&#39;&quot;,<br>    &quot;Access-Control-Allow-Origin&quot;= &quot;&#39;${var.allow_origin}&#39;&quot;,<br>    &quot;Access-Control-Max-Age&quot;= &quot;&#39;${var.allow_max_age}&#39;&quot;,<br>    &quot;Access-Control-Allow-Credentials&quot;= var.allow_credentials ? &quot;&#39;true&#39;&quot; : &quot;&quot;<br>  })<br><br>  # Pick non-empty header values<br>  header_values = compact(values(local.headers))<br><br>  # Pick names that from non-empty header values<br>  header_names = matchkeys(<br>    keys(local.headers),<br>    values(local.headers),<br>    local.header_values<br>  )<br><br>  # Parameter names for method and integration responses<br>  parameter_names = formatlist(&quot;method.response.header.%s&quot;, local.header_names)<br><br>  # Map parameter list to &quot;true&quot; values<br>  true_list = split(&quot;|&quot;,<br>    replace(join(&quot;|&quot;, local.parameter_names), &quot;/[^|]+/&quot;, &quot;true&quot;)<br>  )<br><br>  # Integration response parameters<br>  integration_response_parameters = zipmap(<br>    local.parameter_names,<br>    local.header_values<br>  )<br><br>  # Method response parameters<br>  method_response_parameters = zipmap(<br>    local.parameter_names,<br>    local.true_list<br>  )<br>}</pre><p><em>variables.tf:</em></p><pre>variable &quot;api_id&quot; {<br>  description = &quot;API identifier&quot;<br>}<br><br># var.api_resource_id<br>variable &quot;api_resource_id&quot; {<br>  description = &quot;API resource identifier&quot;<br>}<br><br># -----------------------------------------------------------------------------<br># Variables: CORS-related<br># -----------------------------------------------------------------------------<br><br># var.allow_headers<br>variable &quot;allow_headers&quot; {<br>  description = &quot;Allow headers&quot;<br>  type        = list(string)<br><br>  default = [<br>    &quot;Authorization&quot;,<br>    &quot;Content-Type&quot;,<br>    &quot;X-Amz-Date&quot;,<br>    &quot;X-Amz-Security-Token&quot;,<br>    &quot;X-Api-Key&quot;,<br>  ]<br>}<br><br># var.allow_methods<br>variable &quot;allow_methods&quot; {<br>  description = &quot;Allow methods&quot;<br>  type        = list(string)<br><br>  default = [<br>    &quot;OPTIONS&quot;,<br>    &quot;HEAD&quot;,<br>    &quot;GET&quot;,<br>    &quot;POST&quot;,<br>    &quot;PUT&quot;,<br>    &quot;PATCH&quot;,<br>    &quot;DELETE&quot;,<br>  ]<br>}<br><br># var.allow_origin<br>variable &quot;allow_origin&quot; {<br>  description = &quot;Allow origin&quot;<br>  type        = string<br>  default     = &quot;*&quot;<br>}<br><br># var.allow_max_age<br>variable &quot;allow_max_age&quot; {<br>  description = &quot;Allow response caching time&quot;<br>  type        = string<br>  default     = &quot;7200&quot;<br>}<br><br># var.allowed_credentials<br>variable &quot;allow_credentials&quot; {<br>  description = &quot;Allow credentials&quot;<br>  default     = false<br>}</pre><p>Finally, in a file “outputs.tf” declare a block to outbut the API Gateway invoke URL after applying the entire Terraform configuration:</p><pre># Test API Gateway URL<br>output &quot;api_gateway_url&quot; {<br>  value = aws_api_gateway_deployment.example.invoke_url<br>}</pre><h3>Step 5: add authentication with Cognito</h3><p>Writing operations (POST, PATCH, DELETE) on the DynamoDB table can be harmful, we do not want to expose our REST API publicly, so we want to restrict access to some HTTP endpoints. So we want to implement some authentication and to do so the first step is to create a Cognito user pool:</p><pre># authentication.tf<br><br>resource &quot;aws_cognito_user_pool&quot; &quot;pool&quot; {<br>  name = &quot;mypool&quot;<br>}</pre><p>To enable the application to access the user pool, we have to define a user pool client. We are specifying allowed OAuth flows and user scopes (email, openid, profile) for basic user information. No client secret is generated. We are also allowing for both administrative and user password authentication. Cognito is the identity provider. Then sample URLs are defined where the OAuth 2.0 authorization server should redirect the user after successful authentication and where to redirect after logout. Anyway, going so much into the details is not that important for this project.</p><pre># authentication.tf<br><br>resource &quot;aws_cognito_user_pool_client&quot; &quot;client&quot; {<br>  name = &quot;client&quot;<br>  allowed_oauth_flows_user_pool_client = true<br>  generate_secret = false<br>  allowed_oauth_scopes = [&quot;aws.cognito.signin.user.admin&quot;,&quot;email&quot;, &quot;openid&quot;, &quot;profile&quot;]<br>  allowed_oauth_flows = [&quot;implicit&quot;, &quot;code&quot;]<br>  explicit_auth_flows = [&quot;ADMIN_NO_SRP_AUTH&quot;, &quot;USER_PASSWORD_AUTH&quot;]<br>  supported_identity_providers = [&quot;COGNITO&quot;]<br><br>  user_pool_id = aws_cognito_user_pool.pool.id<br>  callback_urls = [&quot;https://example.com&quot;]<br>  logout_urls = [&quot;https://example.com&quot;]<br>}</pre><p>Inside this user pool we also create a user to test API access.</p><pre># authentication.tf<br><br>resource &quot;aws_cognito_user&quot; &quot;example&quot; {<br>  user_pool_id = aws_cognito_user_pool.pool.id<br>  username = &quot;mattia&quot;<br>  password = &quot;Test@123&quot;<br>}</pre><p>Now apply this configuration and make sure that all the resources are created properly (user pool, user pool client and user). So go to “Amazon Cognito” in the AWS management console and select “User pools” and click on the pool we just created. Take note of the User pool ID.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lOjIW4_D9SLqlHBa5h4Ndw.png" /></figure><p>You will also see the new user:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z2mlffeZhdl95bQox6_nfw.png" /></figure><p>Click on “App integration” and scroll down to “App clients and analytics” and you will see also the client we have created. Take note of the Client ID.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ljc6-a8TDlBkKAYATXL-ZQ.png" /></figure><p>To actually implement authentication and restrict public access to some API endpoints of the application, we must first define an authorizer inside our Cognito user pool. When the authorizer is enabled, any incoming request token is first validated against this Cognito user pool before Lambda is triggered. So we define the authorizer in “api_gateway.tf”:</p><pre># api_gateway.tf<br><br>resource &quot;aws_api_gateway_authorizer&quot; &quot;demo&quot; {<br>  name = &quot;my_apig_authorizer2&quot;<br>  rest_api_id = aws_api_gateway_rest_api.API-gw.id<br>  type = &quot;COGNITO_USER_POOLS&quot;<br>  provider_arns = [aws_cognito_user_pool.pool.arn]<br>}</pre><p>If you remember, when defining the resource blocks for the HTTP methods we were setting “authorization” to “NONE”. Now we want to change this value and set it to “COGNITO_USER_POOLS” and specify the authorizer id. For example for the POST HTTP method:</p><pre># api_gateway.tf<br><br>#####################################################################################################<br>########################### POST /dish #########################################################<br>#####################################################################################################<br><br>resource &quot;aws_api_gateway_method&quot; &quot;POST_method&quot; {<br>  rest_api_id   = aws_api_gateway_rest_api.API-gw.id<br>  resource_id   = aws_api_gateway_resource.API-resource-dish.id<br>  http_method   = &quot;POST&quot;<br>  # authorization = &quot;NONE&quot; // comment this out<br>  authorization = &quot;COGNITO_USER_POOLS&quot;<br>  authorizer_id = aws_api_gateway_authorizer.demo.id<br>}</pre><p>Do this for each critical endpoint (POST, PATCH, DELETE)</p><p>If we apply also this configuration, going back to Postman if we send a new request it should return 401 Unauthorized:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*bJBGPQh-mYg2N0A90_gg_Q.png" /></figure><p>So now we need to provide an access token to be authorized when submitting our HTTP requests. To generate the access token, I will use the command “aws cognito-idp” this way passing some information we took note before:</p><pre>aws cognito-idp admin-initiate-auth --user-pool-id &lt;USER_POOL_ID&gt; --client-id &lt;CLIENT_ID&gt; --auth-flow ADMIN_NO_SRP_AUTH --auth-parameters USERNAME=mattia,PASSWORD=Test@123</pre><p>Ensure to replace the User Pool ID, the User Pool client ID as well as the username and password of the test user defined before.</p><p>We are authenticating the test user against the Cognito user pool and in return we get an access token back. The output of the above command is something similar to this:</p><pre>{<br>    &quot;ChallengeParameters&quot;: {},<br>    &quot;AuthenticationResult&quot;: {<br>        &quot;AccessToken&quot;: &lt;ACCESS_TOKEN&gt;,<br>        &quot;ExpiresIn&quot;: 3600,<br>        &quot;TokenType&quot;: &quot;Bearer&quot;,<br>        &quot;RefreshToken&quot;: &lt;REFRESH_TOKEN&gt;,<br>        &quot;IdToken&quot;: &lt;ID_TOKEN&gt; # copy the value of ID token<br>    }<br>}</pre><p>To test these tokens, copy the value in ID token and in the AWS management console go to “API Gateway”, select your API and click on “Authorizers” on the left:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*evU4BD3uT7nSRnBcNAXbGg.png" /></figure><p>Now click on the authorizer. Then in the section Test authorizer paste the ID token copied before and then click on the button “Test authorizer”. You should have an output like that one in the blue box:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gwq0fHLdCwikHDeF_LaqAQ.png" /></figure><p>You can see that there is a field “exp” telling you when the tokens will expire, in my case they are valid.</p><p>Now go back to Postman and in the tab “Headers” create a new field and choose as key “Authorization” and then in the value field specify the ID token with this format:</p><pre>Bearer &lt;ID_TOKEN&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aF4ZXEheytVxaquezGZNPg.png" /></figure><p>If you send the request you can see that now we receive a 200 status code and everything is fine.</p><h3>Conclusion</h3><p>I hope you liked this project and see you in the next one! If you have any questions feel free to ask!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f277814d048e" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/a-step-by-step-guide-on-deploying-rest-api-using-api-gateway-lambda-cognito-terraform-f277814d048e">A Step-by-Step Guide On Deploying REST API using API Gateway, Lambda, Cognito — Terraform</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Step-by-Step Guide on Deploying a Kubernetes application using Terraform, EKS Cluster and Jenkins]]></title>
            <link>https://medium.com/@mattiamazzari/a-step-by-step-guide-on-deploying-a-kubernetes-application-using-terraform-eks-cluster-and-jenkins-332b91e90be1?source=rss-e9f146485d51------2</link>
            <guid isPermaLink="false">https://medium.com/p/332b91e90be1</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[jenkins]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[ec2]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Mattiamazzari]]></dc:creator>
            <pubDate>Mon, 29 Apr 2024 16:09:12 GMT</pubDate>
            <atom:updated>2024-04-29T16:09:12.105Z</atom:updated>
            <content:encoded><![CDATA[<p>This is an end-to-end project to deploy a Nginx web server through Jenkins and Kubernetes, using Terraform. What we will build will have this structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*fOyjPWSOJeqCz6Ts6viHpQ.jpeg" /></figure><p>To do this, we will follow several steps:</p><ol><li>Create an EC2 key pair</li><li>Create a Jenkins server and install all the dependencies</li><li>Access and setup the Jenkins server</li><li>Run the Jenkins pipeline to deploy to EKS. In particular it will create a Kubernetes cluster and then we will create a deployment in that cluster, to deploy the Kubernetes Services, in particular we will deploy just Nginx and run it as a Service</li><li>Test the application to make sure it’s running</li><li>Clean up and destroy all resources</li></ol><p>In the real world usually the deployment happens in multiple environments, typically in 3 environments:</p><ul><li>a dev environment</li><li>a test environment</li><li>a production environment</li></ul><p>This project is just one environment deployment, so we will have just a dev environment. Here is the repository with the source code:</p><p><a href="https://github.com/mattiamazzari/jenkins-pipeline">GitHub - mattiamazzari/jenkins-pipeline</a></p><h3>Step 1: create a keypair</h3><p>The first thing you have to do is to create a new keypair. So in the AWS management console go to “EC2” and select “Key pairs” in the listed overview of your resources:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0GU9bg4ObNHpcmOhrJlhvQ.png" /></figure><p>Then select “Create key pair” on the top-right corner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*4tPlxXhKe7VqXrX_ID64qg.png" /></figure><p>Give a name to the keypair and select as key file format “.pem”, then select “Create key pair” and save it in a new folder for this project, if you haven’t created it yet.</p><h3>Step 2: create the projects folders</h3><p>In your project folder you can follow the structure of the code of my repository, you can also directly fork the repository if you prefer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*U_32Ifo-QmI0g3VaVCkZ6w.png" /></figure><p>The structure is the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6oqwHH8BI9jwq-E87hdDFg.png" /></figure><p>Now I will dive in and explain the content each folder.</p><h3>Step 3: setup Jenkins server</h3><p>Here I will explain what the code inside “1-terraform-jenkins-server” does.</p><p>However the first thing that we need to do is to create an S3 bucket that will be used as the Terraform state file storage. Make sure to be consistent with the AWS region you choose, for example for all the project I will always use “eu-west-3”, so I’m creating an S3 bucket on this region. If you plan to use another AWS region, ensure to replace “eu-west-3” anywhere in the code with your region.</p><p>So we create the bucket and ensure that we choose a unique name for the bucket, I will call it “jenkins-app-kub-2024-v2” but choose a different name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*jJ6PjdRxBs16KCDgyssH3Q.png" /></figure><p>Now let’s go back to the folder ““1-terraform-jenkins-server”.</p><p>In the file “provider.tf” we ensure that Terraform uses the specified version of the AWS provider and operates within the “eu-west-3” region when interacting with AWS resources. Choose the same AWS region of the backend S3 bucket. Here is the snippet:</p><pre># provider.tf<br><br>terraform {<br>  required_providers {<br>    aws = {<br>      source  = &quot;hashicorp/aws&quot;<br>      version = &quot;4.52.0&quot;<br>    }<br>  }<br>}<br><br>provider &quot;aws&quot; {<br>  region = &quot;eu-west-3&quot;<br>}</pre><p>In “variables.tf” we define all the variables that we need throughout the proget:</p><pre># variables.tf<br><br>variable &quot;vpc_cidr_block&quot; {}<br>variable &quot;subnet_cidr_block&quot; {}<br>variable &quot;avail_zone&quot; {}<br>variable &quot;env_prefix&quot; {}<br>variable &quot;instance_type&quot; {}</pre><p>And then in “terraform.tfvars” we provide the values that we want to assign to the variables:</p><pre># terraform.tfvars<br>vpc_cidr_block      = &quot;10.0.0.0/16&quot; # VPC address<br>subnet_cidr_block   = &quot;10.0.10.0/24&quot; # subnet address<br>availability_zone   = &quot;eu-west-3a&quot; # availability zone (change it according to your AWS region)<br>env_prefix          = &quot;dev&quot; # prefix for tags<br>instance_type       = &quot;t2.small&quot; # EC2 instance type</pre><p>In the file “backend.tf” we configure the backend to use the S3 bucket created before, where Terraform can store its state file centrally. The state file keeps track of the resources that Terraform manages and their current state. This is also important for collaboration among team members and ensuring consistent infrastructure management:</p><pre># backend.tf<br><br>terraform {<br>  # Configuring Terraform backend to store state file in an S3 bucket<br>  backend &quot;s3&quot; {<br>    # Specify the name of the S3 bucket to store the state file<br>    bucket = &quot;jensins-kubernetes-app-2024-v2&quot;<br>    # Specify the AWS region where the bucket is located<br>    region = &quot;eu-west-3&quot;<br>    # Specify the path within the bucket to store the state file<br>    key = &quot;jenkins-server/terraform.tfstate&quot;<br>  }<br>}</pre><p>In “server.tf” we define an Amazon Linux Image (AMI) and the EC2 instance that will use it. The EC2 instance is our Jenkins server:</p><pre># server.tf<br><br># Fetch the latest Amazon Linux Image (AMI) owned by AWS<br>data &quot;aws_ami&quot; &quot;latest-amazon-linux-image&quot; {<br>  most_recent = true<br>  owners      = [&quot;amazon&quot;]<br>  filter {<br>    name   = &quot;name&quot;<br>    values = [&quot;amzn2-ami-hvm-*-x86_64-gp2&quot;]<br>  }<br>  filter {<br>    name   = &quot;virtualization-type&quot;<br>    values = [&quot;hvm&quot;]<br>  }<br>}<br><br># Define the Jenkins server<br>resource &quot;aws_instance&quot; &quot;jenkins-server&quot; {<br>  # Specify the AMI id defined above<br>  ami                         = data.aws_ami.latest-amazon-linux-image.id<br>  instance_type               = var.instance_type<br>  key_name                    = &quot;jenkins-server-demo&quot;<br>  subnet_id                   = aws_subnet.jenkins-subnet-1.id<br>  vpc_security_group_ids      = [aws_default_security_group.jenkins-sg.id]<br>  availability_zone           = var.availability_zone<br>  associate_public_ip_address = true<br>  # Specify a script to be executed when the instance is launched<br>  user_data                   = file(&quot;jenkins-script.sh&quot;)<br>  tags = {<br>    Name = &quot;${var.env_prefix}-server&quot;<br>  }<br>}</pre><p>In “jenkins-script.sh” we define a list of commands to install and start all the required services and packages:</p><pre>#!/bin/bash<br><br># install jenkins<br><br>sudo yum update<br>sudo wget -O /etc/yum.repos.d/jenkins.repo \<br>    https://pkg.jenkins.io/redhat-stable/jenkins.repo<br>sudo rpm --import https://pkg.jenkins.io/redhat-stable/jenkins.io-2023.key<br>sudo yum upgrade -y<br>sudo amazon-linux-extras install java-openjdk11 -y<br>sudo yum install jenkins -y<br>sudo systemctl enable jenkins<br>sudo systemctl start jenkins<br><br># install git<br>sudo yum install git -y<br><br># install terraform<br><br>sudo yum install -y yum-utils<br>sudo yum-config-manager --add-repo https://rpm.releases.hashicorp.com/AmazonLinux/hashicorp.repo<br>sudo yum -y install terraform<br><br># install kubectl<br><br>sudo curl -LO https://storage.googleapis.com/kubernetes-release/release/v1.23.6/bin/linux/amd64/kubectl<br>sudo chmod +x ./kubectl<br>sudo mkdir -p $HOME/bin &amp;&amp; sudo cp ./kubectl $HOME/bin/kubectl &amp;&amp; export PATH=$PATH:$HOME/bin</pre><p>In “outputs.tf” we tell Terraform that we want to print to the console the address of the EC2 instance once it is launched:</p><pre># Output in the terminal the address of the Jenkins server, once it&#39;s created<br>output &quot;ec2_public_ip&quot; {<br>  value = aws_instance.myapp-server.public_ip<br>}</pre><p>In “vpc.tf” we define the VPC and a private subnet:</p><pre>resource &quot;aws_vpc&quot; &quot;my-vpc&quot; {<br>  cidr_block = var.vpc_cidr_block<br>  tags = {<br>    Name = &quot;${var.env_prefix}-vpc&quot;<br>  }<br>}<br><br>resource &quot;aws_subnet&quot; &quot;jenkins-subnet-1&quot; {<br>  vpc_id            = aws_vpc.my-vpc.id<br>  cidr_block        = var.subnet_cidr_block<br>  availability_zone = var.availability_zone<br>  map_public_ip_on_launch = false # this makes the subnet private<br>  tags = {<br>    Name = &quot;${var.env_prefix}-subnet-1&quot;<br>  }<br>}</pre><p>In “route.tf” we define an Internet Gateway and the default route table for our VPC:</p><ul><li>The Internet Gateway allows communication between the EC2 instance (the Jenkins server) in your VPC and the Internet, without this your EC2 instance in your subnet would not have access to the Internet</li><li>A default route table is automatically created for our VPC, here we are associating the Internet Gateway with the default route (route block) which states: “Any traffic destined to the Internet (0.0.0.0/0) will be routed through the Internet Gateway”.</li></ul><pre># route.tf<br><br># Internet Gateway<br>resource &quot;aws_internet_gateway&quot; &quot;my-igw&quot; {<br>  vpc_id = aws_vpc.myapp-vpc.id<br>  tags = {<br>    Name = &quot;${var.env_prefix}-igw&quot;<br>  }<br>}<br><br># Default Route Table<br>resource &quot;aws_default_route_table&quot; &quot;my-route-table&quot; {<br>  default_route_table_id = aws_vpc.my-vpc.default_route_table_id<br>  route {<br>    cidr_block = &quot;0.0.0.0/0&quot;<br>    gateway_id = aws_internet_gateway.my-igw.id<br>  }<br>  tags = {<br>    Name = &quot;${var.env_prefix}-route-table&quot;<br>  }<br>}</pre><p>In “security.tf” we define a Security Group for our Jenkins server, allowing SSH access and :</p><pre># security.tf<br><br># Security Group of the Jenkins server<br>resource &quot;aws_default_security_group&quot; &quot;jenkins-sg&quot; {<br>  vpc_id = aws_vpc.my-vpc.id<br><br>  # Allow inbound TCP traffic on port 22 (SSH) from any source <br>  ingress {<br>    from_port   = 22<br>    to_port     = 22<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>    ipv6_cidr_blocks = [&quot;::/0&quot;]<br>  }<br>  <br>  # Allow inbound TCP traffic on port 8080 (Jenkins) from any source.<br>  # This is the default port for Jenkins, so we open it to the Internet<br>  # because we will access it from a web browser<br>  ingress {<br>    from_port   = 8080<br>    to_port     = 8080<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>    ipv6_cidr_blocks = [&quot;::/0&quot;]<br>  }<br><br>  # Allow all outbound traffic to any destination<br>  egress {<br>    from_port   = 0<br>    to_port     = 0<br>    protocol    = &quot;-1&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>    ipv6_cidr_blocks = [&quot;::/0&quot;]<br>  }<br>  tags = {<br>    Name = &quot;${var.env_prefix}-default-sg&quot;<br>  }<br>}</pre><p>We have finished commenting this part of the project. Now, if you haven’t already done it, deploy this infrastructure by running these commands in the terminal, make sure you are in the right folder (jenkins-server):</p><pre>terraform init<br>terraform plan<br>terraform apply</pre><p>After running all the commands, make a note of the public IP address of your Jenkins server, which will be printed in the console.</p><p>Now, paste this IP address into your web browser’s address bar, followed by ‘:8080’. The Jenkins server welcome page should show up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1nGgI4_PqY4F3Q6CgYzLug.png" /></figure><p>To access to our Jenkins server, we need a password. So we first connect to our EC2 instance through SSH, make sure that your terminal is opened in the same folder as the key you downloaded before (.pem file) when creating the key pair. So, run the following command to connect to the EC2 instance:</p><pre>ssh -i &quot;jenkins-server.pem&quot; ec2-user@1.234.567.89</pre><p>In the above command, ensure that you replace ‘jenkins-server.pem’ with the name of your key pair and “1.234.567.89” with the public IP you noted earlier.</p><p>After running it, type “yes” and press Enter.</p><p>Once you are connected to the EC2 instance, run:</p><pre>sudo cat /var/lib/jenkins/secrets/initialAdminPassword</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zvVpnhWSvLqgDFA_JpA0sw.png" /></figure><p>You will get a password. Copy it and then paste it in the field “Administrator password” in the Jenkins welcome screen and then click on Continue:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i_Sma1nS7CbO75mdYt1WAA.png" /></figure><p>Then, select “Install suggested plugins”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WHJ9-nolZYEw3XmztuTb_w.png" /></figure><p>It will take a while, but it will install everything you need.</p><p>Next it will ask you to create the first admin user: assign a username, a password, a full name and your e-mail address.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7oAo8cYEjpBKWsii6hAEzw.png" /></figure><p>Then click on “Save and Continue”.</p><p>Now it will show the Jenkins URL, the field is already filled in so we click on “Save and Finish” and we are done!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J7lXRhhLmY2deo250M9UiQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RfgoJJzNvOYSXp5mSAtj5Q.png" /></figure><p>The next thing is to add our GitHub credentials to the Jenkins server. So click on “Manage Jenkins” on the left. Then select “Manage Credentials” under Security:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6s9nKY5KScHOuCY60A8HKw.png" /></figure><p>Then select “(global)”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*mwspXKSp4QIh6dYN2GemJw.png" /></figure><p>Then click on the button “Add Credentials”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yh11px3LOlGZWMGvwKH-Cw.png" /></figure><p>In this form you need to select “Username with password” in the kind field and insert your GitHub username and password and give a random ID that can be your username as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1I0BlT9tiC98pmKpXbfhTA.png" /></figure><p>Then we want to allow Jenkins to access our AWS environment, so we need to add the credentials to our AWS account, in particular the AWS Access Key and AWS Secret Key. If you don’t have them, follow this guide to generate them easily:</p><p><a href="https://medium.com/@mohasina.clt/how-to-generate-access-keys-in-aws-af1a303dde42">How to Generate Access Keys in AWS</a></p><p>If you already have them but you don’t remember them, go on the directory located in “C:\Users\your-PC-username\.aws” and open “credentials”. If you’re on Windows you can open a terminal anywhere and simply run:</p><pre>cd\<br>cd Users\your-PC-username\.aws<br>type credentials</pre><p>Ensure that you replace your-PC-username with your actual username.</p><p>Once you have the access keys, we are now ready to add them in Jenkins but we can do it only one at a time, so first of all we want to specify our AWS Access Key. So click again on “Add Credentials” and as kind select “Secret text”. It will ask you for a Secret and an ID. In ID specify “AWS_ACCESS_KEY_ID” and in Secret paste your AWS Access Key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qhtxVdPw87O8wJa5TnGtkg.png" /></figure><p>Once you’re done, click again on “Add Credentials” and do the same for your AWS Secret Key. In ID type “AWS_SECRET_ACCESS_KEY”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-ogYPC33A6QHslKgYp8e3A.png" /></figure><p>Now all the credentials are set up:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WdbcFHScYCFK3jwSmIqpfQ.png" /></figure><h3>Step 4: Jenkins pipeline</h3><p>Here I will explain the other folder “2-terraform-eks-deployment”, that we have not discussed about yet and also the folder “kubernetes”.</p><p>We want to create an Elastic Kubernetes Service (EKS) cluster and deploy Kubernetes manifest files inside it using Jenkins.</p><p>First we start from “2-terraform-eks-deployment”.</p><p>In “backend.tf” we configure the same backend as before, it just changes the key:</p><pre>terraform {<br>  backend &quot;s3&quot; {<br>    bucket = &quot;jensins-kubernetes-app-2024-v2&quot;<br>    region = &quot;eu-west-3&quot;<br>    key = &quot;eks/terraform.tfstate&quot;<br>  }<br>}</pre><p>In “eks.tf” we are defining a module to create an EKS cluster. We are using the same VPC we created earlier. The source is a module published in the Terraform registry, if you are curious and want to see what it does go and check it out on:</p><p><a href="https://registry.terraform.io/modules/terraform-aws-modules/eks/aws/latest">Terraform Registry</a></p><p>It is widely used and it will basically create several resources for us, such as EKS nodes and a Load Balancer. This one is important because we will be able to access to our application through the Load Balancer DNS name.</p><pre># eks.tf<br><br>module &quot;eks&quot; {<br>    source  = &quot;terraform-aws-modules/eks/aws&quot;<br>    version = &quot;~&gt; 19.0&quot;<br>    cluster_name = &quot;eks-cluster&quot;<br>    cluster_version = &quot;1.24&quot;<br><br>    cluster_endpoint_public_access  = true<br><br>    vpc_id = module.my-vpc.vpc_id<br>    subnet_ids = module.my-vpc.private_subnets<br><br>    tags = {<br>        environment = &quot;development&quot;<br>        application = &quot;myapp&quot;<br>    }<br><br>    eks_managed_node_groups = {<br>        dev = {<br>            min_size = 1<br>            max_size = 3<br>            desired_size = 2<br><br>            instance_types = [&quot;t2.small&quot;]<br>        }<br>    }<br>}</pre><p>In “vpc.tf” we specify the VPC with a module but again we take the code from a module of the Terraform registry, so we don’t create it from scratch</p><pre># vpc.tf<br><br>data &quot;aws_availability_zones&quot; &quot;azs&quot; {}<br><br>module &quot;my-vpc&quot; {<br>  source          = &quot;terraform-aws-modules/vpc/aws&quot;<br>  version         = &quot;5.8.1&quot;<br>  name            = &quot;my-vpc&quot;<br>  cidr            = var.vpc_cidr_block<br>  private_subnets = var.private_subnet_cidr_blocks<br>  public_subnets  = var.public_subnet_cidr_blocks<br>  azs             = data.aws_availability_zones.azs.names<br><br>  enable_nat_gateway   = true<br>  single_nat_gateway   = true<br>  enable_dns_hostnames = true<br><br>  tags = {<br>    &quot;kubernetes.io/cluster/myapp-eks-cluster&quot; = &quot;shared&quot;<br>  }<br><br>  public_subnet_tags = {<br>    &quot;kubernetes.io/cluster/myapp-eks-cluster&quot; = &quot;shared&quot;<br>    &quot;kubernetes.io/role/elb&quot;                  = 1<br>  }<br><br>  private_subnet_tags = {<br>    &quot;kubernetes.io/cluster/myapp-eks-cluster&quot; = &quot;shared&quot;<br>    &quot;kubernetes.io/role/internal-elb&quot;         = 1<br>  }<br>}</pre><p>And then in “variables.tf” and “terraform.tfvars” we specify the ranges of IP addresses that the VPC and the subnets can take</p><pre># variables.tf<br><br>variable &quot;vpc_cidr_block&quot; {}<br>variable &quot;private_subnet_cidr_blocks&quot; {}<br>variable &quot;public_subnet_cidr_blocks&quot; {}</pre><pre># terraform.tfvars<br><br>vpc_cidr_block = &quot;10.0.0.0/16&quot;<br>private_subnet_cidr_blocks=[&quot;10.0.1.0/24&quot;,&quot;10.0.2.0/24&quot;,&quot;10.0.3.0/24&quot;]<br>public_subnet_cidr_blocks=[&quot;10.0.4.0/24&quot;,&quot;10.0.5.0/24&quot;,&quot;10.0.6.0/24&quot;]</pre><p>In the root folder there is a Jenkinsfile written in Groovy. This is the main file that Jenkins will use to do the deployment process for us in stages. So we will not need to deploy ourselves with the usual Terraform commands, but the Jenkins server will do that for us, as you can also see from the Jenkinsfile.</p><pre>#!/usr/bin/env groovy<br>pipeline {<br>    agent any<br>    environment {<br>        # Jenkins will use the credentials added earlier<br>        AWS_ACCESS_KEY_ID = credentials(&#39;AWS_ACCESS_KEY_ID&#39;)<br>        AWS_SECRET_ACCESS_KEY = credentials(&#39;AWS_SECRET_ACCESS_KEY&#39;)<br>        AWS_DEFAULT_REGION = &quot;eu-west-3&quot;<br>    }<br>    stages {<br>        # Stage 1<br>        stage(&quot;Create an EKS Cluster&quot;) {<br>            steps {<br>                script {<br>                    dir(&#39;2-terraform-eks-deployment&#39;) {<br>                        # Jenkins will run these commands for us<br>                        sh &quot;terraform init&quot;<br>                        sh &quot;terraform apply -auto-approve&quot;<br>                    }<br>                }<br>            }<br>        }<br>        # Stage 2<br>        stage(&quot;Deploy to EKS&quot;) {<br>            steps {<br>                script {<br>                    dir(&#39;kubernetes&#39;) {<br>                        # Update packages inside the cluster<br>                        sh &quot;aws eks update-kubeconfig --name eks-cluster&quot;<br>                        # Deploy an application<br>                        sh &quot;kubectl apply -f nginx-deployment.yaml&quot;<br>                        # Deploy a service<br>                        sh &quot;kubectl apply -f nginx-service.yaml&quot;<br>                    }<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>As you can see, we have two stages.</p><p>In the first stage, it initializes and applies a Terraform configuration to create an EKS cluster.</p><p>In the second stage, it updates the kubeconfig with the EKS cluster information and applies Kubernetes YAML files (nginx-deployment.yaml and nginx-service.yaml) to deploy Nginx to the EKS cluster. These two files are located in the “kubernetes” folder.</p><p>So, in nginx-deployment.yamlit is described a Kubernetes deployment for deploying a simple Nginx web server:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: nginx # Deployment name<br>spec:<br>  selector:<br>    matchLabels:<br>      app: nginx # Select pods with label &#39;app: nginx&#39;<br>  replicas: 1 # Number of pod replicas<br>  template:<br>    metadata:<br>      labels:<br>        app: nginx # Label for pods<br>    spec:<br>      containers:<br>      - name: nginx # Container name<br>        image: nginx # Nginx Docker image<br>        ports:<br>        - containerPort: 80 # Port on which the container listens</pre><p>In nginx-service.yaml instead we are setting up a Kubernetes Service for exposing the Nginx deployment:</p><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: nginx # Service name<br>  labels:<br>    app: nginx # Label for Service<br>spec:<br>  ports:<br>  - name: http # Port name<br>    port: 80 # Port on which the Service listens<br>    protocol: TCP # Protocol used<br>    targetPort: 80 # Port to forward traffic to in the pods<br>  selector:<br>    app: nginx # Selects pods with label &#39;app: nginx&#39;<br>  type: LoadBalancer # Exposes the Service outside the cluster as a LoadBalancer</pre><p><strong>Again:</strong> we do not have to run the usual Terraform commands to deploy this code, because Jenkins will do that for us. We will host this code in a GitHub repository and then Jenkins will connect to it and pull it down following the deployment process described in the Jenkinsfile.</p><h3>Step 5: Create a GitHub repository</h3><p>So Jenkins need to access to this code to do the deployment for us, so create a new GitHub repository and name it “my-jenkins-pipeline” or call it whatever you want. Leave it public and do not add a README.md file.</p><p>Then pull down the repository with “git clone” and move the following files to the cloning folder:</p><ul><li>Jenkinsfile</li><li>The folder “2-terraform-eks-deployment”</li><li>The folder “kubernetes”</li></ul><p>Then push your changes to the main branch</p><h3>Step 6: create a Jenkins pipeline</h3><p>On the Jenkins homepage, click on “New Item” on the left.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RfgoJJzNvOYSXp5mSAtj5Q.png" /></figure><p>Then select “Pipeline” and give it a name, I call it jenkins-pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-2BJpDrdcN5XcxdlcRCceQ.png" /></figure><p>Click OK and then scroll to the bottom of the page and under Pipeline select “Pipeline script from SCM” and as SCM choose “Git” and then you want to give your GitHub Repository URL and select the credentials we defined before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o19dvPPjpfIaQ0tqGiKb7g.png" /></figure><p>In branch, specify */main instead of */master.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F6F3xsO73XXybftqorSg5g.png" /></figure><p>Then click on Save.</p><p>Now that it is all set it up we just need to run it by clicking on “Build Now” on the left.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HAOwPwMUvADFWTlklQODpQ.png" /></figure><p>You will see the process of creation and deployment defined with the two stages that we have defined before in the code. Jenkins will take about 10–15 minutes to create the EKS cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e8_ZZTOlp7ySTW290ZRBAg.png" /></figure><p>In the bottom-left in “Build History” you should see your build running, if you click on it and then click on “Console output” in the menu on the left you should see the logs and you can see that it is creating several resources, and you can follow all the process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*apuEWoetyR0z-adSJb4zpg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sMtTqVICRqJvFY3Wwp3kZg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oCq6uWEp4ixrrQCnIIRY9A.png" /></figure><p>Those are the same logs that you would see if you run the usual Terraform commands to deploy the infrastructure using Visual Studio Code.</p><p>Now wait until the whole deployment process is finished. I guess you have time to take a coffee or to go to the bathroom</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/0*4mFVRB6ugCMa6P7e.gif" /></figure><h3>Step 7: Test the application</h3><p>Alright! Now it’s time to test the application. In the AWS management console go to the “Elastic Kubernetes Service” and you should see that the cluster is running:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qCsXsAoDnREWQuTXVPgD2A.png" /></figure><p>If you go to the tab “Resources” you can see what resources it has created (Pods, Deployment, ..).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*URW7qks9NDtHVZcsNdMvIw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R03WRukKrMvrAekHsRYFNA.png" /></figure><p>If you don’t see them, there should be a message above that says that your user doesn’t have the permissions to get Kubernetes objects. Click on “Learn more” and follow the guide to grant the access to your resources. Anyway, this is just to see what happens behind the scenes.</p><p>Now, if you go to the “EC2” AWS service and select “Load balancers” you should see the Application Load Balancer created by Kubernetes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WcFOONCOHBllqEcQcEaSyA.png" /></figure><p>If you click on it you can see its DNS name:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CCpsFItVtfQJOPXRLfH8Lw.png" /></figure><p>Copy it and navigate to it in a new tab and you should see the Nginx welcome page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NyyHGoE7OAz_rTXdlPW7cQ.png" /></figure><h3>Step 8: Clean up the resources</h3><p>Now I will show you how to delete all the resources.</p><p>Go to the “2-terraform-eks-deployment” folder in your project and run:</p><pre>terraform init<br>terraform destroy -auto-approve</pre><p>Now go to the “1-terraform-jenkins-server” and run:</p><pre>terraform destroy -auto-approve</pre><p>That’s it! I hope you liked this project, please leave a thumbs up and see you in the next project</p><p>REMEMBER TO CHANGE THE VERSION OF THE MODULE OF VPC TO 5.8.1 IN NEW FOLDER (2) / 2-terraform-deploy-to-eks / vpc.tf — → THEN PUSH</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=332b91e90be1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy a React application on AWS using Amplify, Cognito, GitHub and setup a CI/CD pipeline]]></title>
            <link>https://medium.com/@mattiamazzari/deploy-a-react-application-on-aws-a43c2e35a22c?source=rss-e9f146485d51------2</link>
            <guid isPermaLink="false">https://medium.com/p/a43c2e35a22c</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[cognito]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[amplify]]></category>
            <dc:creator><![CDATA[Mattiamazzari]]></dc:creator>
            <pubDate>Sat, 27 Apr 2024 18:57:58 GMT</pubDate>
            <atom:updated>2024-04-27T19:20:41.662Z</atom:updated>
            <content:encoded><![CDATA[<h3>Goals</h3><p>This guide will lead you through building a React application that leverages the following AWS services to achieve a secure and automated development workflow:</p><ul><li><strong>Amazon Cognito:</strong> For user authentication and authorization. Cognito will handle user registration, sign-in, and manage user data securely.</li><li><strong>AWS Amplify:</strong> To simplify the integration of Cognito and other AWS services within your React application. Amplify provides libraries and UI components for user authentication flows and interacting with AWS resources. It allows also to implement a CI/CD pipeline. This pipeline will automate building, testing, and deploying your React application to a production environment whenever you commit code changes to your GitHub repository.</li></ul><p>This combination of tools allows you to focus on building your React application’s core features while ensuring a secure and efficient development workflow.</p><p>So, this is the architecture we are going to build:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*9LymwbkanUSTWOzZqlmI_Q.jpeg" /></figure><p>Now let’s dive in!</p><h3>Step 1: set up the environment</h3><ul><li>I will use Microsoft Visual Studio Code as IDE, but you can use whatever IDE you want</li><li>If you haven’t already done it, you need to install Node (<a href="https://nodejs.org/en/download">https://nodejs.org/en/download</a>)</li></ul><p>Now first of all we need to setup the Amplify CLI, we will use the npm package to do it, so open a terminal and run this:</p><pre>npm install -g @aws-amplify/cli</pre><p>Next we need to configure Amplify to make the CLI work with your AWS account, we will have to setup a new user, configure access keys and so on. So run:</p><pre>amplify configure</pre><p>It will ask you to sign in as an AWS administrator account, so type in the credentials for a user that has admin permissions but not your root account. If you haven’t already created this user, you can follow along this guide:</p><p><a href="https://medium.com/@houseofarby/aws-iam-creating-an-iam-user-for-access-management-f791228501a0">AWS IAM: Creating an IAM User for Access Management</a></p><p>After you have signed in, select your region by moving up and down with your arrow keys. Choose the one that is closest to you to have minimal latency, I will choose “eu-west-3” which corresponds to “Europe/Paris”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*TG6Cr7KzJydKuDNfOPDvcQ.png" /></figure><p>Click enter and this will show up:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*6O8nwKE-IuPmaz3PVFXIBg.png" /></figure><p>In the meantime this page will open automatically in your browser to create a new user:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kBUnbOpQLg36sNNzGtWSHw.png" /></figure><p>If not, navigate to the “IAM” service and select “Users” &gt; “Create a user”, now it should open the same window.</p><p>Create a new user, call it whatever you want and click “Next”. Then choose the option “Attach policies directly” and type “amplify” in the search bar and select “AdministratorAccess-Amplify”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9NSTPLpbw2U2sMJN2XvRFg.png" /></figure><p>Then click “Next” &gt; “Create user”.</p><p>Back in the terminal, if you press Enter it will ask you for your access key:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*DdzWJAHaq7ddc88bj4JifA.png" /></figure><p>So back in the AWS console in the IAM dashboard select the newly created user:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*52BWLS245MuqQGR6a1jyMA.png" /></figure><p>Then go to the “Security credentials” tab and under “Access keys” click on “Create access key”.</p><p>As Use case select the first option (“Command Line Interface (CLI)”), tick the confirmation checkbox “I understand…” and click on Next and then create the access key. Copy the access key and paste it in the terminal where it asked for your access key. Then press Enter and do the same for the secret access key.</p><p>Now it will ask you to create the AWS Profile to save all the information we just put (the region, the access key, and so on) on your local PC, so choose a name:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*Yz3eEOR6F_znQgTgbicfng.png" /></figure><h3>Step 2: create the React application</h3><p>Now we are ready to create our application. In the terminal run the following command:</p><pre>npx create-react-app quiz-app</pre><p>This will create a vanilla React application. Now we will move to the folder of the application and run “amplify init” to initialize the Amplify project, it will ask some information to create our project like the name, the programming language and so on, but some information will ne automatically detected. So to do this run:</p><pre>cd quiz-app<br>amplify init</pre><p>This will be displayed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*EdgsG_BnZGX8FXWO7-WP8g.png" /></figure><p>Now type “Y” to initialize the project with the above configuration and press Enter.</p><p>It will ask you the authentication method to use, you have to select “AWS profile” and then “amplify-dev-local” (the profile we created before, if you chose another name then select it).</p><p>Next it will show a message about helping improve Amplify CLI by sharing configurations, type “N”.</p><p>Then check in the AWS console if the project has been set up succesfully, go to the AWS service “Amplify” and you should see your application:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*XTVGzj8vk2SLAvse7R1FSA.png" /></figure><p>If you don’t see it, please make sure you are in the right AWS region, the one that you selected before (change it on the top-right on the AWS console).</p><p>If you click on the application it will open the overview, under the tab “Backend environments” there is an environment called “dev” that AWS created for us, but it is basically empty:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lwrbss_tv1nK5iZ7uh0tmA.png" /></figure><h3>Step 3: Add authentication with Cognito</h3><p>The next step is to add authentication to the React app using Cognito, another AWS service. To add Cognito, in the terminal simply run:</p><pre>amplify add auth</pre><p>It will ask if we want to use the default configuration, select “Default configuration” as we do not want to set up Google or Facebook authentication or to implement it manually.</p><p>Then we want users to sign in using their email, so select “Email”.</p><p>Next it will ask if you want to configure advanced settings, select “No, I am done.”</p><p>To push these changes to AWS run:</p><pre>amplify push</pre><p>It will ask you for confirmation, type “Y” to confirm your push action.</p><p>Now if you go to the AWS service “Amazon Cognito” in the AWS management console you should see a new user pool created for us:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9mDsRZfzFfujO8XsbOc2QQ.png" /></figure><p>If you click on it you can see that we do not have any users yet. So let’s set up the UI so that we can create an account and log in as a user. So go to the “src/App.js” file in your React application and paste this code:</p><pre>import React from &#39;react&#39;;<br>import &#39;./App.css&#39;;<br><br>// Imports the Amplify library from &#39;aws-amplify&#39; package. This is used to configure your app to interact with AWS services.<br>import {Amplify} from &#39;aws-amplify&#39;;<br><br>// Imports the Authenticator and withAuthenticator components from &#39;@aws-amplify/ui-react&#39;.<br>// Authenticator is a React component that provides a ready-to-use sign-in and sign-up UI.<br>// withAuthenticator is a higher-order component that wraps your app component to enforce authentication.<br>import { Authenticator, withAuthenticator } from &#39;@aws-amplify/ui-react&#39;;<br><br>// Imports the default styles for the Amplify UI components. This line ensures that the authenticator looks nice out of the box.<br>import &#39;@aws-amplify/ui-react/styles.css&#39;;<br><br>// Imports the awsExports configuration file generated by the Amplify CLI. This file contains the AWS service configurations (like Cognito, AppSync, etc.) specific to your project.<br>import awsExports from &#39;./aws-exports&#39;;<br><br>// Imports the Quiz component from Quiz.js for use in this file.<br>// import Quiz from &#39;./Quiz&#39;;<br><br>// Configures the Amplify library with the settings from aws-exports.js, which includes all the AWS service configurations for this project.<br>Amplify.configure(awsExports);<br><br>function App() {<br>  return (<br>    &lt;div className=&quot;w-full h-full flex flex-col bg-gradient-to-r from-indigo-500 from-10% via-sky-500 via-30% to-emerald-500 to-90%&quot;&gt;<br>      &lt;Authenticator&gt;<br>        {({ signOut }) =&gt; (<br>          &lt;main className=&quot;flex flex-col flex-grow&quot;&gt;<br>            &lt;header className=&quot;flex justify-between items-center p-4&quot;&gt;<br>              &lt;div&gt;&lt;/div&gt;<br>              &lt;button <br>                onClick={signOut} <br>                className=&quot;bg-white hover:bg-blue-700 hover:text-white text-blue-500 font-bold py-2 px-4 rounded&quot;<br>              &gt;<br>                Sign Out<br>              &lt;/button&gt;<br>            &lt;/header&gt;<br>            &lt;div className=&quot;flex-grow&quot;&gt;<br>              {/* Quiz Component */}<br>              {/* &lt;Quiz /&gt; */}<br>            &lt;/div&gt;<br>          &lt;/main&gt;<br>        )}<br>      &lt;/Authenticator&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default withAuthenticator(App);</pre><p>Then we need to install the Amplify libraries that give us the login user interface, so run the following command:</p><pre>npm install aws-amplify @aws-amplify/ui-react</pre><p>Then run this command to start your application:</p><pre>npm start</pre><p>A new tab in your browser will open, showing this login page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*nBHaXM7XX9jqiH6luGuJmg.png" /></figure><p>Now click on “Create account”. Enter a valid email and a password, if you click on Next an authentication code will be sent to your email to activate your account, so enter the confirmation code and confirm.</p><p>You should now see this page as soon as you log in, with only a Sign Out button in the centre:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*Ln0l2G1XJooMt5sBngF-UQ.png" /></figure><p>In the AWS console, if you refresh the Users section in the Amazon Cognito’s user pool, you should see now one user:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KBzf3R7_IdKVlw4BamlSsw.png" /></figure><h3>Step 4: add functionality and styling for quiz</h3><p>Create a “Quiz.js” file in the “src” directory of your React application and paste this code:</p><pre>import React, { useState, useEffect } from &#39;react&#39;;<br>import he from &#39;he&#39;;<br><br>function Quiz() {<br>  const [questions, setQuestions] = useState([]);<br>  const [answerOptions, setAnswerOptions] = useState([]);<br>  const [currentQuestion, setCurrentQuestion] = useState(0);<br>  const [score, setScore] = useState(0);<br>  const [showScore, setShowScore] = useState(false);<br>  const [selectedAnswer, setSelectedAnswer] = useState(&quot;&quot;); <br>  const [isCorrect, setIsCorrect] = useState(null);<br>  const [error, setError] = useState(null);<br><br>  useEffect(() =&gt; {<br>    // Fetch questions from the API URL provided by Open Trivia DB (https://opentdb.com/api_config.php)<br>    const fetchQuestions = async () =&gt; {<br>      try {<br>        const response = await fetch(&#39;https://opentdb.com/api.php?amount=15&amp;category=11&amp;difficulty=hard&amp;type=multiple&#39;);<br>        if (!response.ok) {<br>          throw new Error(&#39;Failed to fetch questions&#39;);<br>        }<br>        const data = await response.json();<br>        console.log(data);<br>        const questions = data.results.map((q) =&gt; ({<br>            question: he.decode(q.question),<br>            options: [...q.incorrect_answers.map(a =&gt; he.decode(a)), he.decode(q.correct_answer)].sort(() =&gt; Math.random() - 0.5),<br>            answer: he.decode(q.correct_answer),<br>            }));<br>        setQuestions(questions);<br>        console.log(questions);<br><br>        setError(null);<br>      } catch (error) {<br>        setError(error.message);<br>      }<br>    };<br><br>    fetchQuestions();<br>  }, []);<br><br>  const handleAnswerOptionClick = (option) =&gt; {<br>    const correctAnswer = questions[currentQuestion].answer;<br>    setSelectedAnswer(option);<br>    if (option === correctAnswer) {<br>      setScore(score + 1);<br>      setIsCorrect(true);<br>    } else {<br>      setIsCorrect(false);<br>    }<br><br>    // Delay moving to the next question to allow the user to see feedback<br>    setTimeout(() =&gt; {<br>      const nextQuestion = currentQuestion + 1;<br>      if (nextQuestion &lt; questions.length) {<br>        setCurrentQuestion(nextQuestion);<br>        setIsCorrect(null); // Reset for the next question<br>        setSelectedAnswer(&quot;&quot;); // Reset selected answer<br>      } else {<br>        setShowScore(true);<br>      }<br>    }, 1000); // Adjust time as needed<br>  };<br><br>  return (<br>    &lt;div className=&#39;text-center&#39;&gt;<br>      &lt;div className=&quot;min-h-screen flex flex-col justify-center&quot;&gt;<br>        &lt;h1 className=&#39;text-4xl font-bold mb-4 text-white font-sans&#39;&gt;Incredible Quiz App&lt;/h1&gt;<br>      {showScore ? (<br>        &lt;div&gt;<br>          &lt;h2 className=&#39;text-xl font-semibold mb-4 text-white&#39;&gt;<br>          Your score: {score} / {questions.length}<br>          &lt;/h2&gt;<br>          &lt;button className=&#39;bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded&#39; onClick={() =&gt; window.location.reload()}&gt;<br>            Restart Quiz<br>          &lt;/button&gt;<br>        &lt;/div&gt;<br>      ) : (<br>        &lt;div className=&#39;bg-slate-100 mx-52 rounded-md p-10&#39;&gt;<br>          {questions.length &gt; 0 ? (<br>            &lt;div&gt;<br>            &lt;h2 className= &quot;text-xl font-semibold mb-4 font-sans&quot;&gt;<br>                Question {currentQuestion + 1}/{questions.length}<br>            &lt;/h2&gt;<br>            &lt;p className=&#39;text-lg mb-4 font-semibold font-sans&#39;&gt;{questions[currentQuestion].question}&lt;/p&gt;<br>            &lt;/div&gt;<br>          ) : (<br>            &lt;p className=&#39;text-lg mb-4 font-semibold text-black font-sans&#39;&gt;Loading questions ⏳ ... if you don&#39;t see them refresh the page&lt;/p&gt;<br>          )}<br>          {questions.length &gt; 0 &amp;&amp; (<br>            &lt;div className=&#39;grid grid-cols-2 gap-4 mx-44&#39;&gt;<br>              {questions[currentQuestion].options.map((option) =&gt; (<br>                &lt;button <br>                  onClick={() =&gt; handleAnswerOptionClick(option)} <br>                  key={option}<br>                  className=&#39;bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-md font-sans&#39;<br>                  style={{ backgroundColor: selectedAnswer === option ? (isCorrect ? &#39;lightgreen&#39; : &#39;pink&#39;) : &#39;&#39; }}<br>                &gt;<br>                  {option}<br>                &lt;/button&gt;<br>              ))}<br>            &lt;/div&gt;<br>          )}<br>          {selectedAnswer &amp;&amp; (<br>            &lt;div style={{ marginTop: &#39;10px&#39; }}&gt;<br>              {isCorrect ? &#39;Correct! 🎉&#39; : &#39;Sorry, that is not right. 😢&#39;}<br>            &lt;/div&gt;<br>          )}<br>        &lt;/div&gt;<br>      )}<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default Quiz;</pre><p>We are fetching quiz questions and answers from a service called Open Trivia DB which exposes an API. You can customize your quiz as you want by changing the API options in <a href="https://opentdb.com/api_config.php">https://opentdb.com/api_config.php</a> and then based on the configuration it will generate the corresponding URL to replace in the code in “Quiz.js”, for example for the one already provided in the code:</p><p><a href="https://opentdb.com/api.php?amount=15&amp;category=11&amp;difficulty=hard&amp;type=multiple">“https://opentdb.com/api.php?<strong>amount</strong>=15&amp;<strong>category</strong>=11&amp;<strong>difficulty</strong>=hard&amp;<strong>type</strong>=multiple</a>”</p><p>In this case in the API configuration I selected:</p><ul><li><strong>Number of questions:</strong> 15</li><li><strong>Category:</strong> Entertainment Film</li><li><strong>Difficulty:</strong> Hard</li><li><strong>Type:</strong> Multiple Choice</li></ul><p>Once you have finished with “Quiz.js”, in “App.js” you should uncomment these two lines:</p><ul><li>“import Quiz from ‘./Quiz’”</li><li>&lt;Quiz /&gt;</li></ul><p>In addition to this, the application uses Tailwind CSS for the UI (<a href="https://tailwindcss.com/">https://tailwindcss.com/</a>) and the “he” library, which is a robust HTML entity encoder/decoder to resolve ambiguous sequences of characters returned by the API in the questions and answers.</p><p>So run:</p><pre>npm install he<br>npm install -D tailwindcss<br>npx tailwindcss init</pre><p>Then in “tailwind.config.js”, replace with this code:</p><pre>module.exports = {<br>  content: [<br>    &quot;./src/**/*.{js,jsx,ts,tsx}&quot;,<br>  ],<br>  theme: {<br>    extend: {},<br>  },<br>  plugins: [],<br>}</pre><p>Finally, run <em>“npm start”</em> and the application will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z_y7EiBo6gZ9i-xY_A8cjg.png" /></figure><h3>Step 5: push local code to GitHub</h3><p>We have run our frontend locally on localhost using Cognito on the backend. However in the real world it is more likely that you have your code in GitHub or another source control repository, and you have Amplify that pulls from the repo and will host the frontend.</p><p>Create a new remote GitHub repository (do not add a README.md file, otherwise you will have to merge) and then run the following commands inside the directory of your React application:</p><pre>git init<br>git add .<br>git commit -m &quot;Initial Commit&quot;<br>git branch -M main<br># Here replace with your clone URL<br>git remote add origin https://github.com/....../amplify-cognito-quizapp.git<br>git push -u origin main</pre><h3>Step 6: set up a CI/CD pipeline</h3><p>Whenever we make a change to the code in GitHub we want to trigger a new build and deploy in Amplify, so we want to set up a basic implementation of a continuous integration continuous deployment (CI/CD) pipeline.</p><p>In AWS Amplify in “Hosting environments” is where we say where is our application, select “GitHub” and then “Connect branch”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x1hQhk7NV_dx5tnrIJ4Z8Q.png" /></figure><p>If you don’t see your repo, right-click on “View GitHub permissions” and open it in a new tab, a GitHub page will open. Here click on “Only select repositories” and select your repository and click Save.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1JfQ5pWgonPraCVCA5ahjA.png" /></figure><p>Then refresh the page in the console and now you should see your repository, then click on Next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yYHKRp-YZy6BKzPxXBJ0wQ.png" /></figure><p>Here you should only change the backend environment, in my case it’s called “quizapp”, it is the name of the app in AWS Amplify, select the envrionment which is “dev”. Also make sure to tick “Enable full-stack continuous deployments (CI/CD).</p><p>Then we need to create a service role, so click on “Create new role”. Then click on Next twice and then “Create role”.</p><p>Go back to the previous tab and click on the refresh button in the field of the service role.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*gZzxbcOL4pNCkSVctwfvDg.png" /></figure><p>Then click on Next and then “Save and deploy”.</p><p>Now wait few minutes and you should be able to access to your application from the URL similar to “https://main…amplifyapp.com” displayed in the screenshot below under that window image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a4eSYE_jmPD-P39eKdDn2g.png" /></figure><h3>Step 7: test the CI/CD deployment</h3><p>Now if we make a small change to the code, for example changing the title above the questions from “Quiz App” to “Incredible Quiz App” in App.js and push our changes to GitHub, Amplify should detect the change and automatically provision, build and deploy our updated code.</p><p>So I apply the change:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iR7LqSTqIGzti5lXwxcOSQ.png" /></figure><p>Then run:</p><pre>git add .<br>git commit -m &quot;Changed title&quot;<br>git push origin main</pre><p>In the console we will see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2uomuvpkX3POi5eG5TSKOg.png" /></figure><p>And, after few minutes, we will see the change reflected into our application:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BsQlyGVtCg9RVfmWqkNmuw.png" /></figure><h3>Step 8: clean up</h3><p>Delete your application in AWS Amplify. Once you’ve done that, this will automatically remove the associated user pool in Amazon Cognito.</p><p>This project is finished, if you liked it please leave a thumbs up and see you in the next project!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a43c2e35a22c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced WordPress deployment, using Terraform]]></title>
            <link>https://medium.com/@mattiamazzari/advanced-wordpress-deployment-using-terraform-db797f3453df?source=rss-e9f146485d51------2</link>
            <guid isPermaLink="false">https://medium.com/p/db797f3453df</guid>
            <category><![CDATA[rds]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[wordpress]]></category>
            <category><![CDATA[application-load-balancer]]></category>
            <category><![CDATA[ec2]]></category>
            <dc:creator><![CDATA[Mattiamazzari]]></dc:creator>
            <pubDate>Mon, 15 Apr 2024 11:12:50 GMT</pubDate>
            <atom:updated>2024-04-15T11:12:50.393Z</atom:updated>
            <content:encoded><![CDATA[<p>The focus of this project is to replicate the following configuration using Terraform:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*R9bSesOaMxxzS9IaaGpuAw.jpeg" /></figure><p>We want to:</p><ol><li>Create a VPC with 3 public subnets and 3 private subnets</li><li>Deploy an RDS database instance in a private subnet</li><li>Deploy a Wordpress EC2 instance in the same private subnet and connect it to the RDS database through a Security Group</li><li>Deploy an Application Load Balancer (ALB) in the public subnet and connect it to the EC2 instance using a target group</li><li>Connect to the EC2 instance in the private subnet using an EC2 Instance Connect Endpoint placed in the public subnet. In other old guides you might see a Bastion Host replacing this block, which is not needed anymore.</li></ol><h3>Step 0: setup Terraform provider and variables</h3><p>First of all, we setup our provider and define variables which will be helpful during the project.</p><pre># provider.tf<br><br>provider &quot;aws&quot; {<br>    region = &quot;eu-west-3&quot;<br>    access_key = var.aws_access_key<br>    secret_key = var.aws_secret_key<br>}<br><br>terraform {<br>    required_providers {<br>        aws = {<br>        source  = &quot;hashicorp/aws&quot;<br>        version = &quot;~&gt; 5.0&quot;<br>        }<br>    }<br>}</pre><pre># variables.tf<br><br>variable &quot;vpc_cidr&quot; {<br>    description = &quot;CIDR block for the VPC&quot;<br>    type = string<br>    default = &quot;10.0.0.0/16&quot;<br>}<br><br>variable &quot;subnet_cidrs&quot; {<br>    description = &quot;CIDR blocks for the subnets&quot;<br>    type = list(string)<br>    default = [&quot;10.0.1.0/24&quot;, &quot;10.0.2.0/24&quot;, &quot;10.0.3.0/24&quot;, &quot;10.0.4.0/24&quot;, &quot;10.0.5.0/24&quot;, &quot;10.0.6.0/24&quot;]<br>}<br><br>variable &quot;availability_zones&quot; {<br>    description = &quot;Availability zones for the subnets&quot;<br>    type = list(string)<br>    default = [&quot;eu-west-3a&quot;, &quot;eu-west-3b&quot;, &quot;eu-west-3c&quot;]<br><br>}<br><br>variable &quot;aws_access_key&quot; {<br>  description = &quot;AWS access key&quot;<br>  type = string<br>}<br><br>variable &quot;aws_secret_key&quot; {<br>  description = &quot;AWS secret key&quot;<br>  type = string<br>}<br><br>variable &quot;db_name&quot; {<br>  description = &quot;Name of the database&quot;<br>  type = string<br>  default = &quot;wordpress&quot;<br>}<br><br>variable &quot;db_user&quot; {<br>  description = &quot;Name of the database user&quot;<br>  type = string<br>  default = &quot;wordpress&quot;<br>}<br><br>variable &quot;db_password&quot; {<br>  description = &quot;Password of the database user&quot;<br>  type = string<br>  default = &quot;wordpress&quot;<br>}</pre><pre># terraform.tfvars<br><br>aws_access_key = &quot;your-access-key&quot;<br>aws_secret_key = &quot;your-secret-key&quot;<br>db_name = &quot;wordpress&quot;<br>db_user = &quot;admin&quot;<br>db_password = &quot;password&quot;</pre><p>Note that you should have your access key and secret key, so make sure you have generated them. Otherwise follow this guide:</p><p><a href="https://medium.com/@mohasina.clt/how-to-generate-access-keys-in-aws-af1a303dde42">How to Generate Access Keys in AWS</a></p><p>In “variables.tf” we are defining several useful variables, for example those that define the IP addresses for the VPC and its subnets.</p><p>In “terraform.tfvars” we provide the value for the variables, this is a file that must be kept secret.</p><h3>Step 1: create VPC and subnets</h3><p>Next, we declare our VPC, along with 3 public subnets and 3 private subnets.</p><pre># vpc.tf<br><br>resource &quot;aws_vpc&quot; &quot;my_new_vpc&quot; {<br>    cidr_block = var.vpc_cidr<br>    enable_dns_support = true<br>    enable_dns_hostnames = true<br>    tags = {<br>        Name = &quot;My new VPC&quot;<br>    }<br>}<br><br>resource &quot;aws_subnet&quot; &quot;public_subnet_1&quot; {<br>    vpc_id = aws_vpc.my_new_vpc.id<br>    cidr_block = var.subnet_cidrs[0]<br>    availability_zone = var.availability_zones[0]<br>    map_public_ip_on_launch = true # what makes the subnet public<br>    tags = {<br>        Name = &quot;Public Subnet 1&quot;<br>    }<br>}<br><br>resource &quot;aws_subnet&quot; &quot;public_subnet_2&quot; {<br>    vpc_id = aws_vpc.my_new_vpc.id<br>    cidr_block = var.subnet_cidrs[1]<br>    availability_zone = var.availability_zones[1]<br>    map_public_ip_on_launch = true<br>    tags = {<br>        Name = &quot;public Subnet 2&quot;<br>    }<br>}<br><br>resource &quot;aws_subnet&quot; &quot;public_subnet_3&quot; {<br>    vpc_id = aws_vpc.my_new_vpc.id<br>    cidr_block = var.subnet_cidrs[2]<br>    availability_zone = var.availability_zones[2]<br>    map_public_ip_on_launch = true<br>    tags = {<br>        Name = &quot;Public Subnet 3&quot;<br>    }<br>}<br><br>resource &quot;aws_subnet&quot; &quot;private_subnet_1&quot; {<br>    vpc_id = aws_vpc.my_new_vpc.id<br>    cidr_block = var.subnet_cidrs[3]<br>    availability_zone = var.availability_zones[0]<br>    map_public_ip_on_launch = false<br>    tags = {<br>        Name = &quot;Private Subnet 1&quot;<br>    }<br>}<br><br>resource &quot;aws_subnet&quot; &quot;private_subnet_2&quot; {<br>    vpc_id = aws_vpc.my_new_vpc.id<br>    cidr_block = var.subnet_cidrs[4]<br>    availability_zone = var.availability_zones[1]<br>    map_public_ip_on_launch = false<br>    tags = {<br>        Name = &quot;Private Subnet 2&quot;<br>    }<br>}<br><br>resource &quot;aws_subnet&quot; &quot;private_subnet_3&quot; {<br>    vpc_id = aws_vpc.my_new_vpc.id<br>    cidr_block = var.subnet_cidrs[5]<br>    availability_zone = var.availability_zones[2]<br>    map_public_ip_on_launch = false<br>    tags = {<br>        Name = &quot;Private Subnet 3&quot;<br>    }<br>}</pre><h3>Step 2: setup Security Groups</h3><p>Then, since we will have an EC2 Instance, an RDS instance and an Application Load Balancer (ALB), we need to create 3 Security Groups.</p><pre># security.tf<br><br>resource &quot;aws_security_group&quot; &quot;ec2_allow_http_ssh_sg&quot; {<br>    vpc_id = aws_vpc.my_new_vpc.id<br>    ingress {<br>        description = &quot;Allow SSH access from anywhere&quot;<br>        from_port = 22<br>        to_port = 22<br>        protocol = &quot;tcp&quot;<br>        cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>    }<br>    ingress {<br>        description = &quot;Allow HTTP access from anywhere&quot;<br>        from_port = 80<br>        to_port = 80<br>        protocol = &quot;tcp&quot;<br>        cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>    }<br>    egress {<br>        description = &quot;Allow all traffic to go out&quot;<br>        from_port = 0<br>        to_port = 0<br>        protocol = -1<br>        cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>        ipv6_cidr_blocks = [&quot;::/0&quot;]<br>    }<br>} <br><br>resource &quot;aws_security_group&quot; &quot;rds_sg&quot; {<br>    vpc_id = aws_vpc.my_new_vpc.id<br>    ingress {<br>        description = &quot;Allow MySQL/Aurora access from EC2 instances&quot;<br>        from_port = 3306<br>        to_port = 3306<br>        protocol = &quot;tcp&quot;<br>        # Specify the security group that will be assigned to the EC2 instance<br>        security_groups = [aws_security_group.ec2_allow_http_ssh_sg.id]<br>    }<br>    egress {<br>        description = &quot;Allow all traffic to go out&quot;<br>        from_port = 0<br>        to_port = 0<br>        protocol = -1<br>        cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>    }<br>}<br><br>resource &quot;aws_security_group&quot; &quot;alb_sg&quot; {<br>    vpc_id = aws_vpc.my_new_vpc.id<br>    ingress {<br>        description = &quot;Allow HTTP access from anywhere&quot;<br>        from_port = 80<br>        to_port = 80<br>        protocol = &quot;tcp&quot;<br>        cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>    }<br>    egress {<br>        description = &quot;Allow all traffic to go out&quot;<br>        from_port = 0<br>        to_port = 0<br>        protocol = -1<br>        cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>        ipv6_cidr_blocks = [&quot;::/0&quot;]<br>    }<br>}</pre><p>In the resource “rds_sg”, make sure you enable access to the RDS DB from the EC2 instance.</p><h3>Step 3: setup routing</h3><p>In a typical AWS VPC setup, a private subnet is one that does not have a route to the internet. This is often desired for security reasons, as it prevents instances within the private subnet from being directly accessible from the internet. However, there are scenarios where you might still want your EC2 instances in a private subnet to access resources on the internet or for resources on the internet to access your EC2 instances. So the following components are needed:</p><ul><li><strong>Internet gateway</strong>: serves as a bridge between your VPC and the internet. By attaching an Internet Gateway to your VPC, you enable communication between resources within your VPC and the internet. This means that even though your EC2 instances are in a private subnet, they can still access resources on the internet or be accessed from the internet if necessary. Common use cases are software updates and accessing external APIs or services.</li><li><strong>NAT gateway</strong>: allows a private subnet to have access to the Internet, but prevents the Internet from initiating a connection directly to the EC2 Instance. Moreover, the NAT gateway needs an Elastic IP (EIP) address because it provides a static public IP address that doesn’t change, even if the NAT gateway instance is stopped or replaced. This static IP address is necessary for outbound traffic to be properly routed to the internet and for external services to respond back to the NAT gateway.</li></ul><pre># routing.tf<br><br># Internet gateway<br>resource &quot;aws_internet_gateway&quot; &quot;my_new_igw&quot; {<br>    vpc_id = aws_vpc.my_new_vpc.id<br>    tags = {<br>        Name = &quot;VPC IGW&quot;<br>    }<br>}<br><br># Public route table<br>resource &quot;aws_route_table&quot; &quot;public_route_table&quot; {<br>    vpc_id = aws_vpc.my_new_vpc.id<br>    # Default route to forward traffic destined for the internet (0.0.0.0/0)<br>    # to the internet gateway<br>    route {<br>        cidr_block = &quot;0.0.0.0/0&quot;<br>        gateway_id = aws_internet_gateway.my_new_igw.id<br>    }<br>    tags = {<br>        Name = &quot;Public route table&quot;<br>    }<br>}<br><br># Private route table<br>resource &quot;aws_route_table&quot; &quot;private_route_table&quot; {<br>    vpc_id = aws_vpc.my_new_vpc.id<br>    # Default route that directs traffic to a NAT gateway (nat_gateway_id) for<br>    # outbound internet access<br>    route {<br>        cidr_block = &quot;0.0.0.0/0&quot;<br>        nat_gateway_id = aws_nat_gateway.nat_gateway.id<br>    }<br>    tags = {<br>        Name = &quot;Private route table&quot;<br>    }<br>}<br><br># Route table associations<br>resource &quot;aws_route_table_association&quot; &quot;public_subnet_1_association&quot; {<br>    subnet_id = aws_subnet.public_subnet_1.id<br>    route_table_id = aws_route_table.public_route_table.id<br>}<br><br>resource &quot;aws_route_table_association&quot; &quot;public_subnet_2_association&quot; {<br>    subnet_id = aws_subnet.public_subnet_2.id<br>    route_table_id = aws_route_table.public_route_table.id<br>}<br><br>resource &quot;aws_route_table_association&quot; &quot;public_subnet_3_association&quot; {<br>    subnet_id = aws_subnet.public_subnet_3.id<br>    route_table_id = aws_route_table.public_route_table.id<br>}<br><br>resource &quot;aws_route_table_association&quot; &quot;private_subnet_1_association&quot; {<br>    subnet_id = aws_subnet.private_subnet_1.id<br>    route_table_id = aws_route_table.private_route_table.id<br>}<br><br>resource &quot;aws_route_table_association&quot; &quot;private_subnet_2_association&quot; {<br>    subnet_id = aws_subnet.private_subnet_2.id<br>    route_table_id = aws_route_table.private_route_table.id<br>}<br><br>resource &quot;aws_route_table_association&quot; &quot;private_subnet_3_association&quot; {<br>    subnet_id = aws_subnet.private_subnet_3.id<br>    route_table_id = aws_route_table.private_route_table.id<br>}<br><br># Elastic IP address for the NAT gateway<br>resource &quot;aws_eip&quot; &quot;eip&quot; {<br>    domain = &quot;vpc&quot;<br>    depends_on = [ aws_internet_gateway.my_new_igw ]<br>}<br><br># NAT gateway<br>resource &quot;aws_nat_gateway&quot; &quot;nat_gateway&quot; {<br>    allocation_id = aws_eip.eip.id<br>    subnet_id = aws_subnet.public_subnet_1.id<br>    depends_on = [ aws_internet_gateway.my_new_igw ]<br>}</pre><h3>Step 4: setup RDS database</h3><p>Then, setup the RDS DB instance. Note that we are defining a DB subnet group with all the private subnets. A DB subnet group defines the subnets that the database instances can be created in.</p><pre># database.tf<br><br>resource &quot;aws_db_subnet_group&quot; &quot;my_db_subnet_group&quot; {<br>    name       = &quot;my_db_subnet_group&quot;<br>    subnet_ids = [aws_subnet.private_subnet_1.id, aws_subnet.private_subnet_2.id, aws_subnet.private_subnet_3.id]<br>    tags = {<br>        Name = &quot;My DB Subnet Group&quot;<br>    }<br>}<br><br>resource &quot;aws_db_instance&quot; &quot;my_db_instance&quot; {<br>    allocated_storage    = 10<br>    storage_type         = &quot;gp2&quot;<br>    engine               = &quot;mysql&quot;<br>    engine_version       = &quot;8.0&quot;<br>    instance_class       = &quot;db.t3.micro&quot;<br>    identifier           = var.db_name<br>    db_name              = var.db_name<br>    username             = var.db_user<br>    password             = var.db_password<br>    parameter_group_name = &quot;default.mysql8.0&quot;<br>    db_subnet_group_name = aws_db_subnet_group.my_db_subnet_group.name<br>    skip_final_snapshot  = true<br>    vpc_security_group_ids = [aws_security_group.rds_sg.id]<br>    tags = {<br>        Name = &quot;My DB&quot;<br>    }<br>}<br><br>output &quot;rds_endpoint&quot; {<br>  value = aws_db_instance.my_db_instance.endpoint<br>}</pre><p>Observe that an output block defines an output value for the RDS database instance endpoint. It allows you to retrieve and display the endpoint URL of the RDS instance after the Terraform apply operation, in the terminal.</p><h3>Step 5: provision the EC2 instance</h3><p>Then, setup the EC2 instance:</p><pre># compute.tf<br><br>resource &quot;aws_instance&quot; &quot;wordpress_server&quot; {<br>    ami = &quot;ami-0322211ccfe5b6a20&quot; # Ubuntu LTS 20.04, eu-west-3<br>    instance_type = &quot;t2.micro&quot;<br>    key_name = &quot;TF_key&quot;<br>    vpc_security_group_ids = [aws_security_group.ec2_allow_http_ssh_sg.id]<br>    subnet_id = aws_subnet.private_subnet_1.id<br>    tags = {<br>        Name = &quot;Wordpress Server&quot;<br>    }<br>}<br><br>resource &quot;tls_private_key&quot; &quot;rsa&quot; {<br>    algorithm = &quot;RSA&quot;<br>    rsa_bits = 4096<br>}<br><br>resource &quot;aws_key_pair&quot; &quot;TF_key&quot; {<br>    key_name = &quot;TF_key&quot;<br>    public_key = tls_private_key.rsa.public_key_openssh<br>}<br><br>resource &quot;local_file&quot; &quot;TF-key&quot; {<br>    content = tls_private_key.rsa.private_key_pem<br>    filename = &quot;tfkey&quot;<br>}<br><br># This resource is used to connect to the EC2 instance using the EC2 Instance Connect feature.<br># It is needed because the EC2 instance is in a private subnet and does not have a public IP address.<br># An alternative way is to define another &quot;aws_instance&quot; that is in a public subnet and use it to connect to the EC2 instance in the private subnet,<br># and we would call it a &quot;bastion host&quot;.<br>resource &quot;aws_ec2_instance_connect_endpoint&quot; &quot;wordpress_ec2_connect_endpoint&quot; {<br>    subnet_id = aws_subnet.public_subnet_1.id<br>    security_group_ids = [aws_security_group.ec2_allow_http_ssh_sg.id]<br>    preserve_client_ip = false<br>}</pre><p>Note that it creates a new RSA private key and defines a new key-pair to SSH to the EC2 instance. Moreover, we assign the security group for EC2 we defined before and deploy the instance in the first private subnet.</p><p>Then it is defined an EC2 Instance Connect Endpoint to be able to connect to the EC2 instance located in the private subnet.</p><h3>Step 6: setup the Application Load Balancer (ALB)</h3><pre># load_balancer.tf<br><br>resource &quot;aws_lb&quot; &quot;application_load_balancer&quot; {<br>    name            = &quot;my-alb-2024&quot;<br>    internal        = false<br>    load_balancer_type = &quot;application&quot;<br>    security_groups = [aws_security_group.alb_sg.id]<br>    subnets         = [aws_subnet.public_subnet_1.id, aws_subnet.public_subnet_2.id, aws_subnet.public_subnet_3.id]<br>    enable_deletion_protection = false<br>    tags = {<br>        Name = &quot;My ALB 2024&quot;<br>    }<br>}<br><br>resource &quot;aws_lb_target_group&quot; &quot;target_group&quot; {<br>    name     = &quot;my-target-group&quot;<br>    port     = 80<br>    protocol = &quot;HTTP&quot;<br>    vpc_id   = aws_vpc.my_new_vpc.id<br>    target_type = &quot;instance&quot;<br>    health_check {<br>        path                = &quot;/&quot;<br>        protocol            = &quot;HTTP&quot;<br>        port                = &quot;traffic-port&quot;<br>        interval            = 30<br>        timeout             = 5<br>        healthy_threshold   = 2<br>        unhealthy_threshold = 2<br>        matcher             = &quot;200&quot;<br>    }<br>    tags = {<br>        Name = &quot;MyTargetGroup&quot;<br>    }<br>}<br><br>resource &quot;aws_lb_target_group_attachment&quot; &quot;target_group_attachment&quot; {<br>    target_group_arn = aws_lb_target_group.target_group.arn<br>    target_id        = aws_instance.wordpress_server.id<br>    port             = 80<br>}<br><br>resource &quot;aws_lb_listener&quot; &quot;alb_listener&quot; {<br>    load_balancer_arn = aws_lb.application_load_balancer.arn<br>    port              = &quot;80&quot;<br>    protocol          = &quot;HTTP&quot;<br><br>    default_action {<br>        type             = &quot;forward&quot;<br>        target_group_arn = aws_lb_target_group.target_group.arn<br>    }<br>}</pre><p>This Terraform configuration sets up an Application Load Balancer (ALB) along with its associated components in AWS.</p><p>The “aws_lb” resource defines the ALB itself, which is configured to be an external-facing ALB for handling HTTP traffic. It&#39;s associated with a security group for controlling inbound and outbound traffic, and it&#39;s placed in the public subnets to ensure accessibility from the internet.</p><p>The “aws_lb_target_group” resource defines a target group which is configured to route traffic to instances on port 80 using the HTTP protocol. Health checks are set up to monitor the health of the instances by sending HTTP requests to the root path (&quot;/&quot;) every 30 seconds, with a timeout of 5 seconds. Instances are considered healthy if they respond with a status code of 200. This target group is associated with the ALB for forwarding incoming traffic.</p><p>The “aws_lb_target_group_attachment” resource attaches the EC2 instance to the target group, allowing the ALB to route traffic to it.</p><p>Finally, the “aws_lb_listener” resource defines a listener for the ALB on port 80, configured to forward incoming HTTP requests to the target group.</p><h3>Conclusion</h3><p>Excellent! You have configured an advanced WordPress infrastructure. So deploy it:</p><pre>terraform init<br>terraform plan<br>terraform apply</pre><p>Then, if you browse to the DNS name of the ALB it appear the initial welcome screen of WordPress:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X5RgqvFECO9wuy7tA8GnXg.png" /></figure><p>I hope you liked this guide, see you in other tutorials!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db797f3453df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Backup and restore EC2 instance, using Terraform]]></title>
            <link>https://medium.com/@mattiamazzari/backup-and-restore-ec2-instance-using-terraform-d86276c73266?source=rss-e9f146485d51------2</link>
            <guid isPermaLink="false">https://medium.com/p/d86276c73266</guid>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[backup-and-restore]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[s3-bucket]]></category>
            <category><![CDATA[ec2]]></category>
            <dc:creator><![CDATA[Mattiamazzari]]></dc:creator>
            <pubDate>Mon, 15 Apr 2024 09:41:26 GMT</pubDate>
            <atom:updated>2024-04-15T09:41:26.902Z</atom:updated>
            <content:encoded><![CDATA[<h3>Backup and restore EC2 instances, using Terraform</h3><p>The objective of this project is to master the backup and restoration process of EC2 Instances, a crucial aspect of disaster recovery, utilizing Terraform. The aim is to provision an EC2 instance, transfer a file (e.g., a simple .TXT file) onto it, and generate an Amazon Machine Image (AMI) from it. Subsequently, by launching a fresh EC2 Instance using the created AMI, we aim to validate the presence of the transferred file within the new instance.</p><p><strong>Steps:</strong></p><ol><li><strong>Provision an EC2 Instance</strong>: Utilize Terraform to provision an EC2 instance within the AWS infrastructure.</li><li><strong>Transfer File onto EC2 Instance</strong>: Upload a specified file onto the provisioned EC2 instance. This file will serve as our test case, ensuring that data persistence is maintained through the backup and restoration process.</li><li><strong>Create an Amazon Machine Image (AMI)</strong>: Generate an AMI from the configured EC2 instance. This image will encapsulate the entire state of the instance, including the uploaded file.</li><li><strong>Launch a New EC2 Instance from AMI</strong>: Instantiate a new EC2 instance within the AWS environment using the previously created AMI. Upon successful launch, validate the presence of the transferred file within the new instance.</li></ol><h3>Step 0: setup Terraform provider and variables</h3><p>First of all, we setup the provider (“aws”) with the region, the access key and the secret key. We will define some variables in a file called “variables.tf”.</p><p>So create a file “provider.tf”:</p><pre>provider &quot;aws&quot; {<br>  region = &quot;eu-west-3&quot; # choose the region closest to you for minimal latency<br>  access_key = var.access_key<br>  secret_key = var.secret_key<br>}<br><br>terraform {<br>    required_providers {<br>        aws = {<br>        source  = &quot;hashicorp/aws&quot;<br>        version = &quot;~&gt; 3.0&quot;<br>        }<br>    }<br>}</pre><p>Then a file “variables.tf”:</p><pre>variable &quot;access_key&quot; {<br>  description = &quot;AWS access key&quot;<br>  type = string<br>}<br><br>variable &quot;secret_key&quot; {<br>  description = &quot;AWS secret key&quot;<br>  type = string<br>}</pre><p>In “terraform.tfvars” we provide the values for this variables:</p><pre>access_key = &quot;your-access-key&quot;<br>secret_key = &quot;your-secret-key&quot;</pre><p>If you haven’t generated the access key and the secret key for your IAM user, follow this guide:</p><p><a href="https://medium.com/@mohasina.clt/how-to-generate-access-keys-in-aws-af1a303dde42">How to Generate Access Keys in AWS</a></p><h3>Step 1: create a Security Group</h3><p>Define a Security Group that we will attach to it, allowing SSH access in the ingress rule and permitting access to anywhere with the egress rule. So create a file “security.tf”:</p><pre># security.tf<br><br>resource &quot;aws_security_group&quot; &quot;ec2_sg_new&quot; {<br>    name        = &quot;ec2-sg-new&quot;<br>    description = &quot;Allow inbound traffic on port 22&quot;<br>    vpc_id      = data.aws_vpc.default.id<br>    <br>    ingress {<br>        description = &quot;SSH from VPC&quot;<br>        from_port   = 22<br>        to_port     = 22<br>        protocol    = &quot;tcp&quot;<br>        cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>        ipv6_cidr_blocks = [&quot;::/0&quot;]<br>    }<br><br>    egress {<br>        from_port   = 0<br>        to_port     = 0<br>        protocol    = -1<br>        cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>        ipv6_cidr_blocks = [&quot;::/0&quot;]<br>    }<br>}</pre><h3>Step 2: setup an IAM role</h3><p>We also need to create a new IAM role to assign to our EC2 instance and we will attach some policies to it. IAM roles are entities that define a set of permissions for making AWS service requests. For example, the EC2 instance will rely on an S3 bucket to store the .TXT file we want to upload, so it should be able to perform some actions on the S3 bucket.</p><p>We define also an instance profile, which is a container for an IAM role that can be used to pass role information to an EC2 instance at launch. The role attribute specifies the IAM role created earlier to be associated with this instance profile.</p><p>So create a file “iam.tf” with the following code:</p><pre># iam.tf<br><br># Policy that allows the EC2 service to assume a role.<br>data &quot;aws_iam_policy_document&quot; &quot;ec2_assume_role&quot; {<br>    statement {<br>      actions = [ &quot;sts:AssumeRole&quot; ]<br>      principals {<br>        type        = &quot;Service&quot;<br>        identifiers = [ &quot;ec2.amazonaws.com&quot; ]<br>      }<br>    }<br>}<br><br># IAM role that references the IAM policy document defined in<br># the data block above, specifying who can assume this role.<br>resource &quot;aws_iam_role&quot; &quot;ec2_iam_role&quot; {<br>    name = &quot;ec2-iam-role&quot;<br>    path = &quot;/&quot;<br>    assume_role_policy = data.aws_iam_policy_document.ec2_assume_role.json<br>}<br><br># Create an IAM instance profile<br>resource &quot;aws_iam_instance_profile&quot; &quot;ec2_instance_profile&quot; {<br>    name = &quot;ec2-instance-profile&quot;<br>    role = aws_iam_role.ec2_iam_role.name<br>}<br><br># Attach EC2 Policies to Instance Role<br>resource &quot;aws_iam_policy_attachment&quot; &quot;ec2_attach_1&quot; {<br>  name = &quot;ec2-iam-attachment&quot;<br>  roles = [ aws_iam_role.ec2_iam_role.id ]<br>  policy_arn = &quot;arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore&quot;<br>}<br>resource &quot;aws_iam_policy_attachment&quot; &quot;ec2_attach_2&quot; {<br>  name = &quot;ec2-iam-attachment&quot;<br>  roles = [ aws_iam_role.ec2_iam_role.id ]<br>  policy_arn = &quot;arn:aws:iam::aws:policy/service-role/AmazonEC2RoleforSSM&quot;<br>}<br><br># Create S3 IAM policy<br># Allows some S3 actions on a specific bucket<br>resource &quot;aws_iam_policy&quot; &quot;s3-ec2-policy&quot; {<br>    name = &quot;s3-ec2-policy&quot;<br>    description = &quot;Allow EC2 to access S3&quot;<br>    policy = jsonencode({<br>        &quot;Version&quot;: &quot;2012-10-17&quot;,<br>        &quot;Statement&quot;: [<br>            {<br>                &quot;Effect&quot;: &quot;Allow&quot;,<br>                &quot;Action&quot;: [<br>                    &quot;s3:getObject&quot;,<br>                    &quot;s3:putObject&quot;,<br>                    &quot;s3:deleteObject&quot;,<br>                    &quot;s3:ListBucket&quot;<br>                ],<br>                &quot;Resource&quot;: &quot;arn:aws:s3:::my-deposit-bucket-2024/*&quot;<br>            }<br>        ]<br>      })<br>}<br><br># Attach S3 Policies to the IAM Role<br>resource &quot;aws_iam_policy_attachment&quot; &quot;s3_attach&quot; {<br>  name = &quot;s3-iam-attachment&quot;<br>  roles = [ aws_iam_role.ec2_iam_role.id ]<br>  policy_arn = aws_iam_policy.s3-ec2-policy.arn<br>}</pre><h3>Step 3: define the default VPC</h3><p>In another file “vpc.tf” define the default VPC (which is already created in your AWS account) because it will be referenced by other resource blocks.</p><pre># vpc.tf<br><br>data &quot;aws_vpc&quot; &quot;default&quot; {<br>  default = true<br>} </pre><h3>Step 4: create the file and setup an S3 bucket</h3><p>Then in your project directory create a folder “data”, inside of it create a new file “example.txt” and write anything to it. Now create a file “storage.tf” in which we define:</p><ul><li>an S3 bucket that will be the “deposit” for our object</li><li>an S3 bucket object, which is our “example.txt” file.</li><li>a data source “template_file” that generates a file based on a template. It reads the contents of a file named “s3upload.sh” located in the current module directory (path.module) and substitutes the bucket_name variable with the name of the S3 bucket created earlier. This variable will be used by the script “s3upload.sh” to copy the .TXT file from the S3 bucket to the EC2 instance.</li></ul><p>So create a file “s3upload.sh”, the content is the following:</p><pre>#!/bin/bash<br><br># Copy the file from the S3 Bucket to the EC2 instance in &quot;/home/ec2-user/example.txt&quot;<br>sudo aws s3 cp s3://${bucket_name}/example.txt /home/ec2-user/example.txt</pre><p>In the file “storage.tf” paste the following code:</p><pre># storage.tf<br><br># Bucket<br>resource &quot;aws_s3_bucket&quot; &quot;my_deposit_bucket&quot; {<br>    bucket = &quot;my-deposit-bucket-2024&quot;<br>    tags = {<br>        Name = &quot;my-deposit-bucket&quot;<br>    }<br>}<br><br># .TXT file<br>resource &quot;aws_s3_bucket_object&quot; &quot;my_deposit_object&quot; {<br>    bucket = aws_s3_bucket.my_deposit_bucket.bucket<br>    key    = &quot;example.txt&quot;<br>    source = &quot;data/example.txt&quot;<br>    force_destroy = true<br>}<br><br># Retrieve and display the name of the S3 bucket<br># after the Terraform apply operation.<br>output &quot;s3_bucket_automation&quot; {<br>    value = aws_s3_bucket.my_deposit_bucket.bucket<br>}<br><br># Template file<br>data &quot;template_file&quot; &quot;server&quot; {<br>    template = file(&quot;${path.module}/s3upload.sh&quot;)<br>    vars = {<br>        bucket_name = aws_s3_bucket.my_deposit_bucket.bucket<br>    }<br>}</pre><h3>Step 5: provision EC2 instances and define an AMI</h3><p>Now, in a file “compute.tf” provision the EC2 instances and the AMI.</p><pre># compute.tf<br><br>resource &quot;aws_instance&quot; &quot;origin_ec2_instance&quot; {<br>  ami           = &quot;ami-0facbf2a36e11b9dd&quot; # Amazon Linux 2023, eu-west-3<br>  instance_type = &quot;t3.micro&quot;<br>  key_name = &quot;TF_key&quot;<br>  tags = {<br>    Name = &quot;origin ec2 instance&quot;<br>  }<br>  vpc_security_group_ids = [ aws_security_group.ec2_sg_new.id ]<br>  user_data = data.template_file.server.rendered<br>  iam_instance_profile = aws_iam_instance_profile.ec2_instance_profile.id<br>}<br><br>resource &quot;tls_private_key&quot; &quot;rsa&quot; {<br>  algorithm = &quot;RSA&quot;<br>  rsa_bits  = 4096<br>}<br><br># Creating key-pair on AWS using SSH-public key<br>resource &quot;aws_key_pair&quot; &quot;TF_key&quot; {<br>  key_name   = &quot;TF_key&quot;<br>  public_key = tls_private_key.rsa.public_key_openssh<br>}<br><br>resource &quot;local_file&quot; &quot;TF-key&quot; {<br>  content = tls_private_key.rsa.private_key_pem<br>  filename = &quot;tfkey&quot;<br>}<br><br># Build AMI from the EC2 instance<br>resource &quot;aws_ami_from_instance&quot; &quot;origin_ami&quot; {<br>  name              = &quot;my-ami-from-ec2-2024&quot;<br>  source_instance_id = aws_instance.origin_ec2_instance.id<br>  tags = {<br>    Name = &quot;my ami from ec2 2024&quot;<br>  }<br>}<br><br># Output the AMI ID<br>output &quot;origin_ami_id&quot; {<br>  value = aws_ami_from_instance.origin_ami.id<br>}<br><br># Create a new EC2 instance from the AMI<br>resource &quot;aws_instance&quot; &quot;new_ec2_instance&quot; {<br>  ami             = aws_ami_from_instance.origin_ami.id<br>  key_name        = &quot;TF_key&quot;<br>  instance_type   = &quot;t3.micro&quot;<br>  vpc_security_group_ids = [ aws_security_group.ec2_sg_new.id ]<br><br>  tags = {<br>    Name = &quot;new ec2 instance&quot;<br>  }<br>}</pre><p>Note that in the first “aws_instance” block, I am using Amazon Linux and the AMI ID is associated to the region specified before in the “provider” block. To find yours, go to the “EC2” service in the AWS management console and click on “Launch an instance”. Among the options, if you select Amazon Linux 2023 you should read an AMI ID valid for your region. Create an RSA private key with the resource “tls_private_key” and define a new key-pair with the block “aws_key_pair”. This will be used to connect to your EC2 instance through SSH. “local_file” saves the key in your current directory with the name “tfkey”. Then we specify the key name in the EC2 instance block. Also attach the previously created Security Group in “vpc_security_group_ids”. In addition to this, in user data it is specified the template defined before.</p><p>Then we build an AMI utilizing the previous EC2 instance with “aws_ami_from_instance”.</p><p>Finally, it is defined a new EC2 instance which will be built from the newly created image.</p><h3>Conclusion</h3><p>Excellent! Now you are ready to deploy your infrastructure with:</p><pre>terraform init<br>terraform plan<br>terraform apply</pre><p>If you want to verify that the file is in the new EC2 instance, you need to connect through SSH to it with:</p><pre>ssh -i tfkey ec2-user@ec2-13-37-46-17.eu-west-3.compute.amazonaws.com</pre><p>Make sure you replace “13–37–46–17” with the public IP address of your EC2 instance (go to the AWS management console &gt; “EC2” &gt; select the EC2 instance &gt; “Public IP address”). When you replace it change the dots (.) into dashes (-). Also make sure to replace the region code “eu-west-3” with yours. “tfkey” is the name of the SSH key we created before in the project folder, if you assigned a different name change it.</p><pre>resource &quot;local_file&quot; &quot;TF-key&quot; {<br>  content = tls_private_key.rsa.private_key_pem<br>  filename = &quot;tfkey&quot; # name of the key saved in your folder<br>}</pre><p>If you gave a filename like “tfkey.pem” you should specify the extension in the command:</p><pre>ssh -i tfkey.pem ec2-user@ec2-13-37-46-17.eu-west-3.compute.amazonaws.com</pre><p>That’s all! I hope you liked this project and see you in other guides!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d86276c73266" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Auto Scaling with CloudWatch Scaling Alarms using Terraform]]></title>
            <link>https://medium.com/@mattiamazzari/auto-scaling-with-cloudwatch-scaling-alarms-using-terraform-dbd83211fd17?source=rss-e9f146485d51------2</link>
            <guid isPermaLink="false">https://medium.com/p/dbd83211fd17</guid>
            <category><![CDATA[cloudwatch]]></category>
            <category><![CDATA[cloudwatch-alarm]]></category>
            <category><![CDATA[auto-scaling-groups]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Mattiamazzari]]></dc:creator>
            <pubDate>Sun, 14 Apr 2024 17:22:39 GMT</pubDate>
            <atom:updated>2024-04-15T08:47:56.630Z</atom:updated>
            <content:encoded><![CDATA[<p>Auto Scaling is an effective way to improve availability and reliability of applications. You can increase the number of EC2 instances when there is high demand (scale out) and reduce it when there is low demand for your application (scale in). It helps monitor EC2 instance health and when it founds any instance is unhealthy or terminated, it will automatically create it and register it in the load balancer.</p><h3><strong>Auto Scaling parameters and policies</strong></h3><p>When we create or define an Auto Scaling Group, we need to specify the following sizes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*dhsXOfV8dryNhf-YKQD0XQ.png" /></figure><ul><li><strong>Minimum size</strong>: an Auto Scaling Group ensures that the group never goes below this size.</li><li><strong>Maximum size</strong>: an Auto Scaling Group ensures that the group never goes above this size</li><li><strong>Desired capacity</strong>: an Auto Scaling Group ensures that the group has this many instances. When I setup the Auto Scaling Group for the first time, it will run the number of EC2 instances equal to this number.</li></ul><p>There are multiple types of Auto Scaling Policies:</p><ul><li><strong>Dynamic scaling policies</strong></li><li><strong>Target tracking scaling</strong>: increase and decrease the current capacity of the group based on an Amazon CloudWatch metric and a target value (f.e. ASGAverageCPUUtilization = 50%). It will never go above the maximum capacity. So you just specify how much CPU utilization you want.</li><li><strong>Step scaling</strong>: increase and decrease the current capacity of the group based on a set of scaling adjustments, known as step adjustments, mentioning how many EC2 instances you want to create. It requires to create CloudWatch alarms for the scaling policies. For example: when ASGAverageCPUUtilization is between 30% — 40%, then add 1 EC2 instance, when between 50% — 60%, then add 2 EC2 instances and so on.</li><li><strong>Simple scaling</strong>: increase and decrease the current capacity of the group based on a single scaling adjustment, with a cooldown period between each scaling activity. It requires to create CloudWatch alarms for the scaling policies. Example: when ASGAverageCPUUtilization = 50%, then add 2 EC2 instances</li><li><strong>Predictive scaling policies**</strong>: uses Machine Learning to predict capacity requirements based on historical data from CloudWatch.</li><li><strong>Schedule scaling</strong>: scheduled scaling helps to set up your own scaling schedule according to predictable load changes. For example: At every Friday night at 9.00 PM, add 5 EC2 instances.</li></ul><h3><strong>Architecture of the project</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*iad9UWgWyCTJEVuQGkc8ig.png" /><figcaption>High-level architecture</figcaption></figure><p>First I give you an high-level overview of what we are going to build. We have an Auto Scaling Group whose goal is to manage EC2 instances in a scalable way. Then we have an Application Load Balancer, the user will type in the browser its DNS name to navigate to the website. In addition to this, CloudWatch Scaling Alarms will be triggered based on average CPU utilization: if it is goes above 70% it will scale in (add an EC2 instance), whereas if it is goes below 40% it will scale out (remove an EC2 instance).</p><p>Now let’s go a bit in more depth:</p><ul><li>Create a VPC with 3 public subnets and 3 private subnets.</li><li>Setup an EC2 instance in the private subnet and install Nginx on it.</li><li>Setup a NAT gateway to provide Internet access for the web server, in the public subnet. The EC2 instance is in a private subnet, so it needs a NAT gateway to access to Internet.</li><li>Create an Application Load Balancer (ALB) in the public subnet. Once we have created it, we create a Target Group. An Internet gateway is needed to allow incoming internet traffic to reach the ALB.</li><li>Build an AMI from the EC2 instance and create a launch template, that is used to deploy an Auto Scaling Group. Create and set up the Auto Scaling Group such that it takes into account the ALB as well as the EC2.</li><li>Setup a CloudWatch Scaling Alarm that increases the number of EC2 instances available in the Auto Scaling Group if the CPU utilization goes above 70% and reduces the number of EC2 instances available in the Auto Scaling Group if the CPU utilization goes below 40%</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*jvkQ1AoDDalqg0VZc5hOHQ.jpeg" /></figure><h3>Step 1: setup AWS provider and variables</h3><p>First of all we setup the region, the provider and all the variables needed</p><pre># provider.tf<br><br>provider &quot;aws&quot; {<br>  region = &quot;eu-west-3&quot;<br>  access_key = var.aws_access_key<br>  secret_key = var.aws_secret_key<br>}<br><br>terraform {<br>    required_providers {<br>        aws = {<br>        source  = &quot;hashicorp/aws&quot;<br>        version = &quot;~&gt; 5.0&quot;<br>        }<br>    }<br>}</pre><pre># variables.tf<br><br># VPC IP address<br>variable &quot;vpc_cidr&quot; {<br>    description = &quot;CIDR block for the VPC&quot;<br>    type = string<br>    default = &quot;10.0.0.0/16&quot;<br>}<br><br># Subnets IP addresses<br>variable &quot;subnet_cidrs&quot; {<br>    description = &quot;CIDR blocks for the subnets&quot;<br>    type = list(string)<br>    default = [&quot;10.0.1.0/24&quot;, &quot;10.0.2.0/24&quot;, &quot;10.0.3.0/24&quot;, &quot;10.0.4.0/24&quot;, &quot;10.0.5.0/24&quot;, &quot;10.0.6.0/24&quot;]<br>}<br><br># Availability zones<br>variable &quot;availability_zones&quot; {<br>    description = &quot;Availability zones for the subnets&quot;<br>    type = list(string)<br>    default = [&quot;eu-west-3a&quot;, &quot;eu-west-3b&quot;, &quot;eu-west-3c&quot;]<br><br>}<br><br># AWS Access Key and Secret Key<br>variable &quot;aws_access_key&quot; {<br>  description = &quot;AWS access key&quot;<br>  type = string<br>}<br>variable &quot;aws_secret_key&quot; {<br>  description = &quot;AWS secret key&quot;<br>  type = string<br>}</pre><pre># terraform.tfvars<br><br>aws_access_key = &quot;your-access-key&quot;<br>aws_secret_key = &quot;your-secret-key&quot;</pre><p>If you don’t have your access key and secret key and you don’t have configured AWS CLI, I suggest you to follow this guide:</p><p><a href="https://medium.com/@mohasina.clt/how-to-generate-access-keys-in-aws-af1a303dde42">How to Generate Access Keys in AWS</a></p><h3>Step 2: setup VPC and subnets</h3><pre># vpc.tf<br><br>resource &quot;aws_vpc&quot; &quot;my_new_vpc&quot; {<br>    cidr_block = var.vpc_cidr<br>    enable_dns_support = true<br>    enable_dns_hostnames = true<br>    tags = {<br>        Name = &quot;My new VPC&quot;<br>    }<br>}<br><br>resource &quot;aws_subnet&quot; &quot;public_subnet_1&quot; {<br>    vpc_id = aws_vpc.my_new_vpc.id<br>    cidr_block = var.subnet_cidrs[0]<br>    availability_zone = var.availability_zones[0]<br>    map_public_ip_on_launch = true # this makes the subnet public<br>    tags = {<br>        Name = &quot;Public subnet 1&quot;<br>    }<br>}<br><br>resource &quot;aws_subnet&quot; &quot;public_subnet_2&quot; {<br>    vpc_id = aws_vpc.my_new_vpc.id<br>    cidr_block = var.subnet_cidrs[1]<br>    availability_zone = var.availability_zones[1]<br>    map_public_ip_on_launch = true # this makes the subnet public<br>    tags = {<br>        Name = &quot;Public subnet 2&quot;<br>    }<br>}<br><br>resource &quot;aws_subnet&quot; &quot;public_subnet_3&quot; {<br>    vpc_id = aws_vpc.my_new_vpc.id<br>    cidr_block = var.subnet_cidrs[2]<br>    availability_zone = var.availability_zones[2]<br>    map_public_ip_on_launch = true # this makes the subnet public<br>    tags = {<br>        Name = &quot;Public subnet 3&quot;<br>    }<br>}<br><br>resource &quot;aws_subnet&quot; &quot;private_subnet_1&quot; {<br>    vpc_id = aws_vpc.my_new_vpc.id<br>    cidr_block = var.subnet_cidrs[3]<br>    availability_zone = var.availability_zones[0]<br>    map_public_ip_on_launch = false # this makes the subnet private<br>    tags = {<br>        Name = &quot;Private subnet 1&quot;<br>    }<br>}<br><br>resource &quot;aws_subnet&quot; &quot;private_subnet_2&quot; {<br>    vpc_id = aws_vpc.my_new_vpc.id<br>    cidr_block = var.subnet_cidrs[4]<br>    availability_zone = var.availability_zones[1]<br>    map_public_ip_on_launch = false # this makes the subnet private<br>    tags = {<br>        Name = &quot;Private subnet 2&quot;<br>    }<br>}<br><br>resource &quot;aws_subnet&quot; &quot;private_subnet_3&quot; {<br>    vpc_id = aws_vpc.my_new_vpc.id<br>    cidr_block = var.subnet_cidrs[5]<br>    availability_zone = var.availability_zones[2]<br>    map_public_ip_on_launch = false # this makes the subnet private<br>    tags = {<br>        Name = &quot;Private subnet 3&quot;<br>    }<br>}</pre><p>We setup our VPC and its public and private subnets. The attribute “map_public_ip_on_launch” in each subnet is the one that discriminates public subnets from private ones.</p><h3>Step 3: setup routing</h3><p>We need to define these actors in our scene:</p><ul><li>Internet gateway</li><li>NAT gateway</li><li>Public route table and private route table, with their associations to the corresponding subnets</li></ul><pre># routing.tf<br><br># Internet gateway: to allow incoming internet traffic to reach the ALB<br>resource &quot;aws_internet_gateway&quot; &quot;my_igw&quot; {<br>    vpc_id = aws_vpc.my_new_vpc.id<br>    tags = {<br>        Name = &quot;My IGW&quot;<br>    }<br>}<br><br># Public route table<br>resource &quot;aws_route_table&quot; &quot;public_route_table&quot; {<br>    vpc_id = aws_vpc.my_new_vpc.id<br>    # all the traffic should be routed to the internet gateway<br>    route {<br>        cidr_block = &quot;0.0.0.0/0&quot;<br>        gateway_id = aws_internet_gateway.my_igw.id<br>    }<br>    tags = {<br>        Name = &quot;Public route table&quot;<br>    }<br>    depends_on = [ aws_internet_gateway.my_igw ]<br>}<br><br>resource &quot;aws_route_table_association&quot; &quot;public_subnet_1_association&quot; {<br>    subnet_id      = aws_subnet.public_subnet_1.id<br>    route_table_id = aws_route_table.public_route_table.id<br>}<br><br>resource &quot;aws_route_table_association&quot; &quot;public_subnet_2_association&quot; {<br>    subnet_id      = aws_subnet.public_subnet_2.id<br>    route_table_id = aws_route_table.public_route_table.id<br>}<br><br>resource &quot;aws_route_table_association&quot; &quot;public_subnet_3_association&quot; {<br>    subnet_id      = aws_subnet.public_subnet_3.id<br>    route_table_id = aws_route_table.public_route_table.id<br>}<br><br># Private route table<br>resource &quot;aws_route_table&quot; &quot;private_route_table&quot; {<br>    vpc_id = aws_vpc.my_new_vpc.id<br>    # all the traffic should be routed to the NAT gateway<br>    route {<br>        cidr_block = &quot;0.0.0.0/0&quot;<br>        nat_gateway_id = aws_nat_gateway.my_nat_gateway.id<br>    }<br>    tags = {<br>        Name = &quot;Private route table&quot;<br>    }<br>    depends_on = [ aws_nat_gateway.my_nat_gateway ]<br>}<br><br>resource &quot;aws_route_table_association&quot; &quot;private_subnet_1_association&quot; {<br>    subnet_id      = aws_subnet.private_subnet_1.id<br>    route_table_id = aws_route_table.private_route_table.id<br>}<br><br>resource &quot;aws_route_table_association&quot; &quot;private_subnet_2_association&quot; {<br>    subnet_id      = aws_subnet.private_subnet_2.id<br>    route_table_id = aws_route_table.private_route_table.id<br>}<br><br>resource &quot;aws_route_table_association&quot; &quot;private_subnet_3_association&quot; {<br>    subnet_id      = aws_subnet.private_subnet_3.id<br>    route_table_id = aws_route_table.private_route_table.id<br>}<br><br># Allocate Elastic IP address for the NAT gateway<br>resource &quot;aws_eip&quot; &quot;my_eip&quot; {<br>    domain = &quot;vpc&quot;<br>    depends_on = [ aws_internet_gateway.my_igw ]<br>}<br><br># NAT gateway: to provide Internet access to EC2 instances<br>resource &quot;aws_nat_gateway&quot; &quot;my_nat_gateway&quot; {<br>    allocation_id = aws_eip.my_eip.id<br>    subnet_id     = aws_subnet.public_subnet_1.id<br>    tags = {<br>        Name = &quot;My NAT Gateway&quot;<br>    }<br>    depends_on = [ aws_internet_gateway.my_igw ]<br>}</pre><p>Note that we use “depends_on”. In Terraform, the “depends_on” meta-argument is used to specify explicit dependencies between resources. It&#39;s used to ensure that certain resources are created, updated, or destroyed in a specific order, based on the dependencies defined.</p><h3>Step 4: setup Security Groups</h3><p>Now we need to create Security Groups. Specifically, we define a Security Group for EC2 instances (or for the Auto Scaling Group) and a Security Group for the load balancer. Note that in the first one we are allowing HTTP traffic from the load balancer by specifying the other security group in the attribute “security_groups”.</p><pre># security.tf<br><br>resource &quot;aws_security_group&quot; &quot;ec2_sg&quot; {<br>    vpc_id = aws_vpc.my_new_vpc.id<br>    ingress {<br>        from_port = 80<br>        to_port = 80<br>        protocol = &quot;tcp&quot;<br>        security_groups = [ aws_security_group.alb_sg.id ]<br>    }<br>    egress {<br>        from_port = 0<br>        to_port = 0<br>        protocol = -1<br>        cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>        ipv6_cidr_blocks = [&quot;::/0&quot;]<br>    }<br>}<br><br>resource &quot;aws_security_group&quot; &quot;alb_sg&quot; {<br>    vpc_id = aws_vpc.my_new_vpc.id<br>    ingress {<br>        from_port = 80<br>        to_port = 80<br>        protocol = &quot;tcp&quot;<br>        cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>        ipv6_cidr_blocks = [&quot;::/0&quot;]<br>    }<br>    ingress {<br>        from_port = 443<br>        to_port = 443<br>        protocol = &quot;tcp&quot;<br>        cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>        ipv6_cidr_blocks = [&quot;::/0&quot;]<br>    }<br>    egress {<br>        from_port = 0<br>        to_port = 0<br>        protocol = -1<br>        cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>        ipv6_cidr_blocks = [&quot;::/0&quot;]<br>    }<br>}</pre><p>Moreover, both “cidr_blocks” and “ipv6_cidr_blocks” are specified to allow traffic from anywhere (ingress rule) and to anywhere (egress rule), the reason why we use both of them is that we permit access for both IPv4 and IPv6 addresses.</p><h3>Step 5: setup an Application Load Balancer (ALB)</h3><p>Then we define an Application Load Balancer (ALB) and its target group.</p><p>The target group is used to route traffic to EC2 instances on port 80 over HTTP and will be the resource that allows to connect the ALB to the Auto Scaling Group we will define later on.</p><p>Then we will define a resource “aws_lb_listener” that attaches a listener to the ALB to listen on port 80 for incoming HTTP traffic on the ALB and forwards incoming requests to the target group “my-target-group”.</p><p>Create a file “load_balancer.tf” and paste this code:</p><pre>resource &quot;aws_lb&quot; &quot;my_application_load_balancer&quot; {<br>    name               = &quot;my-application-load-balancer&quot;<br>    internal           = false<br>    load_balancer_type = &quot;application&quot;<br>    security_groups    = [aws_security_group.alb_sg.id]<br>    subnets            = [aws_subnet.public_subnet_1.id, aws_subnet.public_subnet_2.id, aws_subnet.public_subnet_3.id]<br>    enable_cross_zone_load_balancing = true<br>    enable_deletion_protection = false<br>    tags = {<br>        Name = &quot;My application load balancer&quot;<br>    }<br>    depends_on = [ aws_internet_gateway.my_igw ]<br>}<br><br>resource &quot;aws_lb_target_group&quot; &quot;my_target_group&quot; {<br>    name     = &quot;my-target-group&quot;<br>    port     = 80<br>    protocol = &quot;HTTP&quot;<br>    vpc_id   = aws_vpc.my_new_vpc.id<br>    target_type = &quot;instance&quot;<br>    health_check {<br>        path                = &quot;/&quot;<br>        protocol            = &quot;HTTP&quot;<br>        port                = &quot;traffic-port&quot;<br>        healthy_threshold   = 2<br>        unhealthy_threshold = 2<br>        timeout             = 4<br>        interval            = 5<br>    }<br>    tags = {<br>        Name = &quot;My target group&quot;<br>    }<br>}<br><br><br>resource &quot;aws_lb_listener&quot; &quot;my_listener&quot; {<br>    load_balancer_arn = aws_lb.my_application_load_balancer.arn<br>    port              = &quot;80&quot;<br>    protocol          = &quot;HTTP&quot;<br><br>    default_action {<br>        type             = &quot;forward&quot;<br>        target_group_arn = aws_lb_target_group.my_target_group.arn<br>    }<br>}</pre><h3>Step 5: deploy an Auto Scaling Group</h3><p>Now it is time to setup our Auto Scaling Group.</p><p>First of all I define a launch template, which is used by the Auto Scaling Group to define the configuration of the instances it launches, specifying the various parameters needed for launching EC2 instances, such as the Amazon Machine Image (AMI), instance type, security groups, key pair, and other launch parameters.</p><ul><li>In particular for the AMI I used Ubuntu (find your AMI ID according to the region you specified in the “provider” block before: <a href="https://cloud-images.ubuntu.com/locator/ec2/">https://cloud-images.ubuntu.com/locator/ec2/</a>).</li><li>For the instance type I choose “t3.micro”, which is included in the Free-Tier resources offered by AWS</li><li>Define a key name that will be used to access through SSH to the EC2 instances that will be managed by the Auto Scaling Group</li><li>Specify the security group created before in “vpc_security_group_ids”</li><li>Create a new bash script (user_data.sh), which consists of a list of commands that will run immediately after the EC2 instance creation. Specify its path in “user_data” in the launch template.</li></ul><pre># autoscaling.tf<br><br># Define a launch template<br>resource &quot;aws_launch_template&quot; &quot;my_launch_template&quot; {<br>    name_prefix = &quot;my_launch_template_&quot;<br>    image_id = &quot;ami-0322211ccfe5b6a20&quot; # Ubuntu 20.04, eu-west-3<br>    instance_type = &quot;t3.micro&quot;<br>    key_name = &quot;TF_key&quot;<br>    vpc_security_group_ids = [ aws_security_group.ec2_sg.id ]<br>    user_data = filebase64(&quot;user_data.sh&quot;)<br>}<br><br># Generate an RSA private key<br>resource &quot;tls_private_key&quot; &quot;rsa&quot; {<br>    algorithm = &quot;RSA&quot;<br>    rsa_bits = 4096<br>}<br><br># Define an AWS key pair resource named &quot;TF_key&quot;.<br># It creates an SSH key pair where the public key is derived<br># from the RSA private key generated in the previous block.<br># This key pair can be used to authenticate with EC2 instances launched in AWS.<br>resource &quot;aws_key_pair&quot; &quot;TF_key&quot; {<br>    key_name = &quot;TF_key&quot;<br>    public_key = tls_private_key.rsa.public_key_openssh<br>}<br><br># Defines a local file resource named &quot;private_key&quot;.<br># It writes the content of the RSA private key generated in<br># the first block to a file named &quot;tfkey&quot; on the local filesystem.<br>resource &quot;local_file&quot; &quot;private_key&quot; {<br>    content = tls_private_key.rsa.private_key_pem<br>    filename = &quot;tfkey&quot;<br>}<br><br>resource &quot;aws_autoscaling_group&quot; &quot;my_asg&quot; {<br>    vpc_zone_identifier = [aws_subnet.private_subnet_1.id, aws_subnet.private_subnet_2.id, aws_subnet.private_subnet_3.id]<br>    <br>    # Minimum number of instances the Auto Scaling group should maintain. <br>    min_size = 1<br><br>    # Maximum number of instances the Auto Scaling group can scale up to<br>    max_size = 2<br><br>    # Specifies the desired number of instances that the Auto Scaling group<br>    # should maintain. It is set to 1, which means the Auto Scaling group will<br>    # initially launch and maintain one instance.<br>    desired_capacity = 1<br><br>    # Associate with ALB target group<br>    target_group_arns = [aws_lb_target_group.my_target_group.arn]<br><br>    tag {<br>        key = &quot;Name&quot;<br>        value = &quot;My ASG&quot;<br>        propagate_at_launch = true<br>    }<br><br>    # Specify the launch template defined before<br>    launch_template {<br>        id = aws_launch_template.my_launch_template.id<br>        version = &quot;$Latest&quot;<br>    }<br>}<br><br># Policy that increases the number of instances by 1 when triggered.<br># This policy type is &quot;SimpleScaling&quot;, meaning it directly adjusts<br># the desired capacity of the Auto Scaling group.<br>resource &quot;aws_autoscaling_policy&quot; &quot;increase_ec2&quot; {<br>    name                   = &quot;increase-ec2&quot;<br>    scaling_adjustment     = 1<br>    adjustment_type        = &quot;ChangeInCapacity&quot;<br>    cooldown               = 300<br>    autoscaling_group_name = aws_autoscaling_group.my_asg.name<br>    policy_type = &quot;SimpleScaling&quot;<br>    <br>}<br><br># Policy that decreases the number of instances by 1 when triggered,<br># also using the &quot;SimpleScaling&quot; policy type.<br>resource &quot;aws_autoscaling_policy&quot; &quot;reduce_ec2&quot; {<br>    name                   = &quot;reduce-ec2&quot;<br>    scaling_adjustment     = -1<br>    adjustment_type        = &quot;ChangeInCapacity&quot;<br>    cooldown               = 300<br>    autoscaling_group_name = aws_autoscaling_group.my_asg.name<br>    policy_type = &quot;SimpleScaling&quot;<br>}<br><br># Attach the Auto Scaling Group to the ALB target group<br>resource &quot;aws_autoscaling_attachment&quot; &quot;my_asg_attachment&quot; {<br>    autoscaling_group_name = aws_autoscaling_group.my_asg.id<br>    lb_target_group_arn = aws_lb_target_group.my_target_group.arn<br>}</pre><p><em>user_data.sh</em>:</p><pre>#!/bin/bash<br>sudo apt update -y<br>sudo apt install -y nginx<br>sudo systemctl start nginx<br>sudo systemctl enable nginx<br>echo &quot;Quanto è buono il cannolo&quot; &gt; /var/www/html/index.html</pre><h3>Step 6: setup CloudWatch Scaling Alarms</h3><p>Then, in a file “cloudwatch.tf” we define the CloudWatch Alarms. I leave some comments for the first one, which will be valid also for the other as well.</p><pre>resource &quot;aws_cloudwatch_metric_alarm&quot; &quot;increase_ec2_alarm&quot; {<br>  alarm_name                = &quot;increase-ec2-alarm&quot;<br>  # The alarm will trigger if the CPU utilization is greater than or equal<br>  # to the specified threshold<br>  comparison_operator       = &quot;GreaterThanOrEqualToThreshold&quot;<br>  # Number of periods over which the alarm condition must be met to trigger<br>  # the alarm. It is set to 2, meaning the CPU utilization must remain above<br>  # the threshold for two consecutive periods<br>  evaluation_periods        = 2<br>  # Name of the metric to monitor. Here, it&#39;s &quot;CPUUtilization&quot;,<br>  # indicating the CPU utilization metric of EC2 instances<br>  metric_name               = &quot;CPUUtilization&quot;<br>  namespace                 = &quot;AWS/EC2&quot;<br>  # The alarm evaluates CPU utilization data over a period of 120 seconds (2 minutes)<br>  period                    = 120<br>  # Average CPU utilization<br>  statistic                 = &quot;Average&quot;<br>  # Threshold value that, when crossed, triggers the alarm<br>  threshold                 = 70<br>  alarm_description         = &quot;This metric monitors ec2 cpu utilization, if it goes above 70% for 2 periods it will trigger an alarm.&quot;<br>  insufficient_data_actions = []<br><br>  # Actions to take when the alarm state changes to &quot;ALARM&quot;.<br>  # When the alarm triggers, it will send notifications to the SNS topic<br>  # and execute the specified Auto Scaling policy.<br>  alarm_actions = [<br>      &quot;${aws_sns_topic.my_sns_topic.arn}&quot;,<br>      &quot;${aws_autoscaling_policy.increase_ec2.arn}&quot;<br>  ]<br>}<br><br>resource &quot;aws_cloudwatch_metric_alarm&quot; &quot;reduce_ec2_alarm&quot; {<br>  alarm_name                = &quot;reduce-ec2-alarm&quot;<br>  comparison_operator       = &quot;LessThanOrEqualToThreshold&quot;<br>  evaluation_periods        = 2<br>  metric_name               = &quot;CPUUtilization&quot;<br>  namespace                 = &quot;AWS/EC2&quot;<br>  period                    = 120<br>  statistic                 = &quot;Average&quot;<br>  threshold                 = 40<br>  alarm_description         = &quot;This metric monitors ec2 cpu utilization, if it goes below 40% for 2 periods it will trigger an alarm.&quot;<br>  insufficient_data_actions = []<br><br>  alarm_actions = [<br>      &quot;${aws_sns_topic.my_sns_topic.arn}&quot;,<br>      &quot;${aws_autoscaling_policy.increase_ec2.arn}&quot;<br>  ]<br>}</pre><h3>Step 7: define an SNS topic to receive emails</h3><p>In a file “sns.tf” we can define an SNS topic to tell to receive an email when the alarm changes to the state “ALARM”.</p><pre>resource &quot;aws_sns_topic&quot; &quot;my_sns_topic&quot; {<br>  name = &quot;cpu_alarm_topic&quot;<br>}<br><br>resource &quot;aws_sns_topic_subscription&quot; &quot;my_sns_topic_subscription&quot; {<br>  topic_arn = aws_sns_topic.my_sns_topic.arn<br>  protocol  = &quot;email&quot;<br>  endpoint  = &quot;example@gmail.com&quot;<br>}</pre><h3>Conclusion</h3><p>That’s all! You have configured a system that monitors an Auto Scaling Group in AWS with some policies that scales up or down automatically based on average CPU utilization of EC2 instances. Run the commands to deploy your infrastructure:</p><pre>terraform init<br>terraform plan<br>terraform apply</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dbd83211fd17" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced CI/CD pipeline with production and development branches, using Terraform]]></title>
            <link>https://medium.com/@mattiamazzari/advanced-ci-cd-pipeline-with-production-and-development-branches-using-terraform-607e82782f50?source=rss-e9f146485d51------2</link>
            <guid isPermaLink="false">https://medium.com/p/607e82782f50</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[aws-codedeploy]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[aws-codepipeline]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Mattiamazzari]]></dc:creator>
            <pubDate>Fri, 12 Apr 2024 17:54:30 GMT</pubDate>
            <atom:updated>2024-04-12T18:10:48.467Z</atom:updated>
            <content:encoded><![CDATA[<p>This project is all about deploying a realistic CI/CD setup. Organizations usually have</p><ul><li>a production environment which is the server or services that actually serves the code or the application to the end client</li><li>a development environment which is where developers can upload code where they can test the application and test that everything works, then they can deploy that code into the production environment</li></ul><p>So we will have:</p><ul><li>Two servers (EC2 instances)</li><li>Two pipelines in CodePipeline</li><li>Two CodeDeploy applications</li><li>Two branches on the GitHub repository: <em>main</em> (production branch) and <em>dev</em> (development branch)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*9HpbWplgw5fA6S7ueJUa-A.png" /></figure><p>The idea here is that when you deploy or upload to the development branch on GitHub, it triggers the development pipeline which uploads to the development EC2 server. Then, once we’re happy, we can merge that branch to the main branch on GitHub which will trigger the production pipeline that finally deploys to the EC2 production server.</p><h3>Step 1: setup the GitHub repository</h3><p>Create a GitHub repository and clone it. We need to populate it, you can download this zip which contains a basic static web page:</p><pre>wget https://github.com/mattiamazzari/advanced-ci-cd-pipeline/archive/refs/heads/main.zip</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LRryPgmUC6mSuJgxtz0Blw.png" /></figure><p>Copy the files into your repository, commit and push. Then create another branch called “dev” and push the same code in that branch</p><pre>git checkout -b dev<br>git add .<br>git commit -m &quot;initial commit&quot;<br>git push origin dev</pre><p>The structure of the code you downloaded is the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*4Tnqf2vHWivmrhrn3w9STw.png" /></figure><p>The most important file among the ones listed is <strong>appspec.yml</strong>:</p><pre>version: 0.0<br>os: linux<br>files:<br>  - source: /index.html<br>    destination: /usr/share/nginx/html/<br>hooks:<br>  BeforeInstall:<br>    - location: scripts/install_dependencies<br>      timeout: 300<br>      runas: root<br>    - location: scripts/start_server<br>      timeout: 300<br>      runas: root<br>  ApplicationStop:<br>    - location: scripts/stop_server<br>      timeout: 300<br>      runas: root</pre><p>Basically we are telling CodeDeploy how to deploy our application. Your deployment will call different hooks while deploying your application (it will pass through different stages), in this case BeforeInstall and ApplicationStop. For each hook we tell the location of a bash script inside the scripts folder; they will install Nginx, start or stop the web service.</p><h3>Step 2: setup Terraform provider and variables</h3><p>Create a new folder that will contain your Terraform project and the first files you need to create are:</p><ul><li>provider.tf</li></ul><pre>provider &quot;aws&quot; {<br>  region = &quot;eu-west-3&quot;<br>  access_key = var.aws_access_key<br>  secret_key = var.aws_secret_key<br>}<br><br>terraform {<br>    required_providers {<br>        aws = {<br>        source  = &quot;hashicorp/aws&quot;<br>        version = &quot;~&gt; 5.0&quot;<br>        }<br>    }<br>}</pre><ul><li>variables.tf</li></ul><pre>variable &quot;aws_access_key&quot; {<br>  description = &quot;AWS access key&quot;<br>  type = string<br>}<br><br>variable &quot;aws_secret_key&quot; {<br>  description = &quot;AWS secret key&quot;<br>  type = string<br>}</pre><ul><li>terraform.tfvars</li></ul><pre>aws_access_key = &quot;your-access-key&quot;<br>aws_secret_key = &quot;your-secret-key&quot;</pre><p>If you don’t have generated your access keys yet, follow this guide.</p><p><a href="https://medium.com/@mohasina.clt/how-to-generate-access-keys-in-aws-af1a303dde42">How to Generate Access Keys in AWS</a></p><p>Also you need to choose an AWS region, choose the one you prefer and that has the lowest latency for you.</p><h3>Step 3: define the default VPC</h3><p>We will use the default VPC provided by AWS. We need to define it in a file called “vpc.tf”:</p><pre>resource &quot;aws_default_vpc&quot; &quot;default&quot; {<br>  tags = {<br>    Name = &quot;Default VPC&quot;<br>  }<br>}</pre><h3>Step: create a Security Group</h3><p>Then we need a security group to be able to SSH our EC2 instances and access to them through the browser. So create a file named “security.tf” and paste this code:</p><pre>resource &quot;aws_security_group&quot; &quot;ec2_sg&quot; {<br>    vpc_id = aws_default_vpc.default.id<br>    ingress {<br>        from_port = 80<br>        to_port = 80<br>        protocol = &quot;tcp&quot;<br>        cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>        ipv6_cidr_blocks = [&quot;::/0&quot;]<br>    }<br>    ingress {<br>        from_port = 22<br>        to_port = 22<br>        protocol = &quot;tcp&quot;<br>        cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>        ipv6_cidr_blocks = [&quot;::/0&quot;]<br>    }<br>    egress {<br>        from_port = 0<br>        to_port = 0<br>        protocol = -1<br>        cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>        ipv6_cidr_blocks = [&quot;::/0&quot;]<br>    }<br>}</pre><p>We are defining one ingress rule to allow HTTP access (port 80), another one for SSH (port 22) and an egress rule to allow the EC2 instance to reach anywhere.</p><h3>Step 4: setup EC2 instances</h3><p>Create your Production and Development EC2 instances.</p><ol><li>For this project I am using Amazon Linux AMI 2023. Choose an AMI according to your region. In my case I chose an Amazon Linux 2023 AMI for eu-west-3. For Amazon Linux, you can pick one of the AMIs listed when you launch an EC2 instance from the AWS management console. For Ubuntu, you can find it here searching for your region code: <a href="https://cloud-images.ubuntu.com/locator/ec2/">https://cloud-images.ubuntu.com/locator/ec2/</a></li></ol><p>2. A key-pair is defined to SSH the instances.</p><p>3. We attach the security group defined before and assign a tag name.</p><pre>resource &quot;aws_instance&quot; &quot;nginx_instance_prod&quot; {<br>    ami = &quot;ami-0facbf2a36e11b9dd&quot; # Amazon Linux 2023 AMI, eu-west-3<br>    instance_type = &quot;t3.micro&quot;<br>    key_name = &quot;TF_key&quot;<br>    user_data = filebase64(&quot;user_data.sh&quot;)<br>    iam_instance_profile = aws_iam_instance_profile.ec2_instance_profile.name<br>    vpc_security_group_ids = [aws_security_group.ec2_sg.id]<br>    tags = {<br>        Name = &quot;Production EC2&quot;<br>    }<br>}<br><br>resource &quot;aws_instance&quot; &quot;nginx_instance_dev&quot; {<br>    ami = &quot;ami-0facbf2a36e11b9dd&quot; # Amazon Linux 2023 AMI, eu-west-3<br>    instance_type = &quot;t3.micro&quot;<br>    key_name = &quot;TF_key&quot;<br>    user_data = filebase64(&quot;user_data.sh&quot;)<br>    iam_instance_profile = aws_iam_instance_profile.ec2_instance_profile.name<br>    vpc_security_group_ids = [aws_security_group.ec2_sg.id]<br>    tags = {<br>        Name = &quot;Development EC2&quot;<br>    }<br>}<br><br>resource &quot;tls_private_key&quot; &quot;rsa&quot; {<br>    algorithm = &quot;RSA&quot;<br>    rsa_bits = 4096<br>}<br><br>resource &quot;aws_key_pair&quot; &quot;TF_key&quot; {<br>    key_name = &quot;TF_key&quot;<br>    public_key = tls_private_key.rsa.public_key_openssh<br>}<br><br>resource &quot;local_file&quot; &quot;private_key&quot; {<br>    content = tls_private_key.rsa.private_key_pem<br>    filename = &quot;tfkey&quot;<br>}</pre><p>4. Define a file named “user_data.sh” that will install the CodeDeploy agent.</p><pre>#!/bin/bash<br><br># Install the CodeDeploy agent<br>sudo yum install -y ruby<br>sudo yum install -y wget<br>cd /home/ubuntu<br>wget https://aws-codedeploy-eu-west-3.s3.eu-west-3.amazonaws.com/latest/install<br>chmod +x ./install<br>sudo ./install auto<br><br># Remove the default index.html file provided by Nginx<br>cd ../../usr/share/nginx/html<br>sudo rm -rf index.html</pre><p>Since we need to add a new role that we will assign to the EC2 instances and attach a policy “AmazonEC2RoleforAWSCodeDeploy”, we create a file “iam.tf” in which we allow “ec2.amazonaws.com” to assume roles (this kind of policy has to be defined also for CodeDeploy and CodePipeline, changing the corresponding identifier, you will see after).</p><pre>data &quot;aws_iam_policy_document&quot; &quot;assume_role_ec2&quot; {<br>  statement {<br>    effect = &quot;Allow&quot;<br><br>    principals {<br>      type        = &quot;Service&quot;<br>      identifiers = [&quot;ec2.amazonaws.com&quot;]<br>    }<br><br>    actions = [&quot;sts:AssumeRole&quot;]<br>  <br>  }<br>}<br><br>resource &quot;aws_iam_role&quot; &quot;ec2_role_2024&quot; {<br>  name = &quot;ec2_role_2024&quot;<br>  assume_role_policy = data.aws_iam_policy_document.assume_role_ec2.json<br>}<br><br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;AmazonEC2RoleforAWSCodeDeploy&quot; {<br>  policy_arn = &quot;arn:aws:iam::aws:policy/service-role/AmazonEC2RoleforAWSCodeDeploy&quot;<br>  role       = aws_iam_role.ec2_role_2024.name<br>}<br><br>resource &quot;aws_iam_instance_profile&quot; &quot;ec2_instance_profile&quot; {<br>  name = &quot;ec2_instance_profile&quot;<br>  role = aws_iam_role.ec2_role_2024.name<br>}</pre><h3>Step 5: setup CodeDeploy</h3><p>The next step is to define create a CodeDeploy application and define a deployment group attached to it, but first we need to add a new IAM service role and attach a policy named “AWSCodeDeployRole” to it in “iam.tf”:</p><pre>data &quot;aws_iam_policy_document&quot; &quot;assume_role_codedeploy&quot; {<br>  statement {<br>    effect = &quot;Allow&quot;<br><br>    principals {<br>      type        = &quot;Service&quot;<br>      identifiers = [&quot;codedeploy.amazonaws.com&quot;]<br>    }<br><br>    actions = [&quot;sts:AssumeRole&quot;]<br>  }<br>}<br><br>resource &quot;aws_iam_role&quot; &quot;service-role-codedeploy&quot; {<br>  name               = &quot;service-role-codedeploy&quot;<br>  assume_role_policy = data.aws_iam_policy_document.assume_role_codedeploy.json<br>}<br><br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;AWSCodeDeployRole&quot; {<br>  policy_arn = &quot;arn:aws:iam::aws:policy/service-role/AWSCodeDeployRole&quot;<br>  role       = aws_iam_role.service-role-codedeploy.name<br>}</pre><p>Then, we create a file “deploy.tf” in which we define the CodeDeploy application and a deployment group:</p><pre># Development<br>resource &quot;aws_codedeploy_app&quot; &quot;myapp_dev&quot; {<br>  compute_platform = &quot;Server&quot; # corresponds to &quot;EC2/On-Premises&quot; in the console<br>  name             = &quot;myapp_dev&quot;<br>}<br><br>resource &quot;aws_codedeploy_deployment_group&quot; &quot;deployment_group_dev&quot; {<br>  app_name     = aws_codedeploy_app.myapp_dev.name<br>  deployment_group_name = &quot;deployment_group_dev&quot;<br>  service_role_arn = aws_iam_role.service-role-codedeploy.arn<br>  deployment_config_name = &quot;CodeDeployDefault.AllAtOnce&quot;<br><br>  ec2_tag_set {<br>        ec2_tag_filter {<br>        key   = &quot;Name&quot;<br>        type  = &quot;KEY_AND_VALUE&quot;<br>        value = &quot;Development EC2&quot;<br>        }<br>  }<br><br>  auto_rollback_configuration {<br>    enabled = true<br>    events  = [&quot;DEPLOYMENT_FAILURE&quot;]<br>  }<br>}<br><br># Production<br>resource &quot;aws_codedeploy_app&quot; &quot;myapp_prod&quot; {<br>  compute_platform = &quot;Server&quot; # corresponds to &quot;EC2/On-Premises&quot; in the console<br>  name             = &quot;myapp_prod&quot;<br>}<br><br>resource &quot;aws_codedeploy_deployment_group&quot; &quot;deployment_group_prod&quot; {<br>  app_name     = aws_codedeploy_app.myapp_prod.name<br>  deployment_group_name = &quot;deployment_group_prod&quot;<br>  service_role_arn = aws_iam_role.service-role-codedeploy.arn<br>  deployment_config_name = &quot;CodeDeployDefault.AllAtOnce&quot;<br><br>  ec2_tag_set {<br>        ec2_tag_filter {<br>        key   = &quot;Name&quot;<br>        type  = &quot;KEY_AND_VALUE&quot;<br>        value = &quot;Production EC2&quot;<br>        }<br>  }<br><br>  auto_rollback_configuration {<br>    enabled = true<br>    events  = [&quot;DEPLOYMENT_FAILURE&quot;]<br>  }<br>}</pre><h3>Step 6: setup CodePipeline</h3><p>First, we need to define a new IAM role to assign to the pipelines, so in “iam.tf” we add the following:</p><pre>data &quot;aws_iam_policy_document&quot; &quot;assume_role_codepipeline&quot; {<br>  statement {<br>    effect = &quot;Allow&quot;<br><br>    principals {<br>      type        = &quot;Service&quot;<br>      identifiers = [&quot;codepipeline.amazonaws.com&quot;]<br>    }<br><br>    actions = [&quot;sts:AssumeRole&quot;]<br>  }<br>}<br><br>resource &quot;aws_iam_role&quot; &quot;service-role-codepipeline&quot; {<br>  name               = &quot;service-role-codepipeline&quot;<br>  assume_role_policy = data.aws_iam_policy_document.assume_role_codepipeline.json<br>}<br><br># CodePipeline policy: allowing access to S3, CodeStarConnections<br># and CodeBuild<br>data &quot;aws_iam_policy_document&quot; &quot;codepipeline_policy&quot; {<br>  statement {<br>    effect = &quot;Allow&quot;<br><br>    actions = [<br>      &quot;s3:GetObject&quot;,<br>      &quot;s3:GetObjectVersion&quot;,<br>      &quot;s3:GetBucketVersioning&quot;,<br>      &quot;s3:PutObjectAcl&quot;,<br>      &quot;s3:PutObject&quot;,<br>    ]<br><br>    resources = [<br>      aws_s3_bucket.codepipeline_bucket_dev.arn,<br>      &quot;${aws_s3_bucket.codepipeline_bucket_dev.arn}/*&quot;,<br>      aws_s3_bucket.codepipeline_bucket_prod.arn,<br>      &quot;${aws_s3_bucket.codepipeline_bucket_prod.arn}/*&quot;<br>    ]<br>  }<br>  # we will skip the build stage, these permissions are not necessary<br>  # for our simple static website, but this is good to have<br>  statement {<br>    effect = &quot;Allow&quot;<br>    actions = [<br>      &quot;codebuild:BatchGetBuilds&quot;,<br>      &quot;codebuild:StartBuild&quot;,<br>      &quot;codebuild:StopBuild&quot;<br>    ]<br><br>    resources = [&quot;*&quot;]<br>  }<br><br>  statement {<br>    sid = &quot;AllowCodedepoloy&quot;<br>    effect = &quot;Allow&quot;<br><br>    actions = [<br>      &quot;codedeploy:CreateDeployment&quot;,<br>      &quot;codedeploy:GetApplication&quot;,<br>      &quot;codedeploy:GetApplicationRevision&quot;,<br>      &quot;codedeploy:GetDeployment&quot;,<br>      &quot;codedeploy:GetDeploymentConfig&quot;,<br>      &quot;codedeploy:RegisterApplicationRevision&quot;<br>    ]<br>    resources = [&quot;*&quot;]<br>  }<br><br>  statement {<br>    sid = &quot;AllowResources&quot;<br>    effect = &quot;Allow&quot;<br><br>    actions = [<br>      &quot;elasticbeanstalk:*&quot;,<br>      &quot;ec2:*&quot;,<br>      &quot;elasticloadbalancing:*&quot;,<br>      &quot;autoscaling:*&quot;,<br>      &quot;cloudwatch:*&quot;,<br>      &quot;s3:*&quot;,<br>      &quot;sns:*&quot;,<br>      &quot;cloudformation:*&quot;,<br>      &quot;rds:*&quot;,<br>      &quot;sqs:*&quot;,<br>      &quot;ecs:*&quot;,<br>      &quot;opsworks:*&quot;,<br>      &quot;devicefarm:*&quot;,<br>      &quot;servicecatalog:*&quot;,<br>      &quot;iam:PassRole&quot;<br>    ]<br>    resources = [&quot;*&quot;]<br>  }<br><br>  statement {<br>    # Allow CodeCommit (only if we use CodeCommit instead of GitHub)<br>    effect = &quot;Allow&quot;<br>    actions = [<br>      &quot;codecommit:GetBranch&quot;,<br>      &quot;codecommit:GetCommit&quot;,<br>      &quot;codecommit:GetUploadArchiveStatus&quot;,<br>      &quot;codecommit:GetRepository&quot;,<br>      &quot;codecommit:CancelUploadArchive&quot;,<br>      &quot;codecommit:ListBranches&quot;,<br>      &quot;codecommit:ListRepositories&quot;,<br>      &quot;codecommit:UploadArchive&quot;,<br>      &quot;codecommit:GitPull&quot;,<br>      &quot;codecommit:GitPush&quot;<br>    ]<br><br>    resources = [&quot;${aws_codecommit_repository.my_repository.arn}&quot;]<br>  }<br>}<br><br>resource &quot;aws_iam_role_policy&quot; &quot;codepipeline_policy&quot; {<br>  name   = &quot;codepipeline_policy&quot;<br>  role   = aws_iam_role.service-role-codepipeline.id<br>  policy = data.aws_iam_policy_document.codepipeline_policy.json<br>}</pre><p>Then, we create two buckets that CodePipeline relies upon to store different versions of your application code, build outputs, and other artifacts generated during the pipeline execution. So we create a file named “storage.tf”:</p><pre>resource &quot;aws_s3_bucket&quot; &quot;codepipeline_bucket_dev&quot; {<br>  bucket = &quot;my-codepipeline-bucket-2024-v2-dev&quot;<br>}<br><br>resource &quot;aws_s3_bucket_public_access_block&quot; &quot;codepipeline_bucket_dev_pab&quot; {<br>  bucket = aws_s3_bucket.codepipeline_bucket_dev.id<br><br>  block_public_acls       = true<br>  block_public_policy     = true<br>  ignore_public_acls      = true<br>  restrict_public_buckets = true<br>}<br><br>resource &quot;aws_s3_bucket&quot; &quot;codepipeline_bucket_prod&quot; {<br>  bucket = &quot;my-codepipeline-bucket-2024-v2-prod&quot;<br>}<br><br>resource &quot;aws_s3_bucket_public_access_block&quot; &quot;codepipeline_bucket_prod_pab&quot; {<br>  bucket = aws_s3_bucket.codepipeline_bucket_prod.id<br><br>  block_public_acls       = true<br>  block_public_policy     = true<br>  ignore_public_acls      = true<br>  restrict_public_buckets = true<br>}</pre><p>Define a file “pipeline.tf” in which we define two pipelines: a development one and a production one.</p><pre>resource &quot;aws_codepipeline&quot; &quot;pipeline_dev&quot; {<br>    name     = &quot;pipeline_dev&quot;<br>    role_arn = aws_iam_role.service-role-codepipeline.arn<br>    pipeline_type = &quot;V2&quot;<br>    <br>    artifact_store {<br>        location = aws_s3_bucket.codepipeline_bucket_dev.bucket<br>        type     = &quot;S3&quot;<br>    }<br>    <br>    stage {<br>        name = &quot;Source&quot;<br>    <br>        action {<br>            name             = &quot;Source&quot;<br>            category         = &quot;Source&quot;<br>            owner            = &quot;AWS&quot;<br>            provider         = &quot;CodeStarSourceConnection&quot;<br>            version          = &quot;1&quot;<br>            output_artifacts = [&quot;source_output&quot;]<br>    <br>            configuration = {<br>                ConnectionArn    = aws_codestarconnections_connection.example.arn<br>                FullRepositoryId = &quot;mattiamazzari/advanced-ci-cd-pipeline&quot; # your repository<br>                BranchName       = &quot;dev&quot; # development branch<br>            }<br>        }<br>    }<br>    <br>    stage {<br>        name = &quot;Deploy&quot;<br>    <br>        action {<br>            name            = &quot;Deploy&quot;<br>            category        = &quot;Deploy&quot;<br>            owner           = &quot;AWS&quot;<br>            provider        = &quot;CodeDeploy&quot;<br>            version         = &quot;1&quot;<br>            input_artifacts = [&quot;source_output&quot;]<br>        <br>            configuration = {<br>                ApplicationName = aws_codedeploy_app.myapp_dev.name<br>                DeploymentGroupName = aws_codedeploy_deployment_group.deployment_group_dev.deployment_group_name<br>            }<br>        }<br>    }<br>}<br><br>resource &quot;aws_codepipeline&quot; &quot;pipeline_prod&quot; {<br>    name     = &quot;pipeline_prod&quot;<br>    role_arn = aws_iam_role.service-role-codepipeline.arn<br>    pipeline_type = &quot;V2&quot;<br>    <br>    artifact_store {<br>        location = aws_s3_bucket.codepipeline_bucket_prod.bucket<br>        type     = &quot;S3&quot;<br>    }<br>    <br>    stage {<br>        name = &quot;Source&quot;<br>    <br>        action {<br>            name             = &quot;Source&quot;<br>            category         = &quot;Source&quot;<br>            owner            = &quot;AWS&quot;<br>            provider         = &quot;CodeStarSourceConnection&quot;<br>            version          = &quot;1&quot;<br>            output_artifacts = [&quot;source_output&quot;]<br>    <br>            configuration = {<br>                ConnectionArn    = aws_codestarconnections_connection.example.arn<br>                FullRepositoryId = &quot;mattiamazzari/advanced-ci-cd-pipeline&quot; # your repository<br>                BranchName       = &quot;main&quot; # production branch<br>            }<br>        }<br>    }<br>    <br>    stage {<br>        name = &quot;Deploy&quot;<br>    <br>        action {<br>            name            = &quot;Deploy&quot;<br>            category        = &quot;Deploy&quot;<br>            owner           = &quot;AWS&quot;<br>            provider        = &quot;CodeDeploy&quot;<br>            version         = &quot;1&quot;<br>            input_artifacts = [&quot;source_output&quot;]<br>        <br>            configuration = {<br>                ApplicationName = aws_codedeploy_app.myapp_prod.name<br>                DeploymentGroupName = aws_codedeploy_deployment_group.deployment_group_prod.deployment_group_name<br>            }<br>        }<br>    }<br>}<br><br>resource &quot;aws_codestarconnections_connection&quot; &quot;example&quot; {<br>  name          = &quot;example-connection&quot;<br>  provider_type = &quot;GitHub&quot;<br>}</pre><p>Note that we need to create a CodeStar connection to connect to GitHub and link our repository. When we will perform “terraform apply”, it will create the connection and leave it in a <em>PENDING</em> state, we will need to complete the configuration in the AWS management console. We go to CodePipeline, select our pipeline, go to “Edit: Source” and click on the pencil icon. Then “Update pending state” &gt; “Install a new app”, select your repository, connect. At the end you shoud see a message “Ready to connect”.</p><h3>Step 7: deploy your infrastructure</h3><p>That’s all! Now we are ready to run:</p><pre>terraform init<br>terraform plan<br>terraform apply -auto-approve</pre><h3>Step 8: testing</h3><p>Once your pipelines are ready, to see if everything works, in your development branch you can apply a minor change to the index.html file in your repository and push it. Then you can do a merge into the production branch and this will trigger the production pipeline and if you search the public IP address of your production EC2 instance you will see that the change has been applied.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*Ew3c7P3Kq4kO6HzKRbX0Hw.png" /></figure><h3>Troubleshooting:</h3><p>If the deployment stage fails, check that your CodeDeploy agent is active and running. In particular open the terminal in your project directory and SSH your EC2 instance:</p><pre>ssh -i tfkey ec2-user@ec2-13-37-46-17.eu-west-3.compute.amazonaws.com</pre><p>Note that you need to replace “13–37–46–17” with the IP address of your EC2 instance and “eu-west-3” with the region you selected.</p><p>After having logged in, run:</p><pre>sudo systemctl status codedeploy-agent</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=607e82782f50" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>