<?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 Dasanirban on Medium]]></title>
        <description><![CDATA[Stories by Dasanirban on Medium]]></description>
        <link>https://medium.com/@dasanirban834?source=rss-59a29a5892be------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*V5bLMaqOSlmFHaGG</url>
            <title>Stories by Dasanirban on Medium</title>
            <link>https://medium.com/@dasanirban834?source=rss-59a29a5892be------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 02:12:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dasanirban834/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[Automatic Troubleshooting & ITSM System using EventBridge and Lambda]]></title>
            <link>https://medium.com/@dasanirban834/automatic-troubleshooting-itsm-system-using-eventbridge-and-lambda-d8b60da2125f?source=rss-59a29a5892be------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8b60da2125f</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Dasanirban]]></dc:creator>
            <pubDate>Fri, 23 Aug 2024 17:13:46 GMT</pubDate>
            <atom:updated>2024-08-23T17:13:46.138Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*pSCy0pyaeHXEDiAb.png" /></figure><h3>Introduction :</h3><p>Folks, In IT Operations, it’s a very generic task to monitor server metrices like utilization of cpu/memory and disk or filesystems, but in case any of the metrics gets triggered to be critical, then dedicated persons need to perform some basic troubleshooting by logging into server and find out the initial cause of utilization which person has to perform multiple times if he gets multiple same alert that creates boredom and not productive at all. So as a workaround, there can be a system developed which will react once alarm gets triggered and act on those instances by executing few basic troubleshooting commands. Just to summarize the problem statement and expectation -</p><h3>Problem Statement :</h3><p>Develop a system which will fulfill below expectations -</p><ul><li>Each EC2 instances should be monitored by CloudWatch.</li><li>Once alarm gets triggered, something has to be there which will login to that affected EC2 instance and perform some basic troubleshooting commands.</li><li>Then, create a JIRA issue to document that incident and add the output of commands in comment section.</li><li>Then, send an automatic email with providing all alarm details and JIRA issue details.</li></ul><p>Please find this link for full blogs -&gt; <a href="https://dev.to/aws-builders/automatic-troubleshooting-itsm-system-using-eventbridge-and-lambda-nd">https://dev.to/aws-builders/automatic-troubleshooting-itsm-system-using-eventbridge-and-lambda-nd</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8b60da2125f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How CloudWatch Network Monitor Performs Connectivity Test to EC2 Instances]]></title>
            <link>https://aws.plainenglish.io/how-cloudwatch-network-monitor-performs-connectivity-test-to-ec2-instances-2b1b9f01dedc?source=rss-59a29a5892be------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b1b9f01dedc</guid>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[cloudwatch]]></category>
            <category><![CDATA[eventbridge]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Dasanirban]]></dc:creator>
            <pubDate>Mon, 01 Jan 2024 13:18:05 GMT</pubDate>
            <atom:updated>2024-01-02T08:51:27.121Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction:</h3><p>Amazon Web Services recently released a feature in CloudWatch “Network Monitor” which is responsible to perform connectivity tests between source and destination. This feature doesn’t require any manual user intervention, it’s a manage service by AWS which works smoothly without any agents installation i.e. no requirement of agents as well. This feature not only works within AWS environment, but also works between AWS and On-Premises environment to ensure no connectivity losses.</p><p>Ref Link: <a href="https://aws.amazon.com/about-aws/whats-new/2023/12/amazon-cloudwatch-network-monitor-generally-available/">https://aws.amazon.com/about-aws/whats-new/2023/12/amazon-cloudwatch-network-monitor-generally-available/</a></p><h3>Pattern:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/0*WS01ceThB8V-iWHw.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*ONOO39BmpbmvSRhe.jpg" /></figure><h3>Solution Overview:</h3><p>Below steps to be followed to implement -</p><ul><li>Open CloudWatch console and click on “Network Monitor” option.</li><li>Click on “Create Monitor” and provide the basic required details as below.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/0*hLxLBl5hKNAKB4ex.png" /></figure><ul><li>Provide subnet name as “Source” and give “Destination IP” or IP ranges.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*JTJJPTzt5EaTCFL_mnWjFA.png" /></figure><ul><li>Review the provided details and submit.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/0*j_Amedfl-kz687d3.png" /></figure><ul><li>Once submitted, the monitoring resource would be created along with provided probe information. Generally it takes time around 3–4 minutes to set up completely and come in “Active” state. After taking time to get metrics, it will display like below.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*gtfhdwkIUTNx-9Zt.png" /></figure><ul><li>Please make sure this resource status is “Healthy” which confirms successful connectivity test.</li></ul><p>As we have provided aggregated time as 30s, so the servers will be pinged in each 30 seconds time interval and provide the status of healthiness since it creation.</p><h3>Packet Loss:</h3><p>If this connectivity test gets failed or interrupted due to some network glitches or failure, packet loss section would provide the value “100%” with graphical representation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*M1SJQwSvQe05dRaH.png" /></figure><h3>Round Trip Time(RTT):</h3><p>That defines the travel duration of traffics from source to destination.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*oCYIvD0wg-d7jJiS.png" /></figure><h3>Communication Protocols:</h3><p>TCP and ICMP these two protocols are supported by this feature for now. ICMP probes carry echo request from mentioned source address to mentioned destination address and if destination resources replies back with echo request, then it gets considered as successful connectivity test. RTT and packet loss both are calculated on metric information from source to destination and vice versa.</p><p>RTT = (time taken from source-to-destination) + (time taken from destination-to-source)<br>Packet Loss = (% loss from source-to-destination) + (% loss from destination-to-source)</p><p>Note: The port number for corresponding protocol must be opened at security group level of that instance. For ICMP, it takes “All” in port section so no action required apart from adding ICMP rule, but in TCP, port needs to be taken care.</p><p>In case of TCP, probe carries TCP SYN packets from mentioned source details to destination and expects TCP SYN+ACK reply from destination.</p><h3>Supported Region:</h3><p>Asia Pacific (Hong Kong) ap-east-1<br>Asia Pacific (Mumbai) ap-south-1<br>Asia Pacific (Seoul) ap-northeast-2<br>Asia Pacific (Singapore) ap-southeast-1<br>Asia Pacific (Sydney) ap-southeast-2<br>Asia Pacific (Tokyo) ap-northeast-1<br>Canada West (Calgary) ca-west-1<br>Europe (Frankfurt) eu-central-1<br>Europe (Ireland) eu-west-1<br>Europe (London) eu-west-2<br>Europe (Paris) eu-west-3<br>Europe (Stockholm) eu-north-1<br>Middle East (Bahrain) me-south-1<br>South America (São Paulo) sa-east-1<br>US East (N. Virginia) us-east-1<br>US East (Ohio) us-east-2<br>US West (N. California) us-west-1<br>US West (Oregon) us-west-2</p><h3>Create an Alarm:</h3><ul><li>Open CloudWatch metrics and choose “AWS/NetworkMonitor” default namespace.</li><li>Search with correct probe ID.</li><li>Select the metrics and click on “bell” icon to configure alarms.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*zwaPjjnM1FQk0bCS.png" /></figure><ul><li>Keep the details as it is and set condition that Packet Loss should not be greater than “0” as below -</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/0*MNPw9ZkSTUGyHCZ4.png" /></figure><ul><li>As a trigger, we have created EventBridge rule with lambda function, so that once packet loss alarm gets triggered, then it sends an email with sufficient information using SNS topic API.</li></ul><p><strong>EventBridge Rule Configuration:</strong></p><p>Category: CloudWatch Alarm State Change</p><ul><li>Below is the schema of event pattern.</li></ul><pre>{<br>  &quot;source&quot;: [&quot;aws.cloudwatch&quot;],<br>  &quot;detail-type&quot;: [&quot;CloudWatch Alarm State Change&quot;],<br>  &quot;resources&quot;: [&quot;arn:aws:cloudwatch:us-east-1:&lt;account-id&gt;:alarm:cw-network-packetloss-alarm-ec2&quot;],<br>  &quot;detail&quot;: {<br>    &quot;state&quot;: {<br>      &quot;value&quot;: [&quot;ALARM&quot;]<br>    }<br>  }<br>}</pre><ul><li>Integrate EventBridge rule with Lambda function.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/0*50P4Y0Qa7g2dzBGQ.png" /></figure><p><strong>Lambda Function Code:</strong></p><pre>import json<br>import boto3<br>import os<br>def lambda_handler(event, context):<br>    id = event[&#39;id&#39;]<br>    account = event[&#39;account&#39;]<br>    timestamps = event[&#39;time&#39;]<br>    region = event[&#39;region&#39;]<br>    alarmarn = event[&#39;resources&#39;][0]<br>    alarmname = event[&#39;detail&#39;][&#39;alarmName&#39;]<br>    alarmreason = event[&#39;detail&#39;][&#39;state&#39;][&#39;reason&#39;]<br>    previousState = event[&#39;detail&#39;][&#39;previousState&#39;][&#39;value&#39;]<br>    currentstate = event[&#39;detail&#39;][&#39;state&#39;][&#39;value&#39;]<br>    Monitorname = event[&#39;detail&#39;][&#39;configuration&#39;][&#39;metrics&#39;][0][&#39;metricStat&#39;][&#39;metric&#39;][&#39;dimensions&#39;][&#39;Monitor&#39;]    <br>    msg = f&#39;Hi Team,\n\nPlease be informed that alarm \&#39;{alarmname}\&#39; in accountId {account} is in {currentstate} state. Please find below set of details to get more insights.\n\nAlarm Details:\n ID = {id},\nAccount = {account},\nTimestamp = {timestamps},\nRegion = {region},\nPreviousState = {previousState},\nCurrentState = {currentstate},\nAlarmARN = {alarmarn},\nAlarm_Reason = {alarmreason}\n\nThanks &amp; Regards,\nAmazon Cloud Services&#39;<br>    sns_client = boto3.client(&#39;sns&#39;)<br>    res = sns_client.publish(<br>        TopicArn = os.environ[&#39;snsarn&#39;],<br>        Subject = f&#39;Alarm: High Packet Loss Trigger Alert&#39;,<br>        Message = str(msg)<br>        )</pre><h3>Testing:</h3><p>For simplicity, we have executed below command which changes the alarm status from OK to ALARM forcefully for short period of time.<br>As a result, alarm status of probe has been changed as below snap.</p><p><strong>Command</strong>: <em>aws cloudwatch set-alarm-state — alarm-name “cw-network-packetloss-alarm-ec2” — state-value ALARM — state-reason “testing purposes”</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*xVw9i79dO3st_-Mm.png" /></figure><p>Once lambda function is triggered successfully, it interacts with SNS topic to send email messages to subscribed email address.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*WGBevfTlzjJ22_os.png" /></figure><h3>Pricing:</h3><p>Please check below link to get pricing estimation on CloudWatch NetworkMonitor.</p><p>Link: <a href="https://aws.amazon.com/cloudwatch/pricing/">https://aws.amazon.com/cloudwatch/pricing/</a></p><h3>Conclusion:</h3><p>In this article we have seen how we can configure agentless network monitoring system within AWS network or hybrid network to ensure proper monitoring of packet loss and other metrices.<br>Hope this blog will help you to configure the things properly. Please let me know for more information or suggestion and follow me to get more on AWS.</p><p>Cheers!!</p><h3><a href="https://plainenglish.io/">PlainEnglish.io</a> 🚀</h3><p><em>Thank you for being a part of the In Plain English community! Before you go:</em></p><ul><li><em>Be sure to </em><strong><em>clap</em></strong><em> and </em><strong><em>follow</em></strong><em> the writer</em><strong>️</strong></li><li><em>Learn how you can also </em><a href="https://plainenglish.io/blog/how-to-write-for-in-plain-english"><strong><em>write for In Plain English</em></strong></a><em>️</em></li><li><em>Follow us: </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>X</em></strong></a><strong><em> | </em></strong><a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><strong><em> | </em></strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><strong><em> | </em></strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong><em>Discord</em></strong></a><strong><em> | </em></strong><a href="https://newsletter.plainenglish.io/"><strong><em>Newsletter</em></strong></a></li><li><em>Visit our other platforms: </em><a href="https://stackademic.com/"><strong><em>Stackademic</em></strong></a><strong><em> | </em></strong><a href="https://cofeed.app/"><strong><em>CoFeed</em></strong></a><strong><em> | </em></strong><a href="https://venturemagazine.net/"><strong><em>Venture</em></strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b1b9f01dedc" width="1" height="1" alt=""><hr><p><a href="https://aws.plainenglish.io/how-cloudwatch-network-monitor-performs-connectivity-test-to-ec2-instances-2b1b9f01dedc">How CloudWatch Network Monitor Performs Connectivity Test to EC2 Instances</a> was originally published in <a href="https://aws.plainenglish.io/">AWS in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Get Custom Email Notification for EC2 State Changes]]></title>
            <link>https://aws.plainenglish.io/how-to-get-custom-email-notification-for-ec2-state-changes-c7ca87279da1?source=rss-59a29a5892be------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7ca87279da1</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[lambda]]></category>
            <dc:creator><![CDATA[Dasanirban]]></dc:creator>
            <pubDate>Sun, 24 Dec 2023 16:47:38 GMT</pubDate>
            <atom:updated>2023-12-26T05:10:32.416Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introduction:</strong></h3><p>In any sort of architecture, monitoring is an important part without which an architecture cannot be treated as well architect. So, Cloudwatch is there to provide monitoring service, but aoart from this, any kind of state change must be tracked so closely so that operations team can be aware of this change and work on accordingly. Amazon EventBridge provides that level of triggering service which gets triggered in different sort of activities and SNS topic would be there to get people notified. One of those use cases is EC2 state change.</p><p>Suppose someone did patching activity and rebooted post patching or someone launched some new instances or due to some network glitches server got rebooted, but you’re not notified as there is no alerting system configured. Definitely there is a ap which you think off to get those fixed, otherwise servers would keep starting/rebooting/stopping and team won’t be aware.</p><p>To sort this issue, EventBridge comes into the picture with integration of SNS topic. So, you might be thinking that SNS will send an alert to recipients. YES, that’s correct, it will send an alert for sure, but that notification email seems to be clumsy to you as you’ll see so many information which seems not to be needed. Customers prefect neat and clear and “to-the-point” information to have better clarification. Here is a problem as sns notification email cannot be modified according to customers wish. That clearly tells that scripting is needed for sure to get this implemented.</p><h3><strong>Pattern:</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/0*fNCWgV491_WtRSWx.gif" /></figure><h3><strong>Solutions Overview:</strong></h3><p>This blog consists of following steps:</p><ol><li>Create an EventBridge rule as below.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/0*wb3zdy7UVYSBWtvA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/0*OlpJcAyAo9GXwPhD.png" /></figure><p>So, here basically EventBridge rule is checking below API calls from CloudTrail -</p><ul><li>RunInstances</li><li>StopInstances</li><li>StartInstances</li><li>RebootInstances</li></ul><p>2. Associate this rule with Lambda function. Below is the python code which takes events details in JSON as an input and fetches required details from JSON content.</p><pre>import os<br>import json<br>import boto3<br>def lambda_handler(event, context):<br>    EventID = event[&#39;detail&#39;][&#39;eventID&#39;]<br>    Account = event[&#39;account&#39;]<br>    Timestamp = event[&#39;time&#39;]<br>    Region = event[&#39;region&#39;]<br>    InstanceID = event[&#39;detail&#39;][&#39;requestParameters&#39;][&#39;instancesSet&#39;][&#39;items&#39;]<br>    EventName = event[&#39;detail&#39;][&#39;eventName&#39;]<br>    SourceIP = event[&#39;detail&#39;][&#39;sourceIPAddress&#39;]<br>    InitiatedBy = event[&#39;detail&#39;][&#39;userIdentity&#39;][&#39;arn&#39;]<br>    msg_status = {&#39;StopInstances&#39;: &#39;stopped&#39;, &#39;StartInstances&#39;: &#39;started&#39;, &#39;TerminateInstances&#39;: &#39;terminated&#39;, &#39;RebootInstances&#39;: &#39;rebooted&#39;}<br>    instance_id = []<br>    if len(InstanceID) &gt; 1:<br>        for id in range(0, len(event[&#39;detail&#39;][&#39;requestParameters&#39;][&#39;instancesSet&#39;][&#39;items&#39;])):<br>            v = event[&#39;detail&#39;][&#39;requestParameters&#39;][&#39;instancesSet&#39;][&#39;items&#39;][id][&#39;instanceId&#39;]<br>            instance_id.append(v)<br>        body = f&#39;Hi Team, \n\nPlease be informed that multiple instances got {msg_status[EventName]} simultaneously.\n\nEventID = {EventID}, \nAccount = {Account}, \nTimestamp = {Timestamp}, \nRegion = {Region}, \nInstanceID = {instance_id}, \nEventName = {EventName}, \nSourceIP = {SourceIP}, \nInitiatedBy = {InitiatedBy} \n\nRegards,\nCloud Team&#39;<br>        sns_client = boto3.client(&#39;sns&#39;)<br>        snsarn = os.environ[&#39;snsarn&#39;]<br>        res = sns_client.publish(<br>            TopicArn = snsarn,<br>            Subject = f&#39;Alert-Multiple Instances are {msg_status[EventName]}&#39;,<br>            Message = str(body)<br>            )<br>    elif len(InstanceID) == 1:<br>        instance_id = InstanceID[0][&#39;instanceId&#39;]<br>        body = f&#39;Hi Team, \n\nThis is to inform you that EC2 instance with {instance_id} is {msg_status[EventName]}.Please find below information. \n\nEventID = {EventID}, \nAccount = {Account}, \nTimestamp = {Timestamp}, \nRegion = {Region}, \nInstanceID = {instance_id}, \nEventName = {EventName}, \nSourceIP = {SourceIP}, \nInitiatedBy = {InitiatedBy} \n\nRegards,\nCloud Team&#39;<br>        sns_client = boto3.client(&#39;sns&#39;)<br>        snsarn = os.environ[&#39;snsarn&#39;]<br>        res = sns_client.publish(<br>            TopicArn = snsarn,<br>            Subject = f&#39;Alert - {instance_id} is {msg_status[EventName]}&#39;,<br>            Message = str(body)<br>            )</pre><p>3. Here, SNS topic name is stored in Environment Variable section in lambda.</p><p>Note: Here, we didn’t add SNS topic in Destination section because there will be below unwanted stuffs occurred if added in destination section.</p><ul><li>SNS will send email as per python code with customizations you did. (Expected Behavior)</li><li>SNS will also send email with complete lambda execution details like EventID, Event Timestamps, Payload etc. which is already part of customized email, no need to get separate email. Hence adding sns topic as destination has been omitted.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*NyBkRIekAOh-P4NF.png" /></figure><h3><strong>Summary:</strong></h3><p>This post will guide you to configure customize email notification settings using EventBridge and Lambda with the help of python scripting. This same approach can be used in other cases as well like getting notified when ec2 metrics(cpu/mem/disk) is in ALARM state, so basically EventBridge will be triggered once alarm status will be switched from OK to ALARM.</p><p>From configurational changes perspective this will help a lot to identify details in deep with AWS Config service. For more details, please checkout</p><p><a href="https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-what-is.html">docs.aws.amazon.com</a></p><p>Please follow me for more contents.</p><p>Thanks for Reading!!</p><p>Let’s connect <a href="https://www.linkedin.com/in/anirban-das-507816169/">https://www.linkedin.com/in/anirban-das-507816169/</a></p><h3><a href="https://plainenglish.io/">PlainEnglish.io</a> 🚀</h3><p><em>Thank you for being a part of the In Plain English community! Before you go:</em></p><ul><li><em>Be sure to </em><strong><em>clap</em></strong><em> and </em><strong><em>follow</em></strong><em> the writer</em><strong>️</strong></li><li><em>Learn how you can also </em><a href="https://plainenglish.io/blog/how-to-write-for-in-plain-english"><strong><em>write for In Plain English</em></strong></a><em>️</em></li><li><em>Follow us: </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>X</em></strong></a><strong><em> | </em></strong><a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><strong><em> | </em></strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><strong><em> | </em></strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong><em>Discord</em></strong></a><strong><em> | </em></strong><a href="https://newsletter.plainenglish.io/"><strong><em>Newsletter</em></strong></a></li><li><em>Visit our other platforms: </em><a href="https://stackademic.com/"><strong><em>Stackademic</em></strong></a><strong><em> | </em></strong><a href="https://cofeed.app/"><strong><em>CoFeed</em></strong></a><strong><em> | </em></strong><a href="https://venturemagazine.net/"><strong><em>Venture</em></strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7ca87279da1" width="1" height="1" alt=""><hr><p><a href="https://aws.plainenglish.io/how-to-get-custom-email-notification-for-ec2-state-changes-c7ca87279da1">How to Get Custom Email Notification for EC2 State Changes</a> was originally published in <a href="https://aws.plainenglish.io/">AWS in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Get a Custom Weekly Inventory of EC2 Instances Using Lambda Function]]></title>
            <link>https://aws.plainenglish.io/get-a-custom-weekly-inventory-of-ec2-instance-using-lambda-function-204f1da6dbb4?source=rss-59a29a5892be------2</link>
            <guid isPermaLink="false">https://medium.com/p/204f1da6dbb4</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[amazon-web-services]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Dasanirban]]></dc:creator>
            <pubDate>Mon, 16 Oct 2023 13:00:51 GMT</pubDate>
            <atom:updated>2023-10-17T00:51:20.387Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction:</h3><p>While working in any projects based on AWS, it’s mandatory to have an inventory of EC2 instances weekly/monthly basis to get compact details on instances and their attributes if the environment is very big. Also, from compliance perspective, it helps to auditor to understand the details very precisely like when an instance got build, what was the image version or when that image was created, whether SSM agent is working fine or not, something like this can be playing a key role during compliance assessment.</p><h3>Pattern:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*-NdTOSEsraJidCwLGIk9hw.gif" /></figure><h3>Functionalities:</h3><p>This is a very straightforward solution to get weekly EC2 instances inventory report that uses EventBridge as a scheduler, lambda function used as a trigger based service which holds the actually python script. Once the inventory file is generated, lambda pushes it to S3 bucket for storing for long term and parallelly sends an email notification using SES(Simple Email Service).</p><h3>Lets Get Started:</h3><h4>1. Create a Lambda Function:</h4><ul><li>Create a lambda function as below with python 3.11 runtime.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QddfTQUHvOS3RddRXF-Yrw.png" /></figure><ul><li>Before uploading the source code, just wanted to let you all know that lambda doesn’t support any external python community modules like xmltodict, openpyxl etc. So here, while developing the codes locally, we can install python modules in that project folder.</li><li>Use “pip3 install openpyxl -t . — no-user” to install python modules in same project directory. Post that, make the entire project directory compressed. Below one is the python code to generate inventory file</li></ul><pre>import boto3<br>import openpyxl<br>import time<br>import os<br>from botocore.exceptions import ClientError<br>from email.mime.multipart import MIMEMultipart<br>from email.mime.text import MIMEText<br>from email.mime.application import MIMEApplication<br><br>client = boto3.client(&#39;ec2&#39;, region_name = &#39;us-east-1&#39;)<br>ssm_client = boto3.client(&#39;ssm&#39;, region_name = &#39;us-east-1&#39;)<br>s3 = boto3.client(&#39;s3&#39;, region_name = &#39;us-east-1&#39;)<br>ses = boto3.client(&#39;ses&#39;,region_name=&#39;us-east-1&#39;)<br><br>def instance_attributes():<br>    data = [[&#39;InstanceName&#39;, &#39;InstanceID&#39;, &#39;InstanceType&#39;, &#39;PrivateIP&#39;, &#39;Operaring System&#39;, &#39;State&#39;, &#39;SGID&#39;,&#39;SubnetID&#39;,&#39;VPCID&#39;,&#39;AvailabilityZone&#39;,&#39;SSM&#39;, &#39;ImageID&#39;, &#39;ImageCreated&#39;, &#39;OSDisk&#39;, &#39;OSDiskID&#39;, &#39;OSDiskSize&#39;],]<br>    resp = client.describe_instances()<br>    for res in resp[&#39;Reservations&#39;]:<br>        for ins in res[&#39;Instances&#39;]:<br>            os = ins[&#39;PlatformDetails&#39;]<br>            priv_ip = ins[&#39;PrivateIpAddress&#39;]<br>            state = ins[&#39;State&#39;][&#39;Name&#39;]<br>            subnetid = ins[&#39;SubnetId&#39;]<br>            vpcid = ins[&#39;VpcId&#39;]<br>            sgid = [sg[&#39;GroupId&#39;] for sg in ins[&#39;SecurityGroups&#39;]][0]<br>            ins_id = ins[&#39;InstanceId&#39;]<br>            image_id = ins[&#39;ImageId&#39;]<br>            image_date = [img[&#39;CreationDate&#39;] for img in client.describe_images(ImageIds=[image_id])[&#39;Images&#39;]]<br>            image_final_date = image_date[0] if len(image_date) &gt;= 1 else &#39;Image may not be available&#39;<br>            ins_ty = ins[&#39;InstanceType&#39;]<br>            monitoring_stat = ins[&#39;Monitoring&#39;][&#39;State&#39;]<br>            launch_time = ins[&#39;LaunchTime&#39;]<br>            az = ins[&#39;Placement&#39;][&#39;AvailabilityZone&#39;]<br>            ssm_agent_stat = ssm_client.get_connection_status(Target=ins_id)[&#39;Status&#39;]<br>            volname = [vol[&#39;DeviceName&#39;] for vol in ins[&#39;BlockDeviceMappings&#39;]]<br>            volid = [vol[&#39;Ebs&#39;][&#39;VolumeId&#39;] for vol in ins[&#39;BlockDeviceMappings&#39;]]<br>            root_disk_name = volname[0]<br>            root_disk_id = volid[0]<br>            root_vol_size = [sz[&#39;Size&#39;] for sz in client.describe_volumes(VolumeIds=[root_disk_id])[&#39;Volumes&#39;]][0]<br>            #last_reboot = ssm_client.send_command(DocumentName=&#39;AWS-RunShellScript&#39;, Parameters={&#39;commands&#39;: [cmd]}, InstanceIds=ins_id)<br>            for tag_name in ins[&#39;Tags&#39;]:<br>                if tag_name[&#39;Key&#39;] == &#39;Name&#39;:<br>                    name = tag_name[&#39;Value&#39;]<br>                    data.append([name, ins_id, ins_ty, priv_ip, os, state, sgid, subnetid, vpcid, az, ssm_agent_stat, image_id, image_final_date, root_disk_name, root_disk_id, root_vol_size])<br><br>    if name and ins_id:<br>        print(&#39;All the attributes are extracted from Instances&#39;)<br>        time.sleep(1)<br>        print(&#39;Creating an Inventory&#39;)<br>        workbook = openpyxl.Workbook()<br>        worksheet = workbook.active<br>        worksheet.title = &#39;Inventory&#39;<br>        for row_data in data:<br>            worksheet.append(row_data)<br>        path = &#39;/tmp/ec2-inventory.xlsx&#39;<br>        workbook.save(path)<br>        print(f&#39;Success!! Workbook created at {path} location&#39;, &#39;\n&#39;)<br>        s3.upload_file(path, &#39;cf-templates-czmyfizwsx0a-us-east-1&#39;, &#39;ec2-inventory.xlsx&#39;)<br>    else:<br>        print(&#39;Fail!! Please check the syntax once again&#39;, &#39;\n&#39;)<br><br>def sendemail():<br>    SENDER = &#39;&lt;emailid registered in SES&gt;&#39;<br>    RECIPIENT = &#39;&lt;emailid registered in SES&gt;&#39;<br>    SUBJECT = &quot;Weekly Instances Report&quot;<br>    #CONFIGURATION_SET = &quot;ConfigSet&quot;<br>    ATTACHMENT = &quot;/tmp/ec2-inventory.xlsx&quot;<br>    BODY_TEXT = &quot;Hello Team,\n\nPlease find the attached instance inventory report.\n\nRegards,\nAnirban Das\nCloud Operations Team&quot;<br>    BODY_HTML = &quot;&quot;&quot;\<br>    &lt;html&gt;<br>    &lt;head&gt;&lt;/head&gt;<br>    &lt;body&gt;<br>    &lt;p&gt;Hello Team&lt;/p&gt;<br>    &lt;p&gt;Please find the attached instance inventory report.&lt;/p&gt;<br>    &lt;p&gt;Regards,&lt;/p&gt;<br>    &lt;p&gt;Anirban Das&lt;/p&gt;<br>    &lt;p&gt;Cloud Operations Team&lt;/p&gt;<br>    &lt;/body&gt;<br>    &lt;/html&gt;<br>    &quot;&quot;&quot;<br>    CHARSET = &quot;utf-8&quot;<br>    msg = MIMEMultipart(&#39;mixed&#39;)<br>    # Add subject, from and to lines.<br>    msg[&#39;Subject&#39;] = SUBJECT <br>    msg[&#39;From&#39;] = SENDER <br>    msg[&#39;To&#39;] = RECIPIENT<br>    # Create a multipart/alternative child container.<br>    msg_body = MIMEMultipart(&#39;alternative&#39;)<br>    <br>    # Encode the text and HTML content and set the character encoding. This step is<br>    # necessary if you&#39;re sending a message with characters outside the ASCII range.<br>    textpart = MIMEText(BODY_TEXT.encode(CHARSET), &#39;plain&#39;, CHARSET)<br>    htmlpart = MIMEText(BODY_HTML.encode(CHARSET), &#39;html&#39;, CHARSET)<br>    <br>    # Add the text and HTML parts to the child container.<br>    msg_body.attach(textpart)<br>    msg_body.attach(htmlpart)<br>    <br>    # Define the attachment part and encode it using MIMEApplication.<br>    att = MIMEApplication(open(ATTACHMENT, &#39;rb&#39;).read())<br>    <br>    # Add a header to tell the email client to treat this part as an attachment,<br>    # and to give the attachment a name.<br>    att.add_header(&#39;Content-Disposition&#39;,&#39;attachment&#39;,filename=os.path.basename(ATTACHMENT))<br>    <br>    # Attach the multipart/alternative child container to the multipart/mixed<br>    # parent container.<br>    msg.attach(msg_body)<br>    <br>    # Add the attachment to the parent container.<br>    msg.attach(att)<br>    #print(msg)<br>    try:<br>        #Provide the contents of the email.<br>        response = ses.send_raw_email(<br>            Source=SENDER,<br>            Destinations=[<br>                RECIPIENT<br>            ],<br>            RawMessage={<br>                &#39;Data&#39;:msg.as_string(),<br>            },<br>            #ConfigurationSetName=CONFIGURATION_SET<br>        )<br>    # Display an error if something goes wrong. <br>    except ClientError as e:<br>        print(e.response[&#39;Error&#39;][&#39;Message&#39;])<br>    else:<br>        print(f&quot;Email sent! Message ID: {response[&#39;MessageId&#39;]}&quot;)<br><br>def lambda_handler(event, conte):<br>    instance_attributes()<br>    sendemail()</pre><ul><li>Open the lambda function you created and upload the zip file.</li></ul><h4>2. Create an EventBridge Rule:</h4><ul><li>Open the AWS services option and select EventBridge service</li><li>In the left navigation pane, you’ll see option <strong>“Rules”</strong>, click on it.</li><li>Once you click on <strong>“Create Rule” </strong>option, fill the <strong>“Name” </strong>and <strong>“Description”</strong> options.</li><li>Choose rule type as <strong>“Schedule”</strong>.</li><li>Click on <strong>“Continue in EventBridge Scheduler”</strong> option to proceed further.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*lyv4NOXn2QFsjiVbQH51hQ.png" /></figure><ul><li>Choose occurrence as <strong>“Recurring Schedule” </strong>and select <strong>“Cron Based Schedule” </strong>as a type.</li><li>Here, it’s setup that lambda function is supposed to trigger in every <strong>SUNDAY</strong> at 12:00 AM. Accordingly cron expression is give like this <strong>cron(00 12 ? * SUN *)</strong>.</li><li>Flexible window is not chosen here, so taken as <strong>“Off” </strong>which means rule should triggered instantly.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*HCBezF3qSkm1dM_B9ifKrw.png" /></figure><ul><li>Choose the target as Lambda function which we created in step 1.</li><li>Finally submit the request.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xa_Hqyt7W0WkL9jqzvGFaQ.png" /></figure><h4>3. Create Verified Identities in SES:</h4><ul><li>Open the Simple Email Service console and click on <strong>“Verified Identities”</strong> option.</li><li>Choose <strong>“Email address”</strong> as an email type and provide the email address.</li><li>Once created, you will get an email from AWS an click on the confirmation link to approve this identity request.</li><li>Post that, verify the status of identity. It must be <strong>“Verified”</strong>.</li></ul><h3>Testing:</h3><p>As we have created EventBridge rule with a particular cron schedule, hence it will be triggered as per schedule we have mentioned. For Adhoc testing, we can use “Test” option in Lambda.</p><p>In Test option normally some JSON content is required to put as Lambda internal structure takes an event and context as an input, so deleting that would result an error. That’s a reason we need to use blank JSON format i.e. {} like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kUfZSQWiAsdGPJynCiyh4w.png" /></figure><p>Below is the output you’ll get after testing through Lambda.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R_YcLrJnW699A_NkdzrBGg.png" /></figure><p>Below is the kind of email you’ll receive with an attachment of EC2 inventory.</p><p>Mail Snapshot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*TaxwjotedC_gTNtjYLmB6w.png" /></figure><p>Inventory Snapshot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dmsqCKlbjcSI_66-P3Slig.png" /></figure><p>~~ Happy Ending ~~</p><p>Hope this blog will help to understand how a good inventory can be generated for small as well as big environments. Here, we have chosen a few attributes of EC2 instances and related volumes, but yes there can be so many things we can include in the same inventory, that will definitely be a part of the requirement. 🙂🙂</p><p>Cheers!</p><h3>In Plain English</h3><p><em>Thank you for being a part of our community! Before you go:</em></p><ul><li><em>Be sure to </em><strong><em>clap</em></strong><em> and </em><strong><em>follow</em></strong><em> the writer! 👏</em></li><li><em>You can find even more content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><strong><em> 🚀</em></strong></li><li><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. 🗞️</em></li><li><em>Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><strong><em>(X</em></strong>), <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a>, <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a>, and <a href="https://discord.gg/in-plain-english-709094664682340443"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=204f1da6dbb4" width="1" height="1" alt=""><hr><p><a href="https://aws.plainenglish.io/get-a-custom-weekly-inventory-of-ec2-instance-using-lambda-function-204f1da6dbb4">Get a Custom Weekly Inventory of EC2 Instances Using Lambda Function</a> was originally published in <a href="https://aws.plainenglish.io/">AWS in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deployment of Containerized ReactJS Application in ECS Cluster with ALB in AWS]]></title>
            <link>https://aws.plainenglish.io/deployment-of-containerized-reactjs-application-in-ecs-cluster-with-alb-in-aws-a11a30b0bea9?source=rss-59a29a5892be------2</link>
            <guid isPermaLink="false">https://medium.com/p/a11a30b0bea9</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Dasanirban]]></dc:creator>
            <pubDate>Mon, 10 Jul 2023 01:18:44 GMT</pubDate>
            <atom:updated>2023-07-11T04:05:22.394Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introduction</strong></h3><p>This article will describe the way how we can dockarize an application using aws ECS cluster service and distribute the incoming traffic using application load balancer. As we are in the age of containerization, we really need to understand why container ? what is the purpose ? benefits ?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*ZLjo8t8JXfLTI4GD.jpg" /></figure><p><strong>What Is Container &amp; Containerization ?</strong></p><p>Container is nothing but a lightweight machine which can be installed on top the virtual machine by installing docker application. It doesn’t have any operating system concept, but that doesn’t mean it works without OS :) basically container supports such level of advancement due to which it can utilize the resources of host virtual machine, normally virtual machines virtualizes the underlying hardware, but here in case of container, it virtualizes the operating system of host virtual machine and that’s a reason it doesn’t have any explicit OS concept and have been light weighted.</p><p>So the way we package all application codes and create a container where application works fine with required port configuration with host machine, is known as containerization.</p><p><strong>Purpose:</strong></p><p>Container is light weight and is easy to tackle in every aspects. If we consider traditional approach, then we see once upon a time the whole application was supposed to be deployed in single host machine. In case of any outages or problems it affects the entire application components, that kind of application architecture was known as Monolithic Architecture. But containerization has opened up a different approach where each and every application components can be broken down into multiple pieces and deployed in isolated containers which prevents others containers from affected one from outages. So that only affected components can be troubleshooted, not all and dedicated engineer team will focus on that particular issue.</p><h3><strong>Diagram</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*B7GOqml_Oj8knaYTxYjpBA.png" /><figcaption>Architectural Diagram</figcaption></figure><h3><strong>Services Used:</strong></h3><ul><li>ECS FARGATE</li><li>VPC</li><li>Application Load Balancer</li><li>CloudWatch Log Groups</li></ul><h3><strong>What Is ECS:</strong></h3><p>Amazon Elastic Container Service (ECS) is a highly scalable, high performance container management service that supports Docker containers and allows you to easily run applications on a managed cluster of Amazon Elastic Compute Cloud (Amazon EC2) instances.</p><p><strong>Task Definition:</strong> A task definition is a blueprint that defines the infrastructure parameters like docker image which we are going to refer, container CPU and memory, host type(EC2 or Fargate), IAM role, Logging configuration and docker networking etc.</p><p><strong>Tasks: </strong>Based on the parameters defined in the task definition, containers can be launched using that image with same cpu/memory configuration mentioned in task definition.</p><p><strong>Services: </strong>Service is the component of ECS that manages all the tasks i.e. containers based upon the health checks. It continuously monitors the incoming traffic flow into containers, in case traffic doesn’t come, then those containers will be treated as unhealthy. So service destroys all and recreates using same image.</p><h3><strong>Deployment Of Resources</strong></h3><p>Here, all the resources deployment have been codified using Terraform and GitLab CI Pipeline. We have created separate repositories for each resources to maintain transparency and simplicity.</p><p><strong>Terraform Provider Details:</strong></p><pre>terraform {<br>  required_providers {<br>    aws = {<br>      source  = &quot;hashicorp/aws&quot;<br>      version = &quot;4.67.0&quot;<br>    }<br>  }<br>}<br><br>provider &quot;aws&quot; {<br>  # Configuration options<br>  region = &quot;us-east-1&quot;<br>}</pre><h3><strong>1. ECR</strong>:</h3><p>There a image repository has been created in ECR service where the docker image has been pushed and maintained with version.</p><p>var.tf</p><pre>variable &quot;ecr_repo&quot; {<br>  description = &quot;Name of repository&quot;<br>  default     = &quot;aws-ecs-reactjs-personal-portfolio&quot;<br>}<br><br>variable &quot;ecr_tags&quot; {<br>  type = map(any)<br>  default = {<br>    &quot;AppName&quot; = &quot;ReactJS&quot;<br>    &quot;Env&quot;     = &quot;Dev&quot;<br>  }<br>}</pre><p>ecr.tf</p><pre>resource &quot;aws_ecr_repository&quot; &quot;aws-ecr&quot; {<br>  name = var.ecr_repo<br>  tags = var.ecr_tags<br>}</pre><p>output.tf</p><pre>output &quot;ecr_arn&quot; {<br>  value = aws_ecr_repository.aws-ecr.arn<br>}<br><br>output &quot;ecr_registry_id&quot; {<br>  value = aws_ecr_repository.aws-ecr.registry_id<br>}<br><br>output &quot;ecr_url&quot; {<br>  value = aws_ecr_repository.aws-ecr.repository_url<br>}</pre><p>Pipeline File</p><pre>default:<br>  tags: <br>    - gitlab-runner-test<br><br>stages:<br>  - image_repo_create<br><br>Image_Repository_Build:<br>  stage: image_repo_create<br>  script:<br>    - terraform init<br>    - terraform plan<br>    - terraform apply --auto-approve</pre><h3><strong>2. Image Creation:</strong></h3><p>Here, to build an application image, we have prepared a Dockerfile that builds a custom application image and push to ECR registry in aws.</p><p>Application Code: &lt;<a href="https://github.com/dasanirban834/home">Link</a>&gt;</p><p>Dockerfile</p><pre>#Stage 1<br># Fetch the latest image of node<br>FROM node:alpine as er<br># Set up working directry<br>WORKDIR /app<br># Copy package.json to working directory<br>COPY package.json ./<br>COPY package-lock.json ./<br>COPY . .<br>RUN npm install<br># Coping all file in our project<br>#Starting <br>CMD [ &quot;npm&quot;, &quot;run&quot;, &quot;start&quot; ]</pre><p>Pipeline File</p><pre>default:<br>  tags: <br>    - gitlab-runner-test<br><br>stages:<br>  - image_build<br><br>Image Build:<br>  variables:<br>    region: &quot;us-east-1&quot;<br>  stage: image_build<br>  script:<br>    - export aws_account_id=$(aws sts get-caller-identity | jq .&#39;Account&#39; | xargs)<br>    - sudo docker build -t reactjs-image .<br>    - sudo docker tag reactjs-image:latest $aws_account_id.dkr.ecr.$region.amazonaws.com/aws-ecs-reactjs-personal-portfolio<br>    - sudo aws ecr get-login-password --region $region | docker login --username AWS --password-stdin $aws_account_id.dkr.ecr.$region.amazonaws.com<br>    - sudo docker push $aws_account_id.dkr.ecr.$region.amazonaws.com/aws-ecs-reactjs-personal-portfolio</pre><h3><strong>3. Application Load Balancer:</strong></h3><p>var.tf</p><pre>variable &quot;TG_conf&quot; {<br>  type = object({<br>    name              = string<br>    port              = string<br>    protocol          = string<br>    target_type       = string<br>    enabled           = bool<br>    healthy_threshold = string<br>    interval          = string<br>    path              = string<br>  })<br>}<br><br>variable &quot;ALB_conf&quot; {<br>  type = object({<br>    name               = string<br>    internal           = bool<br>    load_balancer_type = string<br>    ip_address_type    = string<br>  })<br>}<br><br>variable &quot;Listener_conf&quot; {<br>  type = map(object({<br>    port     = string<br>    protocol = string<br>    type     = string<br>    priority = number<br>  }))<br>}<br><br>variable &quot;alb_tags&quot; {<br>  description = &quot;provides the tags for ALB&quot;<br>  type = object({<br>    Environment = string<br>    Email       = string<br>    Type        = string<br>    Owner       = string<br>  })<br>  default = {<br>    Email       = &quot;dasanirban0806@gmail.com&quot;<br>    Environment = &quot;Production&quot;<br>    Owner       = &quot;Anirban Das&quot;<br>    Type        = &quot;External&quot;<br>  }<br>}</pre><p>terraform.tfvars</p><pre>TG_conf = {<br>  enabled           = true<br>  healthy_threshold = &quot;2&quot;<br>  interval          = &quot;30&quot;<br>  name              = &quot;TargetGroup-External&quot;<br>  port              = &quot;3000&quot;<br>  protocol          = &quot;HTTP&quot;<br>  target_type       = &quot;ip&quot;<br>  path              = &quot;/home&quot;<br>}<br><br>ALB_conf = {<br>  internal           = false<br>  ip_address_type    = &quot;ipv4&quot;<br>  load_balancer_type = &quot;application&quot;<br>  name               = &quot;ALB-External&quot;<br>}<br><br>Listener_conf = {<br>  &quot;1&quot; = {<br>    port     = &quot;80&quot;<br>    priority = 100<br>    protocol = &quot;HTTP&quot;<br>    type     = &quot;forward&quot;<br>  }<br>}</pre><p>data.tf</p><pre>data &quot;aws_security_group&quot; &quot;ext_alb&quot; {<br>  filter {<br>    name   = &quot;tag:Name&quot;<br>    values = [&quot;InternetFacing-ALB&quot;]<br>  }<br>}<br><br># vpc details :<br>data &quot;aws_vpc&quot; &quot;this_vpc&quot; {<br>  state = &quot;available&quot;<br>  filter {<br>    name   = &quot;tag:Name&quot;<br>    values = [&quot;custom-vpc&quot;]<br>  }<br>}<br># subnets details :<br>data &quot;aws_subnet&quot; &quot;web_subnet_1a&quot; {<br>  vpc_id = data.aws_vpc.this_vpc.id<br>  filter {<br>    name   = &quot;tag:Name&quot;<br>    values = [&quot;weblayer-pub1-1a&quot;]<br>  }<br>}<br><br>data &quot;aws_subnet&quot; &quot;web_subnet_1b&quot; {<br>  vpc_id = data.aws_vpc.this_vpc.id<br>  filter {<br>    name   = &quot;tag:Name&quot;<br>    values = [&quot;weblayer-pub2-1b&quot;]<br>  }<br>}</pre><p>ext_alb.tf</p><pre>resource &quot;aws_lb_target_group&quot; &quot;this_tg&quot; {<br>  name     = var.TG_conf[&quot;name&quot;]<br>  port     = var.TG_conf[&quot;port&quot;]<br>  protocol = var.TG_conf[&quot;protocol&quot;]<br>  vpc_id   = data.aws_vpc.this_vpc.id<br>  health_check {<br>    enabled           = var.TG_conf[&quot;enabled&quot;]<br>    healthy_threshold = var.TG_conf[&quot;healthy_threshold&quot;]<br>    interval          = var.TG_conf[&quot;interval&quot;]<br>    path              = var.TG_conf[&quot;path&quot;]<br>  }<br>  target_type = var.TG_conf[&quot;target_type&quot;]<br>  tags = {<br>    Attached_ALB_dns = aws_lb.this_alb.dns_name<br>  }<br>}<br><br><br>resource &quot;aws_lb&quot; &quot;this_alb&quot; {<br>  name               = var.ALB_conf[&quot;name&quot;]<br>  load_balancer_type = var.ALB_conf[&quot;load_balancer_type&quot;]<br>  ip_address_type    = var.ALB_conf[&quot;ip_address_type&quot;]<br>  internal           = var.ALB_conf[&quot;internal&quot;]<br>  security_groups    = [data.aws_security_group.ext_alb.id]<br>  subnets            = [data.aws_subnet.web_subnet_1a.id, data.aws_subnet.web_subnet_1b.id]<br>  tags               = merge(var.alb_tags)<br>}<br><br>resource &quot;aws_lb_listener&quot; &quot;this_alb_lis&quot; {<br>  for_each          = var.Listener_conf<br>  load_balancer_arn = aws_lb.this_alb.arn<br>  port              = each.value[&quot;port&quot;]<br>  protocol          = each.value[&quot;protocol&quot;]<br>  default_action {<br>    type             = each.value[&quot;type&quot;]<br>    target_group_arn = aws_lb_target_group.this_tg.arn<br>  }<br>}<br></pre><p>output.tf</p><pre>output &quot;arn&quot; {<br>  value = [aws_lb.this_alb.arn]<br>}<br><br>output &quot;dns_name&quot; {<br>  value = [aws_lb.this_alb.dns_name]<br>}</pre><p>Pipeline File</p><pre>default:<br>  tags: <br>    - gitlab-runner-test<br><br>stages:<br>  - external_alb_create<br><br>Ext_ALB:<br>  stage: external_alb_create<br>  script:<br>    - terraform init<br>    - terraform plan<br>    - terraform apply --auto-approve</pre><h3><strong>4. ECS</strong></h3><p>var.tf</p><pre>variable &quot;region&quot; {<br>  type    = string<br>  default = &quot;us-east-1&quot;<br>}<br>variable &quot;ecs_role&quot; {<br>  description = &quot;ecs roles&quot;<br>  default     = &quot;ecsTaskExecutionRole&quot;<br>}<br><br>variable &quot;ecs_details&quot; {<br>  description = &quot;details of ECS cluster&quot;<br>  type = object({<br>    Name                           = string<br>    logging                        = string<br>    cloud_watch_encryption_enabled = bool<br>  })<br>}<br><br>variable &quot;ecs_task_def&quot; {<br>  description = &quot;defines the configurations of task definition&quot;<br>  type = object({<br>    family                   = string<br>    cont_name                = string<br>    cpu                      = number<br>    memory                   = number<br>    essential                = bool<br>    logdriver                = string<br>    containerport            = number<br>    networkmode              = string<br>    requires_compatibilities = list(string)<br><br>  })<br>}<br><br>variable &quot;ecsservice&quot; {<br>  description = &quot;defines the configuration of ecs service&quot;<br>  type = object({<br>    name                 = string<br>    launch_type          = string<br>    scheduling_strategy  = string<br>    desired_count        = number<br>    force_new_deployment = bool<br>  })<br>}<br><br><br>variable &quot;cw_log_grp&quot; {<br>  description = &quot;defines the log group in cloudwatch&quot;<br>  type        = string<br>  default     = &quot;&quot;<br>}<br><br>variable &quot;kms_key&quot; {<br>  description = &quot;defines the kms key&quot;<br>  type = object({<br>    description             = string<br>    deletion_window_in_days = number<br>  })<br>}<br><br>variable &quot;custom_tags&quot; {<br>  description = &quot;defines common tags&quot;<br>  type        = object({})<br>  default = {<br>    AppName = &quot;ReactJS&quot;<br>    Env     = &quot;Dev&quot;<br>  }<br>}</pre><p>terraform.tfvars</p><pre>ecs_details = {<br>  Name                           = &quot;ecs-cluster&quot;<br>  logging                        = &quot;OVERRIDE&quot;<br>  cloud_watch_encryption_enabled = true<br>}<br><br>ecs_task_def = {<br>  family                   = &quot;custom-task-definition&quot;<br>  cont_name                = &quot;ReactJS-Container&quot;<br>  cpu                      = 256<br>  memory                   = 512<br>  essential                = true<br>  logdriver                = &quot;awslogs&quot;<br>  containerport            = 3000<br>  networkmode              = &quot;awsvpc&quot;<br>  requires_compatibilities = [&quot;FARGATE&quot;,]<br>}<br><br>ecsservice = {<br>  name                 = &quot;ecs-service&quot;<br>  launch_type          = &quot;FARGATE&quot;<br>  scheduling_strategy  = &quot;REPLICA&quot;<br>  desired_count        = 2<br>  force_new_deployment = true<br>}<br><br><br>cw_log_grp = &quot;cloudwatch-log-group-ecs-cluster&quot;<br><br>kms_key = {<br>  description             = &quot;log group encryption&quot;<br>  deletion_window_in_days = 7<br>}</pre><p>iam.tf</p><pre>resource &quot;aws_iam_role&quot; &quot;ecsTaskExecutionRole&quot; {<br>  name               = var.ecs_role<br>  assume_role_policy = data.aws_iam_policy_document.assume_role_policy.json<br>}<br><br>data &quot;aws_iam_policy_document&quot; &quot;assume_role_policy&quot; {<br>  statement {<br>    actions = [&quot;sts:AssumeRole&quot;]<br><br>    principals {<br>      type        = &quot;Service&quot;<br>      identifiers = [&quot;ecs-tasks.amazonaws.com&quot;]<br>    }<br>  }<br>}<br><br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;ecsTaskExecutionRole_policy&quot; {<br>  role       = aws_iam_role.ecsTaskExecutionRole.name<br>  policy_arn = &quot;arn:aws:iam::aws:policy/service-role/AmazonEC2ContainerServiceforEC2Role&quot;<br>}</pre><p>data.tf</p><pre>data &quot;aws_ecr_repository&quot; &quot;ecr&quot; {<br>  name = &quot;aws-ecs-reactjs-personal-portfolio&quot;<br>}<br><br># vpc details :<br>data &quot;aws_vpc&quot; &quot;this_vpc&quot; {<br>  state = &quot;available&quot;<br>  filter {<br>    name   = &quot;tag:Name&quot;<br>    values = [&quot;custom-vpc&quot;]<br>  }<br>}<br><br>data &quot;aws_security_group&quot; &quot;sg&quot; {<br>  filter {<br>    name   = &quot;tag:Name&quot;<br>    values = [&quot;WebSG&quot;]<br>  }<br>}<br><br>data &quot;aws_security_group&quot; &quot;ext_alb&quot; {<br>  filter {<br>    name   = &quot;tag:Name&quot;<br>    values = [&quot;InternetFacing-ALB&quot;]<br>  }<br>}<br><br># subnets details :<br>data &quot;aws_subnet&quot; &quot;web_subnet_1a&quot; {<br>  vpc_id = data.aws_vpc.this_vpc.id<br>  filter {<br>    name   = &quot;tag:Name&quot;<br>    values = [&quot;weblayer-pub1-1a&quot;]<br>  }<br>}<br><br>data &quot;aws_subnet&quot; &quot;web_subnet_1b&quot; {<br>  vpc_id = data.aws_vpc.this_vpc.id<br>  filter {<br>    name   = &quot;tag:Name&quot;<br>    values = [&quot;weblayer-pub2-1b&quot;]<br>  }<br>}<br><br># Fetching the details of target group:<br>data &quot;aws_lb_target_group&quot; &quot;this_tg&quot; {<br>  name = &quot;TargetGroup-External&quot;<br>}<br><br>data &quot;aws_lb&quot; &quot;this_lb&quot; {<br>  name = &quot;ALB-External&quot;<br>}<br><br>data &quot;aws_lb_listener&quot; &quot;this_lb_listener&quot; {<br>  load_balancer_arn = data.aws_lb.this_lb.arn<br>  port              = 80<br>}</pre><p>cw_log_group.tf</p><pre>resource &quot;aws_cloudwatch_log_group&quot; &quot;log-group&quot; {<br>  name = var.cw_log_grp<br>  tags = var.custom_tags<br>}</pre><p>aws_kms_key.tf</p><pre>resource &quot;aws_kms_key&quot; &quot;kms&quot; {<br>  description             = var.kms_key[&quot;description&quot;]<br>  deletion_window_in_days = var.kms_key[&quot;deletion_window_in_days&quot;]<br>  tags                    = var.custom_tags<br>}</pre><p>ecs.tf</p><pre>resource &quot;aws_ecs_cluster&quot; &quot;aws-ecs-cluster&quot; {<br>  name = var.ecs_details[&quot;Name&quot;]<br>  configuration {<br>    execute_command_configuration {<br>      kms_key_id = aws_kms_key.kms.arn<br>      logging    = var.ecs_details[&quot;logging&quot;]<br>      log_configuration {<br>        cloud_watch_encryption_enabled = true<br>        cloud_watch_log_group_name     = aws_cloudwatch_log_group.log-group.name<br>      }<br>    }<br>  }<br>  tags = var.custom_tags<br>}<br><br>resource &quot;aws_ecs_task_definition&quot; &quot;taskdef&quot; {<br>  family                   = var.ecs_task_def[&quot;family&quot;]<br>  container_definitions    = jsonencode([<br>    {<br>      &quot;name&quot;: &quot;${var.ecs_task_def[&quot;cont_name&quot;]}&quot;,<br>      &quot;image&quot;: &quot;${data.aws_ecr_repository.ecr.repository_url}:latest&quot;,<br>      &quot;entrypoint&quot;: [],<br>      &quot;essential&quot;: &quot;${var.ecs_task_def[&quot;essential&quot;]}&quot;,<br>      &quot;logConfiguration&quot;: {<br>        &quot;logDriver&quot;: &quot;${var.ecs_task_def[&quot;logdriver&quot;]}&quot;,<br>        &quot;options&quot;: {<br>          &quot;awslogs-group&quot;: &quot;${aws_cloudwatch_log_group.log-group.id}&quot;,<br>          &quot;awslogs-region&quot;: &quot;${var.region}&quot;,<br>          &quot;awslogs-stream-prefix&quot;: &quot;app-prd&quot;<br>        }<br>      },<br>      &quot;portMappings&quot;: [<br>        {<br>          &quot;containerPort&quot;: &quot;${var.ecs_task_def[&quot;containerport&quot;]}&quot;,<br>        }<br>      ],<br>      &quot;cpu&quot;: &quot;${var.ecs_task_def[&quot;cpu&quot;]}&quot;,<br>      &quot;memory&quot;: &quot;${var.ecs_task_def[&quot;memory&quot;]}&quot;,<br>      &quot;networkMode&quot;: &quot;${var.ecs_task_def[&quot;networkmode&quot;]}&quot;<br>    }<br>  ])<br><br>  requires_compatibilities = var.ecs_task_def[&quot;requires_compatibilities&quot;]<br>  network_mode             = var.ecs_task_def[&quot;networkmode&quot;]<br>  memory                   = var.ecs_task_def[&quot;memory&quot;]<br>  cpu                      = var.ecs_task_def[&quot;cpu&quot;]<br>  execution_role_arn       = aws_iam_role.ecsTaskExecutionRole.arn<br>  task_role_arn            = aws_iam_role.ecsTaskExecutionRole.arn<br><br>  tags = var.custom_tags<br>}<br><br>resource &quot;aws_ecs_service&quot; &quot;aws_ecs-service&quot; {<br>  name                 = var.ecsservice[&quot;name&quot;]<br>  cluster              = aws_ecs_cluster.aws-ecs-cluster.id<br>  task_definition      = aws_ecs_task_definition.taskdef.family<br>  launch_type          = var.ecsservice[&quot;launch_type&quot;]<br>  scheduling_strategy  = var.ecsservice[&quot;scheduling_strategy&quot;]<br>  desired_count        = var.ecsservice[&quot;desired_count&quot;]<br>  force_new_deployment = var.ecsservice[&quot;force_new_deployment&quot;]<br>  health_check_grace_period_seconds = 100<br><br>  network_configuration {<br>    subnets          = [data.aws_subnet.web_subnet_1a.id, data.aws_subnet.web_subnet_1b.id]<br>    assign_public_ip = true<br>    security_groups = [<br>      data.aws_security_group.sg.id<br>    ]<br>  }<br><br>  load_balancer {<br>    target_group_arn = data.aws_lb_target_group.this_tg.id<br>    container_name   = &quot;ReactJS-Container&quot;<br>    container_port   = 3000<br>  }<br>  depends_on = [<br>    data.aws_lb_listener.this_lb_listener,<br>    ]<br><br>}</pre><p>output.tf</p><pre>output &quot;ecs_arn&quot; {<br>  value = aws_ecs_cluster.aws-ecs-cluster.id<br>}<br><br>output &quot;cw_log_group_arn&quot; {<br>  value = aws_cloudwatch_log_group.log-group.arn<br>}<br><br>output &quot;kms_id&quot; {<br>  value = aws_kms_key.kms.id<br>}<br><br>output &quot;kms_arn&quot; {<br>  value = aws_kms_key.kms.arn<br>}</pre><p>Pipeline File</p><pre>default:<br>  tags: <br>    - gitlab-runner-test<br><br>stages:<br>   - ecs_cluster_build<br><br>ECS_Cluster_Build:<br>  stage: ecs_cluster_build<br>  script:<br>    - terraform init<br>    - terraform plan<br>    - terraform apply --auto-approve</pre><p>Now, we are coming to an end as we have deployed all required resources sequentially as above. Once ecs nodes are treated as healthy, then we can hit load balancer URL, so we can see below screenshot that ensures application is running fine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5V_FllN1uYYFjpSeSwWHUg.png" /></figure><h3><strong>Benefits</strong></h3><ul><li>Customer will be billed for containers only, not underlying hosts, hence it reduces more expenses than earlier.</li><li>Due to light weight, containers can process the user request in very low latency. Also there is no chances of OS crash.</li><li>Containers can be configured with volume which resides on host machine, so the application codes can be resided there that completely removes the space requirement inside a container.</li><li>As containers support microservices approach, so application components can be broken down into multiple isolated sections that are deployed in different containers which reduces the probability of entire application outages.</li></ul><p>That’s all about the containerization, I hope it has been helpful to all of you. In this article I kept the entire concept very simple and that’s why I have chosen public subnets and container with public ips, but in real time scenarios it can’t be public. Of course it must be placed in private subnet in order to make those safe from external networks.</p><p>Hence in coming articles, I will definitely try to cover up same kind of architecture with more security and compliance considerations.</p><p>GitHub Link: <a href="https://github.com/dasanirban834/aws-ecs-reactjs-personal-portfolio">https://github.com/dasanirban834/aws-ecs-reactjs-personal-portfolio</a></p><p>Thanks!! 🙂🙂</p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>.</em></p><p><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>, </em><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><em>, and </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a11a30b0bea9" width="1" height="1" alt=""><hr><p><a href="https://aws.plainenglish.io/deployment-of-containerized-reactjs-application-in-ecs-cluster-with-alb-in-aws-a11a30b0bea9">Deployment of Containerized ReactJS Application in ECS Cluster with ALB in AWS</a> was originally published in <a href="https://aws.plainenglish.io/">AWS in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design and Build a Three Tier Architecture with complete end-to-end Automation]]></title>
            <link>https://aws.plainenglish.io/design-and-build-a-three-tier-architecture-with-complete-end-to-end-automation-9a5e847d9ed0?source=rss-59a29a5892be------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a5e847d9ed0</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[gitlab]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[ansible]]></category>
            <dc:creator><![CDATA[Dasanirban]]></dc:creator>
            <pubDate>Fri, 14 Apr 2023 11:13:39 GMT</pubDate>
            <atom:updated>2023-04-14T13:32:51.133Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introduction:</strong></h3><p>A three tier architecture is a basic approach to design and build any application where application component would be broken into three parts i.e. Presentation Layer(Web layer), Business Logic Layer(Application Layer) and Data Storage layer(Database Layer), the traffic in every servers under each layer will be distributed by Application Load Balancer in order to ensure load is balanced equally across the servers and High Availability. As per traditional approach of application deployment, there was an approach, called Monolithic Architecture which gives a clearance to setup Web, App and DB layer in same machine, hence from cost perspective, definitely this approach is very effective, but not from service or business continuity perspective as there is high chance of all layers down if server gets crashed due to any reason. So, to remove such chances, we follow designing architecture in segregated way where all layers would be placed in different underlying hardware in order to ensure security, compliance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HTEg728WMTLDraGf.jpg" /></figure><h3><strong>Design Considerations:</strong></h3><ul><li><strong>High Availability:</strong> HA is the one of the key considerations while designing an architecture that has been a mandatory practices to be implemented to ensure no failure. In traditional data centers, applications used to be seated in a single data center and in case of any power shutdown issues or natural calamities if data center goes down, then entire application would be down, also huge chances of data loss and all. So, keeping this in mind, AWS brought availability zone concept within a region where multiple data center we can have in a single region, so that applications can be highly available within a region.</li><li><strong>Independency: </strong>As per transitional approach, application used to deploy in a single server that can be risky for all layers. Hence there tier architecture has been introduced where all layers are separated out from each other, so that in case of any faults nothings impacts to other layer, each layer is operating independently.</li><li><strong>Scalability: </strong>When the instances are getting utilized more, then there is need of scaling to ensure that workloads getting operated as usual without any blockages. Hence, Autoscaling group with load balancer can be used to include the instances under a group with proper load balancing. Assuming two instances are equally load balanced, now if any server is getting 80% (threshold 70%) utilized in a Autoscaling group, then another instance will be launched as per mentioned launch template.</li></ul><h3><strong>Architecture:</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FU7qU1lVK4ultl3fogD3Ng.png" /><figcaption>Pic 1: Architecture Diagram</figcaption></figure><h3><strong>Workflow:</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*86LIiJPNqYDqTtR9KOKUZA.png" /><figcaption>Pic 2: Design Workflow</figcaption></figure><ul><li>Here, GitLab is used as a SCM tool as well as CI/CD workflow.</li><li>Terraform Cloud console is being used to build resources in AWS. Here, Terraform Cloud API method is being taken to integrate GitLab project with corresponding terraform Workspace.</li><li>Post build activity is done, Ansible playbooks are ready to execute for provisioning the servers along with OS hardening.</li></ul><h3><strong>Prerequisites:</strong></h3><ol><li>As we are using GitLab CI/CD here, so as gitlab runner a Linux server is provisioned.</li><li>Install ansible-core in same runner machine.</li><li>Create an instance profile and attach it to have admin access to other aws resources.</li><li>Setup a directory for storing secrets in a file. Here, for personal use case, I have created a directory and a JSON file for storing all secrets(passwords/tokens etc.). Also, you can use any other key storage solutions like Hashicorp Vault or AWS secret store.</li><li>Install latest version of python. Also, install <strong>boto3, requests</strong> python modules.</li></ol><h3><strong>Application Source Code Repository:</strong></h3><p><a href="https://github.com/aws-samples/aws-three-tier-web-architecture-workshop.git">https://github.com/aws-samples/aws-three-tier-web-architecture-workshop.git</a></p><h3><strong>Credential Storage File:</strong></h3><p><strong>cred.json</strong></p><pre>{<br> “DB_USER”: “”,<br> “DB_PASSWORD”: “”,<br> “AWS_ACCESS_KEY_ID”: “”,<br> “AWS_SECRET_ACCESS_KEY”: “”,<br> “AWS_DEFAULT_REGION”: “us-east-1”,<br> “ANSIBLE_USER_PASSWORD”: “”,<br> “TFC_API_TOKEN_TEST”: “”,<br> “TFC_API_TOKEN_PROD”: “”<br>}</pre><h3><strong>Customized Scripts:</strong></h3><p>As we are approaching DevOps model here, so there would be a requirement to create some customized scripts to get better realistic view. Here, we have Terraform Cloud API methods to create the resources, using gitlab CI/CD pipeline triggers terraform API through below python script.</p><p>Below two scripts are common for each layer as we are deploying resources through terraform. For better clarity, please check <a href="https://github.com/dasanirban834/aws-three-tier-web-architecture">https://github.com/dasanirban834/aws-three-tier-web-architecture</a></p><p><strong>Name: 1_Env.sh</strong></p><p><strong>Purpose</strong>: Export some variables in bash shell and packages the terraform configuration files.</p><pre>#/bin/bash<br><br>export AWS_ACCESS_KEY_ID=$(cat /home/gitlab-runner/creds/cred.json | jq .AWS_ACCESS_KEY_ID | xargs)<br>export AWS_SECRET_ACCESS_KEY=$(cat /home/gitlab-runner/creds/cred.json | jq .AWS_SECRET_ACCESS_KEY | xargs)<br>export AWS_DEFAULT_REGION=$(cat /home/gitlab-runner/creds/cred.json | jq .AWS_DEFAULT_REGION | xargs)<br>export TFC_API_TOKEN_TEST=$(cat /home/gitlab-runner/creds/cred.json | jq .TFC_API_TOKEN_TEST | xargs)<br>export TFC_API_TOKEN_PROD==$(cat /home/gitlab-runner/creds/cred.json | jq .TFC_API_TOKEN_PROD | xargs)<br>export ENV=&quot;prod&quot;<br>export GITLAB_PROJECT_ID=&quot;&quot;<br>export GITLAB_PROJECT_NAME=&quot;1_web-tier&quot;<br>export GITLAB_PROJECT_PATH=&quot;&quot;<br>export GITLAB_PROJECT_URL=&quot;&quot;<br><br>declare -a arr=(&quot;ENV&quot; &quot;GITLAB_PROJECT_ID&quot; &quot;GITLAB_PROJECT_NAME&quot; &quot;GITLAB_PROJECT_PATH&quot; &quot;GITLAB_PROJECT_URL&quot;)<br>for i in &quot;${arr[@]}&quot;<br>do<br>        echo &quot;$i = ${!i}&quot;<br>done<br><br>export CONTENT_DIRECTORY=Terraform<br>export UPLOAD_FILE_NAME=&quot;./content.tar.gz&quot;<br>tar -zcvf &quot;$UPLOAD_FILE_NAME&quot; -C &quot;$CONTENT_DIRECTORY&quot; .</pre><p><strong>Name: 2_CreateTFCWorkspace.py</strong></p><p><strong>Purpose</strong>: Trigger terraform workspace and create terraform plans</p><pre>#############################################################################################################<br><br>                #Description: Create Terraform Cloud Workspace<br>                # Author: Anirban Das<br><br>#############################################################################################################<br>print(&#39;******************************************************Start Creation of Terraform Cloud Workspace******************************************************&#39;, &#39;\n&#39;)<br><br>import os<br>import requests<br>import json<br>import sys<br>import time<br><br>time.sleep(5)<br># Fetch variables:<br><br>HEADERS = {&quot;Content-Type&quot;: &quot;application/vnd.api+json&quot;,}<br>ENV = os.environ[&quot;ENV&quot;]<br>GITLAB_PROJECT_NAME = os.environ[&#39;GITLAB_PROJECT_NAME&#39;]<br>WORKSPACE_NAME = f&quot;tfc-{GITLAB_PROJECT_NAME}-{ENV}&quot;<br>ORGANIZATION = [&#39;PROD_TFC&#39;, &#39;TEST_TFC&#39;]<br>TFC_URL = &#39;app.terraform.io&#39;<br>print(&#39;\n&#39;)<br># Load credentials :<br><br>def load_api_credentials():<br>    path = &#39;/home/gitlab-runner/creds/cred.json&#39;<br>    with open(path, &#39;r&#39;) as f:<br>        read_data = f.read()<br>        load_data = json.loads(read_data)<br>        if ENV == &#39;prod&#39;:<br>            TFC_API_TOKEN = load_data[&quot;TFC_API_TOKEN_PROD&quot;]<br>            print(f&#39;*************Authentication Update : Production token has been added*************&#39;, &#39;\n&#39;)<br>        elif ENV == &#39;test&#39;:<br>            TFC_API_TOKEN = load_data[&quot;TFC_API_TOKEN_TEST&quot;]<br>            print(f&#39;*************Authentication Update : Testing token has been added*************&#39;, &#39;\n&#39;)<br>        else:<br>            print(&quot;Not Found&quot;)<br><br>        if not TFC_API_TOKEN:<br>            raise RuntimeError(f&quot;Unable to load credentials at {path}&quot;)<br>        else:<br>            HEADERS[&quot;Authorization&quot;] = f&quot;Bearer {TFC_API_TOKEN}&quot;<br><br>load_api_credentials()<br><br>ORGANIZATION = ORGANIZATION[0] if ENV == &#39;prod&#39; else ORGANIZATION[1]<br>os.environ[&#39;ORGANIZATION&#39;] =  ORGANIZATION<br><br>def createtfcworkspce():<br>    get_req = requests.request(&quot;GET&quot;, f&quot;https://{TFC_URL}/api/v2/organizations/{ORGANIZATION}/workspaces/{WORKSPACE_NAME}&quot;, headers=HEADERS)<br>    if get_req.status_code == 200 and &quot;id&quot; in json.loads(get_req.text)[&#39;data&#39;]:<br>        WORKSPACE_ID = json.loads(get_req.text)[&#39;data&#39;][&#39;id&#39;]<br>        print(f&quot;Workspace : \&#39;{WORKSPACE_NAME}\&#39; does already exist. Workspace ID : &quot;, json.loads(get_req.text)[&#39;data&#39;][&#39;id&#39;], &#39;\n&#39;)<br>        time.sleep(5)<br>        os.environ[&#39;WORKSPACE_ID&#39;] = json.loads(get_req.text)[&#39;data&#39;][&#39;id&#39;]<br>    else:<br>        print(&#39;************* Creating of TFC workspaces*************&#39;)<br>        PAYLOAD = json.dumps(<br>                {<br>                      &quot;data&quot;: {<br>                            &quot;attributes&quot;: {<br>                                &quot;name&quot;: WORKSPACE_NAME,<br>                            },<br>                            &quot;type&quot;: &quot;workspaces&quot;<br>                        }<br>                })<br><br>        post_req = requests.request(&quot;POST&quot;, f&quot;https://{TFC_URL}/api/v2/organizations/{ORGANIZATION}/workspaces&quot;, headers=HEADERS, data=PAYLOAD)<br>        print(&#39;\n&#39;)<br>        print(post_req.text, &#39;\n&#39;)<br>        if post_req.status_code == 201 and &quot;id&quot; in json.loads(post_req.text)[&#39;data&#39;]:<br>            WORKSPACE_ID = json.loads(post_req.text)[&#39;data&#39;][&#39;id&#39;]<br>            print(f&#39;Success !! Workspace has been created with {post_req.status_code} code. Workspace ID : {WORKSPACE_ID}&#39;, &#39;\n&#39;)<br>            os.environ[&#39;WORKSPACE_ID&#39;] = json.loads(post_req.text)[&#39;data&#39;][&#39;id&#39;]<br>            def setVar():<br>                print(&#39;***********Add the variables to the workspace***********&#39;, &#39;\n&#39;)<br>                PAYLOAD1 = json.dumps(<br>                        {<br>                            &quot;data&quot;: {<br>                                &quot;type&quot;: &quot;vars&quot;,<br>                                &quot;attributes&quot;: {<br>                                    &quot;key&quot;: &quot;AWS_DEFAULT_REGION&quot;,<br>                                    &quot;value&quot;: os.environ[&#39;AWS_DEFAULT_REGION&#39;],<br>                                    &quot;category&quot;: &quot;env&quot;,<br>                                    &quot;hcl&quot;: False,<br>                                    &quot;sensitive&quot;: True<br>                                },<br>                                &quot;relationships&quot;: {<br>                                    &quot;workspace&quot;: {<br>                                        &quot;data&quot;: {<br>                                            &quot;id&quot;: WORKSPACE_ID,<br>                                            &quot;type&quot;: &quot;workspaces&quot;<br>                                        }<br>                                    }<br>                                }<br>                            }<br>                        })<br><br>                PAYLOAD2 = json.dumps(<br>                        {<br>                            &quot;data&quot;: {<br>                                &quot;type&quot;: &quot;vars&quot;,<br>                                &quot;attributes&quot;: {<br>                                    &quot;key&quot;: &quot;AWS_SECRET_ACCESS_KEY&quot;,<br>                                    &quot;value&quot;: os.environ[&#39;AWS_SECRET_ACCESS_KEY&#39;],<br>                                    &quot;category&quot;: &quot;env&quot;,<br>                                    &quot;hcl&quot;: False,<br>                                    &quot;sensitive&quot;: True<br>                                },<br>                                &quot;relationships&quot;: {<br>                                    &quot;workspace&quot;: {<br>                                        &quot;data&quot;: {<br>                                            &quot;id&quot;: WORKSPACE_ID,<br>                                            &quot;type&quot;: &quot;workspaces&quot;<br>                                        }<br>                                    }<br>                                }<br>                            }<br>                        })<br><br>                PAYLOAD3 = json.dumps(<br>                        {<br>                            &quot;data&quot;: {<br>                                &quot;type&quot;: &quot;vars&quot;,<br>                                &quot;attributes&quot;: {<br>                                    &quot;key&quot;: &quot;AWS_ACCESS_KEY_ID&quot;,<br>                                    &quot;value&quot;: os.environ[&#39;AWS_ACCESS_KEY_ID&#39;],<br>                                    &quot;category&quot;: &quot;env&quot;,<br>                                    &quot;hcl&quot;: False,<br>                                    &quot;sensitive&quot;: True<br>                                },<br>                                &quot;relationships&quot;: {<br>                                    &quot;workspace&quot;: {<br>                                        &quot;data&quot;: {<br>                                            &quot;id&quot;: WORKSPACE_ID,<br>                                            &quot;type&quot;: &quot;workspaces&quot;<br>                                        }<br>                                    }<br>                                }<br>                            }<br>                        })<br><br>                post_req1 = requests.request(&quot;POST&quot;, f&quot;https://{TFC_URL}/api/v2/vars&quot;, headers=HEADERS, data=PAYLOAD1)<br>                print(post_req1.text, post_req1.status_code, &#39;\n&#39;)<br>                time.sleep(1)<br>                post_req2 = requests.request(&quot;POST&quot;, f&quot;https://{TFC_URL}/api/v2/vars&quot;, headers=HEADERS, data=PAYLOAD2)<br>                print(post_req2.text, &#39;\n&#39;)<br>                time.sleep(1)<br>                post_req3 = requests.request(&quot;POST&quot;, f&quot;https://{TFC_URL}/api/v2/vars&quot;, headers=HEADERS, data=PAYLOAD3)<br>                print(post_req3.text, &#39;\n&#39;)<br>                print(&#39;Success !! All the variables have been added to the workspace&#39;, &#39;\n&#39;)<br><br>            setVar()<br>            os.system(&#39;bash&#39;)<br><br>        else:<br>            raise RuntimeError(f&quot;Failed !! Try again.&quot;)<br><br>createtfcworkspce()<br>os.system(&#39;bash&#39;)<br><br># Fetching Workspace ID:<br><br>WORKSPACE_ID = os.environ[&#39;WORKSPACE_ID&#39;]<br><br><br>#############################################################################################################<br><br>                #Description: Create Configuration Versions<br>                # Author: Anirban Das<br><br>#############################################################################################################<br>print(&#39;******************************************************Start Creation of Configuration Versions******************************************************&#39;, &#39;\n&#39;)<br>time.sleep(5)<br>&#39;&#39;&#39; Start Creating Configuration Versions &#39;&#39;&#39;<br><br>PAYLOAD = json.dumps(<br>        {<br>              &quot;data&quot;: {<br>                    &quot;type&quot;: &quot;configuration-versions&quot;,<br>                    &quot;attributes&quot;: {<br>                        &quot;auto-queue-runs&quot;: False<br>                    }<br>                }<br>        })<br><br>post_req = requests.request(&quot;POST&quot;, f&quot;https://{TFC_URL}/api/v2/workspaces/{WORKSPACE_ID}/configuration-versions&quot;, headers=HEADERS, data=PAYLOAD)<br>time.sleep(2)<br>print(post_req.text, &#39;\n&#39;)<br>time.sleep(1)<br>if post_req.status_code == 201 and &#39;id&#39; in json.loads(post_req.text)[&#39;data&#39;]:<br>    print(f&quot;Status Code : {post_req.status_code}. Configuration version is created succesfully.&quot;, &#39;\n&#39;)<br>    time.sleep(1)<br>    CV_ID = json.loads(post_req.text)[&#39;data&#39;][&#39;id&#39;]<br>    os.environ[&#39;CV_ID&#39;] = CV_ID<br>    print(f&quot;Configuration Versions ID : {CV_ID}&quot;, &#39;\n&#39;)<br>    time.sleep(1)<br>    UPLOAD_URL = json.loads(post_req.text)[&#39;data&#39;][&#39;attributes&#39;][&#39;upload-url&#39;]<br>    time.sleep(2)<br>    print(f&quot;UPLOAD URL : {UPLOAD_URL}&quot;, &#39;\n&#39;)<br>    os.environ[&#39;UPLOAD_URL&#39;] = UPLOAD_URL<br>else:<br>    raise RuntimeError(&quot;Creation Failed. Please try again.&quot;)<br><br><br>#############################################################################################################<br><br>                #Description: Uploading COnfiguration Files<br>                # Author: Anirban Das<br><br>#############################################################################################################<br>print(&#39;******************************************************Uploading Configuration Versions******************************************************&#39;, &#39;\n&#39;)<br>time.sleep(5)<br><br>&#39;&#39;&#39;Upload Configuration Files&#39;&#39;&#39;<br><br>UPLOAD_URL = os.environ[&#39;UPLOAD_URL&#39;]<br>UPLOAD_FILE_NAME = os.environ[&#39;UPLOAD_FILE_NAME&#39;]<br>HEADER_1 = {&#39;Content-Type&#39;: &#39;multipart/form-data&#39;}<br>files = {&#39;files&#39;: open(UPLOAD_FILE_NAME, &#39;rb&#39;)}<br><br>put_req = requests.request(&quot;PUT&quot;, UPLOAD_URL, files=files)<br>time.sleep(1)<br>print(f&#39;Status : {put_req.status_code}&#39;, &#39;\n&#39;)<br>#print(put_req.text)<br>if put_req.status_code == 200:<br>    time.sleep(1)<br>    print(&quot;Success !! Files have been uploaded&quot;, &#39;\n&#39;)<br>else:<br>    print(&quot;Failed. Try again&quot;, &#39;\n&#39;)<br><br># Fetching Oragnization and CV_ID:<br><br>ORGANIZATION = os.environ[&#39;ORGANIZATION&#39;]<br>CV_ID = os.environ[&#39;CV_ID&#39;]<br><br>#############################################################################################################<br><br>                #Description: Create Terraform Run and Plan<br>                # Author: Anirban Das<br><br>#############################################################################################################<br>print(&#39;******************************************************Start Create Run Job******************************************************&#39;, &#39;\n&#39;)<br>time.sleep(5)<br><br>&#39;&#39;&#39;Create a run:&#39;&#39;&#39;<br><br>PAYLOAD = json.dumps(<br>        {<br>            &quot;data&quot;: {<br>                &quot;attributes&quot;: {<br>                    &quot;message&quot;: &quot;Triggered via API&quot;<br>                },<br>            &quot;type&quot;: &quot;runs&quot;,<br>            &quot;relationships&quot;: {<br>                &quot;workspace&quot;: {<br>                    &quot;data&quot;: {<br>                        &quot;type&quot;: &quot;workspaces&quot;,<br>                        &quot;id&quot;: WORKSPACE_ID<br>                    }<br>                },<br>                &quot;configuration-version&quot;: {<br>                    &quot;data&quot;: {<br>                        &quot;type&quot;: &quot;configuration-versions&quot;,<br>                        &quot;id&quot;: CV_ID<br>                    }<br>                }<br>            }<br>            }<br>        })<br><br>post_req = requests.request(&quot;POST&quot;, f&quot;https://{TFC_URL}/api/v2/runs&quot;, headers=HEADERS, data=PAYLOAD)<br>print(post_req.text, &#39;\n&#39;)<br>status = json.loads(post_req.text)[&#39;data&#39;][&#39;attributes&#39;][&#39;status&#39;]<br>if post_req.status_code == 201 and json.loads(post_req.text)[&#39;data&#39;][&#39;attributes&#39;][&#39;status&#39;] == &#39;pending&#39;:<br>    run_id = json.loads(post_req.text)[&#39;data&#39;][&#39;id&#39;]<br>    if run_id == &quot;&quot;:<br>        print(&quot;Running workspace failed&quot;)<br>    else:<br>        print(f&quot;Succeeded. The run id is : {run_id}&quot;, &#39;\n&#39;)<br>        os.environ[&#39;RUN_ID&#39;] = run_id<br>        run_details = requests.request(&quot;GET&quot;, f&quot;https://{TFC_URL}/api/v2/runs/{run_id}&quot;, headers=HEADERS)<br>        print(run_details.text, &#39;\n&#39;)<br>        status = json.loads(run_details.text)[&#39;data&#39;][&#39;attributes&#39;][&#39;status&#39;]<br>        print(f&quot;Run Status : {status}&quot;, &#39;\n&#39;)<br>        plan_id = json.loads(run_details.text)[&#39;data&#39;][&#39;relationships&#39;][&#39;plan&#39;][&#39;data&#39;][&#39;id&#39;]<br>        apply_id = json.loads(run_details.text)[&#39;data&#39;][&#39;relationships&#39;][&#39;apply&#39;][&#39;data&#39;][&#39;id&#39;]<br>        os.environ[&#39;PLAN_ID&#39;] =  plan_id<br>        os.environ[&#39;APPLY_ID&#39;] = apply_id<br>        print(f&quot;Plan execution status : \&#39;{status}\&#39; and Plan ID is : {plan_id}&quot;, &#39;\n&#39;)<br>        time.sleep(5)<br>        def call_api(number):<br>            for i in range(number):<br>                time.sleep(1.5)<br>                show_status = requests.request(&quot;GET&quot;, f&quot;https://{TFC_URL}/api/v2/plans/{plan_id}&quot;, headers=HEADERS)<br>                plan_status = json.loads(show_status.text)[&#39;data&#39;][&#39;attributes&#39;][&#39;status&#39;]<br>                if plan_status ==  &quot;pending&quot;:<br>                        print(f&quot;Plan Status : {plan_status}&quot;)<br>                elif plan_status == &quot;agent_queued&quot;:<br>                        print(f&quot;Plan Status : {plan_status}&quot;)<br>                elif plan_status == &quot;running&quot;:<br>                        print(f&quot;Plan Status : {plan_status}&quot;)<br>                elif plan_status == &quot;errored&quot;:<br>                        print(f&quot;Plan Status : {plan_status}&quot;, &#39;\n&#39;)<br>                        raise RuntimeError(&quot;Error !! Please try again&quot;)<br>                elif plan_status == &quot;canceled&quot;:<br>                        print(f&quot;Plan Status : {plan_status}&quot;, &#39;\n&#39;)<br>                        raise RuntimeError(&quot;Cancelation has been triggered, hence closing this process&quot;)<br>                        sys.exit(0)<br>                elif plan_status == &quot;finished&quot;:<br>                        print(f&quot;Plan Status : {plan_status}&quot;, &#39;\n&#39;)<br>                        print(&quot;Planning has been completed successfully&quot;, &#39;\n&#39;)<br>                        RUN_ID = os.environ[&#39;RUN_ID&#39;]<br>                        PLAN_ID = os.environ[&#39;PLAN_ID&#39;]<br>                        APPLY_ID = os.environ[&#39;APPLY_ID&#39;]<br>                        print(f&quot; Run ID : {RUN_ID} \n Plan ID : {PLAN_ID} \n Apply ID : {APPLY_ID} \n &quot;)<br>                        sys.exit(0)<br><br>        call_api(30)</pre><p><strong>Name: validate_ec2_ready.py</strong></p><p><strong>Purpose: </strong>To get real time Instance health status since instances launched.</p><p>This script gets executed based on the tag “Layer” added to the instances. For App layer and Web layer the value would be “App” and “Web” respectively and script will fetch those instances only which is having same tags. This script keeps on showing the status once instances start initializing until 2/2 checks are green.</p><pre>import boto3<br>import json<br>import os<br>import sys<br>import time<br><br>client = boto3.client(&#39;ec2&#39;)<br>response = client.describe_instances(<br>    Filters=[<br>        {<br>            &#39;Name&#39;: &#39;tag:Layer&#39;,<br>            &#39;Values&#39;: [<br>                &#39;App&#39;<br>            ]<br>        }<br>    ]<br>)<br><br>status_code = []<br>instance_id = []<br>for r in response[&#39;Reservations&#39;]:<br>    for i in r[&#39;Instances&#39;]:<br>        id = i[&#39;InstanceId&#39;]<br>        instance_id.append(id)<br><br>def validate_ec2_ready():<br>        for ins in range(0, len(instance_id)):<br>            instance_status_resp = client.describe_instance_status(<br>                InstanceIds=[<br>                    instance_id[ins],<br>                ],<br>            )<br>            for insstat in instance_status_resp[&#39;InstanceStatuses&#39;]:<br>                Instance_Status = insstat[&#39;InstanceStatus&#39;][&#39;Status&#39;]<br>                System_Status = insstat[&#39;SystemStatus&#39;][&#39;Status&#39;]<br>                print(f&quot;Index: {ins} =&gt; InstanceId: {instance_id[ins]} =&gt; Instance_Status: {Instance_Status} =&gt; System_Status: {System_Status}&quot;)<br>                if Instance_Status and System_Status == &quot;initializing&quot;:<br>                    status_dict = {<br>                        &quot;Status_Code&quot;: &quot;1&quot;,<br>                        &quot;Comments&quot;: &quot;Instances are not ready. Please wait few minutes&quot;<br>                    }<br>                    status_code.append(status_dict[&#39;Status_Code&#39;])<br>                elif Instance_Status and System_Status == &quot;impaired&quot;:<br>                    status_dict = {<br>                        &quot;Status_Code&quot;: &quot;0&quot;,<br>                        &quot;Comments&quot;: &quot;Instances are not instantiated due to some reasons. Please try to stop and start the instances again.&quot;<br>                    }<br>                    status_code.append(status_dict[&#39;Status_Code&#39;])<br><br>                elif Instance_Status and System_Status == &quot;ok&quot;:<br>                    status_dict = {<br>                        &quot;Status_Code&quot;: &quot;2&quot;,<br>                        &quot;Comments&quot;: &quot;Success!! Instances are ready.&quot;<br>                    }<br>                    status_code.append(status_dict[&#39;Status_Code&#39;])<br><br><br>for i in range(100):<br>    print(&quot;Iteration:&quot;, i)<br>    if len(status_code) != len(instance_id) and status_code.count(&quot;2&quot;) != len(instance_id):<br>        time.sleep(5)<br>        validate_ec2_ready()<br>        print(f&quot;Status code in iteration {i}: {status_code}&quot;, &#39;\n&#39;)<br>        if status_code.count(&quot;2&quot;) == len(instance_id):<br>            print(f&quot;All EC2 instances are ready to work. Standing time starts..&quot;)<br>            time.sleep(30)<br>            sys.exit()<br>        status_code.clear()</pre><h3><strong>Networking:</strong></h3><p>For this implementation, all networking components and security groups are created manually. Later the properties of those resources are fetched using data block in Terraform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*cuOLEDRKRu2FBxEskVQ3Aw.png" /></figure><h3><strong>Database Tier:</strong></h3><p>For database layer, Multi-AZ RDS cluster has been chosen with aurora-mysql DB engine. One is writer instance to accept all write operations and other one is a read replica for handling read operations. Read replica is a key factor to reduce workload from writer node and forward all read level operations to reader node to get better performance.</p><pre>├── Scripts<br>│   ├── 1_Env.sh<br>│   ├── 2_CreateTFCWorkspace.py<br>│   └── 7_Cleanup.sh<br>└── Terraform<br>    ├── data.tf<br>    ├── db.tf<br>    ├── output.tf<br>    ├── provider.tf<br>    ├── terraform.tfvars<br>    └── var.tf</pre><ul><li><strong>data.tf</strong></li></ul><pre># vpc details :<br>data &quot;aws_vpc&quot; &quot;this_vpc&quot; {<br>  state = &quot;available&quot;<br>  filter {<br>    name   = &quot;tag:Name&quot;<br>    values = [&quot;custom-vpc&quot;]<br>  }<br>}<br><br># subnets details :<br>data &quot;aws_subnet&quot; &quot;db_subnet_1a&quot; {<br>  vpc_id = data.aws_vpc.this_vpc.id<br>  filter {<br>    name   = &quot;tag:Name&quot;<br>    values = [&quot;dblayer-priv1-1a&quot;]<br>  }<br>}<br><br>data &quot;aws_subnet&quot; &quot;db_subnet_1b&quot; {<br>  vpc_id = data.aws_vpc.this_vpc.id<br>  filter {<br>    name   = &quot;tag:Name&quot;<br>    values = [&quot;dblayer-priv2-1b&quot;]<br>  }<br>}<br><br># DB Security group details:<br>data &quot;aws_security_group&quot; &quot;sg&quot; {<br>  filter {<br>    name   = &quot;tag:Layer&quot;<br>    values = [&quot;DB&quot;]<br>  }<br>}</pre><ul><li>var.tf</li></ul><pre>variable &quot;subnet_grp_name&quot; {<br>  description = &quot;Subnet Group Name of RDS instance&quot;<br>  type        = string<br>  default     = &quot;&quot;<br>}<br><br>variable &quot;subnet_grp_tags&quot; {<br>  type = map(any)<br>  default = {<br>    &quot;Name&quot; = &quot;RDS-Subnet-Group&quot;<br>  }<br>}<br><br>variable &quot;cluster_details&quot; {<br>  type = map(object({<br>    cluster_identifier      = string<br>    database_name           = string<br>    engine                  = string<br>    engine_version          = string<br>    master_username         = string<br>    master_password         = string<br>    backup_retention_period = number<br>    apply_immediately       = bool<br><br><br>  }))<br><br>}<br><br>variable &quot;cluster_instance_class&quot; {<br>  type    = string<br>  default = &quot;&quot;<br>}</pre><ul><li><strong>terraform.tfvars</strong></li></ul><pre>subnet_grp_name = &quot;db-subnet-group&quot;<br><br>cluster_details = {<br>  &quot;db_1&quot; = {<br>    cluster_identifier      = &quot;database1&quot;<br>    database_name           = &quot;database1&quot;<br>    engine                  = &quot;aurora-mysql&quot;<br>    engine_version          = &quot;5.7.mysql_aurora.2.11.2&quot;<br>    master_username         = &quot;&quot;<br>    master_password         = &quot;&quot;<br>    backup_retention_period = 1<br>    apply_immediately       = true<br>  }<br>}<br><br>cluster_instance_class = &quot;db.t3.small&quot;</pre><ul><li>db.tf</li></ul><pre>locals {<br>  subnet = [data.aws_subnet.db_subnet_1a.id, data.aws_subnet.db_subnet_1b.id]<br>}<br><br>resource &quot;aws_db_subnet_group&quot; &quot;subnet_grp&quot; {<br>  name       = var.subnet_grp_name<br>  subnet_ids = local.subnet<br>  tags       = var.subnet_grp_tags<br>}<br><br>resource &quot;aws_rds_cluster&quot; &quot;cluster&quot; {<br>  for_each                = var.cluster_details<br>  cluster_identifier      = each.value.cluster_identifier<br>  database_name           = each.value.database_name<br>  db_subnet_group_name    = aws_db_subnet_group.subnet_grp.name<br>  engine                  = each.value.engine<br>  engine_version          = each.value.engine_version<br>  master_username         = each.value.master_username<br>  master_password         = each.value.master_password<br>  backup_retention_period = each.value.backup_retention_period<br>  apply_immediately       = each.value.apply_immediately<br>  vpc_security_group_ids  = [data.aws_security_group.sg.id]<br>}<br><br>resource &quot;aws_rds_cluster_instance&quot; &quot;cluster_instances&quot; {<br>  count              = 2<br>  identifier         = &quot;instance-${count.index}&quot;<br>  cluster_identifier = element([for i in aws_rds_cluster.cluster : i.id], 0)<br>  instance_class     = var.cluster_instance_class<br>  engine             = element([for i in aws_rds_cluster.cluster : i.engine], 0)<br>  engine_version     = element([for i in aws_rds_cluster.cluster : i.engine_version_actual], 0)<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*avARxFpRY30RQVfyigiHxg.png" /></figure><h3><strong>Application Tier:</strong></h3><p>Deploying application tier consists of multiple phases in gitlab ci/cd pipeline 1. Build Instances and internal ALB, 2.Provisioning and OS hardening using Ansible, 3. Application installation and provisioning using Ansible.</p><pre>app-tier<br>├── Ansible<br>│   ├── inventory<br>│   ├── playbook<br>│   ├── roles<br>│   └── variable<br>├── AppScript<br>     └── deployment<br>        |── application.yml<br>        |── DbConfig.js<br>        ├── deployment.sh<br>        ├── env.sh<br>        ├── hosts<br>        └── vars.yml<br>├── BuildScript<br>│   ├── 1_Env.sh<br>│   ├── 2_CreateTFCWorkspace.py<br>│   ├── 7_Cleanup.sh<br>│   ├── inventory.sh<br>│   └── validate_ec2_ready.py<br>├── README.md<br>└── Terraform<br>    ├── data.tf<br>    ├── ec2.tf<br>    ├── internal_alb.tf<br>    ├── output.tf<br>    ├── provider.tf<br>    ├── terraform.tfvars<br>    ├── user_data.sh<br>    └── variable.tf</pre><p><strong>Resource Deployment:</strong></p><ul><li><strong>data.tf</strong></li></ul><pre>################ Fetch AZs details#################<br>data &quot;aws_availability_zones&quot; &quot;azs&quot; {<br>  state = &quot;available&quot;<br>}<br><br><br>########################################################################<br>#                                                                      #<br>#             :: Fetch IAM roles for Administrative actions ::         #<br>#                                                                      #<br>########################################################################<br><br>data &quot;aws_iam_role&quot; &quot;role&quot; {<br>  name = &quot;CustomEC2AdminAccess&quot;<br>}<br><br><br>########################################################################<br>#                                                                      #<br>#             :: Fetch Keypair details ::                              #<br>#                                                                      #<br>########################################################################<br><br>data &quot;aws_key_pair&quot; &quot;key&quot; {<br>  key_name           = &quot;keypair&quot;<br>  include_public_key = true<br>}<br><br>########################################################################<br>#                                                                      #<br>#             :: Fetch Web SG details ::                             #<br>#                                                                      #<br>########################################################################<br><br>data &quot;aws_security_group&quot; &quot;sg&quot; {<br>  filter {<br>    name   = &quot;tag:Layer&quot;<br>    values = [&quot;App&quot;]<br>  }<br>}<br>data &quot;aws_security_group&quot; &quot;mgmt&quot; {<br>  filter {<br>    name   = &quot;tag:Layer&quot;<br>    values = [&quot;Management&quot;]<br>  }<br>}<br><br>data &quot;aws_security_group&quot; &quot;int_alb&quot; {<br>  filter {<br>    name   = &quot;tag:Name&quot;<br>    values = [&quot;InternalFacing-ALB&quot;]<br>  }<br>}<br><br>########################################################################<br>#                                                                      #<br>#             :: Fetch Netwroking details ::                           #<br>#                                                                      #<br>########################################################################<br><br># vpc details :<br>data &quot;aws_vpc&quot; &quot;this_vpc&quot; {<br>  state = &quot;available&quot;<br>  filter {<br>    name   = &quot;tag:Name&quot;<br>    values = [&quot;custom-vpc&quot;]<br>  }<br>}<br><br># subnets details :<br>data &quot;aws_subnet&quot; &quot;app_subnet_1a&quot; {<br>  vpc_id = data.aws_vpc.this_vpc.id<br>  filter {<br>    name   = &quot;tag:Name&quot;<br>    values = [&quot;applayer-priv1-1a&quot;]<br>  }<br>}<br><br>data &quot;aws_subnet&quot; &quot;app_subnet_1b&quot; {<br>  vpc_id = data.aws_vpc.this_vpc.id<br>  filter {<br>    name   = &quot;tag:Name&quot;<br>    values = [&quot;applayer-priv2-1b&quot;]<br>  }<br>}<br><br># internet gateway details :<br>data &quot;aws_internet_gateway&quot; &quot;this_igw&quot; {<br>  filter {<br>    name   = &quot;tag:Name&quot;<br>    values = [&quot;Internet Gateway&quot;]<br>  }<br>}<br><br># route table details :<br>data &quot;aws_route_table&quot; &quot;pub_rt&quot; {<br>  filter {<br>    name   = &quot;tag:Name&quot;<br>    values = [&quot;custom-route-table-public&quot;]<br>  }<br>}<br>data &quot;aws_route_table&quot; &quot;priv_rt&quot; {<br>  filter {<br>    name   = &quot;tag:Name&quot;<br>    values = [&quot;custom-route-table-private&quot;]<br>  }<br>}<br><br># public route details :<br>data &quot;aws_route&quot; &quot;pub_r&quot; {<br>  route_table_id = data.aws_route_table.pub_rt.id<br>  gateway_id     = data.aws_internet_gateway.this_igw.id<br>}<br><br># private route details<br>data &quot;aws_route&quot; &quot;priv_r&quot; {<br>  route_table_id = data.aws_route_table.priv_rt.id<br>  nat_gateway_id = data.aws_nat_gateway.ngw.id<br>}<br><br>#NAT Gateway details :<br>data &quot;aws_nat_gateway&quot; &quot;ngw&quot; {<br>  filter {<br>    name   = &quot;tag:Name&quot;<br>    values = [&quot;NAT&quot;]<br>  }<br>}</pre><ul><li><strong>variable.tf</strong></li></ul><pre>variable &quot;alb_tags&quot; {<br>  description = &quot;provides the tags for ALB&quot;<br>  type = object({<br>    Environment = string<br>    Email       = string<br>    Type        = string<br>    Owner       = string<br>  })<br>  default = {<br>    Email       = &quot;dasanirban0806@gmail.com&quot;<br>    Environment = &quot;Production&quot;<br>    Owner       = &quot;Anirban Das&quot;<br>    Type        = &quot;Internal&quot;<br>  }<br>}<br><br>variable &quot;instance_tags&quot; {<br>  description = &quot;provides customized tags&quot;<br>  type = object({<br>    Environment = string<br>    Email       = string<br>    Layer       = string<br>    Owner       = string<br>  })<br>  default = {<br>    Email       = &quot;dasanirban0806@gmail.com&quot;<br>    Environment = &quot;Production&quot;<br>    Layer       = &quot;App&quot;<br>    Owner       = &quot;Anirban Das&quot;<br>  }<br><br>}<br><br>variable &quot;instance_profile&quot; {<br>  type = string<br>}<br><br>variable &quot;instance_details&quot; {<br>  description = &quot;Provides requiered information regarding instances&quot;<br>  type = map(object({<br><br>    availability_zone           = string<br>    ami                         = string<br>    instance_type               = string<br>    associate_public_ip_address = bool<br>    server_category             = string<br>    source_dest_check           = bool<br><br>    root_block_device = map(object({<br>      volume_size = number<br>      volume_type = string<br>    }))<br>    ebs_block_device = map(object({<br>      volume_size = number<br>      volume_type = string<br>    }))<br>  }))<br><br>}<br><br>############### Application Load Balancer Variables################<br><br>variable &quot;TG_conf&quot; {<br>  type = object({<br>    name              = string<br>    port              = string<br>    protocol          = string<br>    target_type       = string<br>    enabled           = bool<br>    healthy_threshold = string<br>    interval          = string<br>    path              = string<br>  })<br>}<br><br>variable &quot;ALB_conf&quot; {<br>  type = object({<br>    name               = string<br>    internal           = bool<br>    load_balancer_type = string<br>    ip_address_type    = string<br>  })<br>}<br><br>variable &quot;Listener_conf&quot; {<br>  type = map(object({<br>    port        = string<br>    protocol    = string<br>    type        = string<br>    priority    = number<br>  }))<br>}</pre><ul><li><strong>terraform.tfvars</strong></li></ul><pre># ########################################################################<br># #                                                                      #<br># #                 ::  Instance details ::                              #<br># #                                                                      #<br># ########################################################################<br><br>instance_details = {<br>  App-Server-VM1 = {<br>    server_category             = &quot;App&quot;<br>    availability_zone           = &quot;us-east-1a&quot;<br>    ami                         = &quot;ami-04581fbf744a7d11f&quot;<br>    instance_type               = &quot;t2.micro&quot;<br>    associate_public_ip_address = false<br>    source_dest_check           = true<br>    root_block_device = {<br>      &quot;root_block&quot; = {<br>        volume_size = 8<br>        volume_type = &quot;gp2&quot;<br>      }<br>    }<br>    ebs_block_device = {}<br>  },<br><br>  App-Server-VM2 = {<br>    server_category             = &quot;App&quot;<br>    availability_zone           = &quot;us-east-1b&quot;<br>    ami                         = &quot;ami-04581fbf744a7d11f&quot;<br>    instance_type               = &quot;t2.micro&quot;<br>    associate_public_ip_address = false<br>    source_dest_check           = true<br>    root_block_device = {<br>      &quot;root_block&quot; = {<br>        volume_size = 8<br>        volume_type = &quot;gp2&quot;<br>      }<br>    }<br>    ebs_block_device = {}<br>  }<br>}<br><br>instance_profile = &quot;CustomInstanceprofile&quot;<br><br>TG_conf = {<br>  enabled           = true<br>  healthy_threshold = &quot;5&quot;<br>  interval          = &quot;10&quot;<br>  name              = &quot;TargetGroup-Internal&quot;<br>  port              = &quot;4000&quot;<br>  protocol          = &quot;HTTP&quot;<br>  target_type       = &quot;instance&quot;<br>  path              = &quot;/health&quot;<br>}<br><br>ALB_conf = {<br>  internal           = true<br>  ip_address_type    = &quot;ipv4&quot;<br>  load_balancer_type = &quot;application&quot;<br>  name               = &quot;ALB-Internal&quot;<br>}<br><br>Listener_conf = {<br>  &quot;1&quot; = {<br>    port        = &quot;80&quot;<br>    priority    = 100<br>    protocol    = &quot;HTTP&quot;<br>    type        = &quot;forward&quot;<br>  }<br>}</pre><ul><li><strong>internal_alb.tf</strong></li></ul><pre>resource &quot;aws_lb_target_group&quot; &quot;this_tg&quot; {<br>  name     = var.TG_conf[&quot;name&quot;]<br>  port     = var.TG_conf[&quot;port&quot;]<br>  protocol = var.TG_conf[&quot;protocol&quot;]<br>  vpc_id   = data.aws_vpc.this_vpc.id<br>  health_check {<br>    enabled           = var.TG_conf[&quot;enabled&quot;]<br>    healthy_threshold = var.TG_conf[&quot;healthy_threshold&quot;]<br>    interval          = var.TG_conf[&quot;interval&quot;]<br>    path              = var.TG_conf[&quot;path&quot;]<br>  }<br>  target_type = var.TG_conf[&quot;target_type&quot;]<br>  tags = {<br>    Attached_ALB_dns = aws_lb.this_alb.dns_name<br>  }<br>}<br><br>resource &quot;aws_lb_target_group_attachment&quot; &quot;this_tg_atchmnt&quot; {<br>  count            = length(var.instance_details)<br>  target_group_arn = aws_lb_target_group.this_tg.arn<br>  target_id        = element([for v in aws_instance.instance : v.id], count.index)<br>  port             = 4000<br>}<br><br>resource &quot;aws_lb&quot; &quot;this_alb&quot; {<br>  name               = var.ALB_conf[&quot;name&quot;]<br>  load_balancer_type = var.ALB_conf[&quot;load_balancer_type&quot;]<br>  ip_address_type    = var.ALB_conf[&quot;ip_address_type&quot;]<br>  internal           = var.ALB_conf[&quot;internal&quot;]<br>  security_groups    = [data.aws_security_group.int_alb.id]<br>  subnets            = [data.aws_subnet.app_subnet_1a.id, data.aws_subnet.app_subnet_1b.id]<br>  tags               = merge(var.alb_tags)<br>}<br><br>resource &quot;aws_lb_listener&quot; &quot;this_alb_lis&quot; {<br>  for_each          = var.Listener_conf<br>  load_balancer_arn = aws_lb.this_alb.arn<br>  port              = each.value[&quot;port&quot;]<br>  protocol          = each.value[&quot;protocol&quot;]<br>  default_action {<br>    type = each.value[&quot;type&quot;]<br>    target_group_arn = aws_lb_target_group.this_tg.arn<br>  }<br>}<br><br>resource &quot;aws_lb_listener_rule&quot; &quot;this_alb_lis_rule&quot; {<br>  for_each     = var.Listener_conf<br>  listener_arn = element([for k, v in aws_lb_listener.this_alb_lis : v.arn], 0)<br>  priority     = each.value[&quot;priority&quot;]<br>  action {<br>    type             = &quot;forward&quot;<br>    target_group_arn = aws_lb_target_group.this_tg.arn<br>  }<br>  condition {<br>    path_pattern {<br>      values = [&quot;/health&quot;]<br>    }<br>  }<br>}</pre><ul><li><strong>user_data.sh</strong></li></ul><pre>#!/bin/bash<br>sudo yum update -y<br>USER=&#39;ansible&#39;<br>sudo useradd -m $USER<br>sudo mkdir /home/$USER/.ssh<br>sudo echo $ANSIBLE_PUBLIC_SSH_KEY &gt; /home/$USER/.ssh/authorized_keys<br>sudo chown -R $USER:$USER /home/$USER/.ssh/<br>sudo chown -R $USER:$USER /home/$USER/.ssh/authorized_keys<br>sudo echo &#39;&#39;$USER&#39;  ALL=(ALL) NOPASSWD: ALL&#39; &gt; /etc/sudoers.d/11-$USER<br>sudo yum install git -y</pre><ul><li><strong>ec2.tf</strong></li></ul><pre># ########################################################################<br># #                                                                      #<br># #             :: Create instance profile ::                            #<br># #                                                                      #<br># ########################################################################<br><br>resource &quot;aws_iam_instance_profile&quot; &quot;instance_profile&quot; {<br>  name = var.instance_profile<br>  role = data.aws_iam_role.role.name<br>}<br><br># ########################################################################<br># #                                                                      #<br># #             :: Create Web Tier Instances ::                          #<br># #                                                                      #<br># ########################################################################<br><br><br><br>resource &quot;aws_instance&quot; &quot;instance&quot; {<br>  for_each                    = var.instance_details<br>  instance_type               = each.value.instance_type<br>  ami                         = each.value.ami<br>  associate_public_ip_address = each.value.associate_public_ip_address<br>  source_dest_check           = each.value.source_dest_check<br>  availability_zone           = each.value.availability_zone<br>  key_name                    = data.aws_key_pair.key.key_name<br>  iam_instance_profile        = aws_iam_instance_profile.instance_profile.name<br>  subnet_id                   = (each.value.availability_zone == &quot;us-east-1a&quot; ? data.aws_subnet.app_subnet_1a.id : (each.value.availability_zone == &quot;us-east-1b&quot; ? data.aws_subnet.app_subnet_1b.id : &quot;0&quot;))<br>  vpc_security_group_ids      = [data.aws_security_group.sg.id]<br>  root_block_device {<br>    volume_size = each.value.root_block_device.root_block.volume_size<br>    volume_type = each.value.root_block_device.root_block.volume_type<br>  }<br>  user_data = &quot;${file(&quot;user_data.sh&quot;)}&quot;<br>  #ebs_block_device {}<br>  tags = merge({ Name = &quot;${each.key}&quot; }, var.instance_tags)<br>}</pre><p><strong>OS Hardening:</strong></p><p>Before starting the ansible pipeline, we need to make sure that actual ssh key is added in <strong>/home/ansible/.ssh/authorized_keys</strong> file. If the keys content is not there due to any reason, then try to copy the content manually for now.</p><p>Here, we will notice that no inventory file is uploaded in the gitlab project, so actually there is a shell script <strong>inventory.sh </strong>under<strong> </strong>BuildScript folder which basically fetches all the private IP addresses of instances matching with mentioned tag “Layer” and creates a host file during runtime.</p><ul><li><strong>inventory.sh</strong></li></ul><pre>#!/bin/bash<br>TAG_NAME=&quot;Layer&quot;<br>TAG_VAL=&quot;App&quot;<br>echo &quot;`aws ec2 describe-instances --filters &quot;Name=tag:Layer, Values=App&quot; --query &#39;Reservations[*].Instances[*].PrivateIpAddress&#39; --output text | awk &#39;{print $1&quot; &quot;&quot;ansible_user=ansible&quot;}&#39;`\n&quot; &gt; ./Ansible/inventory/host<br>sed &#39;$ s/..$//&#39; ./Ansible/inventory/host &gt; ./Ansible/inventory/hosts<br>rm -f ./Ansible/inventory/host<br>cp -r ./Ansible/inventory/hosts AppScript/deployment/</pre><p>Once “host” file is created, then ansible playbook “main.yml” should be run to provision instances.</p><ul><li><strong>main.yml</strong></li></ul><pre>---<br><br>- name: Play 1 | Install MySQL<br>  hosts: all<br>  become: true<br>  gather_facts: true<br>  tasks:<br>    - yum:<br>        name: mysql<br>        state: present<br>      register: mysql<br><br>    - debug:<br>        msg: &quot;{{ mysql }}&quot;<br><br>- name: Play 2 | Set Hostname and ceate users and provide sudo access<br>  hosts: all<br>  become: true<br>  gather_facts: true<br>  vars_files:<br>    - ../variable/vars.yml<br>    - ../variable/vault.yml<br>  roles:<br>    - ../roles/useradd<br>    - ../roles/sudo<br>    - ../roles/hostnamectl<br><br>- name: Play 3 | Perform OS Hardening actions<br>  hosts: all<br>  gather_facts: false<br>  become: true<br>  roles:<br>    - ../roles/ssh<br>    - ../roles/login_banner<br>    - ../roles/services<br>    - ../roles/timezone<br>    - ../roles/fs_integrity<br>    - ../roles/log_management<br>    - ../roles/rsyslog<br>    - ../roles/cron<br>    - ../roles/journald</pre><p><strong>Application Installation &amp; Provisioning:</strong></p><p>Before application installation, we need to connect database write instance from the app instance residing in same AZ and execute below SQL commands manually to create database and other configurations.</p><p><strong><em>Note: Please make sure before application is installed, Database is configured correctly..</em></strong></p><ul><li><strong>Database Connections (Manual)</strong></li></ul><pre>mysql -h &lt;rds-write-node-endpoint&gt; -u &lt;username&gt; -p<br>CREATE DATABASE webappdb;<br>SHOW DATABASES;<br>USE webappdb;<br>CREATE TABLE IF NOT EXISTS transactions(id INT NOT NULL<br>AUTO_INCREMENT, amount DECIMAL(10,2), description<br>VARCHAR(100), PRIMARY KEY(id));<br>SHOW TABLES;<br>INSERT INTO transactions (amount,description) VALUES (&#39;400&#39;,&#39;groceries&#39;);<br>SELECT * FROM transactions;<br>exit</pre><ul><li><strong>Application Installation:</strong></li></ul><p>Before triggering Application installation pipeline, please follow below actions which needs to be done first -&gt;</p><ul><li><strong>env.sh</strong></li></ul><p>This script is for capturing some resource information like RDS Write Instance Endpoint, DB Username and password etc. and export all these variables for upcoming actions.</p><pre>#!/bin/bash<br><br>RDS_WRITE_INS=instance-0<br>echo RDS_WRITE_LINK: $(aws rds describe-db-instances --db-instance-identifier ${RDS_WRITE_INS} | jq &#39;.DBInstances[0].Endpoint.Address&#39; | xargs) &gt; ./AppScript/deployment/vars.yml<br><br>RDS_READ_INS=instance-1<br>echo RDS_READ_LINK: $(aws rds describe-db-instances --db-instance-identifier ${RDS_READ_INS} | jq &#39;.DBInstances[0].Endpoint.Address&#39; | xargs) &gt;&gt; ./AppScript/deployment/vars.yml<br><br>echo DB_USER: $(cat /home/gitlab-runner/creds/cred.json | jq .DB_USER | xargs) &gt;&gt; ./AppScript/deployment/vars.yml<br>echo DB_PASSWORD: $(cat /home/gitlab-runner/creds/cred.json | jq .DB_PASSWORD | xargs) &gt;&gt; ./AppScript/deployment/vars.yml</pre><ul><li><strong>Dbconfig.js</strong></li></ul><p>Here, we have to put all captured information in Dbconfig.js file to build a connection between application and database.</p><pre>module.exports = Object.freeze({<br>    DB_HOST : &#39;{{RDS_WRITE_LINK}}&#39;,<br>    DB_USER : &#39;{{DB_USER}}&#39;,<br>    DB_PWD : &#39;{{DB_PASSWORD}}&#39;,<br>    DB_DATABASE : &#39;webappdb&#39;<br>});</pre><ul><li><strong>deployment.sh</strong></li></ul><p>That describes step by step procedures to install NodeJS application and other dependencies.</p><pre>#!/bin/bash<br>cd /home/ansible<br>curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.38.0/install.sh | bash<br>source ~/.bashrc<br>nvm install 16<br>nvm use 16<br>npm install -g pm2<br>npm audit fix --force   <br>cd app-tier<br>npm install<br>npm audit fix --force<br>pm2 start index.js<br>pm2 list<br>sudo env PATH=$PATH:/home/ansible/.nvm/versions/node/v16.0.0/bin /home/ansible/.nvm/versions/node/v16.0.0/lib/node_modules/pm2/bin/pm2 startup systemd -u ansible —hp /home/ansible<br>pm2 save</pre><ul><li><strong>application.yml</strong></li></ul><p>This playbook is created to place all these configuration file in right directory with correct permission in the instance. Also, if any dependencies needs to be sorted out, those are written in this playbook which will make sure proper installation of NodeJS and proper placement of all configuration files, so that we can avoid any misconfiguration.</p><pre>---<br>- name: Play 1 | Clone GitHub repo for application<br>  hosts: all<br>  become_user: ansible<br>  gather_facts: true<br>  tasks:<br>    - name: Task 1 | Clone Git repository<br>      shell: &quot;{{ item }}&quot;<br>      with_items:<br>        - git clone https://github.com/aws-samples/aws-three-tier-web-architecture-workshop.git<br>        - cp -r /home/ansible/aws-three-tier-web-architecture-workshop/application-code/app-tier /home/ansible/<br><br><br><br>- name: Play 2 | Create Database credentials<br>  hosts: all<br>  become_user: ansible<br>  gather_facts: true<br>  vars_files:<br>    - ./vars.yml<br>  tasks:<br>    - name: Task 1 | Create sql credentials file<br>      shell: |<br>          cat &lt;&lt; EOF &gt; /home/ansible/.my.cnf<br>          [client]<br>          user={{DB_USER}}<br>          password={{DB_PASSWORD}}<br>          EOF<br>    - name: Task 2 | Set the permissions of sql credential file<br>      shell: chmod 600 /home/ansible/.my.cnf<br><br><br><br><br>- name: Play 3 | Install NVM Packages<br>  hosts: all<br>  gather_facts: true<br>  become_user: ansible<br>  vars_files:<br>    - ./vars.yml<br>  tasks:<br>    - name: Task 1 | Delete exisitng DbConfig.js file from app-tier directory<br>      shell: rm -f /home/ansible/app-tier/DbConfig.js<br><br>    - name: Task 2 | Edit DbConfig.js file with credentials<br>      template:<br>        src: ./DbConfig.js<br>        dest: /home/ansible/app-tier/DbConfig.js<br>        owner: ansible<br>        group: ansible<br>        mode: 755<br><br>    - name: Task 3 | Copy deployment.sh file to /home/ansible location<br>      copy:<br>        src: ./deployment.sh<br>        dest: /home/ansible<br>        owner: ansible<br>        group: ansible<br>        mode: 755<br><br>    - name: Task 4 | Set permission of deployment.sh file<br>      shell: chmod 755 /home/ansible/deployment.sh<br><br>    - name: Task 5 | Execute deployment.sh file<br>      shell: sudo sh /home/ansible/deployment.sh<br><br></pre><ul><li><strong>.gitlab-ci.yml</strong></li></ul><p>To automate all these mentioned steps above, gitlab CI pipeline file is there to segregate all these actions in multiple meaningful stages. under each stage, there are couple of actions to be performed which is done automatically if any changes are identified.</p><pre>default:<br>    tags:<br>     - gitlab-runner-test<br><br># ### Defining Pipeline stages ###<br>stages:<br>    # - Terraform Build<br>    - OS Provisioning<br>    - Application Provisioning<br>    - Cleanup<br><br>Terraform Build:<br>    stage: Terraform Build<br>    script:<br>        - sudo chmod +x BuildScript/1_Env.sh<br>        - source BuildScript/1_Env.sh<br>        - python3 BuildScript/2_CreateTFCWorkspace.py -vvv<br>        - sleep 70s<br>        - python3 BuildScript/validate_ec2_ready.py -vvv<br>        - sleep 3s<br>    artifacts:<br>        paths:<br>            - content.tar.gz<br>    rules:<br>        - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH<br>OS Provisioning:<br>    stage: OS Provisioning<br>    script:<br>        - sudo chmod +x BuildScript/inventory.sh<br>        - source BuildScript/inventory.sh<br>        - ansible-playbook -i Ansible/inventory/hosts Ansible/playbook/main.yml --vault-password-file /home/gitlab-runner/creds/.vault_pass -vvv<br>    when: manual<br>    rules:<br>        - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH<br>    artifacts:<br>        paths:<br>          - ./Ansible/inventory/hosts<br>          - ./AppScript/deployment/hosts<br>Application Provisioning:<br>    stage: Application Provisioning<br>    script:<br>        - chmod +x AppScript/deployment/env.sh<br>        - source AppScript/deployment/env.sh<br>        - ansible-playbook -i AppScript/deployment/hosts AppScript/deployment/application.yml -vvv<br>    when: manual<br>    dependencies:<br>      - OS Provisioning<br>    rules:<br>        - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH<br>Cleanup:<br>    stage: Cleanup<br>    script:<br>        - sudo chmod +x BuildScript/7_Cleanup.sh<br>        - source BuildScript/7_Cleanup.sh<br>    dependencies: <br>        - Application Provisioning<br>    rules:<br>        - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*83czPlC8oza-leuUzR8osg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*aqoBvinGtPPj6lFU-fDBwg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*Lpuul6nPHYbuLQOoxeiOyg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*rj6qpx0wBPSlSgMzQCO9UQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*GEbPwwnK9ZmLe5ZpI8WMHw.png" /></figure><ul><li><strong>Application Testing</strong></li></ul><p>Once application installation is over, then try to execute below commands to ensure that application is able to reach out to the database.</p><p>curl <a href="http://localhost:4000/health">http://localhost:4000/health</a></p><p>Output: “This is the health check”</p><p>curl <a href="http://localhost:4000/transaction">http://localhost:4000/transaction</a></p><p>Output: {“result”:[{“id”:1,”amount”:400,”description”:”groceries”},{“id”:2,”amount”:100,”description”:”class”},{“id”:3,”amount”:200,”description”:”other groceries”},{“id”:4,”amount”:10,”description”:”brownies”}]}</p><h3><strong>Web Tier:</strong></h3><p>Web tier is the first layer in three tier architecture which is load balanced across the instances present in this layer using Application load balancer. For web layer, this load balancer would be an external, so that end user can access the application through this load balancer publicly.</p><pre>├── Ansible<br>│   ├── inventory<br>│   ├── playbook<br>│   ├── roles<br>│   └── variable<br>├── BuildScript<br>│   ├── 1_Env.sh<br>│   ├── 2_CreateTFCWorkspace.py<br>│   ├── 7_Cleanup.sh<br>│   ├── inventory.sh<br>│   └── validate_ec2_ready.py<br>├── README.md<br>├── Terraform<br>│   ├── data.tf<br>│   ├── ec2.tf<br>│   ├── external_alb.tf<br>│   ├── output.tf<br>│   ├── provider.tf<br>│   ├── terraform.tfvars<br>│   ├── user_data.sh<br>│   └── variable.tf<br>└── WebScript<br>    └── deployment<br>        ├── deployment.sh<br>        ├── env.sh<br>        ├── nginx.conf<br>        ├── vars.yml<br>        └── web.yml</pre><ul><li><strong>data.tf</strong></li></ul><pre>################ Fetch AZs details#################<br>data &quot;aws_availability_zones&quot; &quot;azs&quot; {<br>  state = &quot;available&quot;<br>}<br><br><br>########################################################################<br>#                                                                      #<br>#             :: Fetch IAM roles for Administrative actions ::         #<br>#                                                                      #<br>########################################################################<br><br>data &quot;aws_iam_role&quot; &quot;role&quot; {<br>  name = &quot;CustomEC2AdminAccess&quot;<br>}<br><br><br>########################################################################<br>#                                                                      #<br>#             :: Fetch Keypair details ::                              #<br>#                                                                      #<br>########################################################################<br><br>data &quot;aws_key_pair&quot; &quot;key&quot; {<br>  key_name           = &quot;keypair&quot;<br>  include_public_key = true<br>}<br><br>########################################################################<br>#                                                                      #<br>#             :: Fetch Web SG details ::                             #<br>#                                                                      #<br>########################################################################<br><br>data &quot;aws_security_group&quot; &quot;sg&quot; {<br>  filter {<br>    name   = &quot;tag:Layer&quot;<br>    values = [&quot;Web&quot;]<br>  }<br>}<br>data &quot;aws_security_group&quot; &quot;mgmt&quot; {<br>  filter {<br>    name   = &quot;tag:Layer&quot;<br>    values = [&quot;Management&quot;]<br>  }<br>}<br><br>data &quot;aws_security_group&quot; &quot;ext_alb&quot; {<br>  filter {<br>    name = &quot;tag:Name&quot;<br>    values = [&quot;InternetFacing-ALB&quot;]<br>  }<br>}<br><br>########################################################################<br>#                                                                      #<br>#             :: Fetch Netwroking details ::                           #<br>#                                                                      #<br>########################################################################<br><br># vpc details :<br>data &quot;aws_vpc&quot; &quot;this_vpc&quot; {<br>  state = &quot;available&quot;<br>  filter {<br>    name   = &quot;tag:Name&quot;<br>    values = [&quot;custom-vpc&quot;]<br>  }<br>}<br><br># subnets details :<br>data &quot;aws_subnet&quot; &quot;web_subnet_1a&quot; {<br>  vpc_id = data.aws_vpc.this_vpc.id<br>  filter {<br>    name   = &quot;tag:Name&quot;<br>    values = [&quot;weblayer-pub1-1a&quot;]<br>  }<br>}<br><br>data &quot;aws_subnet&quot; &quot;web_subnet_1b&quot; {<br>  vpc_id = data.aws_vpc.this_vpc.id<br>  filter {<br>    name = &quot;tag:Name&quot;<br>    values = [&quot;weblayer-pub2-1b&quot;]<br>  }<br>}<br><br># internet gateway details :<br>data &quot;aws_internet_gateway&quot; &quot;this_igw&quot; {<br>  filter {<br>    name   = &quot;tag:Name&quot;<br>    values = [&quot;Internet Gateway&quot;]<br>  }<br>}<br><br># route table details :<br>data &quot;aws_route_table&quot; &quot;pub_rt&quot; {<br>  filter {<br>    name   = &quot;tag:Name&quot;<br>    values = [&quot;custom-route-table-public&quot;]<br>  }<br>}<br>data &quot;aws_route_table&quot; &quot;priv_rt&quot; {<br>  filter {<br>    name   = &quot;tag:Name&quot;<br>    values = [&quot;custom-route-table-private&quot;]<br>  }<br>}<br><br># public route details :<br>data &quot;aws_route&quot; &quot;pub_r&quot; {<br>  route_table_id = data.aws_route_table.pub_rt.id<br>  gateway_id     = data.aws_internet_gateway.this_igw.id<br>}<br><br># private route details<br>data &quot;aws_route&quot; &quot;priv_r&quot; {<br>  route_table_id = data.aws_route_table.priv_rt.id<br>  nat_gateway_id = data.aws_nat_gateway.ngw.id<br>}<br><br>#NAT Gateway details :<br>data &quot;aws_nat_gateway&quot; &quot;ngw&quot; {<br>  filter {<br>    name   = &quot;tag:Name&quot;<br>    values = [&quot;NAT&quot;]<br>  }<br>}</pre><ul><li><strong>variable.tf</strong></li></ul><pre>variable &quot;alb_tags&quot; {<br>  description = &quot;provides the tags for ALB&quot;<br>  type = object({<br>    Environment = string<br>    Email = string<br>    Type = string<br>    Owner = string<br>  })<br>  default = {<br>    Email = &quot;dasanirban0806@gmail.com&quot;<br>    Environment = &quot;Production&quot;<br>    Owner = &quot;Anirban Das&quot;<br>    Type = &quot;External&quot;<br>  }<br>}<br><br>variable &quot;instance_tags&quot; {<br>  description = &quot;provides customized tags&quot;<br>  type        = object({<br>    Environment = string<br>    Email = string<br>    Layer = string<br>    Owner = string<br>  })<br>  default = {<br>    Email = &quot;dasanirban0806@gmail.com&quot;<br>    Environment = &quot;Production&quot;<br>    Layer = &quot;Web&quot;<br>    Owner = &quot;Anirban Das&quot;<br>  }<br><br>}<br><br>variable &quot;instance_profile&quot; {<br>  type = string<br>}<br><br>variable &quot;instance_details&quot; {<br>  description = &quot;Provides requiered information regarding instances&quot;<br>  type = map(object({<br><br>    availability_zone           = string<br>    ami                         = string<br>    instance_type               = string<br>    associate_public_ip_address = bool<br>    server_category             = string<br>    source_dest_check           = bool<br><br>    root_block_device = map(object({<br>      volume_size = number<br>      volume_type = string<br>    }))<br>    ebs_block_device = map(object({<br>      volume_size = number<br>      volume_type = string<br>    }))<br>  }))<br><br>}<br><br>############### Application Load Balancer Variables################<br><br>variable &quot;TG_conf&quot; {<br>  type = object({<br>    name              = string<br>    port              = string<br>    protocol          = string<br>    target_type       = string<br>    enabled           = bool<br>    healthy_threshold = string<br>    interval          = string<br>    path              = string<br>  })<br>}<br><br>variable &quot;ALB_conf&quot; {<br>  type = object({<br>    name               = string<br>    internal           = bool<br>    load_balancer_type = string<br>    ip_address_type    = string<br>  })<br>}<br><br>variable &quot;Listener_conf&quot; {<br>  type = map(object({<br>    port        = string<br>    protocol    = string<br>    type        = string<br>    priority    = number<br>  }))<br>}</pre><ul><li><strong>terraform.tfvars</strong></li></ul><pre># ########################################################################<br># #                                                                      #<br># #                 ::  Instance details ::                              #<br># #                                                                      #<br># ########################################################################<br><br>instance_details = {<br>  Web-Server-VM1 = {<br>    server_category             = &quot;Web&quot;<br>    availability_zone           = &quot;us-east-1a&quot;<br>    ami                         = &quot;ami-04581fbf744a7d11f&quot;<br>    instance_type               = &quot;t2.micro&quot;<br>    associate_public_ip_address = true<br>    source_dest_check           = true<br>    root_block_device = {<br>      &quot;root_block&quot; = {<br>        volume_size = 8<br>        volume_type = &quot;gp2&quot;<br>      }<br>    }<br>    ebs_block_device = {}<br>  },<br><br>  Web-Server-VM2 = {<br>    server_category             = &quot;Web&quot;<br>    availability_zone           = &quot;us-east-1b&quot;<br>    ami                         = &quot;ami-04581fbf744a7d11f&quot;<br>    instance_type               = &quot;t2.micro&quot;<br>    associate_public_ip_address = true<br>    source_dest_check           = true<br>    root_block_device = {<br>      &quot;root_block&quot; = {<br>        volume_size = 8<br>        volume_type = &quot;gp2&quot;<br>      }<br>    }<br>    ebs_block_device = {}<br>}<br>}<br><br>instance_profile = &quot;CustomInstanceprofile_web&quot;<br><br>TG_conf = {<br>  enabled = true<br>  healthy_threshold = &quot;5&quot;<br>  interval = &quot;10&quot;<br>  name = &quot;TargetGroup-External&quot;<br>  port = &quot;80&quot;<br>  protocol = &quot;HTTP&quot;<br>  target_type = &quot;instance&quot;<br>  path              = &quot;/health&quot;<br>}<br><br>ALB_conf = {<br>  internal = false<br>  ip_address_type = &quot;ipv4&quot;<br>  load_balancer_type = &quot;application&quot;<br>  name = &quot;ALB-External&quot;<br>}<br><br>Listener_conf = {<br>  &quot;1&quot; = {<br>    port = &quot;80&quot;<br>    priority = 100<br>    protocol = &quot;HTTP&quot;<br>    type = &quot;forward&quot;<br>  }<br>}</pre><ul><li><strong>user_data.sh</strong></li></ul><pre>#!/bin/bash<br>sudo yum update -y<br>USER=&#39;ansible&#39;<br>sudo useradd -m $USER<br>sudo mkdir /home/$USER/.ssh<br>sudo echo $ANSIBLE_PUBLIC_SSH_KEY &gt; /home/$USER/.ssh/authorized_keys<br>sudo chown -R $USER:$USER /home/$USER/.ssh/<br>sudo chown -R $USER:$USER /home/$USER/.ssh/authorized_keys<br>sudo echo &#39;&#39;$USER&#39;  ALL=(ALL) NOPASSWD: ALL&#39; &gt; /etc/sudoers.d/11-$USER<br>sudo yum install git -y</pre><ul><li><strong>ec2.tf</strong></li></ul><pre># ########################################################################<br># #                                                                      #<br># #             :: Create instance profile ::                            #<br># #                                                                      #<br># ########################################################################<br><br>resource &quot;aws_iam_instance_profile&quot; &quot;instance_profile&quot; {<br>  name = var.instance_profile<br>  role = data.aws_iam_role.role.name<br>}<br><br># ########################################################################<br># #                                                                      #<br># #             :: Create Web Tier Instances ::                          #<br># #                                                                      #<br># ########################################################################<br><br>resource &quot;aws_instance&quot; &quot;instance&quot; {<br>  for_each                    = var.instance_details<br>  instance_type               = each.value.instance_type<br>  ami                         = each.value.ami<br>  associate_public_ip_address = each.value.associate_public_ip_address<br>  source_dest_check           = each.value.source_dest_check<br>  availability_zone           = each.value.availability_zone<br>  key_name                    = data.aws_key_pair.key.key_name<br>  iam_instance_profile        = aws_iam_instance_profile.instance_profile.name<br>  subnet_id                   = (each.value.availability_zone == &quot;us-east-1a&quot; ? data.aws_subnet.web_subnet_1a.id : (each.value.availability_zone == &quot;us-east-1b&quot; ? data.aws_subnet.web_subnet_1b.id : &quot;0&quot;))<br>  vpc_security_group_ids      = [data.aws_security_group.sg.id]<br>  root_block_device {<br>    volume_size = each.value.root_block_device.root_block.volume_size<br>    volume_type = each.value.root_block_device.root_block.volume_type<br>  }<br>  user_data = &quot;${file(&quot;user_data.sh&quot;)}&quot;<br>  #ebs_block_device {}<br>  tags = merge({Name = &quot;${each.key}&quot;}, var.instance_tags)<br>}</pre><ul><li>external_alb.tf</li></ul><pre>resource &quot;aws_lb_target_group&quot; &quot;this_tg&quot; {<br>  name     = var.TG_conf[&quot;name&quot;]<br>  port     = var.TG_conf[&quot;port&quot;]<br>  protocol = var.TG_conf[&quot;protocol&quot;]<br>  vpc_id   = data.aws_vpc.this_vpc.id<br>  health_check {<br>    enabled           = var.TG_conf[&quot;enabled&quot;]<br>    healthy_threshold = var.TG_conf[&quot;healthy_threshold&quot;]<br>    interval          = var.TG_conf[&quot;interval&quot;]<br>    path              = var.TG_conf[&quot;path&quot;]<br>  }<br>  target_type = var.TG_conf[&quot;target_type&quot;]<br>  tags = {<br>    Attached_ALB_dns = aws_lb.this_alb.dns_name<br>  }<br>}<br><br>resource &quot;aws_lb_target_group_attachment&quot; &quot;this_tg_atchmnt&quot; {<br>  count            = length(var.instance_details)<br>  target_group_arn = aws_lb_target_group.this_tg.arn<br>  target_id        = element([for v in aws_instance.instance : v.id], count.index)<br>  port             = 80<br>}<br><br>resource &quot;aws_lb&quot; &quot;this_alb&quot; {<br>  name               = var.ALB_conf[&quot;name&quot;]<br>  load_balancer_type = var.ALB_conf[&quot;load_balancer_type&quot;]<br>  ip_address_type    = var.ALB_conf[&quot;ip_address_type&quot;]<br>  internal           = var.ALB_conf[&quot;internal&quot;]<br>  security_groups    = [data.aws_security_group.ext_alb.id]<br>  subnets            = [data.aws_subnet.web_subnet_1a.id, data.aws_subnet.web_subnet_1b.id]<br>  tags               = merge(var.alb_tags)<br>}<br><br>resource &quot;aws_lb_listener&quot; &quot;this_alb_lis&quot; {<br>  for_each = var.Listener_conf<br>  load_balancer_arn = aws_lb.this_alb.arn<br>  port              = each.value[&quot;port&quot;]<br>  protocol          = each.value[&quot;protocol&quot;]<br>  default_action {<br>    type = each.value[&quot;type&quot;]<br>    target_group_arn = aws_lb_target_group.this_tg.arn<br>  }<br>}<br><br>resource &quot;aws_lb_listener_rule&quot; &quot;this_alb_lis_rule&quot; {<br>  for_each     = var.Listener_conf<br>  listener_arn = element([for k, v in aws_lb_listener.this_alb_lis : v.arn], 0)<br>  priority     = each.value[&quot;priority&quot;]<br>  action {<br>    type             = &quot;forward&quot;<br>    target_group_arn = aws_lb_target_group.this_tg.arn<br>  }<br>  condition {<br>    path_pattern {<br>      values = [&quot;/health&quot;]<br>    }<br>  }<br>}</pre><ul><li><strong>inventory.sh</strong></li></ul><p>Like application tier, in web tier also, inventory.sh shell script is there to create inventory file during runtime.</p><pre>#!/bin/bash<br>TAG_NAME=&quot;Layer&quot;<br>TAG_VAL=&quot;Web&quot;<br>echo &quot;`aws ec2 describe-instances --filters &quot;Name=tag:$TAG_NAME, Values=$TAG_VAL&quot; --query &#39;Reservations[*].Instances[*].PrivateIpAddress&#39; --output text | awk &#39;{print $1&quot; &quot;&quot;ansible_user=ansible&quot;}&#39;`\n&quot; &gt; ./Ansible/inventory/host<br>sed &#39;$ s/..$//&#39; ./Ansible/inventory/host &gt; ./Ansible/inventory/hosts<br>rm -f ./Ansible/inventory/host<br>cp -r ./Ansible/inventory/hosts WebScript/deployment/</pre><ul><li><strong>env.sh</strong></li></ul><p>This script captures the endpoint of internal application load balancer and pass these all in vars.yml file whic will considered as a variable file for ansible playbook.</p><pre>#!/bin/bash<br>echo ALB_URL: $(aws elbv2 describe-load-balancers | jq &#39;.LoadBalancers[0].DNSName&#39; | xargs) &gt; ./WebScript/deployment/vars.yml<br>echo USER: ansible &gt;&gt; ./WebScript/deployment/vars.yml</pre><ul><li><strong>nginx.conf</strong></li></ul><p>Here, we have customized nginx configuration file where internal application load balancer endpoint needs to be added in specified location to create API connection between web servers and internal ALB.</p><pre># For more information on configuration, see:<br>#   * Official English Documentation: http://nginx.org/en/docs/<br>#   * Official Russian Documentation: http://nginx.org/ru/docs/<br><br>user nginx;<br>worker_processes auto;<br>error_log /var/log/nginx/error.log;<br>pid /run/nginx.pid;<br><br># Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.<br>include /usr/share/nginx/modules/*.conf;<br><br>events {<br>    worker_connections 1024;<br>}<br><br>http {<br>    log_format  main  &#39;$remote_addr - $remote_user [$time_local] &quot;$request&quot; &#39;<br>                      &#39;$status $body_bytes_sent &quot;$http_referer&quot; &#39;<br>                      &#39;&quot;$http_user_agent&quot; &quot;$http_x_forwarded_for&quot;&#39;;<br><br>    access_log  /var/log/nginx/access.log  main;<br><br>    sendfile            on;<br>    tcp_nopush          on;<br>    tcp_nodelay         on;<br>    keepalive_timeout   65;<br>    types_hash_max_size 4096;<br><br>    include             /etc/nginx/mime.types;<br>    default_type        application/octet-stream;<br><br>    # Load modular configuration files from the /etc/nginx/conf.d directory.<br>    # See http://nginx.org/en/docs/ngx_core_module.html#include<br>    # for more information.<br>    include /etc/nginx/conf.d/*.conf;<br><br>    server {<br>        listen       80;<br>        listen       [::]:80;<br>        server_name  _;<br><br>        #health check<br>        location /health {<br>        default_type text/html;<br>        return 200 &quot;&lt;!DOCTYPE html&gt;&lt;p&gt;Web Tier Health Check&lt;/p&gt;\n&quot;;<br>        }<br><br>        #react app and front end files<br>        location / {<br>        root    /home/{{USER}}/web-tier/build;<br>        index index.html index.htm<br>        try_files $uri /index.html;<br>        }<br><br>        #proxy for internal lb<br>        location /api/{<br>                proxy_pass http://{{ALB_URL}}:80/;<br>        }<br><br><br>    }<br><br># Settings for a TLS enabled server.<br>#<br>#    server {<br>#        listen       443 ssl http2;<br>#        listen       [::]:443 ssl http2;<br>#        server_name  _;<br>#        root         /usr/share/nginx/html;<br>#<br>#        ssl_certificate &quot;/etc/pki/nginx/server.crt&quot;;<br>#        ssl_certificate_key &quot;/etc/pki/nginx/private/server.key&quot;;<br>#        ssl_session_cache shared:SSL:1m;<br>#        ssl_session_timeout  10m;<br>#        ssl_ciphers PROFILE=SYSTEM;<br>#        ssl_prefer_server_ciphers on;<br>#<br>#        # Load configuration files for the default server block.<br>#        include /etc/nginx/default.d/*.conf;<br>#<br>#        error_page 404 /404.html;<br>#            location = /40x.html {<br>#        }<br>#<br>#        error_page 500 502 503 504 /50x.html;<br>#            location = /50x.html {<br>#        }<br>#    }<br><br>}</pre><p>In this configuration file, please look into below two section which need to be taken care in order to web server work perfectly. The values of variables “USER” and “ALB_URL” should come from vars.yml file which is generated by env.sh file.</p><p>USER: This is user’s home directory where you clond public git repository for application codes. By default it would be ec2-user, but if you want to set any customized user, then need to change the USER name.</p><p>ALB_URL: that’s the internal application load balancer’s endpoint to establish a connection between web servers and internal ALB.</p><pre>     1. #react app and front end files<br>        location / {<br>        root    /home/{{USER}}/web-tier/build;<br>        index index.html index.htm<br>        try_files $uri /index.html;<br>        }<br><br>     2. #proxy for internal lb<br>        location /api/{<br>                proxy_pass http://{{ALB_URL}}:80/;<br>        }</pre><ul><li><strong>deployment.sh</strong></li></ul><pre>#!/bin/bash<br>cd /home/ansible<br>curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.38.0/install.sh | bash<br>source ~/.bashrc<br>nvm install 16<br>nvm use 16<br>cd web-tier<br>npm install<br>npm audit fix --force <br>npm run build</pre><ul><li><strong>web.yml</strong></li></ul><pre>---<br>- name: Play 1 | Clone GitHub repo for application<br>  hosts: all<br>  become_user: ansible<br>  gather_facts: true<br>  tasks:<br>    - name: Task 1 | Clone Git repository<br>      shell: &quot;{{ item }}&quot;<br>      with_items:<br>        - git clone https://github.com/aws-samples/aws-three-tier-web-architecture-workshop.git<br>        - cp -r /home/ansible/aws-three-tier-web-architecture-workshop/application-code/web-tier /home/ansible/<br><br>- name: Play 2 | Web Server Configurations<br>  hosts: all<br>  become_user: ansible<br>  ignore_errors: true<br>  gather_facts: true<br>  vars_files:<br>    - ./vars.yml<br>  tasks:<br>    - name: Task 1 | Copy deployment.sh file to /home/ansible in remote machine<br>      copy:<br>        src: &quot;{{ item }}&quot;<br>        dest: /home/ansible<br>        owner: ansible<br>        group: ansible<br>        mode: 755<br>      with_items:<br>        - ./deployment.sh<br><br>    - name: Task 2 | Execute NVM build commands<br>      shell: &quot;{{ item }}&quot;<br>      with_items:<br>        - curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.38.0/install.sh | bash<br>        - source ~/.bashrc<br>        - nvm install 16<br>        - nvm use 16<br>    - command: &quot;{{ item }}&quot;<br>      with_items:<br>        - cd web-tier<br>        - npm install<br>        - npm audit fix --force <br>        - npm run build<br><br><br>    - name: Task 3 | Install nginx<br>      shell: sudo amazon-linux-extras install nginx1 -y<br><br>    - name: Task 4 | Copy nginx.conf template in /home/ansible location<br>      template:<br>        src: ./nginx.conf<br>        dest: /home/ansible/<br>        owner: root<br>        group: root<br>        mode: 755<br><br>    - name: Task 5 | Take a backup of nginx.conf file and place actual conf file in /etc directory<br>      shell: sudo cp -r /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bkp<br><br><br>    - name: Delete nginx.conf from /etc/nginx location<br>      command: sudo rm -f /etc/nginx/nginx.conf<br><br>    - name: Task 6 | Copy nginx.conf file from /home/ansible to /etc/nginx<br>      shell: sudo cp -r /home/ansible/nginx.conf /etc/nginx/<br><br>    - name: Task 7 | Set the permission of /home/ansible<br>      shell: chmod -R 755 /home/ansible<br><br>    - name: Task 7 | Restart nginx service<br>      service:<br>        name: nginx<br>        state: restarted<br><br>    - name: Task 8 |  Check conf of nginx<br>      shell: sudo chkconfig nginx on</pre><ul><li><strong>.gitlab-ci.yml</strong></li></ul><pre>default:<br>    tags:<br>     - gitlab-runner-test<br><br># ### Defining Pipeline stages ###<br>stages:<br>    # - Terraform Build<br>    - OS Provisioning<br>    - Web Provisioning<br>    - Cleanup<br><br> Terraform Build:<br>     stage: Terraform Build<br>     script:<br>         - sudo chmod +x BuildScript/1_Env.sh<br>         - source BuildScript/1_Env.sh<br>         - python3 BuildScript/2_CreateTFCWorkspace.py -vvv<br>         - sleep 70s<br>         - python3 BuildScript/validate_ec2_ready.py -vvv<br>         - sleep 3s<br>     artifacts:<br>         paths:<br>             - content.tar.gz<br>     rules:<br>         - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH<br>OS Provisioning:<br>    stage: OS Provisioning<br>    script:<br>        - sudo chmod +x BuildScript/inventory.sh<br>        - source BuildScript/inventory.sh<br>        - ansible-playbook -i Ansible/inventory/hosts Ansible/playbook/main.yml --vault-password-file /home/gitlab-runner/creds/.vault_pass -vvv<br>    when: manual<br>    rules:<br>        - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH<br>    artifacts:<br>        paths:<br>          - ./Ansible/inventory/hosts<br>          - ./WebScript/deployment/hosts<br>Web Provisioning:<br>    stage: Web Provisioning<br>    script:<br>        - chmod +x WebScript/deployment/env.sh<br>        - source WebScript/deployment/env.sh<br>        - ansible-playbook -i WebScript/deployment/hosts WebScript/deployment/web.yml -vvv<br>    when: manual<br>    dependencies:<br>      - OS Provisioning<br>    rules:<br>        - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH<br>Cleanup:<br>    stage: Cleanup<br>    script:<br>        - sudo chmod +x BuildScript/7_Cleanup.sh<br>        - source BuildScript/7_Cleanup.sh<br>    dependencies: <br>        - Web Provisioning<br>    rules:<br>        - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH</pre><ul><li>Testing:</li></ul><p>One all installations and configurations are completed from all layers perspective, then hit the endpoint of external application load balancer in the browser, if we find below pictures, then deployment is done perfectly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xb9HYeX0mg5Efmyqhx_E2g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wObPSg73lHn_bJYeYYN4ug.png" /></figure><h3><strong>Conclusion:</strong></h3><p>We have successfully deployed all three layers in AWS using CI/CD pipeline in GitLab that has been very flexible, smooth deployment approach, also using Ansible and Terraform enhances the comfortability and benefits of IaaC(Infrastructure-as-a-code) as well as reduces the time consumption.</p><p>Reusability is a key factor of IaaC that we can meet using Terraform and Ansible for deployment and configurations respectively. For complete source code, please refer below my GitHub repository</p><p>Link: <a href="https://github.com/dasanirban834/aws-three-tier-web-architecture">https://github.com/dasanirban834/aws-three-tier-web-architecture</a></p><p>Please take a look at this blog and let me know if anything needs to be improved, so that going forward we can introduce some other cocepts or approaches from different aspects.</p><p>Happy learning !!! :)</p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>.</em></p><p><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>, </em><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><em>, and </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></p><p><strong><em>Interested in scaling your software startup</em></strong><em>? Check out </em><a href="https://circuit.ooo/?utm=publication-post-cta"><strong><em>Circuit</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a5e847d9ed0" width="1" height="1" alt=""><hr><p><a href="https://aws.plainenglish.io/design-and-build-a-three-tier-architecture-with-complete-end-to-end-automation-9a5e847d9ed0">Design and Build a Three Tier Architecture with complete end-to-end Automation</a> was originally published in <a href="https://aws.plainenglish.io/">AWS in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Do Start/Reboot/Stop Multiple Instances in a Few Clicks Without Console Help]]></title>
            <link>https://aws.plainenglish.io/do-start-reboot-stop-multiple-instances-in-a-few-clicks-without-console-help-822384fa2c3f?source=rss-59a29a5892be------2</link>
            <guid isPermaLink="false">https://medium.com/p/822384fa2c3f</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ansible]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[gitlab]]></category>
            <dc:creator><![CDATA[Dasanirban]]></dc:creator>
            <pubDate>Mon, 20 Jun 2022 16:18:18 GMT</pubDate>
            <atom:updated>2022-06-21T05:49:19.926Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ldl7XmcLX5PABzKo.jpg" /></figure><p>We all are familiar to start/reboot/stop instances as per our requirements. It’s pretty easy to do this with the help of a console or CLI, but that can be suitable for a few servers, problem may arise when multiple servers (min 50)will come into place. It will become a very hard task to do this activity manually by logging into the console and clicking each and every server.</p><p>As a solution, it can be automated using GitLab/GitHub and do shell scripting using the AWS CLI command, so that tasks can be handled easily. But again we have to log in to GitLab and do modification manually first, then the rest will be executed.</p><p>So here, I wrote a python script that will ask you all instance ids and what action you want to perform (start/reboot/stop). Once execution starts, it will directly override instance ids to the corresponding variable file using the PUT API operation.</p><p><strong>HLD</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UN08wqY-IAvs3VS9RpWV9g.png" /></figure><p><strong>LLD</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4iTbBvz6X_hmghHia0s4KQ.png" /></figure><p><strong>Requirements</strong>:</p><ul><li>Create GitLab API token.</li><li>Have set up GitLab Runner</li><li>Add Environment variables (Access Key, Secret Access Key, Region) in Settings.</li></ul><p><strong>Create GitLab API Token:</strong></p><ul><li>Log in to the GitLab portal and click on the drop down button of your profile.</li><li>Select “Preferences”.</li><li>Click on “Access Tokens” and provide token name, expiry date and check ‘api’ option.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*rCSVD-XvEu5kOi_ZASIJYg.png" /></figure><ul><li>Once created, keep it in safe location. Token :: “glpat-xxxxxxxxxxxxxx”</li></ul><p><strong>Master Python Script:</strong></p><p>This script should be located in your desktop location, so that you can trigger it with your information locally, no need to reach out to remote site.</p><pre>#******************* Master Python Script *************************#<br>#******************* Author : Anirban Das *************************#</pre><pre>import requests<br>import json<br><br># Repository File API link<br>url_start = &quot;https://gitlab.com/api/v4/projects/&lt;project-id&gt;/repository/files/start%2Ejson?ref=main&quot;<br>url_reboot = &quot;https://gitlab.com/api/v4/projects/&lt;project-id&gt;/repository/files/reboot%2Ejson?ref=main&quot;<br>url_stop = &quot;https://gitlab.com/api/v4/projects/&lt;project-id&gt;/repository/files/stop%2Ejson?ref=main&quot;<br><br># provide servers instance ids<br>server_list = list(input(&quot;Please enter the server names : &quot;).split(&quot; &quot;))<br>print(&quot;The list of server : &quot;, server_list)<br><br># servers instance ids in the form of JSON<br>payload = json.dumps({&quot;branch&quot;: &quot;main&quot;, &quot;commit_message&quot;: &quot;update file&quot;, &quot;content&quot;: json.dumps({&quot;Servers&quot;: server_list}, indent=4)})<br><br># provide content type and bearer token/gitlab API token<br>headers = {<br>        &#39;Content-Type&#39;: &#39;application/json&#39;,<br>        &#39;Authorization&#39;: &#39;Bearer glpat-xxxxxxxxxxxxxx&#39;<br>}<br><br># Create choices 1: start, 2: reboot, 3: stop<br>option1 = {&quot;1&quot;:&quot;Start&quot;, &quot;2&quot;: &quot;Reboot&quot;, &quot;3&quot;: &quot;Stop&quot;}<br>v = input(&#39;&#39;&#39;Please select the action from above : <br>1. Start<br>2. Reboot<br>3. Stop<br>Default [1] : &#39;&#39;&#39;)<br><br># Making logics based upon the user choice<br>if v == &quot;1&quot;:<br>   print(&quot;You have chosen : &quot;, option1[&quot;1&quot;])<br>   response_start = requests.request(&quot;PUT&quot;, url_start, headers=headers, data=payload)<br>   print(response_start)<br>elif v == &quot;2&quot;:<br>   print(&quot;You have chosen : &quot;, option1[&quot;2&quot;])<br>   response_reboot = requests.request(&quot;PUT&quot;, url_reboot, headers=headers, data=payload)<br>   print(response_reboot)<br>elif v == &quot;3&quot;:<br>   print(&quot;You have chosen : &quot;, option1[&quot;3&quot;])<br>   response_stop = requests.request(&quot;PUT&quot;, url_stop, headers=headers, data=payload)<br>   print(response_stop)<br>else:<br>   print(&quot;Not Required&quot;)</pre><p>Once you start execution, output will look like below ::</p><pre>Please enter the server names : i-0483d5op2b10c10b5 i-036ae1af8q2527c26 i-05a538f6ec687ae71<br>The list of server :  [&#39;i-0483d5op2b10c10b5&#39;, &#39;i-036ae1af8q2527c26&#39;, &#39;i-05a538f6ec687ae71&#39;]<br>Please select the action from above : <br>1. Start<br>2. Reboot<br>3. Stop<br>Default [1] : 1<br>You have chosen :  Start<br>&lt;Response [200]&gt;</pre><p><strong>Variable File:</strong></p><p>Once master python script got executed and status code is 200, that mean it has been successfully overridden to existing variable file (start.json).</p><pre>{<br>    &quot;Servers&quot;: [<br>        &quot;i-0483d5op2b10c10b5&quot;,<br>        &quot;i-036ae1af8q2527c26&quot;,<br>        &quot;i-05a538f6ec687ae71&quot;<br>    ]<br>}</pre><p><strong>Prechecks Execution:</strong></p><p>Here, I’ll show you only start operation, but rest reboot and stop will become exactly similar. First we will check current status of those servers, so we have <strong>start_prechecks.sh</strong> script. Let’s see the output.</p><pre>#!/bin/bash<br>server_list=$(jq . start.json | jq .Servers)<br>for j in ${#server_list[@]}<br>do<br>        aws ec2 describe-instances --instance-id $(server_list[i]) --query &quot;Reservations[*].Instances[*].{PrivateIP:PrivateIpAddress,Name:Tags[?Key==&#39;Name&#39;]|[0].Value,Status:State.Name}&quot; --output table<br>        j=j+1<br>done</pre><p><strong>./start_prechecks.sh</strong></p><pre>--------------------------------------------<br>|             DescribeInstances            |<br>+------------+-----------------+-----------+<br>|    Name    |    PrivateIP    |  Status   |<br>+------------+-----------------+-----------+<br>|  Host1     |  xxxxxxxxxxxxxx |  stopped  |<br>|  Controller|  xxxxxxxxxxxxxx |  running  |<br>|  Host2     |  xxxxxxxxxxxxxx |  stopped  |<br>|  Host3     |  xxxxxxxxxxxxxx |  stopped  |<br>+------------+-----------------+-----------+</pre><p><strong>Note: Here, Controller servers is actually GitLab runner where all required tools/modules are installed for execution. So it needs to be in running state.</strong></p><p><strong>Actual Config File Execution:</strong></p><p>Once precheck script got executed, then it’s time to execute actual configuration file which is start.sh that basically is a shell script to start instances using JQ package for fetching instance ids and then interpolating them with command.</p><p><strong>./start.sh</strong></p><pre>#!/bin/bash<br><br>#jq . start.json | jq .Servers[0]<br>#jq . start.json | jq .Servers[1]</pre><pre>len=$(jq . start.json | jq &#39;.Servers | length&#39;)<br>#echo $len<br>i=0<br>while [[ i -lt $len ]]<br>do<br>        echo &quot;Index is : &quot; $i<br>        aws ec2 start-instances --instance-ids $(jq . start.json | jq .Servers[$i] | sed &#39;s/&quot;//g&#39;)<br>        ((i++))<br>done</pre><p>Output: It will show you like below, as you can see current status is pending state as it’s going to be started. Similarly you can see for index 1, 2 and so on.</p><pre>Index is :  0<br>{<br>    &quot;StartingInstances&quot;: [<br>        {<br>            &quot;CurrentState&quot;: {<br>                &quot;Code&quot;: 0,<br>                &quot;Name&quot;: &quot;<strong>pending</strong>&quot;<br>            },<br>            &quot;InstanceId&quot;: &quot;i-0483d5op2b10c10b5&quot;,<br>            &quot;PreviousState&quot;: {<br>                &quot;Code&quot;: 80,<br>                &quot;Name&quot;: &quot;stopped&quot;<br>            }<br>        }<br>    ]<br>}</pre><p><strong>Custom CI File:</strong></p><p>Now we have all required component files to get this done succesfully, but we also need a sequence, how it will initiate execution or which file will start execution first or second and so on, hence I added a GitLab CI file <strong>.start.yml. </strong>which will have two stages (<strong>Do_Prechecks and Start_Action</strong>).</p><p>Under each stage, those required scripts will be executed i.e for <strong>Do_Prechecks</strong> stage <strong>start_prechecks.sh</strong> and for <strong>Start_Action</strong> stage <strong>start.sh</strong> will be executed.</p><p>Also, we need to add a condition here as we all know for little changes gitlab CI file gets triggered, just to avoid this scenario we need to use <strong>only:changes:&lt;start.json&gt;</strong> keywords, that simply defines if any changes made into start.json variable file, then only .start.yml CI file will be triggered otherwise <strong>NEVER</strong>.</p><pre>stages:<br>    - Do_Prechecks<br>    - Start_Action<br><br>Do_Prechecks:<br>    stage: Do_Prechecks<br>    script:<br>        - chmod +x start_prechecks.sh<br>        - sh start_prechecks.sh<br>    tags:<br>        - gitlab-runner-test<br>    only:<br>        changes:<br>            - start.json<br>Start_Action:<br>    stage: Start_Action<br>    script:<br>        - chmod +x start.sh<br>        - sh start.sh<br>    tags:<br>        - gitlab-runner-test<br>    only:<br>        changes:<br>            - start.json</pre><p><strong>GitLab CI File:</strong></p><p>Once custom GitLab Ci file gets triggered due to changes in start.json file, then it will ask to actual GitLab Ci file &lt;.gitlab-ci.yml&gt; whether it’s allowed to go ahead or not.</p><p>So that’s why we need to uncomment below start section. By default it needs to be commented, but when you’re going to start servers, at the very first you need to uncomment that section which you want to perform. basically include keyword imports the custom GitLab CI file you created.</p><p><strong>Note: Currently I’m also working to comment or uncomment sections automatically. As of now we have to do this manually.</strong></p><pre>#include:<br>#  - local: &#39;.start.yml&#39;<br><br><br># include:<br>#   - local: &#39;.reboot.yml&#39;<br><br><br># include:<br>#   - local: &#39;.stop.yml&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*rlgMnk0vPKYKH4cwL6ZBTQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*eDrKua6gMYQtGX6bobL2TA.png" /></figure><p>So, as expected we can see all 3 servers have come online without any issues. We have seen that how much time we can save by using this workflow, literally we have nothing to do except providing instance ids. So, from patching or DR perspective I hope this can be playing a massive role in order to reduce execution duration. ✌️✌️✌️</p><p>Please hit the link below for the entire code and definitely try it on your own system and let me know how it can help in your day-to-day work and don’t forget to give me better suggestions/automation ideas/anything else 🙏🏽🙏🏽🙏🏽. Please stay tuned for more interesting tech blogs. 🙂🙂🙂</p><p><a href="https://github.com/dasanirban834/Virtual-Host-Management">GitHub - dasanirban834/Virtual-Host-Management</a></p><p>Cheers,</p><p>Anirban Das</p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><em> and </em><a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>. Check out our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Community Discord</em></strong></a><em> and join our </em><a href="https://inplainenglish.pallet.com/talent/welcome"><strong><em>Talent Collective</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=822384fa2c3f" width="1" height="1" alt=""><hr><p><a href="https://aws.plainenglish.io/do-start-reboot-stop-multiple-instances-in-a-few-clicks-without-console-help-822384fa2c3f">Do Start/Reboot/Stop Multiple Instances in a Few Clicks Without Console Help</a> was originally published in <a href="https://aws.plainenglish.io/">AWS in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating Patching Activity Using Ansible & GitLab CI]]></title>
            <link>https://aws.plainenglish.io/automating-patching-activity-using-ansible-gitlab-ci-f63747515a12?source=rss-59a29a5892be------2</link>
            <guid isPermaLink="false">https://medium.com/p/f63747515a12</guid>
            <category><![CDATA[patching]]></category>
            <category><![CDATA[gitlab]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[ansible]]></category>
            <dc:creator><![CDATA[Dasanirban]]></dc:creator>
            <pubDate>Sun, 06 Mar 2022 15:54:48 GMT</pubDate>
            <atom:updated>2022-05-23T02:10:52.333Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TT5Y89D-znBcFSa6.png" /></figure><h3><strong>Introduction:</strong></h3><p>In this article, we will discuss on how can we complete Patching activity more smoothly and reduce the downtime significantly. Here, I introduced GitLab CI functionality for triggering purpose and Ansible playbooks for prechecking or other tasks.</p><p>So, first let’s break the entire activity into separate tasks. Here, in the GitLab we deployed a custom GitLab runner where we have installed multiple required agents/packages for different purposes and then mapped with our Patching project. Let’s look into the process to install and register this runner.</p><h3><strong>GitLab Runner Installation &amp; Registration:</strong></h3><p>GitLab runner is basically an agent which connects with GitLab portal and executes the scripts in a certain project. By default, in the portal we can have multiple shared runners but can’t have exact packages which is required to get this tasks done.</p><p><strong>Step 1:</strong></p><p><strong>For CentOS/RedHat/Amazon Linux:</strong></p><p><em>curl -LJO “https://gitlab-runner-downloads.s3.amazonaws.com/latest/rpm/gitlab-runner_${arch}.rpm&quot;</em></p><p><strong>For Debian/Ubuntu:</strong></p><p><em>curl -LJO “https://gitlab-runner-downloads.s3.amazonaws.com/latest/rpm/gitlab-runner_${arch}.rpm&quot;</em></p><p><strong>Note: Get the packages name from </strong><a href="https://gitlab-runner-downloads.s3.amazonaws.com/latest/index.html"><strong><em>https://gitlab-runner-downloads.s3.amazonaws.com/latest/index.html</em></strong></a><strong> and replace {arch}.</strong></p><p><strong>Step 2:</strong></p><p><strong>Install for CentOS/RedHat:</strong></p><p><em>rpm -i gitlab-runner_&lt;arch&gt;.rpm</em></p><p><strong>Install for Debian/Ubuntu:</strong></p><p><em>dpkg -i gitlab-runner_&lt;arch&gt;.deb</em></p><p><strong>Step 3:</strong></p><p>Registering runner : <strong><em>sudo gitlab-runner register</em></strong></p><p>After that, it will ask for authentication token, descriptions, tags respectively. Click on <strong>Settings &gt; CI/CD</strong>, then expands Runner tab, it will show authentication token &amp; registered URL</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*-LLDye84t_m_y_VHDbAMaw.png" /><figcaption>Runner Registration Token</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*yeo8SCowjcssllEHurnL4Q.png" /><figcaption>Available Custom Runner</figcaption></figure><h3><strong>Set Environment Variable:</strong></h3><p>Click Settings &gt; CI/CD, then expand variable tab and set the environment variables i.e. AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_DEFAULT_REGION. For security prospective, these all need to be masked and protected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jVjVcaPpkVB0CYG3U2NmOQ.png" /><figcaption>Environment Variables</figcaption></figure><h3><strong>Stages:</strong></h3><p>In this activity we have created few stages to complete this one which includes basically <strong><em>“Do_Prechecks”, “Take_Snapshot”, “Start_Patching”, “Do_Postchecks”</em></strong>. For each stages, there are scripts or playbooks which are to be executed using GitLab runner.</p><h3><strong>Do_Prechecks:</strong></h3><ul><li>This stage requires prechecks.yml to be executed.</li></ul><p><strong>prechecks.yml:</strong></p><pre>- name: Prechecks Before Patching<br>  hosts: remote<br>  become: true<br>  gather_facts: yes<br>  tasks:<br>      - name: &quot;Host Name&quot;<br>        debug:<br>            msg:<br>                - Node_Details: &quot;{{ ansible_nodename }}&quot;<br>      - name: &quot;Network Details&quot;<br>        debug:<br>            msg:<br>                - Hostname: &quot;{{ ansible_hostname }}&quot;<br>                - IPv4_Info: &quot;{{ ansible_eth0.ipv4 }}&quot;<br>                - IPv6_Info: &quot;{{ ansible_eth0.ipv6 }}&quot;<br>                - MAC_Address: &quot;{{ ansible_eth0.macaddress }}&quot;<br>                - FQDN: &quot;{{ ansible_fqdn }}&quot;<br><br>      - name: &quot;OS Details&quot;<br>        debug:<br>            msg:<br>                - Distribution: &quot;{{ ansible_distribution }}&quot;<br>                - OS_Family: &quot;{{ ansible_os_family }}&quot;<br>                - Dist_Version: &quot;{{ ansible_distribution_major_version }}&quot;<br>                - Kernel: &quot;{{ ansible_kernel }}&quot;<br>                - Kernel_Version: &quot;{{ ansible_kernel_version }}&quot;<br>                - Architecture: &quot;{{ansible_architecture}}&quot;<br>                - BIOS_Date: &quot;{{ansible_bios_date}}&quot;<br>                - BIOS_Version: &quot;{{ansible_bios_version}}&quot;<br>                - BOOT_Image: &quot;{{ansible_cmdline.BOOT_IMAGE}}&quot;<br><br>      - name: &quot;CPU/Memory Details&quot;<br>        debug:<br>            msg:<br>                - Memory_total_mb: &quot;{{ ansible_memfree_mb }}&quot;<br>                - Memory_free_mb: &quot;{{ ansible_memfree_mb }}&quot;<br>                - Processors: &quot;{{ ansible_processor }}&quot;<br>                - Processors_cores: &quot;{{ ansible_processor_cores }}&quot;<br>                - Processors_counts: &quot;{{ ansible_processor_count }}&quot;<br>                - vCPUs: &quot;{{ ansible_processor_vcpus }}&quot;<br>                - product_version: &quot;{{ ansible_product_version }}&quot;<br><br>      - name: &quot;File System Details&quot;<br>        command: df -Th<br>        register: file_system<br>      - debug:<br>            var: file_system.stdout<br><br>      - name: &quot;Storage Device Details&quot;<br>        command: lsblk -a<br>        register: root_block<br>      - debug:<br>            var: root_block.stdout<br><br>      - name: Packges to be Updated<br>        command: yum check-update<br>        register: package_tobe_updated<br><br>      - debug:<br>            var: package_tobe_updated.stdout</pre><h3><strong>Take_Snapshot:</strong></h3><ul><li>This stage requires snapshot.sh file to be executed.</li></ul><p><strong>snapshot.sh</strong></p><pre>#/bin/bash<br>volume=(&#39;vol-0b35b9ed5569f4eae&#39; &#39;vol-03efc7ba00eb1488e&#39; &#39;vol-0ac738d0953101894&#39;) # list of all volume ids.<br>i=0<br>while [ $i -lt ${#volume[@]} ]<br>do<br>        echo &quot;Taking Pre-Patching Snapshot of VolumeID: ${volume[$i]}&quot;<br>        aws ec2 create-snapshot --volume-id ${volume[$i]}<br>        ((i++))<br>done</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*Xs0XbNY7ELHVzYHil1_4ZA.png" /><figcaption>Snapshots taken</figcaption></figure><h3><strong>Start_Patching:</strong></h3><ul><li>This stage requires install.yml file to be executed which is basically patching/package updates playbook.</li></ul><p><strong>install.yml</strong></p><pre>---<br>- name: Patch Linux system<br>  hosts: remote<br>  become: true<br>  gather_facts: yes<br>  tasks:<br>      - name: &quot;Patching Time&quot;<br>        debug:<br>            msg:<br>              - timestamp: &quot;{{ ansible_date_time.iso8601_micro }}&quot;<br>        run_once: true<br><br>      - name: Apply patches<br>        yum:<br>             name: &#39;*&#39;<br>             state: latest <br>        when: ansible_distribution == &#39;Amazon&#39;<br>        register: yum_update<br>      - debug:<br>            var: yum_update.stdout</pre><h3><strong>Do_Postchecks:</strong></h3><ul><li>This stage requires postchecks.yml file to be executed.</li></ul><p><strong>postchecks.yml</strong></p><pre>- name: Postchecks After Patching<br>  hosts: remote<br>  become: true<br>  gather_facts: yes<br>  ignore_errors: no<br>  tasks:<br>        - name: &quot;OS Details&quot;<br>          debug:<br>              msg:<br>                - Distribution: &quot;{{ ansible_distribution }}&quot;<br>                - OS_Family: &quot;{{ ansible_os_family }}&quot;<br>                - Dist_Version: &quot;{{ ansible_distribution_major_version }}&quot;<br>                - Kernel: &quot;{{ ansible_kernel }}&quot;<br>                - Kernel_Version: &quot;{{ ansible_kernel_version }}&quot;<br>                - Architecture: &quot;{{ansible_architecture}}&quot;<br>                - BIOS_Date: &quot;{{ansible_bios_date}}&quot;<br>                - BIOS_Version: &quot;{{ansible_bios_version}}&quot;<br>                - BOOT_Image: &quot;{{ansible_cmdline.BOOT_IMAGE}}&quot;</pre><p>Once we have all scripts/playbooks available, then we need define the hosts which all these changes or activities will happen on.</p><p><strong>hosts:</strong></p><p>Created a group “remote” in this file and provided private IPs of all hosts which are part of this activity and also mention the ansible user name.</p><pre>[remote]<br>172.31.85.194 ansible_user=ansible<br>172.31.92.142 ansible_user=ansible<br>172.31.89.181 ansible_user=ansible</pre><p>Now, we have created all configuration ready, so we need to organize all those playbooks in sequential manner, hence .gitlab-ci.yml file comes into a picture which is nothing but a GitLab CI file responsible to execute all scripts in the way we have mentioned over here.</p><p><strong>.gitlab-ci.yml</strong></p><pre>stages:<br> - Do_Prechecks<br> - Take_Snapshot<br> - Start_Patching<br> - Do_Postchecks<br><br>Do_Prechecks:<br> stage: Do_Prechecks<br> script: <br>  - ansible-playbook -i hosts prechecks.yml<br> tags:<br>  - gitlab-runner-test<br><br>Take_Snapshot:<br> stage: Take_Snapshot<br> script:<br>  - echo &quot;Please start triggering snapshot ..&quot;<br>  - chmod +x snapshot.sh<br>  - sh snapshot.sh<br>  - echo &quot;Snapshots are taken and validated successfully !!&quot;<br> tags:<br>  - gitlab-runner-test<br><br>Start_Patching:<br> stage: Start_Patching<br> script:<br>  - ansible-playbook -i hosts install.yml<br> when: manual<br> tags:<br>  - gitlab-runner-test<br><br>Do_Postchecks:<br> stage: Do_Postchecks<br> script: <br>  - ansible-playbook -i hosts postchecks.yml<br> dependencies: <br>  - Start_Patching<br> when: manual<br> tags:<br>  - gitlab-runner-test</pre><p>This file basically depicts how the jobs will be executed under each stages. Each stage defines few tasks to be completed, also it should be executed automatically or manually, is there any dependencies or not and many more. Let’s take an example of <strong>“Do_Prechecks” </strong>stage.</p><pre>Do_Prechecks:                          # Display Name<br> stage: Do_Prechecks                   # stage name<br> script:                               # script includes the file<br>  - <strong>ansible-playbook -i hosts prechecks.yml # prechecks playbook</strong><br> tags:                                 # tags of gitlab-runner<br>  - gitlab-runner-test</pre><p>Now , we can push all configuration files to GitLab portal from VSCode using few commands. Please follow the steps:</p><ol><li><strong>git add .</strong> <em>&lt;This adds all files in current directory into staging area of git&gt;</em></li><li><strong>git status</strong> <em>&lt;Check which files recently got added/modified/deleted&gt;</em></li><li><strong>git commit -m “&lt;commit-message&gt;”</strong> <em>&lt;This commits/saves in local git repo&gt;</em></li><li><strong>git push </strong><em>&lt;This pushes all to GitLab portal&gt;</em></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*749YKW1V9LYXO8lm2h-6NQ.png" /><figcaption>Configuration files</figcaption></figure><p>After all files are push to gitlab portal, pipeline gets triggered. Click on <strong>CICD &gt; Pipeline.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*7RYuDpxi6KnoBA5yr-X1gQ.png" /></figure><h3><strong>Pipeline Details:</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SkNDRYXDXpd_GaGaGmB67A.png" /><figcaption>Pipeline details</figcaption></figure><p>Pipeline details shows us:</p><ul><li>Status of each stage</li><li>Branch Name</li><li>Commit id</li><li>Duration of execution</li></ul><p>To get better insight, click on the status of pipeline “<strong>passed</strong>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*trKfPAuT1NIDsG08sysglA.png" /></figure><p>Among those four stages, first two stages are automated, will start executing once there is any changes in config file. Rest patching and postchecks stages are manually triggered. Just click on play button to trigger.</p><p>During execution of any stage, we can view the logs generated by runner in terminal view. Just click on the stage name (Ex: Do_Prechecks), then will see the terminal sowing the logs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*327MGNPvrIxJJQR6Iw494Q.png" /></figure><p>In this way, once patching stage is completed, then need to trigger postchecks stage to identify what changes are made.</p><p>Note: As kernel version version recently got updated, hence in this tasks it didn’t get reflected, but yes there are few packages have been updated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*LkPjzwoXAy2rngTQVTRjrw.png" /><figcaption>Package update logs for host2</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*fh34TPSBYuE9pyjkCBc78A.png" /><figcaption>Package update logs for host3</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*uoy3goiikL6KNjQafdYZng.png" /><figcaption>Package update logs for host1</figcaption></figure><p>Created separate file for capturing outputs of each stages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*cZbv5yKwetjZ3C35YjZbZA.png" /></figure><p>Hope you’ve liked this blog. Thank you for reading.</p><p><em>Please like it, follow me for more information and comment if you have any suggestions or improvement plans. Also, you can follow this repo.</em></p><p><a href="https://github.com/dasanirban834/Terraform-task/tree/main/Patching">Terraform-task/Patching at main · dasanirban834/Terraform-task</a></p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><em> and </em><a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>. Join our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>community Discord</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f63747515a12" width="1" height="1" alt=""><hr><p><a href="https://aws.plainenglish.io/automating-patching-activity-using-ansible-gitlab-ci-f63747515a12">Automating Patching Activity Using Ansible &amp; GitLab CI</a> was originally published in <a href="https://aws.plainenglish.io/">AWS in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Deploy a Set of EC2 Instances behind an ALB Using Terraform]]></title>
            <link>https://aws.plainenglish.io/deploy-a-set-of-ec2-instances-behind-an-alb-using-terraform-403fe584f09e?source=rss-59a29a5892be------2</link>
            <guid isPermaLink="false">https://medium.com/p/403fe584f09e</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Dasanirban]]></dc:creator>
            <pubDate>Mon, 01 Nov 2021 12:33:05 GMT</pubDate>
            <atom:updated>2021-11-02T05:03:08.816Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introduction</strong></h3><p>In our current scenario, we all know that infrastructure as a code has been a key player for deploying multiple infrastructure components. This usage of IaaC tools has changed a lot of things in terms of cost, security, availability, speed to deploy, and many more things.</p><p>But if we look at the past 10–15 years, so that time people has to provide their effort to create infrastructure elements and most importantly they had to do these things separately within a short time. That was a very challenging task to do manually and separately. Since then different IaaC tools come into the picture, among them Terraform has been chosen by most of the clients just because of its benefits rather than others.</p><h4><strong>Benefits:</strong></h4><ul><li><strong>Multi-Cloud Infrastructure Deployment: </strong>Terraform can create infrastructures in a multi-cloud environment. It can be applied to AWS, Azure, GCP as well as On-Premises environments and even cross-cloud platforms also.</li><li><strong>Reduced Development Costs:</strong> Development costs can be reduced by creating sample infrastructures or on-demand environments.</li><li><strong>Infrastructure-as-a-code:</strong> As we codify infrastructure elements over here, so we will have a copy after deploying as well. To create a DR environment, this copy will be playing an important role to deploy so quickly. In future, if we need to create a few common elements which are already here now, then we just need to execute that copy only, so deployment could be completed within 7–8 mins.</li><li><strong>Reduced Time to Provision:</strong> It takes less time to provision and even to create any element as well. As a manual task, provisioning can be lengthy due to human interference, but as it’s fully automated, so deployment time has been reduced to a great extent.</li></ul><h4>Architecture:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vfgQDMmALACy5dyHnwALbA.png" /></figure><h4><strong>Deployment Elements:</strong></h4><ul><li>Create a VPC</li><li>Create 3 Public Subnets</li><li>Create Internet Gateway</li><li>Public Route Tables</li><li>Security Group</li><li>3 EC2 Instances</li><li>Target Group creation and Application Load Balancer</li></ul><p><strong><em>Note: Here, I have created a single file for networking elements like VPC, subnets, Internet gateway and Route tables. Similarly created ec2.tf for only EC2 instances and so on.</em></strong></p><h4><strong>Step 1: Define Provider Details</strong></h4><ul><li>Create provider.tf to mentioned cloud provider details:</li></ul><pre>terraform {<br>  required_providers {<br>    aws = {<br>      source  = &quot;hashicorp/aws&quot;<br>      version = &quot;3.61.0&quot;<br>    }<br>  }<br>}<br><br># Configure AWS provider:<br><br>provider &quot;aws&quot; {<br>  region  = &quot;us-east-1&quot;<br>  version = &quot;3.61.0&quot;<br>}</pre><h4><strong>Step 2: Defining All Required Variables in the variable.tf File</strong></h4><pre>#####################################################<br># VPC Requirement<br>#####################################################<br><br>variable &quot;custom_vpc&quot; {<br>  description = &quot;VPC for testing environment&quot;<br>  type        = string<br>  default     = &quot;10.0.0.0/16&quot;<br>}<br><br>#####################################################<br># EC2 Requirement<br>#####################################################<br><br>variable &quot;instance_tenancy&quot; {<br>  description = &quot;it defines the tenancy of VPC. Whether it&#39;s defsult or dedicated&quot;<br>  type        = string<br>  default     = &quot;default&quot;<br>}<br><br>variable &quot;ami_id&quot; {<br>  description = &quot;ami id&quot;<br>  type        = string<br>  default     = &quot;ami-087c17d1fe0178315&quot;<br>}<br><br>variable &quot;instance_type&quot; {<br>  description = &quot;Instance type to create an instance&quot;<br>  type        = string<br>  default     = &quot;t2.micro&quot;<br>}<br><br>variable &quot;ssh_private_key&quot; {<br>  description = &quot;pem file of Keypair we used to login to EC2 instances&quot;<br>  type        = string<br>  default     = &quot;./Keypair-01.pem&quot;<br>}</pre><h4><strong>Step 3: Create Networking Components (VPC, Subnets, Igw, Route Tables)</strong></h4><ul><li>First, create the vpc_subnet.tf file and put the below codes:</li></ul><pre>#############################################<br><br>#Creating Virtual Private Cloud:<br><br>#############################################<br>resource &quot;aws_vpc&quot; &quot;custom_vpc&quot; {<br>  cidr_block           = var.custom_vpc<br>  instance_tenancy     = var.instance_tenancy<br>  enable_dns_support   = true<br>  enable_dns_hostnames = true<br>}<br><br>#############################################<br><br># Creating Public subnet:<br><br>#############################################<br><br>resource &quot;aws_subnet&quot; &quot;public_subnet&quot; {<br>  count             = var.custom_vpc == &quot;10.0.0.0/16&quot; ? 3 : 0<br>  vpc_id            = aws_vpc.custom_vpc.id<br>  availability_zone = data.aws_availability_zones.azs.names[count.index]<br>  cidr_block        = element(cidrsubnets(var.custom_vpc, 8, 4, 4), count.index)<br><br>  tags = {<br>    &quot;Name&quot; = &quot;Public-Subnet-${count.index}&quot;<br>  }<br>}<br><br>#############################################<br><br># Creating Internet Gateway:<br><br>#############################################<br><br>resource &quot;aws_internet_gateway&quot; &quot;igw&quot; {<br>  vpc_id = aws_vpc.custom_vpc.id<br><br>  tags = {<br>    &quot;Name&quot; = &quot;Internet-Gateway&quot;<br>  }<br>}<br><br>#############################################<br><br># Creating Public Route Table:<br><br>#############################################<br>resource &quot;aws_route_table&quot; &quot;public_rt&quot; {<br>  vpc_id = aws_vpc.custom_vpc.id<br><br>  tags = {<br>    &quot;Name&quot; = &quot;Public-RouteTable&quot;<br>  }<br>}<br><br>#############################################<br><br># Creating Public Route:<br><br>#############################################<br><br>resource &quot;aws_route&quot; &quot;public_route&quot; {<br>  route_table_id         = aws_route_table.public_rt.id<br>  destination_cidr_block = &quot;0.0.0.0/0&quot;<br>  gateway_id             = aws_internet_gateway.igw.id<br>}<br><br>#############################################<br><br># Creating Public Route Table Association:<br><br>#############################################<br><br>resource &quot;aws_route_table_association&quot; &quot;public_rt_association&quot; {<br>  count          = length(aws_subnet.public_subnet) == 3 ? 3 : 0<br>  route_table_id = aws_route_table.public_rt.id<br>  subnet_id      = element(aws_subnet.public_subnet.*.id, count.index)<br>}<br><br>#############################################<br><br># Creating VPC FlowLogs:<br><br>#############################################<br><br>resource &quot;aws_flow_log&quot; &quot;vpc_flow_log&quot; {<br>  iam_role_arn         = data.aws_iam_role.iam_role.arn<br>  log_destination_type = &quot;cloud-watch-logs&quot;<br>  log_destination      = aws_cloudwatch_log_group.cloudwatch_log_group.arn<br>  traffic_type         = &quot;ALL&quot;<br>  vpc_id               = aws_vpc.custom_vpc.id<br>}<br><br>##############################################<br><br># Creating CloudWatch Log Group:<br><br>##############################################<br><br>resource &quot;aws_cloudwatch_log_group&quot; &quot;cloudwatch_log_group&quot; {<br>  name              = &quot;VPC-FlowLogs-Group&quot;<br>  retention_in_days = 30<br>}</pre><h4><strong>Step 4: Create Custom Security Group</strong></h4><ul><li>Create security_group.tf and put below codes:</li></ul><pre>locals {<br>  ingress_rules = [{<br>    name        = &quot;HTTPS&quot;<br>    port        = 443<br>    description = &quot;Ingress rules for port 443&quot;<br>    },<br>    {<br>      name        = &quot;HTTP&quot;<br>      port        = 80<br>      description = &quot;Ingress rules for port 80&quot;<br>    },<br>    {<br>      name        = &quot;SSH&quot;<br>      port        = 22<br>      description = &quot;Ingress rules for port 22&quot;<br>  }]<br><br>}<br><br>resource &quot;aws_security_group&quot; &quot;sg&quot; {<br><br>  name        = &quot;CustomSG&quot;<br>  description = &quot;Allow TLS inbound traffic&quot;<br>  vpc_id      = aws_vpc.custom_vpc.id<br>  egress = [<br>    {<br>      description      = &quot;for all outgoing traffics&quot;<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>      prefix_list_ids  = []<br>      security_groups  = []<br>      self             = false<br>    }<br>  ]<br><br>  dynamic &quot;ingress&quot; {<br>    for_each = local.ingress_rules<br><br>    content {<br>      description = ingress.value.description<br>      from_port   = ingress.value.port<br>      to_port     = ingress.value.port<br>      protocol    = &quot;tcp&quot;<br>      cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>    }<br>  }<br>  tags = {<br>    Name = &quot;AWS security group dynamic block&quot;<br>  }<br><br>}</pre><h4><strong>Step 5: Create 3 EC2 Instances</strong></h4><ul><li>Create an ec2.tf file and put the below codes:</li></ul><pre>####################################################################<br><br># Creating 3 EC2 Instances:<br><br>####################################################################<br><br>resource &quot;aws_instance&quot; &quot;instance&quot; {<br>  count                = length(aws_subnet.public_subnet.*.id)<br>  ami                  = var.ami_id<br>  instance_type        = var.instance_type<br>  subnet_id            = element(aws_subnet.public_subnet.*.id, count.index)<br>  security_groups      = [aws_security_group.sg.id, ]<br>  key_name             = &quot;Keypair-01&quot;<br>  iam_instance_profile = data.aws_iam_role.iam_role.name<br><br>  tags = {<br>    &quot;Name&quot;        = &quot;Instance-${count.index}&quot;<br>    &quot;Environment&quot; = &quot;Test&quot;<br>    &quot;CreatedBy&quot;   = &quot;Terraform&quot;<br>  }<br><br>  timeouts {<br>    create = &quot;10m&quot;<br>  }<br><br>}<br><br>resource &quot;null_resource&quot; &quot;null&quot; {<br>  count = length(aws_subnet.public_subnet.*.id)<br><br>  provisioner &quot;file&quot; {<br>    source      = &quot;./userdata.sh&quot;<br>    destination = &quot;/home/ec2-user/userdata.sh&quot;<br>  }<br><br>  provisioner &quot;remote-exec&quot; {<br>    inline = [<br>      &quot;chmod +x /home/ec2-user/userdata.sh&quot;,<br>      &quot;sh /home/ec2-user/userdata.sh&quot;,<br>    ]<br>    on_failure = continue<br>  }<br><br>  connection {<br>    type        = &quot;ssh&quot;<br>    user        = &quot;ec2-user&quot;<br>    port        = &quot;22&quot;<br>    host        = element(aws_eip.eip.*.public_ip, count.index)<br>    private_key = file(var.ssh_private_key)<br>  }<br><br>}<br><br><br><br>####################################################################<br><br># Creating 3 Elastic IPs:<br><br>####################################################################<br><br>resource &quot;aws_eip&quot; &quot;eip&quot; {<br>  count            = length(aws_instance.instance.*.id)<br>  instance         = element(aws_instance.instance.*.id, count.index)<br>  public_ipv4_pool = &quot;amazon&quot;<br>  vpc              = true<br><br>  tags = {<br>    &quot;Name&quot; = &quot;EIP-${count.index}&quot;<br>  }<br>}<br><br>####################################################################<br><br># Creating EIP association with EC2 Instances:<br><br>####################################################################<br><br>resource &quot;aws_eip_association&quot; &quot;eip_association&quot; {<br>  count         = length(aws_eip.eip)<br>  instance_id   = element(aws_instance.instance.*.id, count.index)<br>  allocation_id = element(aws_eip.eip.*.id, count.index)<br>}</pre><h4><strong>Step 6: Fetch Availability Zone and Instance Role Details Using Data Block</strong></h4><ul><li>Create data.tf and put below code:</li></ul><pre>###################################################<br><br># Fetching all availability zones in us-east-1<br><br>###################################################<br><br>data &quot;aws_availability_zones&quot; &quot;azs&quot; {}</pre><pre>}</pre><h4><strong>Step 7: Create Target Group and Application Load Balancer</strong></h4><ul><li>Create alb.tf and put below code:</li></ul><pre>####################################################<br># Target Group Creation<br>####################################################<br><br>resource &quot;aws_lb_target_group&quot; &quot;tg&quot; {<br>  name        = &quot;TargetGroup&quot;<br>  port        = 80<br>  target_type = &quot;instance&quot;<br>  protocol    = &quot;HTTP&quot;<br>  vpc_id      = aws_vpc.custom_vpc.id<br>}<br><br>####################################################<br># Target Group Attachment with Instance<br>####################################################<br><br>resource &quot;aws_alb_target_group_attachment&quot; &quot;tgattachment&quot; {<br>  count            = length(aws_instance.instance.*.id) == 3 ? 3 : 0<br>  target_group_arn = aws_lb_target_group.tg.arn<br>  target_id        = element(aws_instance.instance.*.id, count.index)<br>}<br><br>####################################################<br># Application Load balancer<br>####################################################<br><br>resource &quot;aws_lb&quot; &quot;lb&quot; {<br>  name               = &quot;ALB&quot;<br>  internal           = false<br>  load_balancer_type = &quot;application&quot;<br>  security_groups    = [aws_security_group.sg.id, ]<br>  subnets            = aws_subnet.public_subnet.*.id<br>}<br><br>####################################################<br># Listner<br>####################################################<br><br>resource &quot;aws_lb_listener&quot; &quot;front_end&quot; {<br>  load_balancer_arn = aws_lb.lb.arn<br>  port              = &quot;80&quot;<br>  protocol          = &quot;HTTP&quot;<br><br>  default_action {<br>    type = &quot;redirect&quot;<br><br>    redirect {<br>      port        = &quot;443&quot;<br>      protocol    = &quot;HTTPS&quot;<br>      status_code = &quot;HTTP_301&quot;<br>    }<br>  }<br>}<br><br><br>####################################################<br># Listener Rule<br>####################################################<br><br>resource &quot;aws_lb_listener_rule&quot; &quot;static&quot; {<br>  listener_arn = aws_lb_listener.front_end.arn<br>  priority     = 100<br><br>  action {<br>    type             = &quot;forward&quot;<br>    target_group_arn = aws_lb_target_group.tg.arn<br><br>  }<br><br>  condition {<br>    path_pattern {<br>      values = [&quot;/var/www/html/index.html&quot;]<br>    }<br>  }<br>}</pre><h4><strong>Step 8: Create a Shell Script for Bootstrapping Few Tasks</strong></h4><ul><li>Create a bash file userdata.sh and paste the below commands:</li></ul><pre>#!/bin/bash<br>sudo su<br>yum update -y<br>yum install httpd -y<br>systemctl start httpd<br>systemctl enable httpd<br>echo &#39;Welcome to Instance&#39; &gt;&gt; /var/www/html/index.html<br>sed -i &#39;s/^PasswordAuthentication no/PasswordAuthentication yes/&#39; /etc/ssh/sshd_config<br>systemctl restart sshd</pre><h4><strong>Step 9: Provide a Few Required Outputs</strong></h4><ul><li>Create Output.tf file and put below codes:</li></ul><pre>output &quot;private_ip&quot; {<br>  value = zipmap(aws_instance.instance.*.tags.Name, aws_instance.instance.*.private_ip)<br>}<br><br>output &quot;public_ip&quot; {<br>  value = zipmap(aws_instance.instance.*.tags.Name, aws_eip.eip.*.public_ip)<br>}<br><br>output &quot;public_dns&quot; {<br>  value = zipmap(aws_instance.instance.*.tags.Name, aws_eip.eip.*.public_dns)<br>}<br><br>output &quot;private_dns&quot; {<br>  value = zipmap(aws_instance.instance.*.tags.Name, aws_instance.instance.*.private_dns)<br>}<br><br>output &quot;alb_id&quot; {<br>  value = aws_lb.lb.dns_name<br>}</pre><p>After creating all required <strong>tf</strong> files now it’s time to initiate terraform itself so that any modules or providers can be downloaded. Before doing that we can format all <strong>tf</strong> files to make this more understandable.</p><p><strong>terraform fmt:</strong> Use this command to make all files understandable to all. It can detect whether any piece of code is serialized or not and if yes, then it removes that deserialization and gets this more standard.</p><p><strong>terraform validate: </strong>This command is used to validate the codes which are written. If there is any syntax mismatching, then it will throw an error to get this fixed. Otherwise, it will show like the below screenshot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BAZUJ7MIEgSScH1SPzHUTQ.png" /></figure><p><strong>terraform init:</strong> This command is used to initialize modules or providers mentioned in the script, which means by doing that terraform simply downloads all APIs based on the cloud provider and which can take forward remaining operations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PZmmFjnD6c1yqQKy8YKrlQ.png" /></figure><p><strong>terraform plan:</strong> Once we initialize, then we need to know the plan how to terraform will proceed with other operations or which resources should be created first or when, everything will be visible by using terraform plan command.</p><p><strong>terraform apply:</strong> After the terraforming plan, we need to apply the configuration, so that it will be deployed in the AWS environment.</p><p>After deploying infrastructure elements, now I’m going to show you how it looks like in the AWS console. Let’s take a look!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zOcMycerNFyCUQHjufw_5w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*mPv1qoDfU_2a8c5EbE6PLA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tHaFnjc5HZldCweDV5VhLw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*bzLfAD8rANPoYQljGrvYjw.png" /></figure><p>Now, we have come to an end, we have seen that using ALB endpoint we’re able to browse instances, so what our motive was has been successful. Going forward we can deploy an application as well instead of a sample statement.</p><p>Hope you’ve liked this blog. Thank you for reading.</p><p><em>Please like it, follow me for more information and comment if you have any suggestions or improvement plans. Also, you can follow this repo. Here I will update all the scripts of Terraform!</em></p><p><a href="https://github.com/dasanirban834/Terraform-task/tree/main/AWS-infrastructure-with-alb">Terraform-task/AWS-infrastructure-with-alb at main · dasanirban834/Terraform-task</a></p><p><em>More content at </em><a href="http://plainenglish.io/"><em>plainenglish.io</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=403fe584f09e" width="1" height="1" alt=""><hr><p><a href="https://aws.plainenglish.io/deploy-a-set-of-ec2-instances-behind-an-alb-using-terraform-403fe584f09e">How to Deploy a Set of EC2 Instances behind an ALB Using Terraform</a> was originally published in <a href="https://aws.plainenglish.io/">AWS in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Features of AWS Simple Storage Service (S3) and Data Management]]></title>
            <link>https://aws.plainenglish.io/features-of-simple-storage-service-and-data-management-7ee3bfc5cb24?source=rss-59a29a5892be------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ee3bfc5cb24</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Dasanirban]]></dc:creator>
            <pubDate>Mon, 18 Oct 2021 18:52:04 GMT</pubDate>
            <atom:updated>2021-10-19T07:05:15.723Z</atom:updated>
            <content:encoded><![CDATA[<h4>Key features of AWS Simple Storage Service (S3) and Data Management.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*T8uNBhad6eASJodP" /><figcaption>Photo by <a href="https://unsplash.com/@joshua_j_woroniecki?utm_source=medium&amp;utm_medium=referral">Joshua Woroniecki</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What is Simple Storage Service?</h3><p>Amazon’s Simple Storage Service is an object storage service that is used to store data (images, documents, videos, and files with different extensions) as an object. It also offers data security, scalability, availability, and performance. For customers, it provides different tiers of storage for their data based upon their usage frequency and requirement. S3 also provides few management services to optimize, organize, and configure access to your data to meet the business requirements.</p><h3>Amazon S3 Storage Class</h3><p>Simple Storage Services consists of a number of multiple storage tiers. Depending on the requirement, customers can use these tiers or process the data to a certain tier after one or after a few months of using Life Cycle Management in order to reduce the cost.</p><p>There are six tiers of S3:</p><ul><li>S3 Standard</li><li>S3 Standard -IA</li><li>S3 One Zone -IA</li><li>S3 Intelligent-Tiering</li><li>S3 Glacier</li><li>S3 Glacier Deep Archive</li></ul><h4><strong>Performance Comparison</strong></h4><p>The following table shows a comparison of all the S3 tiers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*TY54wXTg_3Xols0hw2fUnA.png" /></figure><h4><strong>Data Store Management</strong></h4><p>Storing data includes few activities such as bucket creation, uploading data, providing granular, and the lowest level of access to the bucket.</p><p>Please look at the steps given below:</p><p>Step 1: Create a Bucket</p><ul><li>First login to AWS console using <a href="https://console.aws.amazon.com/s3/">https://console.aws.amazon.com/s3/</a> link.</li><li>Select S3 under the storage section like the snap below:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*rVxAlx36SfjjZfHMyGPu-w.png" /></figure><ul><li>Once you click on the S3 option, you’ll be able to access the S3 console. Then click on the Create option.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fKts1fYJBuUwI5wWNnceRA.png" /></figure><ul><li>Now you have to provide few details and check settings as per your requirement. Provide bucket name and location, after that, you need to uncheck the “Block all public access” option and do check on below acknowledgement statement.</li></ul><p>The following rules apply for naming buckets in Amazon S3:</p><ul><li>Bucket names must be between 3 and 63 characters long.</li><li>Bucket names can consist only of lowercase letters, numbers, dots (.), and hyphens (-).</li><li>Bucket names must begin and end with a letter or number.</li><li>Bucket names must not be formatted as an IP address (for example, 192.168.5.4).</li><li>Bucket names must not start with the prefix xn--.</li><li>Bucket names must not end with the suffix -s3alias. This suffix is reserved for access point alias names. For more information, see <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/access-points-alias.html">Using a bucket-style alias for your access point</a>.</li><li>Bucket names must be unique within a partition. A partition is a grouping of Regions. AWS currently has three partitions: aws (Standard Regions), aws-cn (China Regions), and aws-us-gov (AWS GovCloud [US] Regions).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*lk0Rt5EOXTjEwuEBWwFZFQ.png" /></figure><ul><li>Let’s keep the same rest other option as default. We can change our settings after creating the bucket also.</li><li>Once the bucket gets created, then select the radio button against the bucket you have created, then select it. You’ll get to view other tabs for configuration changes.</li></ul><p>Step 2: Uploading an object</p><ul><li>Select the bucket name you want to open up, then you’ll be able to see the below screen. Select the “Upload” option.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4DxHD_saiiA3Pkk-MmOIiA.png" /></figure><ul><li>Select the “Add Files” or “Add Folder” option to upload.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*8pvHuoDhzPlQAl90_a3GzA.png" /></figure><ul><li>After selecting the folder/files, just click on the Upload option. Once uploaded, it will show as the below snap:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xbYXMrGj6kSOv4gnlCDxjg.png" /></figure><p>Step 3: Managing Bucket and Object Setting:</p><ul><li>If you click on the file that you uploaded right now, you’ll get to see an overview of this file and a lot more settings:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5NwwkFIrWpDIHXdPkr056Q.png" /></figure><ul><li>Here in the overview, you can see the “Object URL” option which we can use to browse the content. But initially, the contents aren’t viewable as it’s private. Even if you try to browse this URL, you’ll get an error:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*IMjsKlJK-CjduKzdz97rpQ.png" /></figure><ul><li>In order to remove this error, we need to make the object Public. Once we do, then we’ll be able to access it over the internet:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6hYFj-7MNovfDwMzuZwTwA.png" /></figure><ul><li>Now using that URL, I’m able to access the file:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n3piu1r3Qu7c6LcwLplthA.png" /></figure><p>As we have made this file Public, so it can be accessed from anywhere in the world.</p><ul><li>Now instead of one file, if I have 100 files, then it is impossible to make the contents public individually. This is when Bucket Policy comes into the picture. This policy is written in JSON using Policy Generator or you can write this script manually as well, which basically describes the level of access and who can access which files/folders, etc.</li><li>Select the bucket first, then click on the “Permissions” tab, then you’ll see the “Bucket Policy” option:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KhTAko93We3zcpIqS_U7YA.png" /></figure><ul><li>Put this JSON script.</li></ul><pre>{<br> “Version”:”2012–10–17&quot;,<br> “Statement”:[<br> {<br> “Sid”:”PublicRead”,<br> “Effect”:”Allow”,<br> “Principal”: “*”,<br> “Action”:[“s3:GetObject”,”s3:GetObjectVersion”],<br> “Resource”:[“arn:aws:s3:::bucket-test12–098<strong>/*</strong>”]<br> }<br> ]<br>}</pre><p>Note: Just change the bucket ARN details. Also, choose the API operations as per your requirement under the “Action” block.</p><ul><li>Once you put the bucket policy, please verify whether the “<strong>publicly accessible</strong>” tagline is showing or not just under the bucket name. See the below snap for reference:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*ohV6WKuqFZPObfPIeRM7kA.png" /></figure><h3><strong>Versioning</strong></h3><p>Versioning is a process that captures the changes in a particular object and creates another copy of the original object with updated contents. Once we enable it, it starts to capture changes only. Once anyone makes any changes inside the file/object, another version with updated contents will be created.</p><p>You can use this technique to preserve the contents from accidental deletion. Then it can be restored in case of any application failures.</p><p>Once it is enabled, it can’t be disabled, but yes it can be suspended as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T3Bu8uzkidQZLZJ50tdKww.png" /></figure><p>For a non-versioned bucket, an <strong>object retrieval </strong>always returns the only object available, but for a versioned bucket, an object retrieval returns the current object. Non-current objects can be retrieved by specifying the version ID.</p><p>In the case of <strong>object addition</strong>, if an object with the same key is uploaded again, then it overwrites the object. But for a versioned bucket, the newly uploaded object will be the current version and the previous one would be the non-current version.</p><p>In the case of object deletion, for the non-versioned bucket, objects are deleted and can’t be recovered. Whereas in the case of a versioned bucket, all versions remain in the bucket and Amazon inserts a <strong>delete marker</strong> which becomes the current version. If an object with a certain version ID is deleted, then permanent deletion happens and objects can’t be recovered.</p><h3><strong>Server Access Logging</strong></h3><p>Server Access Logging needs to be enabled to track all API operation happened on a particular bucket. This one is specially used for troubleshooting purposes.</p><ul><li>In the “Properties” tab, just scroll down a little and you’ll see the Server Access Logging option which is disabled by default. You need to enable it explicitly:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RilseuwEdp04uYhPgbfZJw.png" /></figure><ul><li>For storing the Access logs, you need to select another bucket as the target location.</li></ul><h3><strong>Object Locking</strong></h3><p>It’s a feature of Simple Storage Service which allows users to write an object once and read multiple times (WORM = Write Once, Read Many). This feature provides extra data security from getting deleted or corrupted by anyone. By default, it’s disabled, but while creating a bucket, we can enable it as per requirement. Once we create the bucket, it cannot be enabled. You need to take help from Customer Support:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s1vJyqPrA2yQpXnRev81XA.png" /></figure><p>Now, we have come to the end of this topic. Here, we have seen what S3 is all about, how to create a bucket and upload objects, how to manage permissions, etc. Hope you all have got an overview of S3. Going forward, I’ll create content on Life Cycle Rule and Data Replication on S3.</p><p>Hope you like this article. Please follow me for further updates. And share in your circle definitely. If you have any suggestions/queries, just drop a comment. Thanks.</p><p>Cheers,</p><p>Anirban Das</p><p><em>More content at </em><a href="http://plainenglish.io/"><em>plainenglish.io</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ee3bfc5cb24" width="1" height="1" alt=""><hr><p><a href="https://aws.plainenglish.io/features-of-simple-storage-service-and-data-management-7ee3bfc5cb24">Features of AWS Simple Storage Service (S3) and Data Management</a> was originally published in <a href="https://aws.plainenglish.io/">AWS in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>