<?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 Cansu Tekin on Medium]]></title>
        <description><![CDATA[Stories by Cansu Tekin on Medium]]></description>
        <link>https://medium.com/@cansutekin23?source=rss-3599111d902f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*iIJ88v9BSTnLz7WpyjtoQQ.jpeg</url>
            <title>Stories by Cansu Tekin on Medium</title>
            <link>https://medium.com/@cansutekin23?source=rss-3599111d902f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 11:54:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@cansutekin23/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[Building a Scalable Web App with AWS Elastic Beanstalk, DynamoDB, CloudFront, and Edge Location —…]]></title>
            <link>https://medium.com/@cansutekin23/building-a-scalable-web-app-with-aws-elastic-beanstalk-dynamodb-cloudfront-and-edge-location-c63a9597e49d?source=rss-3599111d902f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c63a9597e49d</guid>
            <category><![CDATA[cloudfront]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[aws-ebs]]></category>
            <dc:creator><![CDATA[Cansu Tekin]]></dc:creator>
            <pubDate>Wed, 03 Jul 2024 00:41:48 GMT</pubDate>
            <atom:updated>2024-07-03T00:41:48.350Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Scalable Web App with AWS Elastic Beanstalk, DynamoDB, CloudFront, and Edge Location — with AWS Dashboard and EB CLI</h3><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*mxCDCTUxKMbrrEJtvDT4xA.png" /></figure><p>In this real-world project, I was tasked with implementing an application capable of supporting a high volume of simultaneous users. This application was utilized during a large conference attended by over 10,000 people, both in-person and online, from around the globe. The event featured live broadcasts and the drawing of 10 vouchers for 3 Cloud certifications. At the peak moment, more than 10,000 audience members registered their emails to participate in the raffle.</p><p>We used AWS, Elastic Beanstalk services to deploy the web application, DynamoDB to store emails, and CloudFront to cache static and dynamic files in an Edge Location close to the user.</p><h3>Solution Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*mZU0mWyGPiZoGrobEqdphA.png" /></figure><p><strong>Part 1: Create a table in DynamoDB to store users’ email addresses and deploy the application using Elastic Beanstalk</strong></p><p><strong>Part 2: Create a CloudFront distribution</strong></p><p><strong>Part 3: Perform Load testing</strong></p><h3>Part 1: Create a table in DynamoDB to store users’ email addresses and deploy the application using Elastic Beanstalk</h3><p>Create a table in DynamoDB to store users’ email addresses and deploy the application using Elastic Beanstalk, which will provision infrastructures such as EC2, Elastic Load Balancer, and Auto Scaling group.</p><ol><li><strong>Create a table in DynamoDB to store users’ email addresses</strong></li></ol><p>Amazon DynamoDB is a fully managed, high-performance, and highly scalable NoSQL database service designed to handle large-scale data loads and ensure low-latency responses.</p><p>Search for DynamoDB in the AWS console and create a table “users”. Leave anything else as default.</p><p>A partition key is a unique attribute in a DynamoDB table that determines the partition in which the data is stored. Each item in the table must have a unique value for the partition key.</p><p>Table name: users</p><p>Partition key: email, type String</p><figure><img alt="Amazon DynamoDB Table" src="https://cdn-images-1.medium.com/proxy/1*m18oCx8wgqXRVgFDbx7zOQ.png" /></figure><p><strong>2. Create an Elastic Beanstalk Application</strong></p><p>Amazon Elastic Beanstalk is an easy-to-use service for deploying and scaling web applications and services developed with Java, .NET, PHP, Node.js, Python, Ruby, Go, and Docker on familiar servers such as Apache, Nginx, Passenger, and IIS.</p><p>Many people will try accessing our application from a mobile or desktop to register. At this stage, the application needs to be robust and scalable to handle high traffic from many users. Elastic Beanstalk allows us to deploy and manage the web application in AWS Cloud without worrying about the infrastructure. It simplifies the process by provisioning and managing essential AWS resources like EC2 instances, Elastic Load Balancers, and Auto Scaling groups, ensuring the application remains responsive and available under varying loads. We will upload the application files, and Elastic Beanstalk will automatically manage capacity provisioning, load balancing, and scaling.</p><p>Elastic Beanstalk will use the provided application files to deploy the application. It is important to organize the application folders in a way that Elastic Beanstalk can understand. Check the <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/tutorials.html">Elastic Beanstalk documentation</a> before uploading the application files. Each application requires its own folder structure. This project’s folders and files were designed specifically for the Python application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/0*ueDTEsvN4amAyDyv.png" /></figure><p>application.py</p><pre>from flask import Flask, render_template, flash, redirect, url_for, session, request, logging<br>from wtforms import Form, StringField, TextAreaField, PasswordField, validators<br>from wtforms.validators import InputRequired, Email<br>import boto3<br>import os<br>from urllib.parse import quote as url_quote<br><br>application = Flask(__name__)<br><br>#dynamodb = boto3.resource(&#39;dynamodb&#39;, endpoint_url=&quot;http://localhost:8000&quot;)<br>region = os.environ[&#39;AWS_REGION&#39;]<br>dynamodb = boto3.resource(&#39;dynamodb&#39;,region_name=region)<br><br>def put_user(email):<br>    table = dynamodb.Table(&#39;users&#39;)<br>    response = table.put_item(<br>       Item={<br>            &#39;email&#39;: email<br>        }<br>    )<br>    return response<br><br># Index<br>@application.route(&#39;/&#39;, methods=[&#39;GET&#39;, &#39;POST&#39;])<br>def index():<br>    form = RegisterForm(request.form)<br>    if request.method == &#39;POST&#39; and form.validate():<br>        user_resp = put_user(form.email.data)<br>        return render_template(&#39;obrigado.html&#39;)<br>    <br>    return render_template(&#39;index.html&#39;, form=form)<br><br># Register Form Class<br>class RegisterForm(Form):<br>    email = StringField(&#39;Email&#39;, [InputRequired(&quot;Please enter your email.&quot;)])<br><br>if __name__ == &#39;__main__&#39;:<br>    application.secret_key=&#39;secret123&#39;<br>    application.run(debug=True)</pre><p>requirements.txt</p><pre>boto3==1.21.8<br>botocore==1.24.8<br>Flask==2.0.3<br>passlib==1.7.2<br>WTForms==2.3.3<br>jsons==1.6.1<br>itsdangerous==2.1.0<br>Werkzeug==2.0.3</pre><p>Proper organization of the application files helps Elastic Beanstalk deploy the application automatically. Structure your project, zip, and store the zip file in a S3 bucket or locally. Elastic Beanstalk will use it to deploy the application.</p><p><strong>3. Configure environment</strong></p><p>Search for Elastic Beanstalk in the AWS console and “<strong>Create Application”.</strong></p><p>Application name: tcb-conference</p><p>Platform (runtime environment): Python 3.8</p><p>Application code: Upload the application file code</p><p>Presets: High availability</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*96GsS-oAhPV3ObZQ.png" /></figure><p>It launches an environment named tcb-conference-env with these <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/GettingStarted.CreateApp.html">AWS resources:</a></p><ul><li>An Amazon Elastic Compute Cloud (Amazon EC2): An Amazon EC2 virtual machine configured to run web apps on the platform you choose.</li><li>An Amazon EC2 security group: An Amazon EC2 security group configured to allow incoming traffic on port 80. This resource lets HTTP traffic from the load balancer to the EC2 instance running your web app.</li><li>An Amazon Simple Storage Service (Amazon S3) bucket: A storage location for your source code, logs, and other artifacts that are created when you use Elastic Beanstalk.</li><li>Amazon CloudWatch alarms: Two CloudWatch alarms that monitor the load on the instances in your environment and are triggered if the load is too high or too low. When an alarm is triggered, your Auto Scaling group scales up or down in response.</li><li>An AWS CloudFormation stack: Elastic Beanstalk uses AWS CloudFormation to launch the resources in your environment and propagate configuration changes. The resources are defined in a template that you can view in the <a href="https://console.aws.amazon.com/cloudformation">AWS CloudFormation console.</a></li><li>A domain name (autogenerated in our case): A domain name that routes to your web app in the form <a href="http://subdomain.region.elasticbeanstalk.com/">subdomain.</a><a href="http://subdomain.region.elasticbeanstalk.com/">region.elasticbeanstalk.com</a>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZpRAsH9Mt0A0o1OV.png" /></figure><p>We do not need to specify the S3 bucket URL at this point. Once we move to the next step (from environment configuration to service access configuration) an S3 bucket will be automatically created without waiting to complete the EBS application creation process. We can use this bucket to store our application code or create a different one. I will use this one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UZCWISQcmZ8_INQ5.png" /></figure><p>After designing the folder structure for the Python application based on AWS Elastic Beanstalk documentation, the application files will be uploaded to S3 bucked. That location is used to run the application. Go to S3 bucked and upload the application files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Tnf2XE-rlmow_1aH.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-kIsORSNbmqGpmt1.png" /></figure><p>Update your Public S3 URL with the bucket URL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jIjgVnWgSvxSkksy.png" /></figure><p>At this point, all public access to this bucket is allowed as default. I will keep it as it is but update it for later projects.</p><p><strong>4. Configure service access</strong></p><p>We need to set up the necessary permissions and roles that allow Elastic Beanstalk to interact with other AWS services securely.</p><ol><li><strong>Service Role</strong>: Grants permissions to the Elastic Beanstalk service itself, allowing it to manage AWS resources on your behalf. This includes creating and managing EC2 instances, load balancers, and other resources necessary for running your application.</li><li><strong>EC2 Instance Profile:</strong> Grants permissions to the EC2 instances running our application. It allows the instances to interact with other AWS services (e.g., S3, DynamoDB) on your behalf.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2BsRccBwAaC1WhQX.png" /></figure><p>When you click View permission details you will see recommended permission by AWS. We will add them to our IAM roles as well.</p><p><strong>Service role permission recommendations:</strong></p><ol><li><strong>AWSElasticBeanstalkEnhancedHealth</strong> (this comes as default)</li><li><strong>AWSElasticBeanstalkManagedUpdatesCustomerRolePolicy</strong> (we will attach it)<strong>:</strong> This policy is for the AWS Elastic Beanstalk service role used to perform managed updates of Elastic Beanstalk environments. The policy grants broad permissions to create and manage resources across several AWS services including AutoScaling, EC2, ECS, Elastic Load Balancing, and CloudFormation.</li></ol><p><strong>EC2 instance profile recommendations:</strong></p><ol><li><strong>AWSElasticBeanstalkWebTier:</strong> Provide the instances in your web server environment access to upload log files to Amazon S3.</li><li><strong>AWSElasticBeanstalkWorkerTier:</strong> Provide the instances in your worker environment access to upload log files to Amazon S3, to use Amazon SQS to monitor your application’s job queue, to use Amazon DynamoDB to perform leader election, and to Amazon CloudWatch to publish metrics for health monitoring.</li><li><strong>AWSElasticBeanstalkMulticontainerDocker:</strong> Provide the instances in your multicontainer Docker environment access to use the Amazon EC2 Container Service to manage container deployment tasks.</li></ol><p>First, we need to create an IAM role and attach it to the Elastic Beanstalk application. You can select <em>Create and use a new service role</em> if you do not have an existing one, or you want AWS to create one for you. This will create an IAM role with necessary permissions but you may need to add additional permissions based on your application needs. I will create a new one for this project following the steps below:</p><ol><li><strong>Create a Service Role</strong>:</li></ol><p>Go to IAM -&gt; Roles -&gt; Create role -&gt; AWS service</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*D49yFluVQeXUkALl.png" /></figure><p>When we specify the Use case as Elastic Beanstalk it comes with some <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/concepts-roles-service.html">default policies.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KA82knGXtaRW6eEJ.png" /></figure><p>Named :elastic-beanstalk-service-role</p><p><strong>AWSElasticBeanstalkEnhancedHealth:</strong> AWS Elastic Beanstalk Service policy for Health Monitoring system.</p><p><strong>AWSElasticBeanstalkService:</strong> AWS Elastic Beanstalk Service role policy grants permissions to create &amp; manage resources (i.e.: AutoScaling, EC2, S3, CloudFormation, ELB, etc.) on your behalf. This policy comes with the following permissions by default:</p><ul><li><strong>AllowCloudformationOperationsOnElasticBeanstalkStacks</strong>: Allows full CloudFormation operations.</li><li><strong>AllowDeleteCloudwatchLogGroups</strong>: Allows Elastic Beanstalk to clean up log groups when environments are deleted.</li><li><strong>AllowECSTagResource</strong>: Allows tagging of ECS resources</li><li><strong>AllowS3OperationsOnElasticBeanstalkBuckets</strong>: Allows full S3 operations on Elastic Beanstalk-specific buckets. Grants permissions to manage Elastic Beanstalk application versions, environment configurations, and logs stored in S3 buckets.</li><li><strong>AllowLaunchTemplateRunInstances</strong>: Enables Elastic Beanstalk to launch EC2 instances using predefined launch templates.</li><li><strong>AllowOperations</strong>: Allows Elastic Beanstalk to fully manage instances, security groups, load balancers, scaling policies, and other resources necessary for the application environment. Includes permissions for Auto Scaling, EC2, ECS, Elastic Load Balancing, IAM, CloudWatch, RDS, S3, SNS, SQS, and CodeBuild.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CyS6jIPiIeHRElS0.png" /></figure><p>Most of the necessary policies are attached by default. Create a role with given permissions first. If we need any additional permission we need to attach it to this role.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hTH4zxaVrGzx56pb.png" /></figure><p>We will attach the recommended policy we mentioned earlier: <strong>AWSElasticBeanstalkManagedUpdatesCustomerRolePolicy</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RTZUH7S8yg322eOb.png" /></figure><p><strong>AWSElasticBeanstalkManagedUpdatesCustomerRolePolicy</strong>: Includes permissions needed specifically for updating instances and other resources.</p><p><strong>AWSElasticBeanstalkService</strong>: Includes a wider range of permissions necessary for creating, updating, and deleting various AWS resources managed by Elastic Beanstalk. This policy is on a deprecation path. It comes as a default for now.</p><p><strong>2. Create an EC2 Instance Profile</strong></p><p>We will follow similar steps to create an EC2 Instance Profile.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UB8xwU2ypDipUesW.png" /></figure><p>We need to attach specific policies to give additional permission to the EC2 instance that our Python application will run inside it. In our case, our application needs to write data and read data from the DynamoDB table. We need a specific policy for that which is <em>AmazonDynamoDBFullAccess.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*x9WDQKxXxy5-YiR8.png" /></figure><p>Named :elastic-beanstalk-ec2-service-role</p><p>After we added AWS recommended policies, the final role comes with the following policies:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NnBfal262_rPWtq3.png" /></figure><p><strong>3. Create an SSH key:</strong></p><p>To access the EC2 instance via SSH connection we will create an SSH key.</p><p>EC2 -&gt; Key pairs -&gt; Create key pair</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NZoKx_YJUwSDH-Ek.png" /></figure><p>Download and store the key.</p><p>We are all set for service access configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7SkNKbEIWYiHGP62.png" /></figure><p>You can <em>Skip to review</em> and edit configuration there or you can go step by step until the end.</p><p><strong>5. Set up networking, database, and tags-</strong><a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/using-features.managing.vpc.html"><strong>optional</strong></a></p><p>If you don’t configure a VPC, Elastic Beanstalk uses the default VPC. I will use a custom VPC I had before. You can use the default one. The configuration will be the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FaLnOX3T1NmaICm2.png" /></figure><p>We will choose subnets in each AZ for the EC2 instances that run our application. To avoid exposing our application instances to the Internet, we can run them inside private subnets and load balancers in public subnets such that our application will be open the public access through NAT. If we choose private subnets for our EC2 instances, the VPC must have a NAT gateway in a public subnet that the EC2 instances can use to access the Internet. I will not create a NAT gateway and I will run both in public subnets for simplicity. To run the load balancer and instances in the same public subnets, we will assign public IP addresses to the instances.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NmiEGuP9aLyGC6ni.png" /></figure><p>I only picked public subnets and activated public IP addresses for EC2 instances. I am not going to use RDS, I will move to the next configuration.</p><p><strong>6. Configure instance traffic and scaling <em>— optional</em></strong></p><p>We will set the Root volume type: General Purpose SSD — 8 GB</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ej7MY95wQeuteBTi.png" /></figure><p><strong><em>Capacity:</em></strong>Instances Min: 2 Instances Max: 4 Instance type: t2-micro</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*epIeRMMSJkTZppzj.png" /></figure><p>The Elastic Beanstalk will automatically create a Load Balancer for our application, with a minimum of 2 EC2 instances running when we first launch our application, and a maximum of 4 if triggered.</p><p>Configure the trigger that lets the auto-scaling group know when to scale up and add up more instances. if the load goes beyond 50% of CPU utilization, it is going to add more instances up to 4 to keep up with the workload.</p><p><strong><em>Scaling triggers:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JlPzlEqa2pmrtaAv.png" /></figure><p><strong><em>Load balancer network settings:</em></strong> We will use the same setting as we used for EC2 instances.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xqeqKUd7cvYbEcqv.png" /></figure><p><strong><em>Listeners:</em></strong> By default, the load balancer is configured with a standard web server on port 80. I will use default settings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UNOgUFfdyomVygEh.png" /></figure><p>If you wish you can configure Elastic Load Balancer to capture logs with detailed information about requests sent to your Load Balancer. Those logs will be stored in Amazon S3. I will not enable it for this project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WM5NNU8i6Riq-4UL.png" /></figure><p><strong>7. Configure updates, monitoring, and logging <em>— optional</em></strong></p><p>I will not touch settings here, if you want you can configure them based on your needs. It uses NGINX by default.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*T_sfDDK_mWoadTz3.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zkHw224dQCIlDHte.png" /></figure><p>I will only set the AWS_REGION environment variable here. It will be passed to my application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Z6ZCv3V72Zf7MSKV.png" /></figure><p>Submit to create the environment for the application run. It takes a few minutes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aVGmlF_bHDJsMkNH.png" /></figure><p><strong><em>S3 Bucket:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3UNJKn5OF338Ubtd.png" /></figure><p><strong><em>EC2 instances:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lLsjUMX8urMeuMEr.png" /></figure><p><strong><em>Security Groups:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*93NeAFTWzznpvslR.png" /></figure><p>Inbound-outbound rules of security groups:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oBduRmnK9sniLG4F.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*g7D-XmRzWwuXzg76.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zuLxFJU7MVlZgYNc.png" /></figure><p><strong><em>Load Balancer:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*v0OdhrXZD-0hGfmH.png" /></figure><p>The environment health turned to RED, I will look at the logs and figure it out before trying to run my application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bNetjzXXCUADK9bQ.png" /></figure><p>It did not work in my case. I ran this application without any problem with the same settings before. It should work. I do not know if AWS has updated any settings on its services since my last run. I got the following error for this time:</p><p>ERROR: ModuleNotFoundError: No module named &#39;application&#39;</p><p>I applied the solutions below to solve it but I was not able to solve this error after too much debugging.</p><ul><li>AWS calls the Flask instance as an <em>application</em> but Gunicorn calls it as an <em>app.</em> I updated a line, application = app = Flask(__name__), in my <em>application.py</em> file and then set WSGIPath to application:application.</li></ul><p>I will use EB CLI after this point with the exact same settings. If you are also not able to run or debug by yourself you can move with me to use EB CLI.</p><p>Do not forget to destroy all the resources you created with Elastic Bean Stalk; <em>tcb-conference-env</em> and <em>tcb-conference</em> application. Keep the DynamoDB table.</p><h3>Building a Scalable Web App with AWS Elastic Beanstalk, DynamoDB, and CloudFront — with EB CLI</h3><h3>Part 1: Deploy the application using Elastic Beanstalk — with EB CLI</h3><ol><li><strong>Install EB CLI</strong></li></ol><p>EB CLI is AWS Elastic Beanstalk Command Line Interface. First, we will install EB CLI. You can use this <a href="https://github.com/aws/aws-elastic-beanstalk-cli-setup?tab=readme-ov-file#macoslinux">aws-elastic-beanstalk-cli-setup</a> to install based on your operating system. I will follow the instructions for MacOS:</p><pre>pip install awsebcli<br># Verify the EB CLI Installation<br>eb --version</pre><p><strong>2. Configure the EB CLI</strong></p><p>Initialize an EB CLI project and select your region.</p><pre># Initialize <br>eb init<br><br>#or<br>eb init -p python-3.8 tcb-conference --region us-east-1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zrvpz6hHlkO01h94.png" /></figure><p><strong>3. Setup IAM Credentials</strong></p><p>We must provide our credentials first. We must provide a secret key and access key to authenticate (who we are) and authorize (what permission we do have) to allow EB CLI to access and manage AWS resources for us. Let’s go to the IAM console to create a secret and access key. The secret access key is available for download only when you create it, make sure you download it after you create it.</p><p>Go to IAM console -&gt; Users -&gt; Create User</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BXiCWRl2zE8b6Ink.png" /></figure><p>I will give AdministratorAccess access, and I can update later if I wish.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*r7BK4I90wZkUps54.png" /></figure><p>Go and create access key.</p><p>Use case: Command Line Interface (CLI)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GFKBB82fJuDcJmS_.png" /></figure><p>When you run EB CLI it will ask for these credentials. You can also configure the AWS CLI using environment variables</p><p>export AWS_ACCESS_KEY_ID=YOUR_ACCESS_KEY_ID</p><p>export AWS_SECRET_ACCESS_KEY=YOUR_SECRET_ACCESS_KEY</p><p>export AWS_DEFAULT_REGION=us-east-1</p><p>We are ready to configure the EBS environment, similar to what we did on the AWS console before:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kQ1v61MO_bg0mIv7.png" /></figure><p><strong>4. Create an Elastic Beanstalk Environment</strong></p><p>We will use the YAML file for configuration. The YAML file should be under <em>.ebextentions</em>. EBS will automatically detect and run this config file when it is provided. Otherwise, it will use default EBS settings to create an EBS environment.</p><pre>mkdir .ebextensions <br>touch .ebextensions/environment_configuration.config</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/0*d0lxPV_wvcHKU2wn.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DcGAxQ9wS9O-x73N.png" /></figure><p>Our application files will be zipped and uploaded to the S3 bucket while creating the environment.</p><p>We will use the same configuration in our YAML file. This is actually easier and faster compared to using AWS Dashboard.</p><p>YAML config file:</p><pre>option_settings:<br>  aws:elasticbeanstalk:environment:<br>    ServiceRole: &quot;aws-elasticbeanstalk-service-role&quot; # Set service role<br>  aws:autoscaling:launchconfiguration:<br>    InstanceType: t2.micro # Specify the instance type (adjust as needed)<br>    EC2KeyName: ebs-ssh-key # Set EC2 key pair<br>    IamInstanceProfile: aws-elasticbeanstalk-ec2-role # Set IAM instance profile<br>    RootVolumeType: gp2<br>    RootVolumeSize: &quot;10&quot;<br>    DisableIMDSv1: true # Deactivate IMDSv1<br>  aws:autoscaling:asg:<br>    MaxSize: 4 # Maximum number of instances<br>    MinSize: 2 # Minimum number of instances<br>  aws:ec2:vpc:<br>    VPCId: &quot;vpc-03f8678fb9c5d5ea1&quot; # Set the VPC ID<br>    ELBScheme: public<br>    Subnets:<br>      - &quot;subnet-0449c3e40202e7665&quot;<br>      - &quot;subnet-01e26ba1a707f5b13&quot;<br>      - &quot;subnet-06a672c7f4aea1795&quot;<br>      - &quot;subnet-0461ac2c4cea08257&quot;<br>    ELBSubnets:<br>      - &quot;subnet-0449c3e40202e7665&quot;<br>      - &quot;subnet-01e26ba1a707f5b13&quot;<br>      - &quot;subnet-06a672c7f4aea1795&quot;<br>      - &quot;subnet-0461ac2c4cea08257&quot;<br>    AssociatePublicIpAddress: true # Enable public IP addresses for instances<br>  aws:elasticbeanstalk:healthreporting:system:<br>    SystemType: &quot;basic&quot; # Enable enhanced health reporting<br>  aws:autoscaling:trigger:<br>    MeasureName: &quot;CPUUtilization&quot; # Use CPUUtilization as trigger measurement<br>    UpperThreshold: &quot;50&quot; # Upper threshold for CPU utilization<br>    LowerThreshold: &quot;40&quot; # Lower threshold for CPU utilization<br>    Unit: &quot;Percent&quot;<br>    Period: &quot;1&quot;<br>    UpperBreachScaleIncrement: &quot;1&quot; # Increase instance count by 1 on upper breach<br>    LowerBreachScaleIncrement: &quot;-1&quot; # Decrease instance count by 1 on lower breach<br>  aws:elasticbeanstalk:container:python:<br>    WSGIPath: &quot;application:application&quot; # Set WSGIPath to application:application<br>  aws:elasticbeanstalk:application:environment:<br>    AWS_REGION: &quot;us-east-1&quot; # Set AWS_REGION environment property</pre><p>You can use <a href="https://docs.aws.amazon.com/pdfs/elasticbeanstalk/latest/dg/awseb-dg.pdf#command-options-general">EBS documentation</a> here while preparing your YAML file.</p><p>Ready to create an EBS environment:</p><pre>eb create tcb-conference-env --region us-east-1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*94y87p7tVydQJIje.png" /></figure><p>We are now able to create our EBS environment without any problems at this time!</p><p>Health: OK</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*E7xiJD3XBFv8zTVX.png" /></figure><p>Click on the Domain name to open the application:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7vFetVgxw8n0jSBx.png" /></figure><p>Our application files were zipped and uploaded to the S3 bucket. Remember we created an EBS application named <em>tcb-conference</em> at the beginning of the EB CLI initialization. Our files are zipped and placed in a directory named <em>tcb-conference.</em></p><p><em>S3 bucket:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Y0D9LQKIRHt-_uHA.png" /></figure><p><em>EC2 instances (Minimum 2):</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wDTna15NaXLAhvZg.png" /></figure><p><em>Load Balancer:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*q39EjotpNEbqMeDZ.png" /></figure><p><em>Auto Scaling Group:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hMr5HG3M2LSzmpBt.png" /></figure><p><em>CloudFormation:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kKDl8vXIpJWrsbjF.png" /></figure><p><strong>5. Validate the Application</strong></p><p>The participants will need to enter their email address on the web page and the application will insert the email address into the DynamoDB.</p><p>Try to register:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HGcSlJDKqwLiprhw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hQgrgC6zXI3QZUcH.png" /></figure><p>Upps! We are not able to register. Our frontend is working but we are not allowed to register. Our email will not be written to DynamoDB. Let’s go and check our EC2 instance role.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iOiRVgrBVg25fa8b.png" /></figure><p>We do not have permission to write data to DynamoDB. Permit your EC2 instance to write data on the DynamoDB table inside the IAM role. Add the permission <strong>AmazonDynamoDBFullAccess</strong> on the EC2 associate role in IAM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RC57tC5R5LOaLZzY.png" /></figure><p>Try again:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jao8Tew-7DSApR1U.png" /></figure><p>Check the <em>users’</em> DynamoDB table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-G-LtBLNTxzbe6sp.png" /></figure><p>Awesome!</p><h3>Part 2: Create a CloudFront Distribution</h3><p>The CloudFront is a Content Delivery Network. All the static and dynamic files (CSS, HTML, etc) coming from the application will be cached on the edge location closer to the user so that it can improve the application’s performance and provide the lowest latency. When a user requests content, the request is routed to the edge location.</p><p>Go to Console and search for CloudFront -&gt; Create a CloudFront distribution</p><p>Our application origin is our Elastic Load Balancer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4gyrTMqPu9yMHJAG.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bFX-3MEFat36Rd5s.png" /></figure><ul><li>Cache policy: CachingOptimized</li><li>Allowed HTTP methods: GET, HEAD, OPTIONS, PUT, POST, PATCH, DELETE. We want to allow the POST method to insert the data inside DynamoDB.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SBOmJYfNEPNRUrhJ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*J3Ka-vowkuYolYNG.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2cn2fPRLc66idoF2.png" /></figure><ul><li>Once CloudFront distribution is created, a domain name to access our application is already associated with it. This will give the Route 53 DNS entry that we use to access the application throughout CloudFront.</li><li>We could have a Custom SSL certificate — (optional), branded and customized domain name for our purpose associated with our CloudFront distribution and put the SSL certificate associated with that as well. We are going to use the default one created for us.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_oCEduCKnmyC0nGX.png" /></figure><p>Copy the CloudFront domain name when it is ready. Let’s confirm if we can access the application using the CloudFront.</p><p>Here it is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ASJgTA7a-UIv7j8O.png" /></figure><h3>Part 3: Perform Load testing</h3><p>We will basically simulate here what will happen if many users are accessing to EC2 instance at the same time and CPU utilization goes up.</p><p>We will induce load on the CPU. Copy the IP address from one of the EC2 instances. Open remote connectivity on your computer via SSH:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9SERuGyLfqoTK4WW.png" /></figure><p>ssh -i &quot;ebs-ssh-key.pem&quot; ec2-user@<a href="http://ec2-52-201-156-146.compute-1.amazonaws.com/">ec2-52-201-156-146.compute-1.amazonaws.com</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MHY1wz-AzqD4093u.png" /></figure><p>Install the stress tool to perform the load testing:</p><pre>sudo amazon-linux-extras install epel -y<br>sudo yum install stress -y<br>stress -c 4</pre><p>This comment is going to bump up the CPU utilization inside the EC2 instance. Check Elastic Beanstalk status if it is turned “Warning”. Stress command bumping CPU utilization of this instance 100 %. We configured it as if CPU utilization is higher than 50%, the auto-scaling group will add one new instance so we can keep up with the workload.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8W4sCLRyBdF68PNn.png" /></figure><p>Open a new terminal, connect remotely with SSH again, and use the “top” command that shows CPU utilization on the operating system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Dklh_WwBdjhHg9mB.png" /></figure><p>New instances will be added shortly to scale up. Every single user who goes through the load balancer will be redirected to one of these instances.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aqenaqbHLB6-0eZt.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8bwQqhKPtqRa877R.png" /></figure><p>Stop the loading process and end up stress command and check the process is not running anymore by running the command below:</p><pre>Ctrl + C<br>ps -ef | grep stress</pre><p>The stress is running anymore so the health status will change to OK. The auto scale will scale down and remove 3rd instance added before, so we can save cost.</p><p>Once you finish exploring it, please remove the Elastic Beanstalk application, and Elastic Beanstalk environment, disable and delete the CloudFront distribution, and finally delete the DynamoDB users table.</p><p>CONGRATULATIONS!!!</p><p><strong>REFERENCES</strong></p><p><a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/concepts-roles-service.html">Elastic Beanstalk service role</a></p><p><a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/Welcome.html">AWS Elastic Beanstalk Developer Guide</a></p><p><a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-flask.html">AWS-Deploying a Flask application to Elastic Beanstal</a>k</p><p><a href="https://testdriven.io/blog/flask-elastic-beanstalk/">Deploying a Flask Application to Elastic Beanstalk</a></p><p><a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/platforms/platforms-supported.html#platforms-supported.python">Elastic Beanstalk-supported platforms</a></p><p><a href="https://stackoverflow.com/questions/62479386/no-module-named-application-error-while-deploying-simple-web-app-to-elastic-be">No module named ‘application’ Error while deploying a simple web app to Elastic Beanstalk</a></p><p><a href="https://repost.aws/questions/QUcm3GAgnESN2wCOtD-hqzsQ/wsgi-configuration-for-django-deployment-using-eb-cli">WSGI configuration for Django Deployment using EB CLI</a></p><p><a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/applications-sourcebundle.html">Create an application source bundle</a></p><p><a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/Welcome.html">What is AWS Elastic Beanstalk?</a></p><p><a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/GettingStarted.html">Deploy a sample web application using Elastic Beanstalk</a></p><p><a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/eb-cli3-install.html">Install the EB CLI</a></p><p><a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/security-creds.html">AWS security credentials</a></p><p><a href="https://docs.aws.amazon.com/pdfs/elasticbeanstalk/latest/dg/awseb-dg.pdf#command-options-general">EBS configuration options for all environments</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c63a9597e49d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 18 — HumanGov — Developing an Event-Driven and Serverless Python Microservice Triggered by…]]></title>
            <link>https://medium.com/@cansutekin23/part-18-humangov-developing-an-event-driven-and-serverless-python-microservice-triggered-by-8f8173947719?source=rss-3599111d902f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f8173947719</guid>
            <category><![CDATA[cloudwatch]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[boto3]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Cansu Tekin]]></dc:creator>
            <pubDate>Wed, 03 Apr 2024 20:30:34 GMT</pubDate>
            <atom:updated>2024-04-03T21:42:25.386Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 18 — HumanGov — Developing an Event-Driven and Serverless Python Microservice Triggered by DynamoDB Streams Using AWS Lambda Function and AWS SDK Python Boto3</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H3AylOAiGg20RdMMCGztrA.jpeg" /></figure><blockquote>The HumanGov Application is a Human Resources Management Cloud SaaS application for the Department of Education across all 50 states in the US. Whenever a state hired a new employee the registiration of the new employees will be done through the application. Their information will be stored inside AWS DynamoDB and their employment document will be stored inside S3 buckets. Our primary responsibility as DevOps Engineer is to modernize and enhance the HumanGov application.</blockquote><blockquote>1. Provisioned the infrastructure with Terraform onto the AWS Cloud environment (<a href="https://medium.com/@cansutekin23/part-10-final-project-humangov-application-deployment-of-reusable-saas-multi-tenant-aws-0c1447b533f1">Part 10</a>),</blockquote><blockquote>2. Configured and deployed applications on those resources with Ansible (<a href="https://medium.com/@cansutekin23/part-13-humangov-application-ansible-final-project-configuration-and-deployment-of-humangov-e8288cbc3132">Part 1</a>3),</blockquote><blockquote>3. Containerized the HumanGov application using Docker to make it more efficient, portable, and scalable across different computing environments (Part 14),</blockquote><blockquote>4. We introduced Kubernetes to our application modernization focusing on Elastic Kubernetes Service (EKS), Route 53, Application Load Balancer (ALB), and AWS Certificate Manager for SSL endpoint encryption (Part 15).</blockquote><blockquote>5. Used CI/CD Pipeline to automate the process of building and deploying the HumanGov application (Part 16).</blockquote><blockquote>6. Implemented AWS Cloud Watch Synthetics for real-time application URL monitoring integrated with CloudWatch Alarms, SNS, and AWS Chatbot to send real-time Alerts on Slack (Part 17).</blockquote><blockquote>In this section, we will be developing an Event-Driven and Serverless Python Microservice Triggered by DynamoDB Streams Using AWS Lambda Function and AWS SDK Python Boto3.</blockquote><h3>SOLUTION ARCHITECTURE</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KY7XC3GbSCJZ6EybaLgNcQ.jpeg" /></figure><p>This section focuses on serverless architectures and event-driven microservices on AWS. The HumanGov SaaS application is a Python-based application. We will develop a Python-based serverless microservice with the HumanGov application that will respond to data changes in a DynamoDB table and be executed by AWS Lambda functions.</p><p>We already have a Kubernetes cluster, a <em>humangov cluster</em>, with our HumanGov Python application running inside the cluster and a DynamoDB table named <em>humangov-california-dynamodb </em>from the previous project series.</p><p><strong>Step 1: Enable DynamoDB Streams on the <em>humangov-california-dynamodb</em></strong><em> </em><strong>table</strong></p><p>DynamoDB Streams enable capturing data modifications in the DynamoDB table in real-time, facilitating seamless integration with various AWS services such as triggering Lambda functions as in our case for event-driven architectures.</p><p>Turn on the DynamoDB stream:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w0k809zoa8x1PQuWT1eSyQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xsPs2yLHBaB1GdrzqeeJ5g.png" /></figure><p>New Image: Contains the entire item after it was modified.</p><p>Old Image: Contains the entire item as it appeared before it was modified.</p><p>Let&#39;s add a new employee to the table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xIopjq8R3jxQdoGlhFWjCg.png" /></figure><p>DynamoDB table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G_fH-TYftd37gaQOHoV8Sw.png" /></figure><p>S3 bucket:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qnIybp1WU50zEGi_3i0Y6w.png" /></figure><p>Let’s remove one of the records:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xti1B-2kGLkuBs5f-TggfA.png" /></figure><p>Only one record left on the DynamoDB table but we still have two files in the S3 bucket. The employee’s corresponding identification document was not deleted from the S3 bucket. We have to delete the file manually.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1UUWsgJF_DmIEooEviheSw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ISaVq0vjBrsaMUnL0V2vww.png" /></figure><p>We will fix this by triggering a lambda function to delete files from S3 buckets once an employee is removed from the DaynamoDB table.</p><p><strong>Step 2: Create a Lambda function with the necessary permissions</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X7iDDdMPgkF0MlTdjPeLjw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4K0rvwAQioJkslWGRee6PQ.png" /></figure><p>Lambda will create an execution role named HumanGov-Delete-Files-role-pjskkfxu, with permission to upload logs to Amazon CloudWatch Logs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*45-4IXMa9bzJI218bYD7Vw.png" /></figure><p>We also need to give access to the S3 bucket and DynamoDB table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A2GBW45GbXSN3GtUMgCQXA.png" /></figure><p><strong>Step 3: Implement the microservice logic in Python utilizing the AWS SDK Boto3</strong></p><p>Boto3 is the official AWS SDK for Python. It allows creating, configuring, and managing AWS resources, such as EC2 instances, S3 buckets, and DynamoDB tables directly from Python code.</p><p>Update the default lambda function script to automatically trigger the deletion of files from the S3 bucket following the deletion of the employee.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b00QwRfFgYRFYy74-zStvg.png" /></figure><pre>import boto3<br><br>s3_client = boto3.client(&#39;s3&#39;)<br><br>def lambda_handler(event, context):<br>    for record in event[&#39;Records&#39;]:<br>        # Check if the event is a record deletion<br>        if record[&#39;eventName&#39;] == &#39;REMOVE&#39;:<br>            # Extract the file key from the DynamoDB record<br>            pdf_filename = record[&#39;dynamodb&#39;][&#39;OldImage&#39;][&#39;pdf&#39;][&#39;S&#39;]<br>            try:<br>                # Delete the file from the S3 bucket<br>                s3_client.delete_object(Bucket=&#39;humangov-california-s3-l32k&#39;, Key=pdf_filename)<br>                print(f&#39;Successfully deleted {pdf_filename} from the S3 bucket&#39;)<br>            except s3_client.exceptions.NoSuchKey:<br>                print(f&#39;File {pdf_filename} does not exist in the S3 bucket&#39;)<br>            except Exception as e:<br>                print(f&#39;Error deleting {pdf_filename}: {e}&#39;)<br>                raise e<br>                <br>   </pre><p>Deploy changes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GW5puSDmAqQQ5OVv1apCDg.png" /></figure><p><strong>Step 4:</strong> <strong>Trigger Lambda functions upon the data modification on the DynamoDB table</strong></p><p>Add a trigger to the Lambda configuration for the DaynamoDB table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oP0fP5h33qKajWTqlckl9g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3BMwBJdiahSJWPWGIQPfQg.png" /></figure><p><strong>Step 5: Incorporate logging and monitoring through AWS CloudWatch</strong></p><p>View CloudWathc logs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XDUt4xYcXr7lLozDN53XpQ.png" /></figure><p>Create a log groups:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-4A8Oqp_ft8jOD4Q8aE6lw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sBFYgAV61O48bIiwVfmYdg.png" /></figure><p><strong>Step 6: Trigger the Lambda function by modifying the DynamoDB table</strong></p><p>Add a new record to the application:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vTzLMKxzNKuQofX8ld6GSw.png" /></figure><p>Updated DynamoDB table with a new record:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xR2gf0ZgqdW4sHaOlJWAxw.png" /></figure><p>Updated S3 bucket with a new file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OGffEikMaqsOXSk-nrV3Jw.png" /></figure><p>Delete one of the records:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z7PjqFMEZUsSm1Jx9H9xIQ.png" /></figure><p>Only one record left on the DynamoDB table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eJIHs_I9zuSVMe-Uq16p9Q.png" /></figure><p>Check the S3 bucket:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ahNZO3iR4Bwn4E6peT-Vg.png" /></figure><p>The PDF file of the deleted record is also gone!</p><p>Check CloudWatch <em>/aws/lambda/HumanGov-Delete-Files</em> logs group:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WPMzZDWLLdXAA2dvAU2WkQ.png" /></figure><p>Make sure you committed all the changes and have the most recent version of the application and infrastructure configuration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Al63hARwlWjM7V6bERYOnw.png" /></figure><p>It was a great journey modernization of the HumanGov SaaS application using DevOps. We came to an end. I hope you also enjoyed it as much as I did. We did it!</p><p>You can download all the files from the Cloud9 environment to your local machine.</p><p>Now, destroy all the resources and infrastructure you created. otherwise, you will be charged.</p><pre>cd ~/environment/human-gov-application/src<br>kubectl delete -f humangov-ingress-all.yaml<br>kubectl delete -f humangov-california.yaml<br>kubectl delete -f humangov-texas.yaml<br>eksctl delete cluster --name humangov-cluster --region us-east-1<br><br>cd ~/environment/human-gov-infrastructure/terraform<br>terraform destroy</pre><p>Also, delete other resources that we created from the AWS Services Dashboard!</p><p>CONGRATULATIONS!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f8173947719" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 17 — HumanGov Application —  Implementing AWS CloudWatch Synthetics for Real-Time Application…]]></title>
            <link>https://medium.com/@cansutekin23/part-17-humangov-application-implementing-aws-cloudwatch-synthetics-for-real-time-application-d33c2a8a4c89?source=rss-3599111d902f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d33c2a8a4c89</guid>
            <category><![CDATA[sns]]></category>
            <category><![CDATA[cloudwatch]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[slack]]></category>
            <dc:creator><![CDATA[Cansu Tekin]]></dc:creator>
            <pubDate>Wed, 03 Apr 2024 15:16:41 GMT</pubDate>
            <atom:updated>2024-04-03T15:16:41.657Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 17 — HumanGov Application — Implementing AWS CloudWatch Synthetics for Real-Time Application URL Monitoring Integrated With CloudWatch Alarms, SNS, and AWS Chatbot to Send Real-Time Alerts on Slack</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WSuemiCEK2nfZAeszwxi1A.jpeg" /></figure><blockquote>The HumanGov Application is a Human Resources Management Cloud SaaS application for the Department of Education across all 50 states in the US. Whenever a state hired a new employee the registiration of the new employees will be done through the application. Their information will be stored inside AWS DynamoDB and their employment document will be stored inside S3 buckets. Our primary responsibility as DevOps Engineer is to modernize and enhance the HumanGov application.</blockquote><blockquote>1. Provisioned the infrastructure with Terraform onto the AWS Cloud environment (<a href="https://medium.com/@cansutekin23/part-10-final-project-humangov-application-deployment-of-reusable-saas-multi-tenant-aws-0c1447b533f1">Part 10</a>),</blockquote><blockquote>2. Configured and deployed applications on those resources with Ansible (<a href="https://medium.com/@cansutekin23/part-13-humangov-application-ansible-final-project-configuration-and-deployment-of-humangov-e8288cbc3132">Part 1</a>3),</blockquote><blockquote>3. Containerized the HumanGov application using Docker to make it more efficient, portable, and scalable across different computing environments (Part 14),</blockquote><blockquote>4. We introduced Kubernetes to our application modernization focusing on Elastic Kubernetes Service (EKS), Route 53, Application Load Balancer (ALB), and AWS Certificate Manager for SSL endpoint encryption (Part 15).</blockquote><blockquote>5. Used CI/CD Pipeline to automate the process of building and deploying the HumanGov application (Part 16).</blockquote><blockquote>In this section, we will implement AWS Cloud Watch Synthetics for real-time application URL monitoring integrated with CloudWatch Alarms, SNS, and AWS Chatbot to send real-time Alerts on Slack</blockquote><p>SOLUTION ARCHITECTURE</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Toddw7t472m2y7PAzVdJHQ.jpeg" /></figure><p>CloudWatch Alarms offers proactive monitoring and notification alerts for AWS resources based on metrics such as CPU utilization, network traffic, or storage space. Once thresholds are reached, notifications can be triggered using email, SMS, HTTP endpoints, third-party services like Slack, or custom applications. Further, automated actions such as sending notifications via Amazon SNS, invoking AWS Lambda functions, and auto-scaling resources to handle increased demand can be taken.</p><p>As you remember, we created the HumanGov application for California state at URL <a href="https://california.humangov-ct.click/"><em>https://california.humangov-ct.click</em></a><em>. </em>In this section, we will set up<em> </em>real-time monitoring for our Humangov application served at the address <a href="https://california.humangov-ct.click/"><em>https://california.humangov-ct.click </em></a>using AWS CloudWatch Synthetics</p><p><strong>Step 1: Creating SNS Topic for CloudWatch Synthetic canaries</strong></p><p>SNS topics are used to implement real-time notifications and communication workflows within AWS and across various services.</p><p>Go to the SNS console to create and configure the SNS topic:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xu8ozNip6I7URMAR6zaP4g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1uCts2XRhTv5J6A7c_1fwQ.png" /></figure><p><strong>Step 2: Create CloudWatch Synthetic canaries to monitor the HumanGov application URLs continuously</strong></p><p>Amazon CloudWatch Synthetics canaries are configurable scripts to monitor web applications, APIs, and other endpoints by simulating user interactions. These canaries run at specified intervals to check issues such as latency, availability, and functionality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8SQdyxVhoc5ABAqXWAJV2w.png" /></figure><p><strong>Step 3: Create a CloudWatch Canary with Heartbeat URL Monitoring</strong><br>Heartbeat URL monitoring is used to check the availability and responsiveness of web services, APIs, or websites by periodically sending HTTP requests to specific URLs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ivtTcocK1IVhyP_3GCaaPg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cOv9u8FNOuJr4x7WI550Hg.png" /></figure><p>script:</p><pre>const { URL } = require(&#39;url&#39;);<br>const synthetics = require(&#39;Synthetics&#39;);<br>const log = require(&#39;SyntheticsLogger&#39;);<br>const syntheticsConfiguration = synthetics.getConfiguration();<br>const syntheticsLogHelper = require(&#39;SyntheticsLogHelper&#39;);<br><br>const loadBlueprint = async function () {<br><br>    const urls = [&#39;https://california.humangov-ct.click&#39;];<br><br>    // Set screenshot option<br>    const takeScreenshot = true;<br><br>    /* Disabling default step screen shots taken during Synthetics.executeStep() calls<br>     * Step will be used to publish metrics on time taken to load dom content but<br>     * Screenshots will be taken outside the executeStep to allow for page to completely load with domcontentloaded<br>     * You can change it to load, networkidle0, networkidle2 depending on what works best for you.<br>     */<br>    syntheticsConfiguration.disableStepScreenshots();<br>    syntheticsConfiguration.setConfig({<br>       continueOnStepFailure: true,<br>       includeRequestHeaders: true, // Enable if headers should be displayed in HAR<br>       includeResponseHeaders: true, // Enable if headers should be displayed in HAR<br>       restrictedHeaders: [], // Value of these headers will be redacted from logs and reports<br>       restrictedUrlParameters: [] // Values of these url parameters will be redacted from logs and reports<br><br>    });<br><br>    let page = await synthetics.getPage();<br><br>    for (const url of urls) {<br>        await loadUrl(page, url, takeScreenshot);<br>    }<br>};<br><br>// Reset the page in-between<br>const resetPage = async function(page) {<br>    try {<br>        await page.goto(&#39;about:blank&#39;,{waitUntil: [&#39;load&#39;, &#39;networkidle0&#39;], timeout: 30000} );<br>    } catch (e) {<br>        synthetics.addExecutionError(&#39;Unable to open a blank page. &#39;, e);<br>    }<br>}<br><br>const loadUrl = async function (page, url, takeScreenshot) {<br>    let stepName = null;<br>    let domcontentloaded = false;<br><br>    try {<br>        stepName = new URL(url).hostname;<br>    } catch (e) {<br>        const errorString = `Error parsing url: ${url}. ${e}`;<br>        log.error(errorString);<br>        /* If we fail to parse the URL, don&#39;t emit a metric with a stepName based on it.<br>           It may not be a legal CloudWatch metric dimension name and we may not have an alarms<br>           setup on the malformed URL stepName.  Instead, fail this step which will<br>           show up in the logs and will fail the overall canary and alarm on the overall canary<br>           success rate.<br>        */<br>        throw e;<br>    }<br><br>    await synthetics.executeStep(stepName, async function () {<br>        const sanitizedUrl = syntheticsLogHelper.getSanitizedUrl(url);<br><br>        /* You can customize the wait condition here. For instance, using &#39;networkidle2&#39; or &#39;networkidle0&#39; to load page completely.<br>           networkidle0: Navigation is successful when the page has had no network requests for half a second. This might never happen if page is constantly loading multiple resources.<br>           networkidle2: Navigation is successful when the page has no more then 2 network requests for half a second.<br>           domcontentloaded: It&#39;s fired as soon as the page DOM has been loaded, without waiting for resources to finish loading. If needed add explicit wait with await new Promise(r =&gt; setTimeout(r, milliseconds))<br>        */<br>        const response = await page.goto(url, { waitUntil: [&#39;domcontentloaded&#39;], timeout: 30000});<br>        if (response) {<br>            domcontentloaded = true;<br>            const status = response.status();<br>            const statusText = response.statusText();<br><br>            logResponseString = `Response from url: ${sanitizedUrl}  Status: ${status}  Status Text: ${statusText}`;<br><br>            //If the response status code is not a 2xx success code<br>            if (response.status() &lt; 200 || response.status() &gt; 299) {<br>                throw new Error(`Failed to load url: ${sanitizedUrl} ${response.status()} ${response.statusText()}`);<br>            }<br>        } else {<br>            const logNoResponseString = `No response returned for url: ${sanitizedUrl}`;<br>            log.error(logNoResponseString);<br>            throw new Error(logNoResponseString);<br>        }<br>    });<br><br>    // Wait for 15 seconds to let page load fully before taking screenshot.<br>    if (domcontentloaded &amp;&amp; takeScreenshot) {<br>        await new Promise(r =&gt; setTimeout(r, 15000));<br>        await synthetics.takeScreenshot(stepName, &#39;loaded&#39;);<br>    }<br>    <br>    // Reset page<br>    await resetPage(page);<br>};<br><br>exports.handler = async () =&gt; {<br>    return await loadBlueprint();<br>};</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vcmLl7fBZdbaMRgKFXVPYw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aGKhVUZOLrzZXUopWdTn8w.png" /></figure><p><strong>Step 4: Set up CloudWatch Alarms</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zo2_ZDB2ZjIHh_y95gudDA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NtK-ZggfjSXZeIttFsHw7w.png" /></figure><p>I made a spelling mistake on the subdomain name and my first monitoring attempts failed.</p><p>Create another canary for Texas with the same settings as in California:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WKFinQusshOeucKFLUHF4Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pcq6vMbTENyk9bd_-7eGwg.png" /></figure><p><strong>Step 5: Integrate AWS Chatbot to send real-time alerts on Slack</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jBDGD4eWmT0BXpEZjZ-gSg.png" /></figure><p>You will be directed to the Slack webpage. Create a new workspace:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2UC8Itf8Yv8XqDg1oA42Sw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TSlHSCWH7T4irW6U1dZcAw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RvRJw_uJ3xRRv2rGAVoahQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MyXE48sTTUlDkzcY61k1Zw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QaITAJhgLGXTyAnJu0PcTg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gpKcKwCd0Y38Rjf4x-Hu2g.png" /></figure><p>Go back to AWS Chatbot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p-vlsp0ssR3EmnOjUad8GQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m9PAblwf_PsNx0XY9_5FhA.png" /></figure><p>Allow and configure new Slack channel:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RgiAvh7SQ12cMq63fDbz_A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GPpcFdT4tDSTP-ghNbLPUQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9AjKccdU2y5Wvr15Zt4ZNQ.png" /></figure><p>Pick the SNS topic we created earlier:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GY9rnt3dgiyQQkUk0ZXUrQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9YfJ0VMJLWjJGzZAzgUiOQ.png" /></figure><p>Send a test message:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PGUsi3zKQuXvDiRHPBVWxA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hz_vt3TM5hvZ5p_qYnadUA.png" /></figure><p>Testing the Setup:</p><p>Stop the container first for California and then check if there is a Slack notification about failure.</p><pre>kubectl get deployments<br>kubectl scale deployment humangov-nginx-reverse-proxy-california --replicas=0<br>kubectl get deployments</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yu9yaAB2FONB3ud_M5APLg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ph7sa5XMyykqHAd2m6AZZQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D_6g5EfVpCVQGepj_B9bmg.png" /></figure><p>Rerun the container.</p><pre>kubectl scale deployment humangov-nginx-reverse-proxy-california --replicas=1<br>kubectl get deployments</pre><p>CONGRATULATIONS!!!</p><p>Follow me on LinkedIn</p><p><a href="https://www.linkedin.com/in/cansu-t-a5617557/">https://www.linkedin.com/in/cansu-t-a5617557/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d33c2a8a4c89" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 16 — HumanGov Application — CI/CD Pipelines: Automating HumanGov SaaS Application Build and…]]></title>
            <link>https://medium.com/@cansutekin23/part-16-humangov-application-ci-cd-pipelines-automating-humangov-saas-application-build-and-6705645a810b?source=rss-3599111d902f------2</link>
            <guid isPermaLink="false">https://medium.com/p/6705645a810b</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[aws-codepipeline]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Cansu Tekin]]></dc:creator>
            <pubDate>Mon, 01 Apr 2024 17:26:22 GMT</pubDate>
            <atom:updated>2024-04-01T18:16:08.836Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 16 — HumanGov Application — CI/CD Pipelines: Automating HumanGov SaaS Application Build and Deployment Process on Kubernetes with CI/CD Pipelines using the AWS Code Commit, AWS Code Pipeline and AWS Code Build</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nHBAAxfAGyZa9-9-EbhrcA.jpeg" /></figure><blockquote>The HumanGov Application is a Human Resources Management Cloud SaaS application for the Department of Education across all 50 states in the US. Whenever a state hired a new employee the registiration of the new employees will be done through the application. Their information will be stored inside AWS DynamoDB and their employment document will be stored inside S3 buckets. Our primary responsibility as DevOps Engineer is to modernize and enhance the HumanGov application.</blockquote><blockquote>1. Provisioned the infrastructure with Terraform onto the AWS Cloud environment (<a href="https://medium.com/@cansutekin23/part-10-final-project-humangov-application-deployment-of-reusable-saas-multi-tenant-aws-0c1447b533f1">Part 10</a>),</blockquote><blockquote>2. Configured and deployed applications on those resources with Ansible (<a href="https://medium.com/@cansutekin23/part-13-humangov-application-ansible-final-project-configuration-and-deployment-of-humangov-e8288cbc3132">Part 1</a>3),</blockquote><blockquote>3. Containerized the HumanGov application using Docker to make it more efficient, portable, and scalable across different computing environments (Part 14),</blockquote><blockquote>4. We introduced Kubernetes to our application modernization focusing on Elastic Kubernetes Service (EKS), Route 53, Application Load Balancer (ALB), and AWS Certificate Manager for SSL endpoint encryption (Part 15).</blockquote><blockquote>In this part of the project, we will keep improving the application with CI/CD Pipeline to automate the process of building and deploying the HumanGov application.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nHBAAxfAGyZa9-9-EbhrcA.jpeg" /></figure><p>Implementing continuous integration and delivery with AWS services can dramatically enhance the speed and reliability of software deployment.</p><p>CI (Continuous Integration): Automatically integrating code changes and testing those changes, ensuring that new code doesn’t break existing functionality.</p><p>CD (Continuous Deployment/Delivery): Automatically deploying the code changes to production environments after passing tests, enabling faster and more reliable software releases.</p><p><strong>PART 1: Setup Pipeline’s Architecture</strong></p><p><strong>PART 2: Building CI/CD with AWS CodePipeline</strong></p><p><strong>PART 3: Orchestrating Automated Deployment with Kubernetes in the Deployment Stage</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IvJt5sW7JOcD_AJSac1Yqw.jpeg" /></figure><h3><strong>PART 1: Setup Pipeline’s Architecture</strong></h3><p>Previously, we created our HumanGov application with AWS EKS inside a private subnet. Private subnets typically host resources that should not have direct internet access but may still need to communicate with services outside the VPC, such as accessing AWS services or connecting to external APIs. To allow egress traffic from private subnets to the public internet, you need to configure a NAT gateway in a public subnet and set up a route to forward outbound traffic from private subnets to the NAT gateway.</p><p>We need to connect to the internet from our private subnets to download dependencies for our HumanGov application. We can’t connect to the internet from our private subnets. Therefore, we need to create a NAT Gateway in a public subnet and configure the NAT Gateway in the security group to allow outbound connections from our subnets.</p><p>We will select a VPC that our AWS CodeBuild project will access. In this case, we will use <em>humangov cluster’ s </em>VPC where we will deploy our HumanGov application. We will deploy the application from scratch but use the same VPC setting from the <a href="https://medium.com/@cansutekin23/part-15-humangov-application-kubernetes-deployment-of-humangov-saas-application-on-aws-85b62e3f2be1">previous project</a>. AWS EKS already created a VPC, subnets, NAT Gateway, security groups, route tables, etc.</p><p>If you destroyed the cluster and its configurations you can set up it again as follows.</p><p>Create a Kubernetes cluster:</p><pre>eksctl create cluster --name humangov-cluster --region us-east-1 --nodegroup-name standard-workers --node-type t3.medium --nodes 1</pre><pre>eksctl utils associate-iam-oidc-provider --region us-east-1 --cluster humangov-cluster --approve</pre><p>This is the created component for the Kubernetes cluster with AWS CloudFormation:</p><p><em>eksctl-humangov-cluster-cluster.yaml</em></p><pre>AWSTemplateFormatVersion: &#39;2010-09-09&#39;<br>Description: &#39;EKS cluster (dedicated VPC: true, dedicated IAM: true) [created and managed by eksctl]&#39;<br>Mappings:<br>  ServicePrincipalPartitionMap:<br>    aws:<br>      EC2: ec2.amazonaws.com<br>      EKS: eks.amazonaws.com<br>      EKSFargatePods: eks-fargate-pods.amazonaws.com<br>    aws-cn:<br>      EC2: ec2.amazonaws.com.cn<br>      EKS: eks.amazonaws.com<br>      EKSFargatePods: eks-fargate-pods.amazonaws.com<br>    aws-iso:<br>      EC2: ec2.c2s.ic.gov<br>      EKS: eks.amazonaws.com<br>      EKSFargatePods: eks-fargate-pods.amazonaws.com<br>    aws-iso-b:<br>      EC2: ec2.sc2s.sgov.gov<br>      EKS: eks.amazonaws.com<br>      EKSFargatePods: eks-fargate-pods.amazonaws.com<br>    aws-us-gov:<br>      EC2: ec2.amazonaws.com<br>      EKS: eks.amazonaws.com<br>      EKSFargatePods: eks-fargate-pods.amazonaws.com<br>Resources:<br>  ClusterSharedNodeSecurityGroup:<br>    Type: AWS::EC2::SecurityGroup<br>    Properties:<br>      GroupDescription: Communication between all nodes in the cluster<br>      Tags:<br>        - Key: Name<br>          Value: !Sub ${AWS::StackName}/ClusterSharedNodeSecurityGroup<br>      VpcId: !Ref VPC<br>  ControlPlane:<br>    Type: AWS::EKS::Cluster<br>    Properties:<br>      AccessConfig:<br>        AuthenticationMode: API_AND_CONFIG_MAP<br>        BootstrapClusterCreatorAdminPermissions: true<br>      KubernetesNetworkConfig:<br>        IpFamily: ipv4<br>      Name: humangov-cluster<br>      ResourcesVpcConfig:<br>        EndpointPrivateAccess: false<br>        EndpointPublicAccess: true<br>        SecurityGroupIds:<br>          - !Ref ControlPlaneSecurityGroup<br>        SubnetIds:<br>          - !Ref SubnetPublicUSEAST1C<br>          - !Ref SubnetPublicUSEAST1A<br>          - !Ref SubnetPrivateUSEAST1C<br>          - !Ref SubnetPrivateUSEAST1A<br>      RoleArn: !GetAtt ServiceRole.Arn<br>      Tags:<br>        - Key: Name<br>          Value: !Sub ${AWS::StackName}/ControlPlane<br>      Version: &#39;1.29&#39;<br>  ControlPlaneSecurityGroup:<br>    Type: AWS::EC2::SecurityGroup<br>    Properties:<br>      GroupDescription: Communication between the control plane and worker nodegroups<br>      Tags:<br>        - Key: Name<br>          Value: !Sub ${AWS::StackName}/ControlPlaneSecurityGroup<br>      VpcId: !Ref VPC<br>  IngressDefaultClusterToNodeSG:<br>    Type: AWS::EC2::SecurityGroupIngress<br>    Properties:<br>      Description: Allow managed and unmanaged nodes to communicate with each other (all ports)<br>      FromPort: 0<br>      GroupId: !Ref ClusterSharedNodeSecurityGroup<br>      IpProtocol: &#39;-1&#39;<br>      SourceSecurityGroupId: !GetAtt ControlPlane.ClusterSecurityGroupId<br>      ToPort: 65535<br>  IngressInterNodeGroupSG:<br>    Type: AWS::EC2::SecurityGroupIngress<br>    Properties:<br>      Description: Allow nodes to communicate with each other (all ports)<br>      FromPort: 0<br>      GroupId: !Ref ClusterSharedNodeSecurityGroup<br>      IpProtocol: &#39;-1&#39;<br>      SourceSecurityGroupId: !Ref ClusterSharedNodeSecurityGroup<br>      ToPort: 65535<br>  IngressNodeToDefaultClusterSG:<br>    Type: AWS::EC2::SecurityGroupIngress<br>    Properties:<br>      Description: Allow unmanaged nodes to communicate with control plane (all ports)<br>      FromPort: 0<br>      GroupId: !GetAtt ControlPlane.ClusterSecurityGroupId<br>      IpProtocol: &#39;-1&#39;<br>      SourceSecurityGroupId: !Ref ClusterSharedNodeSecurityGroup<br>      ToPort: 65535<br>  InternetGateway:<br>    Type: AWS::EC2::InternetGateway<br>    Properties:<br>      Tags:<br>        - Key: Name<br>          Value: !Sub ${AWS::StackName}/InternetGateway<br>  NATGateway:<br>    Type: AWS::EC2::NatGateway<br>    Properties:<br>      AllocationId: !GetAtt NATIP.AllocationId<br>      SubnetId: !Ref SubnetPublicUSEAST1C<br>      Tags:<br>        - Key: Name<br>          Value: !Sub ${AWS::StackName}/NATGateway<br>  NATIP:<br>    Type: AWS::EC2::EIP<br>    Properties:<br>      Domain: vpc<br>      Tags:<br>        - Key: Name<br>          Value: !Sub ${AWS::StackName}/NATIP<br>  NATPrivateSubnetRouteUSEAST1A:<br>    Type: AWS::EC2::Route<br>    Properties:<br>      DestinationCidrBlock: 0.0.0.0/0<br>      NatGatewayId: !Ref NATGateway<br>      RouteTableId: !Ref PrivateRouteTableUSEAST1A<br>  NATPrivateSubnetRouteUSEAST1C:<br>    Type: AWS::EC2::Route<br>    Properties:<br>      DestinationCidrBlock: 0.0.0.0/0<br>      NatGatewayId: !Ref NATGateway<br>      RouteTableId: !Ref PrivateRouteTableUSEAST1C<br>  PrivateRouteTableUSEAST1A:<br>    Type: AWS::EC2::RouteTable<br>    Properties:<br>      Tags:<br>        - Key: Name<br>          Value: !Sub ${AWS::StackName}/PrivateRouteTableUSEAST1A<br>      VpcId: !Ref VPC<br>  PrivateRouteTableUSEAST1C:<br>    Type: AWS::EC2::RouteTable<br>    Properties:<br>      Tags:<br>        - Key: Name<br>          Value: !Sub ${AWS::StackName}/PrivateRouteTableUSEAST1C<br>      VpcId: !Ref VPC<br>  PublicRouteTable:<br>    Type: AWS::EC2::RouteTable<br>    Properties:<br>      Tags:<br>        - Key: Name<br>          Value: !Sub ${AWS::StackName}/PublicRouteTable<br>      VpcId: !Ref VPC<br>  PublicSubnetRoute:<br>    Type: AWS::EC2::Route<br>    Properties:<br>      DestinationCidrBlock: 0.0.0.0/0<br>      GatewayId: !Ref InternetGateway<br>      RouteTableId: !Ref PublicRouteTable<br>    DependsOn:<br>      - VPCGatewayAttachment<br>  RouteTableAssociationPrivateUSEAST1A:<br>    Type: AWS::EC2::SubnetRouteTableAssociation<br>    Properties:<br>      RouteTableId: !Ref PrivateRouteTableUSEAST1A<br>      SubnetId: !Ref SubnetPrivateUSEAST1A<br>  RouteTableAssociationPrivateUSEAST1C:<br>    Type: AWS::EC2::SubnetRouteTableAssociation<br>    Properties:<br>      RouteTableId: !Ref PrivateRouteTableUSEAST1C<br>      SubnetId: !Ref SubnetPrivateUSEAST1C<br>  RouteTableAssociationPublicUSEAST1A:<br>    Type: AWS::EC2::SubnetRouteTableAssociation<br>    Properties:<br>      RouteTableId: !Ref PublicRouteTable<br>      SubnetId: !Ref SubnetPublicUSEAST1A<br>  RouteTableAssociationPublicUSEAST1C:<br>    Type: AWS::EC2::SubnetRouteTableAssociation<br>    Properties:<br>      RouteTableId: !Ref PublicRouteTable<br>      SubnetId: !Ref SubnetPublicUSEAST1C<br>  ServiceRole:<br>    Type: AWS::IAM::Role<br>    Properties:<br>      AssumeRolePolicyDocument:<br>        Statement:<br>          - Action:<br>              - sts:AssumeRole<br>            Effect: Allow<br>            Principal:<br>              Service:<br>                - !FindInMap<br>                  - ServicePrincipalPartitionMap<br>                  - !Ref AWS::Partition<br>                  - EKS<br>        Version: &#39;2012-10-17&#39;<br>      ManagedPolicyArns:<br>        - !Sub arn:${AWS::Partition}:iam::aws:policy/AmazonEKSClusterPolicy<br>        - !Sub arn:${AWS::Partition}:iam::aws:policy/AmazonEKSVPCResourceController<br>      Tags:<br>        - Key: Name<br>          Value: !Sub ${AWS::StackName}/ServiceRole<br>  SubnetPrivateUSEAST1A:<br>    Type: AWS::EC2::Subnet<br>    Properties:<br>      AvailabilityZone: us-east-1a<br>      CidrBlock: 192.168.96.0/19<br>      Tags:<br>        - Key: kubernetes.io/role/internal-elb<br>          Value: &#39;1&#39;<br>        - Key: Name<br>          Value: !Sub ${AWS::StackName}/SubnetPrivateUSEAST1A<br>      VpcId: !Ref VPC<br>  SubnetPrivateUSEAST1C:<br>    Type: AWS::EC2::Subnet<br>    Properties:<br>      AvailabilityZone: us-east-1c<br>      CidrBlock: 192.168.64.0/19<br>      Tags:<br>        - Key: kubernetes.io/role/internal-elb<br>          Value: &#39;1&#39;<br>        - Key: Name<br>          Value: !Sub ${AWS::StackName}/SubnetPrivateUSEAST1C<br>      VpcId: !Ref VPC<br>  SubnetPublicUSEAST1A:<br>    Type: AWS::EC2::Subnet<br>    Properties:<br>      AvailabilityZone: us-east-1a<br>      CidrBlock: 192.168.32.0/19<br>      MapPublicIpOnLaunch: true<br>      Tags:<br>        - Key: kubernetes.io/role/elb<br>          Value: &#39;1&#39;<br>        - Key: Name<br>          Value: !Sub ${AWS::StackName}/SubnetPublicUSEAST1A<br>      VpcId: !Ref VPC<br>  SubnetPublicUSEAST1C:<br>    Type: AWS::EC2::Subnet<br>    Properties:<br>      AvailabilityZone: us-east-1c<br>      CidrBlock: 192.168.0.0/19<br>      MapPublicIpOnLaunch: true<br>      Tags:<br>        - Key: kubernetes.io/role/elb<br>          Value: &#39;1&#39;<br>        - Key: Name<br>          Value: !Sub ${AWS::StackName}/SubnetPublicUSEAST1C<br>      VpcId: !Ref VPC<br>  VPC:<br>    Type: AWS::EC2::VPC<br>    Properties:<br>      CidrBlock: 192.168.0.0/16<br>      EnableDnsHostnames: true<br>      EnableDnsSupport: true<br>      Tags:<br>        - Key: Name<br>          Value: !Sub ${AWS::StackName}/VPC<br>  VPCGatewayAttachment:<br>    Type: AWS::EC2::VPCGatewayAttachment<br>    Properties:<br>      InternetGatewayId: !Ref InternetGateway<br>      VpcId: !Ref VPC<br>Outputs:<br>  ARN:<br>    Value: !GetAtt ControlPlane.Arn<br>    Export:<br>      Name: !Sub ${AWS::StackName}::ARN<br>  CertificateAuthorityData:<br>    Value: !GetAtt ControlPlane.CertificateAuthorityData<br>  ClusterSecurityGroupId:<br>    Value: !GetAtt ControlPlane.ClusterSecurityGroupId<br>    Export:<br>      Name: !Sub ${AWS::StackName}::ClusterSecurityGroupId<br>  ClusterStackName:<br>    Value: !Ref AWS::StackName<br>  Endpoint:<br>    Value: !GetAtt ControlPlane.Endpoint<br>    Export:<br>      Name: !Sub ${AWS::StackName}::Endpoint<br>  FeatureNATMode:<br>    Value: Single<br>  SecurityGroup:<br>    Value: !Ref ControlPlaneSecurityGroup<br>    Export:<br>      Name: !Sub ${AWS::StackName}::SecurityGroup<br>  ServiceRoleARN:<br>    Value: !GetAtt ServiceRole.Arn<br>    Export:<br>      Name: !Sub ${AWS::StackName}::ServiceRoleARN<br>  SharedNodeSecurityGroup:<br>    Value: !Ref ClusterSharedNodeSecurityGroup<br>    Export:<br>      Name: !Sub ${AWS::StackName}::SharedNodeSecurityGroup<br>  SubnetsPrivate:<br>    Value: !Join<br>      - &#39;,&#39;<br>      - - !Ref SubnetPrivateUSEAST1C<br>        - !Ref SubnetPrivateUSEAST1A<br>    Export:<br>      Name: !Sub ${AWS::StackName}::SubnetsPrivate<br>  SubnetsPublic:<br>    Value: !Join<br>      - &#39;,&#39;<br>      - - !Ref SubnetPublicUSEAST1C<br>        - !Ref SubnetPublicUSEAST1A<br>    Export:<br>      Name: !Sub ${AWS::StackName}::SubnetsPublic<br>  VPC:<br>    Value: !Ref VPC<br>    Export:<br>      Name: !Sub ${AWS::StackName}::VPC<br>Transform: AWS::Serverless-2016-10-31</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1koWtt-d-UKMv142AJIhhQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fl7iqmqRGPL-PTI2ifgMTg.png" /></figure><p>We have 4 subnets (2 per AZ). Each AZ has one private and one public subnet. Each public subnet has a NAT gateway to route outbound traffic from private subnets to the NAT gateway in the same AZ.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G9waDJuwcooKH9F-9bSyFA.png" /><figcaption>The private subnet in AZ-1C</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cjOBDJ_eevO6j9QG4AMKug.png" /><figcaption>The public subnet in AZ-1C</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jfSTyGqnO-j8CVr79aQsAQ.png" /><figcaption>The public subnet in AZ-1A</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_1gGmvOyET4DO2U6hSAekg.png" /><figcaption>The private subnet in AZ-1A</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K1-fCE9mv38-7v6oGoq46g.png" /><figcaption>NAT Gateway in the public subnet in AZ-1C</figcaption></figure><p>Security groups:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UrdZY924lDdocGJLVxQrBA.png" /><figcaption>1st sg-inbound rules</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gSLWVhpp3nQOhaX8aL9keQ.png" /><figcaption>1st sg-outbound rules</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bWtieraG4jajHhgoypalRQ.png" /><figcaption>2nd sg-inbound rules</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3yHBlwEKtlPNQwTCGNprLw.png" /><figcaption>2nd sg-outbound rules</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bz5BK-lniuXasBtpz2P5uw.png" /><figcaption>3rd sg-inbound rules</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rt2lL8Ez3IgatnOcQEgQqw.png" /><figcaption>3rd sg-outbound rules</figcaption></figure><p>EC2 instance:</p><p>We have only one EC2 instance running which will serve as a worker node:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZzvVbST1cLGZFWLgU8mTSg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LuD2QqI_qSI-es6GjgF6Aw.png" /></figure><p>IAM roles:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OhV8peby9gDuHjm1ANgV-g.png" /></figure><p>Configure Application Load Balancer again:</p><pre># Install the AWS Load Balancer Controller<br>helm install aws-load-balancer-controller eks/aws-load-balancer-controller \<br>  -n kube-system \<br>  --set clusterName=humangov-cluster \<br>  --set serviceAccount.create=false \<br>  --set serviceAccount.name=aws-load-balancer-controller<br><br># Verify the controller installation<br>kubectl get deployment -n kube-system aws-load-balancer-controller</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4VQ6fGqYjvnCTnZUCNuiNA.png" /></figure><p>Create an IAM service account to allow pods to access the S3 bucket &amp; DynamoDB table:</p><pre>eksctl create iamserviceaccount \<br>--cluster=humangov-cluster \<br>--name=humangov-pod-execution-role \<br>--role-name=HumanGovPodExecutionRole \<br>--attach-policy-arn=arn:aws:iam::aws:policy/AmazonS3FullAccess \<br>--attach-policy-arn=arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess \<br>--region us-east-1 \<br>--approve</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eb7-EwCIvv_OSLhfswDw6A.png" /></figure><p>Update <em>california.humangov-ct.click</em> and <em>texas.humangov-ct.click</em> Records with newly created ALB address:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cg85ae7LE5qxdOyCeGMgnA.png" /></figure><h3>PART 2: Building CI/CD with AWS CodePipeline</h3><p>We will build a CI/CD pipeline using AWS CodePipeline to automate the building, testing, and deployment of the HumanGov application on the targeted Kubernetes cluster. Any code changes in the source code will automatically trigger a build process, followed by a deployment to the Kubernetes cluster with minimal human intervention.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9ZXspD9Fbbhio3np.jpeg" /><figcaption><a href="https://aws.amazon.com/codepipeline/">https://aws.amazon.com/codepipeline/</a></figcaption></figure><p><strong>Step 1: Navigate to AWS CodePipeline to create a pipeline with the name of your choice (<em>humangov-cicd-pipeline)</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L7hdVqKufGHGO-C_gTtWyQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rgf5uOXhus9ruF-3s_8ipw.png" /></figure><p>This how our role will look like once we create the pipeline:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QELvN4XQW7osEG5TzhOAdg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-iNev-mRIFBwp8sToOQMRg.png" /></figure><p><em>AWSCodePipelineServiceRole-us-east-1-humangov-cicd-pipeline</em></p><pre>{<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Action&quot;: [<br>                &quot;iam:PassRole&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Condition&quot;: {<br>                &quot;StringEqualsIfExists&quot;: {<br>                    &quot;iam:PassedToService&quot;: [<br>                        &quot;cloudformation.amazonaws.com&quot;,<br>                        &quot;elasticbeanstalk.amazonaws.com&quot;,<br>                        &quot;ec2.amazonaws.com&quot;,<br>                        &quot;ecs-tasks.amazonaws.com&quot;<br>                    ]<br>                }<br>            }<br>        },<br>        {<br>            &quot;Action&quot;: [<br>                &quot;codecommit:CancelUploadArchive&quot;,<br>                &quot;codecommit:GetBranch&quot;,<br>                &quot;codecommit:GetCommit&quot;,<br>                &quot;codecommit:GetRepository&quot;,<br>                &quot;codecommit:GetUploadArchiveStatus&quot;,<br>                &quot;codecommit:UploadArchive&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;<br>        },<br>        {<br>            &quot;Action&quot;: [<br>                &quot;codedeploy:CreateDeployment&quot;,<br>                &quot;codedeploy:GetApplication&quot;,<br>                &quot;codedeploy:GetApplicationRevision&quot;,<br>                &quot;codedeploy:GetDeployment&quot;,<br>                &quot;codedeploy:GetDeploymentConfig&quot;,<br>                &quot;codedeploy:RegisterApplicationRevision&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;<br>        },<br>        {<br>            &quot;Action&quot;: [<br>                &quot;codestar-connections:UseConnection&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;<br>        },<br>        {<br>            &quot;Action&quot;: [<br>                &quot;elasticbeanstalk:*&quot;,<br>                &quot;ec2:*&quot;,<br>                &quot;elasticloadbalancing:*&quot;,<br>                &quot;autoscaling:*&quot;,<br>                &quot;cloudwatch:*&quot;,<br>                &quot;s3:*&quot;,<br>                &quot;sns:*&quot;,<br>                &quot;cloudformation:*&quot;,<br>                &quot;rds:*&quot;,<br>                &quot;sqs:*&quot;,<br>                &quot;ecs:*&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;<br>        },<br>        {<br>            &quot;Action&quot;: [<br>                &quot;lambda:InvokeFunction&quot;,<br>                &quot;lambda:ListFunctions&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;<br>        },<br>        {<br>            &quot;Action&quot;: [<br>                &quot;opsworks:CreateDeployment&quot;,<br>                &quot;opsworks:DescribeApps&quot;,<br>                &quot;opsworks:DescribeCommands&quot;,<br>                &quot;opsworks:DescribeDeployments&quot;,<br>                &quot;opsworks:DescribeInstances&quot;,<br>                &quot;opsworks:DescribeStacks&quot;,<br>                &quot;opsworks:UpdateApp&quot;,<br>                &quot;opsworks:UpdateStack&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;<br>        },<br>        {<br>            &quot;Action&quot;: [<br>                &quot;cloudformation:CreateStack&quot;,<br>                &quot;cloudformation:DeleteStack&quot;,<br>                &quot;cloudformation:DescribeStacks&quot;,<br>                &quot;cloudformation:UpdateStack&quot;,<br>                &quot;cloudformation:CreateChangeSet&quot;,<br>                &quot;cloudformation:DeleteChangeSet&quot;,<br>                &quot;cloudformation:DescribeChangeSet&quot;,<br>                &quot;cloudformation:ExecuteChangeSet&quot;,<br>                &quot;cloudformation:SetStackPolicy&quot;,<br>                &quot;cloudformation:ValidateTemplate&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;<br>        },<br>        {<br>            &quot;Action&quot;: [<br>                &quot;codebuild:BatchGetBuilds&quot;,<br>                &quot;codebuild:StartBuild&quot;,<br>                &quot;codebuild:BatchGetBuildBatches&quot;,<br>                &quot;codebuild:StartBuildBatch&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;<br>        },<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;devicefarm:ListProjects&quot;,<br>                &quot;devicefarm:ListDevicePools&quot;,<br>                &quot;devicefarm:GetRun&quot;,<br>                &quot;devicefarm:GetUpload&quot;,<br>                &quot;devicefarm:CreateUpload&quot;,<br>                &quot;devicefarm:ScheduleRun&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;<br>        },<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;servicecatalog:ListProvisioningArtifacts&quot;,<br>                &quot;servicecatalog:CreateProvisioningArtifact&quot;,<br>                &quot;servicecatalog:DescribeProvisioningArtifact&quot;,<br>                &quot;servicecatalog:DeleteProvisioningArtifact&quot;,<br>                &quot;servicecatalog:UpdateProduct&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;<br>        },<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;cloudformation:ValidateTemplate&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;<br>        },<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;ecr:DescribeImages&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;<br>        },<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;states:DescribeExecution&quot;,<br>                &quot;states:DescribeStateMachine&quot;,<br>                &quot;states:StartExecution&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;<br>        },<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;appconfig:StartDeployment&quot;,<br>                &quot;appconfig:StopDeployment&quot;,<br>                &quot;appconfig:GetDeployment&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;<br>        }<br>    ],<br>    &quot;Version&quot;: &quot;2012-10-17&quot;<br>}</pre><p><strong>Step 2: Choose the CodeCommit repository as the source code repository</strong></p><p>Our source code is stored in the CodeCommit repository. You can choose a different option if you are storing yours somewhere else.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lCiv546gzGuYDX0SFErXTg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*icz3lhkVPFPkdJylCDc1gQ.png" /></figure><p><strong>Step 3: Add a Build stage with AWS CodeBuild for building the Docker Images</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WmQkv_gRcdCjMHgbp_WM6A.png" /></figure><p><strong>Implementing AWS CodeBuild: </strong>We will use AWS CodeBuild to automate the building of Docker images. We will package the HumanGov application into containers for consistency across development, testing and deployment environments. Then, we will push the Docker images to the ECR. These images will be pulled during the deployment by the Kubernetes cluster. We haven’t had any CodeBuild projects so far. We need to create one for this project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6vyUmIOLoe0e-vXsIAcWhQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qzd30S9MQjBMs7mkoP9UYA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CpXmSbJ4VBDzImjAdYILag.png" /></figure><p>This is how our service role will look like, once created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8rexzooWLqmMWyR6LTUh2Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Haz6-_87G1oC4AsI2IK1Yg.png" /></figure><p><em>CodeBuildBasePolicy-humangov-build-us-east-1:</em></p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Resource&quot;: [<br>                &quot;arn:aws:logs:us-east-1:626127091134:log-group:/aws/codebuild/humangov-build&quot;,<br>                &quot;arn:aws:logs:us-east-1:626127091134:log-group:/aws/codebuild/humangov-build:*&quot;<br>            ],<br>            &quot;Action&quot;: [<br>                &quot;logs:CreateLogGroup&quot;,<br>                &quot;logs:CreateLogStream&quot;,<br>                &quot;logs:PutLogEvents&quot;<br>            ]<br>        },<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Resource&quot;: [<br>                &quot;arn:aws:s3:::codepipeline-us-east-1-*&quot;<br>            ],<br>            &quot;Action&quot;: [<br>                &quot;s3:PutObject&quot;,<br>                &quot;s3:GetObject&quot;,<br>                &quot;s3:GetObjectVersion&quot;,<br>                &quot;s3:GetBucketAcl&quot;,<br>                &quot;s3:GetBucketLocation&quot;<br>            ]<br>        },<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;codebuild:CreateReportGroup&quot;,<br>                &quot;codebuild:CreateReport&quot;,<br>                &quot;codebuild:UpdateReport&quot;,<br>                &quot;codebuild:BatchPutTestCases&quot;,<br>                &quot;codebuild:BatchPutCodeCoverages&quot;<br>            ],<br>            &quot;Resource&quot;: [<br>                &quot;arn:aws:codebuild:us-east-1:626127091134:report-group/humangov-build-*&quot;<br>            ]<br>        }<br>    ]<br>}</pre><p><em>CodeBuildVpcPolicy-humangov-build-us-east-1:</em></p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;ec2:CreateNetworkInterface&quot;,<br>                &quot;ec2:DescribeDhcpOptions&quot;,<br>                &quot;ec2:DescribeNetworkInterfaces&quot;,<br>                &quot;ec2:DeleteNetworkInterface&quot;,<br>                &quot;ec2:DescribeSubnets&quot;,<br>                &quot;ec2:DescribeSecurityGroups&quot;,<br>                &quot;ec2:DescribeVpcs&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;<br>        },<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;ec2:CreateNetworkInterfacePermission&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;arn:aws:ec2:us-east-1:626127091134:network-interface/*&quot;,<br>            &quot;Condition&quot;: {<br>                &quot;StringEquals&quot;: {<br>                    &quot;ec2:Subnet&quot;: [<br>                        &quot;arn:aws:ec2:us-east-1:626127091134:subnet/subnet-0bfc5bdd10730ca81&quot;,<br>                        &quot;arn:aws:ec2:us-east-1:626127091134:subnet/subnet-04bfc549c2fdafdba&quot;<br>                    ],<br>                    &quot;ec2:AuthorizedService&quot;: &quot;codebuild.amazonaws.com&quot;<br>                }<br>            }<br>        }<br>    ]<br>}</pre><p>In the <em>Additional configuration</em> section, grant privileges for AWS CodeBuild to execute Docker commands to build Docker images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tJMP0bfozhlSqMAw6-Wj9g.png" /></figure><p>Test the internet connection with <em>Validate VPC Settings.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Os9MwZjfFDMNZFp0WUVXgg.png" /></figure><p><strong>Buildspec:</strong> The AWS CodeDeploy buildspec file is a YAML or JSON document that defines the steps for building, testing, and deploying an application. It includes instructions such as installing dependencies, compiling code, running tests, and packaging artifacts. This file is crucial for automating the deployment process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QwF_jv6Kn_NAF7dcAqWO5g.png" /></figure><p>Switch to editor:</p><p>The AWS CodeBuild buildspec file below defines the phases for building and pushing a Docker image to Amazon ECR.</p><p><em>buildspec.yaml:</em></p><pre>version: 0.2<br><br>phases:<br>  install:<br>    runtime versions:<br>      docker: 20<br>  pre_build:<br>    commands:<br>      - cd src<br>      - ls<br>      - echo Logging in to Amazon ECR..<br>      - REPOSITORY_URI=$ECR_REPO  # Set this value as environment variable with your ECR repository URI<br>      - aws ecr-public get-login-password --region us-east-1 | docker login --username AWS --password-stdin public.ecr.aws/r9c2d3d1 <br>  build:<br>    commands:<br>      - echo Building the Docker image...<br>      - docker build -t $REPOSITORY_URI:latest .<br>      - docker tag $REPOSITORY_URI:latest $REPOSITORY_URI:$CODEBUILD_RESOLVED_SOURCE_VERSION<br>  post_build:<br>    commands:<br>      - echo Pushing the Docker image...<br>      - docker push $REPOSITORY_URI:$CODEBUILD_RESOLVED_SOURCE_VERSION<br>      - printf &#39;[{&quot;imageUri&quot;:&quot;%s&quot;}]&#39; &quot;$REPOSITORY_URI:$CODEBUILD_RESOLVED_SOURCE_VERSION&quot; &gt; imagedefinitions.json  # [{&quot;imageUri&quot;:&quot;public.ecr.aws/r9c2d3d1/humangov-app:e70288164727ba42c22b198e3dbf0f11e65110cf&quot;}]<br><br>artifacts:<br>  files: &#39;**/*&#39;  # All files in the project directory and its subdirectories should be packaged as artifacts</pre><p>Obtain the URI of the ECR repository and set the REPOSITORY_URI variable to this URI in the Environment variables section under AWS CodeBuild.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2d_1Qro6uG70siQwYgafjg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5oyeduDgD61s51xFl1lSxQ.png" /></figure><p>Update the login command in the file as described under <em>View push commands</em>(1st step)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ICIOfOpQmYA9xDeIkNXlQ.png" /></figure><p>Tagging the Docker image with $CODEBUILD_RESOLVED_SOURCE_VERSION creates a new tag with the source version resolved by CodeBuild, allowing you to differentiate between different versions of the same image before pushing it to the container registry.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RsEAL5tXNDvDkeTGbSgOsQ.png" /></figure><p>Single Build: The entire codebase is compiled, tested, and packaged in one continuous process. It is suitable for smaller projects or projects with simpler build requirements as in our case.</p><p>Batch Build: It breaks down the build process into multiple smaller builds that can be executed simultaneously or sequentially. Batch builds are beneficial for large projects. They can be used to parallelize the build process.</p><p><strong>Skip the Deployment Stage for now. We will come back to it...</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sb7mYWZCJKbMx6V3Ad6dAg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VYSIlFOjaYgspkHh-WgwtQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*voNvOq9sEDSkvYIb4l8_Sg.png" /></figure><p>Let’s go and check the AWS CodeBuild service role we created while creating a build stage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8rexzooWLqmMWyR6LTUh2Q.png" /></figure><p>There is no policy to access the Docker image in the Amazon Elastic Container Registry (ECR). We need the <em>AmazonElasticContainerRegistryPublicFullAccess</em> policy to be added to the service role.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IMZd_qFXT6xg2GjMz5C8Eg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GoKEAJdGOG7VJZiUJPnNRQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pfRl4jMgZZ78Ee67-KXG_A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E-68fqq05qRNmjOh3okkkA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UWFevyF3MjmoQMRIeoFcpg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b9V1vNf-MiUBz144sdYBKA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gD2Osh5i5nMlWeaCL7A8qg.png" /></figure><p>After the build stage of the pipeline our image will be created and pushed to ECR:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nyF0Hgtisz_vNn3_sWkYqA.png" /></figure><p><strong>Step 4: Adding a Testing Stage after the Build stage</strong></p><p>After building our application images we should test it before deploying it to the production environment. In the real world, developers should write proper tests following business logic. In this step, we will use the <em>pytest</em> library from Python for a simple testing purpose.</p><p>First, create a <em>tests </em>folder under the src folder with app.py and test_app.py files.</p><p><em>app.py</em></p><pre>def home_page(state):<br>    return &quot;Human Resources Management System - state of &quot; + state</pre><p><em>test_app.py</em></p><pre>import pytest<br>from app import home_page<br><br>    def test_home_page():<br>        assert home_page(&quot;California&quot;)==&quot;Human Resources Management System - state of California&quot;</pre><p>Update <em>requirements.txt</em> file adding <em>pytest library.</em></p><p>Go and edit the pipeline to add a new stage:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SMtL-fBig4AelWflb9aOFA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WHhkB_nxWpMYHRpqKlPUCA.png" /></figure><p>Add a new stage after the Build stage:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sP5uup3Xrc9d0GPJcJ9yYA.png" /></figure><p>Add a new action group:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b0Ht_tSoQV3_-xAShhx7rA.png" /></figure><p>Create a new project:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GJx5UbzbGT1dmeswBitDpQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4csrOCBAYOfUmDVCZNM5bA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DY3hHjmdeE1w6mo5EiWBrw.png" /></figure><p><strong>Buildspec:</strong></p><pre>version: 0.2<br><br>phases:<br>  build:<br>    commands:<br>      - cd src<br>      - IMAGE_URI=$(jq -r &#39;.[0].imageUri&#39; imagedefinitions.json)<br>      - echo $IMAGE_URI<br>      - echo Logging in to Amazon ECR..<br>      - aws --version<br>      - aws ecr-public get-login-password --region us-east-1 | docker login --username AWS --password-stdin public.ecr.aws/r9c2d3d1 <br>      - docker pull $IMAGE_URI # Pull the Docker image from ECR<br>      - docker run --rm $IMAGE_URI pytest tests/   # Run pytest in the Docker container  </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*99snmsiCvVN69-SLSzLzfA.png" /></figure><p>Save the pipeline.</p><p>Update codebuild-humangov-test-service-role servis role for test stage granting <em>AmazonElasticContainerRegistryPublicFullAccess</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IdMNL59NWCn-25aomwrmNA.png" /></figure><p>These will be the output log when the test stage is completed successfully:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3ROjqHOb0JNN5xFt9vuy_Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zxFfl7M_aPD4a9pfphT5Ag.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t7OwD2pU1DyttFgACzA8aA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v5osgQCVV_h-cnEnotASkA.png" /></figure><p><strong>Step 5: Adding Manual Approval (<em>Continuous Delivery</em>)(Optional)</strong></p><p>This is an intermediary stage before transitioning from CI to CD before the deployment stage. We can assign a professional to review and approve the process before releasing the application. This is mostly a step in Continuous Delivery. Continuous Deployment deploys changes automatically to production without approval once tests are passed.</p><p>Add Action group:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dbBTK174nChaGHi4224oMQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-vdzYBZifMx6T7RQLJzqQw.png" /></figure><p>When the pipeline reaches the manual approval stage, it will pause, and you will receive a notification to approve or reject the action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sn0NoSfs4B3rW31n_jx9AA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j5ZKbZ6QZi8qLmdDsNZ4gg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*iR9vgtai9fSYDrgYkXSiXA.png" /></figure><p><strong>PART 3: Orchestrating Automated Deployment with Kubernetes in the Deployment Stage</strong></p><p><strong>Step 1: Add a Deployment Stage</strong></p><p>Go and edit the pipeline to add a deployment stage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bAKSGPEIJdfy8OLGuDWWgw.png" /></figure><p>Add action group:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZZBoV5uwGBpF0OF5hPf2fQ.png" /></figure><p>Create a project with the same setting as we did for the build stage:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vXBoSk_3fPY5B_RWQIaJLA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GGmuiPoIUwmLugtwS_fy3A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5In7Kq9bFYncrkYwoWiTIQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8V5Gays8wzsTZWfuKsQwqw.png" /></figure><p>Set the environment variables AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY from our previously created eks-user IAM user credentials on Cloud Build to authenticate in the Kubernetes cluster. In a real-world production environment, use an IAM role for this matter.</p><p>Orchestrating with Kubernetes: We will configure Kubernetes clusters to host and manage the containerized HumanGov application as we did previously.</p><p>Buildspec: Set up Automated Deployment on Kubernetes. Make sure you have AWS CLI 2. If not install it as below.</p><pre>version: 0.2<br><br>phases:<br>  install:<br>      runtime-versions:<br>        docker: 20<br>      commands:<br>        - aws --version<br>        - curl -o kubectl https://amazon-eks.s3.us-west-2.amazonaws.com/1.18.9/2020-11-02/bin/linux/amd64/kubectl<br>        - chmod +x ./kubectl<br>        - mv ./kubectl /usr/local/bin<br>        - kubectl version --short --client<br>  post_build:<br>    commands:<br>      - export DEFAULT_AWS_REGION=us-east-1<br>      - aws eks update-kubeconfig --region $DEFAULT_AWS_REGION --name humangov-cluster<br>      - kubectl get nodes<br>      - ls<br>      - cd src<br>      - IMAGE_URI=$(jq -r &#39;.[0].imageUri&#39; imagedefinitions.json)<br>      - echo $IMAGE_URI<br>      - sed -i &quot;s|CONTAINER_IMAGE|$IMAGE_URI|g&quot; humangov-california.yaml<br>      - sed -i &quot;s|CONTAINER_IMAGE|$IMAGE_URI|g&quot; humangov-texas.yaml<br>      - kubectl apply -f humangov-california.yaml<br>      - kubectl apply -f humangov-texas.yaml<br>      - kubectl apply -f humangov-ingress-all.yaml<br>      - kubectl get pods<br>      - kubectl get services<br>      - kubectl get deployment<br><br>artifacts:<br>  files: &#39;**/*&#39;<br></pre><p>The sed commands you&#39;ve provided are using a placeholder CONTAINER_IMAGE in your YAML files (humangov-california.yaml and humangov-texas.yaml) and replacing it with the value of $IMAGE_URI. This is a common practice to dynamically inject container image URIs into Kubernetes YAML manifests before applying them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3hH4SVrdzMcjFY_zkMhP9w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WfjukZzzgJWFiia1DnSTfA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w011GKYvSBwrYU4kRRp6rw.png" /></figure><p>Save the pipeline after these changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XtsRyJ-P8N3u2-H12mY5MQ.png" /></figure><p>This will be the output log for the deployment stage:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CJTa7HXV2kVaaVT9abathg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vdWtyrgGEZK66vcaWiLLLw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LbvqM_QaTX5yXz2y8-SfWg.png" /></figure><p>Here are all the IAM roles we created and used during our pipeline-building process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jEbP8-YOTjSBd8c67zS4ZQ.png" /></figure><p><strong>Step 2: Update the <em>humangov-california.yaml </em>and<em> humangov-texas.yaml</em> files</strong></p><p>Change image path value to CONTAINER_IMAGE variable:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gbqd4iE4j-FhqBZZFFlh7w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BiiQYfrGDbRJAPeid0_myQ.png" /></figure><p><strong>Step 3: Commit and push changes to the CodeCommit repository</strong></p><pre>git status<br>git add .<br>git commit -m “pipeline builded;build, test and deployment stages were added”<br>git push</pre><p>The pipeline will be triggered and run once we push all the changes to the AWS CodeCommit repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZBzzAGypghyTmeJ-Wp2BSQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lScABRytR_SGPnRS2zTspg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*89j1Hs7POV0tzenfIj8CSQ.png" /></figure><p><strong>Step 4: Test the websites</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gmtiAhUbNx8tSUNV-Iwb1g.png" /></figure><p><em>california.humangov-ct.click</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y39PojeLt3f2J5NDr60mJw.png" /></figure><p><em>texas.humangov-ct.click</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wmJvP9IbkD4WxBS0HvVH9w.png" /></figure><p><strong>Step 4: Destroy the resources</strong></p><p>I will keep the infrastructure created with Terraform and the whole project as it is for the next project. If you won’t use resources for a long time destroy them. Otherwise, you will be charged.</p><pre>cd ~/environment/human-gov-application/src<br>kubectl delete -f humangov-ingress-all.yaml<br>kubectl delete -f humangov-california.yaml<br>kubectl delete -f humangov-texas.yaml<br>eksctl delete cluster --name humangov-cluster --region us-east-1</pre><pre>cd ~/environment/human-gov-infrastructure/terraform<br>terraform destroy</pre><p>CONGRATULATIONS!!!</p><p>Follow me on LinkedIn</p><p><a href="https://www.linkedin.com/in/cansu-t-a5617557/">https://www.linkedin.com/in/cansu-t-a5617557/</a></p><p>REFERENCES</p><ul><li><a href="https://thecloudbootcamp.com/">The Cloud Bootcamp - Main | The Cloud Bootcamp</a></li><li><a href="https://docs.aws.amazon.com/whitepapers/latest/practicing-continuous-integration-continuous-delivery/implementing-continuous-integration-and-continuous-delivery.html">Implementing continuous integration and continuous delivery</a></li><li><a href="https://docs.aws.amazon.com/eks/latest/userguide/aws-load-balancer-controller.html?source=post_page-----85b62e3f2be1--------------------------------">What is the AWS Load Balancer Controller?</a></li><li><a href="https://medium.com/@cansutekin23/part-15-humangov-application-kubernetes-deployment-of-humangov-saas-application-on-aws-85b62e3f2be1">Part 15 —HumanGov Application —  Kubernetes: Deployment of HumanGov SaaS Application on AWS…</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6705645a810b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 15 —HumanGov Application —  Kubernetes: Deployment of HumanGov SaaS Application on AWS…]]></title>
            <link>https://medium.com/@cansutekin23/part-15-humangov-application-kubernetes-deployment-of-humangov-saas-application-on-aws-85b62e3f2be1?source=rss-3599111d902f------2</link>
            <guid isPermaLink="false">https://medium.com/p/85b62e3f2be1</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[aws-eks]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Cansu Tekin]]></dc:creator>
            <pubDate>Wed, 27 Mar 2024 21:22:07 GMT</pubDate>
            <atom:updated>2024-04-01T17:21:57.734Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 15 —HumanGov Application — Kubernetes: Deployment of HumanGov SaaS Application on AWS Elastic Kubernetes Service (EKS) Using a Route 53 Domain, ALB Ingress, and SSL Endpoint Powered by AWS Certificate Manager</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DgKMoNqX9JIFv1kH.png" /></figure><blockquote>The HumanGov Application is a Human Resources Management Cloud SaaS application for the Department of Education across all 50 states in the US. Whenever a state hired a new employee the registiration of the new employees will be done through the application. Their information will be stored inside AWS DynamoDB and their employment document will be stored inside S3 buckets. Our primary responsibility as DevOps Engineer is to modernize and enhance the HumanGov application. We first focused on provisioning the infrastructure with Terraform (<a href="https://medium.com/@cansutekin23/part-10-final-project-humangov-application-deployment-of-reusable-saas-multi-tenant-aws-0c1447b533f1">Part 10</a>) onto the AWS Cloud environment, then we configured and deployed applications on those resources with Ansible (<a href="https://medium.com/@cansutekin23/part-13-humangov-application-ansible-final-project-configuration-and-deployment-of-humangov-e8288cbc3132">Part 1</a>3), and we containerized the HumanGov application using Docker (Part 14) to make it more efficient, portable, and scalable across different computing environments. In this part of the project series, we will focus on Elastic Kubernetes Service (EKS), Route 53, Application Load Balancer (ALB), and AWS Certificate Manager for SSL endpoint encryption. We will keep improving the application with DevOps tools in the following sections.</blockquote><p><strong>PART 1: AWS Elastic Kubernetes Service</strong> (<strong>EKS) Cluster Setup</strong></p><p><strong>PART 2: Installing Ingress Controller and Application Load Balancer</strong> (<strong>ALB)</strong></p><p><strong>PART 3: Deploying the HumanGov Application</strong></p><p><strong>PART 4: Kubernetes</strong> <strong>Ingress and Application Load Balancer (ALB) Setup with SSL</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*M868wjA0UReUwrtk.png" /></figure><h3><strong>Amazon Elastic Kubernetes Service (Amazon EKS)</strong></h3><p>Kubernetes is a container orchestration tool that simplifies containerized applications&#39; deployment, scaling, and management, allowing organizations to focus on building and delivering software rather than managing infrastructure.</p><p>Amazon Elastic Kubernetes Service (Amazon EKS) is a managed Kubernetes service that allows you to run Kubernetes on AWS. It provides features like automated deployment, scaling, load balancing, and self-healing, making building and maintaining complex applications in a cloud-native environment easier.</p><p>A Kubernetes cluster is a collection of physical or virtual machines (called nodes) grouped to run containerized applications orchestrated by Kubernetes.<strong> Kubernetes cluster</strong> consists of a <strong>control plane</strong> and one or more <strong>worker nodes</strong>. The control plane serves as the brains of the Kubernetes cluster being responsible for maintaining the desired state of the cluster, while the worker nodes are EC2 instances that run the pods (containers) for applications.</p><p>The control plane manages the cluster’s resources, schedules workloads, and maintains desired configurations. Worker nodes are responsible for executing the workloads deployed to the cluster. Each worker node hosts multiple pods. AWS manages the control plane, you manage the worker nodes.</p><p>A node group is a set of worker nodes with similar configurations, such as instance type, AMI, and Kubernetes labels. It allows you to manage and scale a group of nodes collectively, making it easier to handle the underlying infrastructure of the Kubernetes cluster.</p><h3><strong>PART 1: </strong>AWS Elastic Kubernetes Service (<strong>EKS) Cluster Setup</strong></h3><p><strong>Step 1: Make sure you have the AWS CLI v2 installed</strong></p><p>The AWS Command Line Interface (AWS CLI) is a unified tool provided by Amazon Web Services (AWS) that allows users to interact with various AWS services from the command line. It provides a set of commands for creating and managing AWS resources such as EC2 instances, S3 buckets, and RDS databases; configuring security and access permissions; deploying and managing applications on AWS services like Elastic Beanstalk, ECS, and Lambda; and automating tasks and workflows using scripts and shell commands.</p><p>AWS CLI version 2 (AWS CLI v2) is recommended for working with Amazon Elastic Kubernetes Service.</p><pre># Check the version<br>aws --version<br><br># Upgrade if it is not installed<br>sudo yum remove awscli<br>curl “https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip&quot; -o “awscliv2.zip”<br>unzip awscliv2.zip<br>sudo ./aws/install --bin-dir /usr/local/bin --install-dir /usr/local/aws-cl --update<br><br># Check the version again<br>aws --version</pre><p><strong>Step 2: Install the <em>eksctl, </em>the <em>kubectl, and helm</em></strong><em> </em><strong>CLI tools on the Cloud9 environment</strong></p><ul><li>The<em> eksctl</em><strong><em> </em></strong>is<strong><em> </em></strong>a command-line tool for creating, managing, and operating Kubernetes clusters specifically on Amazon EKS. It provisions necessary infrastructure with the AWS resources such as EC2 instances, networking components, and IAM roles. It also handles adding, removing, and modifying node groups.</li></ul><pre>curl --silent --location “https://github.com/weaveworks/eksctl/releases/latest/download/eksctl_$(uname -s)_amd64.tar.gz” | tar xz -C /tmp<br>sudo cp /tmp/eksctl /usr/bin<br>eksctl version</pre><p><em>eksctl</em> internally uses <em>kubectl</em> for interacting with Kubernetes clusters.</p><ul><li>The <em>kubectl</em>(Kubernetes Control) is a general-purpose CLI tool for interacting with any Kubernetes cluster regardless of where they are hosted, while eksctl is specifically for managing Kubernetes clusters on AWS EKS. The <em>kubectl</em> allows deploying applications, managing resources, scaling, accessing logs, and debugging.</li></ul><pre>curl -o kubectl https://amazon-eks.s3.us-west-2.amazonaws.com/1.18.9/2020-11-02/bin/linux/amd64/kubectl<br>chmod +x ./kubectl<br>mkdir -p $HOME/bin &amp;&amp; cp ./kubectl $HOME/bin/kubectl &amp;&amp; export PATH=$PATH:$HOME/bin<br>echo ‘export PATH=$PATH:$HOME/bin’ &gt;&gt; ~/.bashrc<br>kubectl version --short --client</pre><ul><li>Helm is a package manager for Kubernetes that simplifies deploying, managing, and scaling applications on Kubernetes clusters. The Helm CLI tool is used to interact with Helm.</li></ul><pre>curl -fsSL -o get_helm.sh https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3<br>chmod 700 get_helm.sh<br>./get_helm.sh<br>helm version</pre><p><strong>Step 3: Create an IAM User with the <em>AdministratorAccess</em> policy</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*boE6JXCZrprqaeSuYt7FDA.png" /></figure><p>Create an Access Key for the <em>eks-user, </em>and save it in <em>export.sh</em> file. We will use it to authenticate AWS CLI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dg7zYAE83aQ3PmO2xkj8ow.png" /></figure><pre>cd ~/environment<br>touch export.sh</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*W3EN0XaXS5Xno8KA_75RaA.png" /></figure><p><strong>Step 4: Disable Managed Credentials on Cloud9 and authenticate AWS CLI</strong></p><p>Settings &gt; AWS Settings</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hEHmPTuY2LDknqXFKposJw.png" /></figure><p>Execute the commands in the export.sh file. Any environment variables or functions defined in the file will be available in the terminal.</p><pre>source export.sh</pre><ul><li>Or configure AWS CLI as below</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*U8pTvELFXyH7B5VcuxESEQ.png" /></figure><p><strong>Step 5: Provision the HumanGov Application infrastructure with Terraform</strong></p><p>Go to the <a href="https://medium.com/@cansutekin23/part-14-humangov-application-proof-of-concept-poc-on-aws-elastic-container-service-ecs-a00121712425">previous project </a>to get Terraform files to provision the S3 and DynamoDB table if you do not have them.</p><p>Update <em>/human-gov-infrastructure/terraform/variables.tf</em> file to provision infrastructure for 2 states.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*eNC65q2bdiENJbkpiXP5IA.png" /></figure><pre>cd human-gov-infrastructure/terraform/<br>terraform show<br>terraform plan<br>terraform apply</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*N_I5LtiWUa9uVeZyjqM3JQ.png" /></figure><pre>Outputs:<br><br>state_infrastructure_outputs = {<br>  &quot;california&quot; = {<br>    &quot;dynamodb_table&quot; = &quot;humangov-california-dynamodb&quot;<br>    &quot;s3_bucket&quot; = &quot;humangov-california-s3-l32k&quot;<br>  }<br>  &quot;texas&quot; = {<br>    &quot;dynamodb_table&quot; = &quot;humangov-texas-dynamodb&quot;<br>    &quot;s3_bucket&quot; = &quot;humangov-texas-s3-6nhm&quot;<br>  }<br>}</pre><p><strong>Step 6: Create an EKS cluster and connect to it using kubectl</strong></p><p>Create an EKS cluster named humangov-cluster in the us-east-1 region with a node group named standard-workers</p><pre>eksctl create cluster --name humangov-cluster --region us-east-1 --nodegroup-name standard-workers --node-type t3.medium --nodes 1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xLosEA1sT1B0ta2gvpaeXw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cn9AXrUgO_8nBQyhkmaXHA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AG0aZ5u3D-UQEpDSz4yQpQ.png" /><figcaption>Compute -&gt; Node groups</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-co-HpoP_XJl-hqSmVDdww.png" /></figure><p>We need to retrieve the access credentials for the humangov-cluster and merge them into the <em>kubeconfig</em> file(/home/ec2-user/.kube/config) on our local machine to be able to connect to the humangov-cluster using <em>kubectl</em>.</p><pre>aws eks update-kubeconfig --name humangov-cluster</pre><pre># Verify Connectivity<br># Lists all the services running in the Kubernetes cluster<br>kubectl get svc<br># Lists all the nodes (or instances) that are part of the Kubernetes cluster<br>kubectl get nodes</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0MYjiZzgz2uyd3ng0UwtFQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ktYha_ZBPCn3Gx-mHkjnYQ.png" /></figure><h3><strong>PART 2: Installing Ingress Controller and Application Load Balancer</strong> (<strong>ALB)</strong></h3><p>We need to set up an Application Load Balancer (ALB) and an Ingress Controller to manage incoming traffic by directing the traffic to the correct services within the EKS cluster.</p><p><strong>Step 1: Create an IAM policy</strong></p><p>We need a policy that defines the permissions required by the AWS Load Balancer Controller to manage resources in your AWS account when deployed in an Amazon EKS cluster. The AWS Load Balancer Controller is a Kubernetes controller that manages Elastic Load Balancers (ELBs) for services running in a Kubernetes cluster.</p><pre>cd ~/environment<br># Download the policy<br>curl -O https://raw.githubusercontent.com/kubernetes-sigs/aws-load-balancer-controller/v2.5.4/docs/install/iam_policy.json<br># Create an IAM policy<br>aws iam create-policy --policy-name AWSLoadBalancerControllerIAMPolicy --policy-document file://iam_policy.json<br># List all the policies in your account<br>aws iam list-policies</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bZuQ6nTH7AA7sRLdj7241g.png" /></figure><p><strong>Step 2: Associate the IAM OIDC identity provider for your Amazon EKS cluster with eksctl</strong></p><p>When you associate the IAM OIDC identity provider with your EKS cluster, it establishes a trust relationship between the Kubernetes cluster and AWS IAM. This allows you to create Kubernetes service accounts and assign them IAM roles to access AWS resources such as S3 buckets, DynamoDB tables, or other AWS services. In our case, we need to access the Application Load Balancer (ALB) service. You can skip this step when you do not use IAM roles.</p><pre>eksctl utils associate-iam-oidc-provider --region us-east-1 --cluster humangov-cluster --approve</pre><p><strong>Step 3: Create a Kubernetes service account and associate an IAM role</strong></p><p>A Kubernetes service account is a Kubernetes-native concept for identity and access management. When a pod is created, it is assigned a service account to authenticate and authorize requests made by containers within the cluster to access Kubernetes resources.</p><p>By associating an IAM role with a Kubernetes service account, you enable the pods running within the Kubernetes cluster to assume the permissions defined by the IAM role when making requests to AWS services outside of the cluster. You’re essentially creating a mapping between a Kubernetes service account and an IAM role.</p><p>Create a Kubernetes service account with <em>AmazonEKSLoadBalancerControllerRole</em>, and attach <em>AWSLoadBalancerControllerIAMPolicy</em> to this role to grant AWS Load Balancer Controller with necessary permissions to create and manage ALB.</p><p>Replace the account ID (626127091134) in the command below with your AWS account ID.</p><pre># Create an Kubernetes service account within your Amazon EKS cluste<br>eksctl create iamserviceaccount \<br>--cluster=humangov-cluster \<br>--namespace=kube-system \<br>--region=us-east-1 \<br>--name=aws-load-balancer-controller \  # Name of the Kubernetes service account<br>--role-name AmazonEKSLoadBalancerControllerRole \ # IAM role name that will be associated with the Kubernetes service account<br>--attach-policy-arn=arn:aws:iam::626127091134:policy/AWSLoadBalancerControllerIAMPolicy \ # Policy that will be attached to the IAM role.<br>--approve</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ajsLtK1wKbNO4p03bxv09g.png" /></figure><p><strong>Step 4: Install the AWS Load Balancer Controller using </strong><a href="https://docs.aws.amazon.com/eks/latest/userguide/helm.html"><strong>Helm V3</strong></a></p><p>Helm is a package manager for Kubernetes. The ALB controller needs to be installed in the Kubernetes cluster. After this point, we will use <em>kubectl </em>to interact with our Kubernetes cluster and its attached services.</p><pre># Add the AWS EKS Helm chart repository to your Helm configuration<br>helm repo add eks https://aws.github.io/eks-charts<br># Ensure that you have access to the most recent versions of the charts available in the repository<br>helm repo update eks<br><br># Install the AWS Load Balancer Controller<br>helm install aws-load-balancer-controller eks/aws-load-balancer-controller \<br>-n kube-system \<br>--set clusterName=humangov-cluster \<br>--set serviceAccount.create=false \  # We already created Kubernetes service account<br>--set serviceAccount.name=aws-load-balancer-controller<br><br># Verify the controller installation<br>kubectl get deployment -n kube-system aws-load-balancer-controller<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j7Cz0Y6Vq1uJtmfgzu5Piw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*S2ctf7wtylITCmXkZymcsg.png" /></figure><h3><strong>PART 3: Deploying the HumanGov Application</strong></h3><p><strong>Step 1: Create a Role and Service Account to provide pods access to S3 and DynamoDB tables</strong></p><p>We will create another IAM service account to allow pods to access the S3 bucket &amp; DynamoDB table. our application will be deployed using pod(s).</p><pre>eksctl create iamserviceaccount \<br>--cluster=humangov-cluster \<br>--name=humangov-pod-execution-role \<br>--role-name=HumanGovPodExecutionRole \<br>--attach-policy-arn=arn:aws:iam::aws:policy/AmazonS3FullAccess \<br>--attach-policy-arn=arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess \<br>--region us-east-1 \<br>--approve</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zApU4H2tAL6a_jy4cHNHkQ.png" /></figure><p><strong>Step 2: Containerize the HumanGov application</strong></p><p>Create a public ECR repository named <em>humangov-app</em>, and build and push the Docker Image to the ECR repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gKzJEEHRo1IWqiNK1kslQg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wW0CQtQmvi9c5llezl99hA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jXbEhjcsCTvJu-EFCpyaXg.png" /></figure><p>Go to <em>View push commands:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Iv8mWOg8bMcTXpwgstuaFA.png" /></figure><pre>cd human-gov-application/src/</pre><ol><li>Retrieve an authentication token and authenticate your Docker client to your registry. Use the AWS CLI:</li></ol><pre>aws ecr-public get-login-password --region us-east-1 | docker login --username AWS --password-stdin public.ecr.aws/r9c2d3d1</pre><p>2. Build your Docker image using the following command. For information on building a Docker file from scratch see the instructions <a href="http://docs.aws.amazon.com/AmazonECS/latest/developerguide/docker-basics.html">here</a>. You can skip this step if your image is already built:</p><pre>docker build -t humangov-app .</pre><p>3. After the build completes, tag your image so you can push the image to this repository:</p><pre>docker tag humangov-app:latest public.ecr.aws/r9c2d3d1/humangov-app:latest</pre><p>4. Run the following command to push this image to your newly created AWS repository:</p><pre>docker push public.ecr.aws/r9c2d3d1/humangov-app:latest</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g-O8Xv6Yznm17Owm0aCI5g.png" /></figure><p><strong>Step 4: Deploy the application for each state</strong><br>Create application deployment YAML files; <em>humangov-california.yaml</em> and <em>humangov-texas.yaml </em>under the human-gov-application/src directory.</p><p>We will manage resources to deploy our application consisting of a Python app and an NGINX reverse proxy in a Kubernetes cluster. The NGINX reverse proxy forwards requests to the Python app service as configured in the deployment YAML file below.</p><ol><li>Deployment (<em>humangov-python-app-california</em>): Specify the desired deployment state for the container named “humangov-python-app-california” using the image from the ECR repository, humangov-app, we created before. Provide environment variables AWS_BUCKET, AWS_DYNAMODB_TABLE, AWS_REGION, and US_STATE to the container for configuration.</li><li>Service (<em>humangov-python-app-service-california</em>): Define a Kubernetes Service to expose the Pods with the label app: humangov-python-app-california internally within the cluster on port 8000.</li><li>Deployment (<em>humangov-nginx-reverse-proxy-california</em>): Deploy NGINX reverse proxy that runs a container named “humangov-nginx-reverse-proxy-california” using the NGINX alpine image. Mount a ConfigMap named “humangov-nginx-config-california” to configure NGINX.</li><li>Service (<em>humangov-nginx-service-california</em>): Define the “humangov-nginx-service-california” Kubernetes Service to expose the NGINX reverse proxy on port 80.</li><li>ConfigMap (<em>humangov-nginx-config-california</em>): Define a ConfigMap containing NGINX configuration (nginx.conf) and proxy parameters (proxy_params) to forward incoming HTTP requests to the backend service running at humangov-python-app-service-california:8000.</li></ol><pre>cd human-gov-application/src/<br>touch humangov-california.yaml</pre><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: humangov-python-app-california<br>spec:                                # Describes the desired state of the Deployment<br>  replicas: 1                        # Specifies the desired number of replicas (instances) of the application to run,<br>  selector:                          # Specifies the labels used to select the Pods that the Service will route traffic to.<br>    matchLabels:<br>      app: humangov-python-app-california<br>  template:                           # Defines the Pod template used by the Deployment<br>    metadata:<br>      labels:<br>        app: humangov-python-app-california<br>    spec:<br>      serviceAccountName: humangov-pod-execution-role   # Name of the Kubernetes service account to use for running the Pods<br>      containers:                                       # Defines the containers that should run in the Pod<br>      - name: humangov-python-app-california<br>        image: public.ecr.aws/r9c2d3d1/humangov-app:latest<br>        env:<br>        - name: AWS_BUCKET<br>          value: &quot;humangov-california-s3-tim7&quot;<br>        - name: AWS_DYNAMODB_TABLE<br>          value: &quot;humangov-california-dynamodb&quot;<br>        - name: AWS_REGION<br>          value: &quot;us-east-1&quot;<br>        - name: US_STATE<br>          value: &quot;california&quot;<br><br>---<br><br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: humangov-python-app-service-california<br>spec:<br>  type: ClusterIP  # ClusterIP means the Service is only accessible within the cluster.<br>  selector:        # Specifies the labels used to select the Pods that the Service will route traffic to<br>    app: humangov-python-app-california <br>  ports:          # Specifies the ports that the Service will listen on<br>    - protocol: TCP<br>      port: 8000  # Port number on which the Service will listen within the cluster<br>      targetPort: 8000 # Port number that the Service will forward traffic to on the Pods<br><br>---<br><br>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: humangov-nginx-reverse-proxy-california<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: humangov-nginx-reverse-proxy-california<br>  template:<br>    metadata:<br>      labels:<br>        app: humangov-nginx-reverse-proxy-california<br>    spec:<br>      containers:<br>      - name: humangov-nginx-reverse-proxy-california<br>        image: nginx:alpine<br>        ports:<br>        - containerPort: 80   # Port 80 the NGINX container will be exposed<br>        volumeMounts:         # Mounts volumes into the container&#39;s filesystem.<br>        - name: humangov-nginx-config-california-vol<br>          mountPath: /etc/nginx/<br>      volumes:<br>      - name: humangov-nginx-config-california-vol<br>        configMap:<br>          name: humangov-nginx-config-california<br><br>---<br><br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: humangov-nginx-service-california<br>spec:<br>  selector:<br>    app: humangov-nginx-reverse-proxy-california<br>  ports:<br>    - protocol: TCP<br>      port: 80<br>      targetPort: 80<br><br>---<br><br>apiVersion: v1<br>kind: ConfigMap # Specifies a set of key-value pairs that can be used to configure Kubernetes resources.<br>metadata:<br>  name: humangov-nginx-config-california<br>data:<br>  nginx.conf: |<br><br>    events {<br>      worker_connections 1024;<br>    }<br><br>    http {<br><br>      server {<br>        listen 80;<br><br>        location / {  # Block defines how NGINX handles request. It specifies the backend service URL (http://humangov-python-app-service-california:8000) to which NGINX should forward requests.<br>          proxy_set_header Host $host;<br>          proxy_set_header X-Real-IP $remote_addr;<br>          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;<br>          proxy_pass http://humangov-python-app-service-california:8000; # App container<br>        }<br>      }<br>    }<br>  <br>  proxy_params: |<br>    proxy_set_header Host $host;<br>    proxy_set_header X-Real-IP $remote_addr;<br>    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;</pre><p>Deploy the HumanGov application for California:</p><pre><br>kubectl apply -f humangov-california.yaml<br># Verify the deployment<br>kubectl get pods<br>kubectl get services<br>kubectl get deployment</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*znjVVk2MICn56ezvQ6IapA.png" /></figure><p>Deploy the HumanGov application for Texas:</p><p>Copy the same settings from the California app deployment and update the AWS_BUCKET, AWS_DYNAMODB_TABLE, and US_STATE environmental variables’ values and names specific to Texas in the <em>humangov-texas.yaml</em> file.</p><pre>cp humangov-california.yaml humangov-texas.yaml</pre><pre><br>kubectl apply -f humangov-texas.yaml<br>kubectl get pods<br>kubectl get services<br>kubectl get deployment</pre><p>Four pods should be running (2 pods/state) with their Cluster IP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pqqQKINeWHYU1iwPqTWpQA.png" /></figure><p>Here are the running pods and namespace:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9HqeUHXo9HGAv3KitQp0NQ.png" /></figure><h3><strong>PART 4: </strong>Kubernetes <strong>Ingress and Application Load Balancer (ALB) Setup with SSL</strong></h3><p>We need a Kubernetes ingress to route HTTP and HTTPS traffic from outside to the cluster to be able to access our application. Kubernetes ingress manages external access to services in a Kubernetes cluster, enables load balancing, and provides SSL termination.</p><p><strong>Step 1: Create a new domain on Route 53</strong></p><p>Amazon Route 53 is a highly scalable and reliable Domain Name System (DNS) service to route end users to internet applications by translating human-readable domain names into IP addresses. We will purchase new a human-readable domain and use this domain to connect our application instead of connecting with its public IP address.</p><p>Go to Route 53 -&gt; Registered domains -&gt; Register domains -&gt; pick whatever you want as a domain name</p><p>I will use the <em>.click</em> extension for this project because it is the cheapest option. You can pick a different extension like <em>.com</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M4SlToTTc7ZAs2jJ2l58cA.png" /></figure><p>Registration takes some time. You can check its status under the <em>Requests </em>tab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rDCYbG7D0pKfpgeLB4bKyg.png" /></figure><p>You also get emails about the registration and approval.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A4rz4wCAN978IdJhAKU8bQ.png" /></figure><p>After registration of the domain name is approved it will be listed under Route 53 -&gt; Registered domains</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JT385ZTnpUzDnD6L9VoHzQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dYYO2Opi6SjbNt4dK5CngQ.png" /></figure><p>You can test record:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rkO26wklQN4R94JD909n1Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*axAeZDYb33dCPt5A13nKXA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KUK9a23SUYRirgRj8C-HmQ.png" /></figure><p><strong>Step 2: Create a Certificate for the ALB</strong></p><p>Go to AWS Certificate Manager and request a new public certificate for the <em>humangov-ct.click </em>domain. It will provide SSL encryption for the <em>humangov-ct.click </em>domain<em> for </em>secure communication between clients and the cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s2OWXpKzOYJCBJSYC_HZug.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KkY-uhhakQmC9F1qvpYywA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4-mydC50oehxOXv66yYVsA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n_9-fMfxDQRwLKjOcJe8-A.png" /></figure><p>Go inside the certificate and click on <em>Create records in Route 53.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QTafdRe2X9YyHPG-A7siHQ.png" /></figure><p>AWS Certificate Manager (ACM) provides a specific DNS record with CNAME type to add to your Route 53 hosted zone to use the certificate with AWS services like ALB. ACM uses this record to validate that you are the owner of the domain.</p><p>Select the certificate you created and create records.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*908rCVlblp29D8AFhTEX5g.png" /></figure><p>Go to Route 53 -&gt; Hosted zones -&gt; your domain name -&gt; Records</p><p>You will see the certificate you created in AWS Certificate Manager is added to <em>Records</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dLCqMEg2R-FTaMPQVMgyVw.png" /></figure><p>After the certificate is issued, we can associate it with an ALB service that requires SSL encryption for secure communication. Next, we should configure the ALB service to use the issued certificate for HTTP and HTTPS communications.</p><p><strong>Step 3: Deploy the Kubernetes Ingress Rules to configure how traffic should be routed to your application using an ALB</strong></p><p>Create an Ingress YAML file <em>humangov-ingress-all.yaml </em>that includes rules for each state.</p><pre>touch humangov-ingress-all.yaml</pre><p>Replace the ARN of the certificate with yours.</p><pre>apiVersion: networking.k8s.io/v1<br>kind: Ingress<br>metadata:<br>  name: humangov-python-app-ingress<br>  annotations:         # Annotations are specific to the AWS ALB Ingress Controller<br>    alb.ingress.kubernetes.io/scheme: internet-facing<br>    alb.ingress.kubernetes.io/target-type: ip<br>    alb.ingress.kubernetes.io/group.name: frontend<br>    alb.ingress.kubernetes.io/certificate-arn: arn:aws:acm:us-east-1:626127091134:certificate/f161f419-49e9-4f62-a88f-e359aa72b4a0<br>    alb.ingress.kubernetes.io/listen-ports: &#39;[{&quot;HTTP&quot;: 80}, {&quot;HTTPS&quot;: 443}]&#39;<br>    alb.ingress.kubernetes.io/ssl-redirect: &#39;443&#39;   # HTTP traffic should be redirected to HTTPS<br>  labels:<br>    app: humangov-python-app-ingress<br>spec:<br>  ingressClassName: alb<br>  rules:                         # route traffic based on hostnames<br>    - host: california.humangov-ct.click  # We will create this subdomain later<br>      http:<br>        paths:<br>        - path: /<br>          pathType: Prefix       # Prefix matches requests with URL paths that start with the specified prefix<br>          backend:               # backend the requests should be forwarded<br>            service:             # Kubernetes service to forward requests to<br>              name: humangov-nginx-service-california<br>              port:<br>                number: 80       # The port number on the backend service<br>    - host: texas.humangov-ct.click # We will create this subdomain later<br>      http:<br>         paths:<br>         - path: /<br>           pathType: Prefix<br>           backend:<br>             service:<br>               name: humangov-nginx-service-texas<br>               port:<br>                 number: 80</pre><p>When we apply these Ingress Rules, the ALB Ingress Controller will automatically provision an ALB in our AWS account based on specified Ingress rules. We already installed the ALB Ingress Controller and configured it in our cluster for this purpose.</p><pre># Apply the ingress<br>kubectl apply -f humangov-ingress-all.yaml<br># Verify the Ingress Controller<br>kubectl get ingress</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DVPtcoqhq31mIpRxaiqSjQ.png" /></figure><p>Check in the Load Balancers under AWS EC2:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ToYskYKjItsARbsgAkRPbA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZmFuUSiHR7nxufItP4YCMA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TzJRI1BNaz0lrlZh9DIgdA.png" /></figure><p><strong>Step 4: Create alias entries (Record Type: A) on Route 53 and point the subdomain to the ALB domain</strong></p><p>Head to Hosted Zones -&gt; humangov-ct.click -&gt; Create records for both California and Texas</p><p>Choose the ALB we created as an Alias Target to which the alias should route the traffic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cpfoHFig2RTYMLucV4oS9Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Esm0tvEarv8mxYVxUNys0w.png" /></figure><p>DNS records are pointing to where our application is hosted:</p><pre>dualstack.k8s-frontend-ded5adda2e-1159621946.us-east-1.elb.amazonaws.com</pre><p><strong>Step 5: Check logs to see if everything is OK</strong></p><pre>kubectl get pods<br>kubectl logs &lt;pod-name&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ytG2Mme1vl4UMA0ZCUomew.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-YXPIz7k9e4r6xD-UIEqLQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AcpqmAQIQSKLlyPDYq1EvQ.png" /></figure><p><strong>Step 6: Test the application on <em>california.humangov-ct.click</em> and <em>texas.humangov-ct.click</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yv5K2nrEKSAZuqoxbC0xxA.png" /><figcaption><strong><em>california.humangov-ct.click</em></strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WbtIgZTqUfGpSVadSnObuA.png" /><figcaption><strong><em>texas.humangov-ct.click</em></strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FGC2G5sT6p-lrh9C2dwKkA.png" /></figure><p>Add a new employee for testing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RnN5muiKm27sXMiEZpNoGw.png" /></figure><p>Check S3 Bucket:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A5e74XuCAwCiTTW3t2H5pQ.png" /></figure><p>Check the DynamoDB table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zZqUd374s1tbMNvsJBzGcA.png" /></figure><p><strong>Step 7: Push HumanGov application source code changes to AWS CodeCommit</strong></p><pre>cd ~/environment/human-gov-application/src<br>git status<br>git add .<br>git commit -m &quot;Code changes for Elastic Kubernetes Service (EKS)&quot;<br>git status<br>git push </pre><p><strong>Step 7: Destroy the resources</strong></p><pre>cd ~/environment/human-gov-application/src<br>kubectl delete -f humangov-ingress-all.yaml<br>kubectl delete -f humangov-california.yaml<br>kubectl delete -f humangov-texas.yaml<br>eksctl delete cluster --name humangov-cluster --region us-east-1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eFuR5ssNr4vDiv0ybx5bSA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QIVwabGgRd_iwzqDaYTjpw.png" /></figure><p>I am going to keep the infrastructure created with Terraform for the next project. If you do not use resources for a long time and do not want to be charged destroy them as well.</p><pre>cd ~/environment/human-gov-infrastructure/terraform<br>terraform destroy</pre><p>CONGRATULATIONS!!!</p><p>Follow me on LinkedIn</p><p><a href="https://www.linkedin.com/in/cansu-t-a5617557/">https://www.linkedin.com/in/cansu-t-a5617557/</a></p><p>REFERENCES</p><ul><li><a href="https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html">Installing or updating to the latest version of the AWS CLI</a></li><li><a href="https://repost.aws/knowledge-center/eks-cluster-connection">Connect to Amazon EKS clusters</a></li><li><a href="https://docs.aws.amazon.com/eks/latest/userguide/install-kubectl.html">Set up kubectl and eksctl</a></li><li><a href="https://docs.aws.amazon.com/eks/latest/userguide/sample-deployment.html">Deploy a sample application</a></li><li><a href="https://docs.aws.amazon.com/eks/latest/userguide/sample-deployment.html">Deploy a sample application</a></li><li><a href="https://docs.aws.amazon.com/eks/latest/userguide/aws-load-balancer-controller.html">Route internet traffic with AWS Load Balancer Controller</a></li><li><a href="https://www.eksworkshop.com/docs/fundamentals/exposing/ingress/multiple-ingress">Multiple Ingress pattern | EKS Workshop</a></li><li><a href="https://docs.aws.amazon.com/eks/latest/userguide/aws-load-balancer-controller.html">Route internet traffic with AWS Load Balancer Controller</a></li><li><a href="https://docs.aws.amazon.com/eks/latest/userguide/sample-deployment.html">Deploy a sample application</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85b62e3f2be1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 14 — HumanGov Application — Proof of Concept (POC) on AWS Elastic Container Service (ECS)…]]></title>
            <link>https://medium.com/@cansutekin23/part-14-humangov-application-proof-of-concept-poc-on-aws-elastic-container-service-ecs-a00121712425?source=rss-3599111d902f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a00121712425</guid>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[aws-ecs-fargate]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[aws-fargate]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Cansu Tekin]]></dc:creator>
            <pubDate>Tue, 19 Mar 2024 14:16:22 GMT</pubDate>
            <atom:updated>2024-03-19T15:05:43.622Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 14 — HumanGov Application — Proof of Concept (POC) on AWS Elastic Container Service (ECS) fronted By Application Load Balancer (ALB) and Storing Docker Images on Elastic Container Registry (ECR)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_68fgr5AsbX1dpgdw8IjnQ.jpeg" /></figure><blockquote>The HumanGov Application is a Human Resources Management Cloud SaaS application for the Department of Education across all 50 states in the US. Whenever a state hired a new employee the registiration of the new employees will be done through the application. Their information will be stored inside AWS DynamoDB and their employment document will be stored inside S3 buckets. Our primary responsibility as DevOps Engineer is to modernize and enhance the HumanGov application. We first focused on provisioning the infrastructure with Terraform (<a href="https://medium.com/@cansutekin23/part-10-final-project-humangov-application-deployment-of-reusable-saas-multi-tenant-aws-0c1447b533f1">Part 10</a>) onto the AWS Cloud environment and then we configured and deployed applications on those resources with Ansible (<a href="https://medium.com/@cansutekin23/part-13-humangov-application-ansible-final-project-configuration-and-deployment-of-humangov-e8288cbc3132">Part </a>3). In this section, we will containerize the HumanGov application using Docker to make it more efficient, portable, and scalable across different computing environments, and keep improving the application architecture with DevOps tools in the following sections.</blockquote><p><strong>PART 1: Containerize the HumanGov application using Docker, and push the image to AWS ECR (Elastic Container Registry)</strong></p><p><strong>PART 2: Provision the AWS S3 Bucket and DynamoDB table using Terraform, and the ECS (Elastic Container Service) cluster manually</strong></p><p><strong>PART 3: Deploy the application by creating a service on ECS</strong></p><p>SOLUTION ARCHITECTURE</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*secG4BhVZVo9OwMT.png" /></figure><h3>PART 1: Containerize the HumanGov application using Docker, and push the image to AWS ECR (Elastic Container Registry)</h3><p>SOLUTION ARCHITECTURE</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*x9Z1pw0in-x6t96G.png" /></figure><p><strong>Step 1: Create an IAM Role for ECS tasks</strong></p><p>When we create an IAM role for ECS tasks, we typically define the permissions required for those tasks to interact with other AWS services, such as accessing Amazon S3 buckets, writing logs to Amazon CloudWatch, or pulling container images from Amazon ECR (Elastic Container Registry).</p><p>Set Permissions:</p><pre># Grant full access to Amazon S3 resources;listing, uploading, downloading, and deleting objects within S3 buckets.<br>AmazonS3FullAccess<br># Provide full access to Amazon DynamoDB; creating, reading, updating, and deleting tables and data within DynamoDB.<br>AmazonDynamoDBFullAccess<br># This policy used by Amazon ECS tasks. <br># It grants permissions necessary for ECS tasks to execute, including accessing Amazon CloudWatch logs and Amazon S3 for task storage.<br>AmazonECSTaskExecutionRolePolicy</pre><p>By specifying “Elastic Container Service Task” as the trusted entity type, we’re indicating that the policy is intended to be attached to IAM roles used by ECS tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LblyrYmtuKxSOEBHLa6ZRw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e45ktJSoT-lvgvNCV3WJKw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zf0tSwEAcNpvs9zsx65bYQ.png" /></figure><p><strong>Step 2: Disable the AWS-managed credentials on Cloud9 and set up new IAM credentials</strong></p><p>Settings &gt; AWS Settings</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dTDO4j-p2kymh4FWqUX99A.png" /></figure><p>We already have a user from the previous project series named cloud9-user. Delete the previously created keys and create a new key for the cloud9-user with the Command Line Interface (CLI) use case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*22HLGbc-gwo09-gEehTTRQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nHQTPaUHmmXvMHJVDkc3hQ.png" /></figure><p>Store them in <em>export.sh</em> file and export it.</p><pre>cd ~/environment<br>touch export.sh<br>source export.sh<br># validate<br>echo $AWS_ACCESS_KEY_ID</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z24R3wEi1DZLdVcmYzBNOA.png" /></figure><p><strong>Step 3: Containerize the HumanGov application using Docker</strong></p><pre>cd human-gov-application/src/<br># Create the Dockerfile<br>touch Dockerfile</pre><p>Dockerfile: This Dockerfile is used to build a Docker image for deploying a Flask application using Gunicorn</p><pre># Use Python as a base image<br># This provides the necessary Python environment to run the Flask application<br>FROM python:3.8-slim-buster<br><br># Set working directory inside the container to /app<br># This will be the directory where the Flask application code will be copied<br># If the /app directory doesn&#39;t exist, Docker will create it. Then, subsequent commands like COPY, RUN, and CMD will be executed relative to this directory<br>WORKDIR /app<br><br># Copies the requirements.txt file from the local directory to the /app directory inside the container<br># Installs the Python dependencies listed in the requirements.txt file using pip<br>COPY requirements.txt ./<br>RUN pip install --no-cache-dir -r requirements.txt<br><br># Copy the entire local directory (containing the Flask application code) to the /app directory inside the container<br>COPY . /app<br><br># Specify the default command to run when the container starts.<br># Start Gunicorn serving the Flask application defined in the humangov module&#39;s app object.<br>CMD [&quot;gunicorn&quot;, &quot;--workers&quot;, &quot;1&quot;, &quot;--bind&quot;, &quot;0.0.0.0:8000&quot;, &quot;humangov:app&quot;]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mwsp9_rHfEpLl0UJ-9xFBw.png" /></figure><p><strong>Step 4: Build Docker Image for <em>humangov-app </em>Flask application and NGINX application, then push them</strong> <strong>to the ECR repository (Elastic Container Registry)</strong></p><p>The Elastic Container Registry (ECR) is a fully managed Docker container registry service provided by Amazon Web Services (AWS). It allows users to store, manage, and deploy Docker container images. ECR integrates with other AWS services such as Amazon ECS (Elastic Container Service) and AWS Fargate.</p><p>Create a new public ECR repository named <em>humangov-app </em>for Flask application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JRvTQ4WNP1nMozgKZXz31w.png" /></figure><p>Go to <em>View push commands:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6D7MavixoURgP9ddIE4xFQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lav8uj-A0J_JHH5CavHfUg.png" /></figure><ol><li>Retrieve an authentication token and authenticate your Docker client to your registry. Use the AWS CLI:</li></ol><pre>aws ecr-public get-login-password --region us-east-1 | docker login --username AWS --password-stdin public.ecr.aws/r9c2d3d1</pre><p>2. Build your Docker image using the following command. For information on building a Docker file from scratch see the instructions <a href="http://docs.aws.amazon.com/AmazonECS/latest/developerguide/docker-basics.html">here</a>. You can skip this step if your image is already built:</p><pre>docker build -t humangov-app .</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DzNP2xQv6tBb2JT1V45hpw.png" /></figure><p>3. After the build completes, tag your image so you can push the image to this repository:</p><pre>docker tag humangov-app:latest public.ecr.aws/r9c2d3d1/humangov-app:latest</pre><p>4. Run the following command to push this image to your newly created AWS repository:</p><pre>docker push public.ecr.aws/r9c2d3d1/humangov-app:latest</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZufwvZXDaYnT5AA8I7s3sQ.png" /></figure><p><strong>Step 5: Containerize the NGINX application</strong></p><pre>cd ..<br>mkdir nginx<br># Create the NGINX configuration files<br>touch nginx.conf<br>touch proxy_params<br>touch Dockerfile</pre><p><em>nginx.conf</em> file:</p><pre>server {<br>    listen 80;<br>    server_name humangov www.humangov;<br><br>    location / {<br>        include proxy_params;<br>        proxy_pass http://localhost:8000; <br>    }<br>}</pre><p>It forwards the request to the container hosting the Flask Python application running on port 8000 of the localhost and configures NGINX to listen for incoming HTTP requests on port 80. http://localhost:8000, indicates that NGINX will forward requests to the Flask application running on port 8000 of the localhost.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cCpptwaCF701a02TOkFvdA.png" /></figure><p>Create the Dockerfile for NGINX image:</p><pre># Use NGINX alpine as a base image<br>FROM nginx:alpine<br><br># Remove the default NGINX configuration file<br>RUN rm /etc/nginx/conf.d/default.conf<br><br># Copy custom configuration file<br>COPY nginx.conf /etc/nginx/conf.d<br><br># Copy proxy parameters<br>COPY proxy_params /etc/nginx/proxy_params<br><br># Expose port 80<br>EXPOSE 80<br><br># Start NGINX<br>CMD [&quot;nginx&quot;, &quot;-g&quot;, &quot;daemon off;&quot;]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IrMeHG3kFksMbmC2fzzsWQ.png" /></figure><p>Create a new public ECR repository named <em>humangov-nginx</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nEfiFo7foOryqosdGZVAUA.png" /></figure><p>Push commands for <em>humangov-nginx:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zu_s_SgfwgwP0gealFySAw.png" /></figure><ol><li>Retrieve an authentication token and authenticate your Docker client to your registry. Use the AWS CLI:</li></ol><pre>aws ecr-public get-login-password --region us-east-1 | docker login --username AWS --password-stdin public.ecr.aws/r9c2d3d1</pre><p>2. Build your Docker image using the following command. For information on building a Docker file from scratch see the instructions <a href="http://docs.aws.amazon.com/AmazonECS/latest/developerguide/docker-basics.html">here</a>. You can skip this step if your image is already built:</p><pre>docker build -t humangov-nginx .</pre><p>3. After the build completes, tag your image so you can push the image to this repository:</p><pre>docker tag humangov-nginx:latest public.ecr.aws/r9c2d3d1/humangov-nginx:latest</pre><p>4. Run the following command to push this image to your AWS repository:</p><pre>docker push public.ecr.aws/r9c2d3d1/humangov-nginx:latest</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UulxOH9-Q2b489AKsgI7XQ.png" /></figure><h3>Part 2: Provision the AWS S3 Bucket and DynamoDB table using Terraform, and the ECS (Elastic Container Service) cluster manually</h3><blockquote>Please be aware that AWS Fargate does not currently offer a free tier, so engaging in this hands-on project will result in incurring a small amount of USD in AWS charges. Remember to promptly delete the cluster once you’ve completed the hands-on to avoid any unnecessary costs.</blockquote><p><strong>Step 1: Update the Terraform files before provisioning the AWS S3 Bucket and DynamoDB table</strong></p><p>We already have a Terraform file with the desired infrastructure from the previous section. We do not need EC2 instance resources and their configuration at this point because we will use AWS Fargate. AWS Fargate is a serverless compute engine for containers that allows you to run containers without managing the underlying infrastructure.</p><p>Comment out the blocks not related to S3 and DynamoDb Table on <em>modules/aws_humangov_infrastructure/main.tf</em></p><p>This is the updated <em>modules/aws_humangov_infrastructure/main.tf </em>file:</p><pre>resource &quot;aws_dynamodb_table&quot; &quot;state_dynamodb&quot; {<br>    name = &quot;humangov-${var.state_name}-dynamodb&quot;<br>    billing_mode = &quot;PAY_PER_REQUEST&quot;<br>    hash_key = &quot;id&quot;<br>    <br>    attribute {<br>        name = &quot;id&quot;<br>        type = &quot;S&quot;<br>    }<br>    <br>    tags = {<br>        Name = &quot;humangov-${var.state_name}&quot;<br>    }    <br>}<br><br>resource &quot;random_string&quot; &quot;bucket_suffix&quot; {<br>    length = 4<br>    special = false<br>    upper = false<br>}<br><br>resource &quot;aws_s3_bucket&quot; &quot;state_s3&quot; {<br>    bucket = &quot;humangov-${var.state_name}-s3-${random_string.bucket_suffix.result}&quot;<br>    <br>    tags = {<br>        Name = &quot;humangov-${var.state_name}&quot;<br>    }       <br>}</pre><p>This is the updated <em>modules/aws_humangov_infrastructure/outputs.tf </em>file:</p><pre>output &quot;state_dynamodb_table&quot; {<br>  value = aws_dynamodb_table.state_dynamodb.name<br>}<br><br>output &quot;state_s3_bucket&quot; {<br>  value = aws_s3_bucket.state_s3.bucket<br>}</pre><p>This is the updated /<em>humangov_infrastructure/terraform/outputs.tf </em>file:</p><pre>output &quot;state_infrastructure_outputs&quot; {<br>  value = {<br>    for state, infrastructure in module.aws_humangov_infrastructure :<br>    state =&gt; {<br>      dynamodb_table = infrastructure.state_dynamodb_table<br>      s3_bucket      = infrastructure.state_s3_bucket<br>    }<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NA1b7cWl0Gy7LCfngw84XA.png" /></figure><p><strong>Step 2: Provision the AWS DynamoDB and S3 bucket using Terraform</strong></p><pre>cd ~/environment/human-gov-infrastructure/terraform/<br>terraform show<br>terraform fmt<br>terraform validate<br>terraform plan<br>terraform apply</pre><p>Take note of your outputs.</p><pre>Outputs:<br><br>state_infrastructure_outputs = {<br>  &quot;california&quot; = {<br>    &quot;dynamodb_table&quot; = &quot;humangov-california-dynamodb&quot;<br>    &quot;s3_bucket&quot; = &quot;humangov-california-s3-eq2h&quot;<br>  }<br>}</pre><p><strong>Step 3: Create a new ECS cluster named <em>humangov-ecs-cluster</em></strong></p><p>An AWS ECS cluster is a logical grouping of container instances that you manage together. Within a cluster, you can deploy multiple services and tasks. ECS clusters can span multiple Availability Zones within a region, providing high availability and fault tolerance for your containerized applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mTOIG0Uev4u9oeO0kN_jew.png" /></figure><h3>Part 3: Deploy the application by creating a service on ECS</h3><p><strong>Step 1: Create the Task Definition</strong></p><p>An AWS ECS task definition is a blueprint for our application containers. It defines various parameters such as Docker image, CPU and memory requirements, networking configuration, and more. When you run a task using ECS, you specify which task definition to use, and ECS launches the containers according to the specifications defined in that task definition.</p><p>Go to your ECS dashboard -&gt; Task Definition -&gt; Create new task definition -&gt; name it<em> humangov-fullstack</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*esuQdgCi4Z-Ziu5o_HMmPw.png" /></figure><pre>Launch type: AWS Fargate<br>Operating system/Architecture: Linux/X86_64<br>CPU: 1 vCPU<br>Memory: 3 GB<br>Task role: HumanGovECSExecutionRole<br>Task execution role: HumanGovECSExecutionRole</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EykoJzpJf9RxDN0WY_QpxQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d6o5jMhavYZdo7ATBSyovw.png" /></figure><pre>humangov-app: public.ecr.aws/r9c2d3d1/humangov-app<br>humangov-nginx: public.ecr.aws/r9c2d3d1/humangov-nginx</pre><p>Create a container for the <em>humangov-app</em> Flask app docker images we created before:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GyIFq-VM-EDCNXfAjAbjwA.png" /></figure><p>Add environment variables for the <em>humangov-app </em>container:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GwrKh5paeqDn7dpi1__5jw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qv-k58eIPlattpmXH6JnIg.png" /></figure><p>Add a container for the <em>humangov-nginx </em>docker images we created before<em>:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a2ze0NMmUaD5i12j7hxVKQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KmXCNn1fPM8tNr2YVxrC7g.png" /></figure><p><strong>Step 2: Create a service</strong></p><p>A service in ECS allows us to define long-running tasks, ensuring that a specified number of instances of a task definition are running and distributing traffic across them as needed. When you create a service, you specify the task definition to use, the desired number of tasks to run, and other configurations. The service manages the deployment and scaling of tasks based on the parameters we’ve defined, making it easier to run and manage containerized applications in ECS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*llWHxUo4R7TfYSpPOmn8Ww.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5UKxZjYKR8uBFqC4BFBKBw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J7Rbywlc0JYoVmSBjZCJDA.png" /></figure><p>Launch type: The EC2 launch type allows you to run tasks on a cluster of EC2 instances, while the Fargate launch type allows you to run tasks without managing the underlying infrastructure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t4fvR6ceCrBkyuMSp1rwYg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2RfJ1asU_J_J2htG1ikIWg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o0vTnAdFKwHUcmhYwpdbGg.png" /></figure><p>During service configuration, we selected the desired task to run as 2. Go to each task and navigate to ENI ID’s. You can see that our application is running two different availability zones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k6hg7Hm2YPY78s9H12NJfQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GDVZFstJ5p_m7EUbQBlZwA.png" /></figure><p><strong>Step 3: Open one of the task DNS to test the application</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ORtbwQY0vkpEFAJxhAFu3A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z_WhYa6KE0HL39IuBkhkBQ.png" /></figure><p><strong>Step 4: Destroy infrastructure and other resources</strong></p><pre>terraform destroy</pre><p>CONGRATULATIONS!!!</p><p>Follow me on LinkedIn</p><p><a href="https://www.linkedin.com/in/cansu-t-a5617557/">https://www.linkedin.com/in/cansu-t-a5617557/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a00121712425" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Seqera Platform Enterprise Deployment on AWS with Docker-Compose to Run Bioinformatics Pipeline…]]></title>
            <link>https://medium.com/@cansutekin23/seqera-platform-enterprise-deployment-on-aws-with-docker-compose-to-run-bioinformatics-pipeline-fc69afb87820?source=rss-3599111d902f------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc69afb87820</guid>
            <category><![CDATA[aws-batch]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[nextflow]]></category>
            <category><![CDATA[bioinformatics]]></category>
            <category><![CDATA[docker-compose]]></category>
            <dc:creator><![CDATA[Cansu Tekin]]></dc:creator>
            <pubDate>Mon, 18 Mar 2024 17:09:29 GMT</pubDate>
            <atom:updated>2024-03-18T17:15:22.770Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Seqera Platform Enterprise Deployment on AWS with Docker-Compose to Run Bioinformatics Pipeline with Nextflow Integration</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ng7RL5-y4et_7re-ckAS6A.png" /><figcaption><a href="https://install.tower.nf/">https://install.tower.nf</a></figcaption></figure><p>In the world of bioinformatics, understanding genetic data is key. That’s where the Seqera Platform comes in. It’s a web application with a microservice-oriented architecture for bioinformatics analysis. At its core, Seqera Platform integrates Nextflow, a workflow management tool, to create, deploy, and manage scalable and reproducible workflows for analyzing large datasets, particularly in genomics. It offers scalability and reproducibility to scale bioinformatics analyses across diverse computing environments while ensuring the integrity and consistency of their findings.</p><p>Seqera Platform is available in two deployment editions.</p><p><strong>1.</strong> <strong>Seqera Platform Cloud: </strong>It is hosted on Seqera Cloud. It is easy to use and set up. It’s available at <a href="https://tower.nf/login">cloud.tower.nf</a>. It contains a list of pre-built community pipelines.</p><p><strong>2.</strong> <strong>Seqera Platform Enterprise: </strong>It is for installing in an organization’s own cloud or on-premises infrastructure.</p><p>You can read more and deploy the application by following the instructions at <a href="https://install.tower.nf/">https://install.tower.nf</a></p><p><strong>PART 1: SET UP AWS PREREQUISITES FOR DOCKER-COMPOSE</strong></p><p><strong>PART 2: SEQERA PLATFORM ENTERPRISE</strong> <strong>DEPLOYMENT with DOCKER COMPOSE</strong></p><p><strong>PART 3: RUN A SIMPLE NEXTFLOW HELLO-WORLD PIPELINE to TEST</strong></p><h3><strong>PART 1: SET UP AWS PREREQUISITES FOR DOCKER-COMPOSE</strong></h3><p>We need a few AWS services ready before deployment:</p><ol><li><strong>Amazon EC2</strong></li><li><strong>Simple Mail Transfer Protocol (SMTP) Server</strong></li><li><strong>Relational Database (RDS)</strong></li><li><strong>Redis Service</strong></li><li><strong>Set up an Identity Provider for Seqera</strong></li></ol><p><strong>Step 1: Configure Amazon EC2</strong></p><p>We will deploy our Seqera application on the EC2 instance.</p><p>Create an EC2 instance with the following settings:</p><pre><br>Amazon Machine Image (AMI): Amazon Linux 2<br>Instance Type: either c5a.xlarge or c5.large — (4 CPUs and 8 GB of RAM)<br>Storage: Add 20GB root storage<br>Configure Security Group:Set connection with SSH, HTTP and port 8000<br>Attach an Elastic IP address<br>IAM profile: Create an IAM role with AWS Parameter Store Access and AWS SES Access Policies. Attach the role to the EC2 instance.<br>Create an IAM user with AdministratorAccess and Configure AWS CLI.</pre><p>IAM role with AWS Parameter Store Access and AWS SES Access Policies:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VLhVp0iWozAsA2CNJPwYjQ.png" /></figure><p>Connect to the Seqera EC2 instance with your own SSH key and public IP address (on Cloud9):</p><pre>ssh -i &quot;tower-key-pair.cer&quot; ec2-user@ec2-54-242-236-30.compute-1.amazonaws.com</pre><p>Configure AWS CLI:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*dbxDVCDexlRNzMUUcxxO2g.png" /></figure><p>Install Docker on EC2:</p><pre>sudo yum update -y<br>sudo amazon-linux-extras install docker<br>sudo service docker start<br>sudo usermod -a -G docker ec2-user<br>#restart instance<br>sudo service docker start</pre><p>Install Docker Compose:</p><pre>DOCKER_CONFIG=${DOCKER_CONFIG:-$HOME/.docker}<br>mkdir -p $DOCKER_CONFIG/cli-plugins<br>curl -SL https://github.com/docker/compose/releases/download/v2.24.6/docker-compose-linux-x86_64 -o $DOCKER_CONFIG/cli-plugins/docker-compose<br>chmod +x $DOCKER_CONFIG/cli-plugins/docker-compose<br># Confirm installations<br>docker compose version</pre><p>Retrieve the Seqera container images for the backend and frontend. We will use docker images from the Seqera Registry. At this point, you need credentials to be able to pull images from this registry. These credentials should be provided by Seqera Lab.</p><pre>sudo docker login -u &#39;xxxxxxxxxxxxx&#39; -p &#39;xxxxxxxxxxxxxx&#39; cr.seqera.io <br>sudo docker pull cr.seqera.io/private/nf-tower-enterprise/backend:v23.4.3<br>sudo docker pull cr.seqera.io/private/nf-tower-enterprise/frontend:v23.4.3 <br>docker images</pre><p><strong>Seqera platform backend </strong>is a JVM-based web application based on the Micronaut framework.</p><p><strong>Seqera platform frontend </strong>is an NGINX web server that serves the Angular application and reverse-proxies HTTP traffic to the backend</p><p><strong>Step 2: Set up Simple Mail Transfer Protocol (SMTP) Server</strong></p><p>SMTP is a communication protocol used for sending emails between servers. We will use Amazon Simple Email Service (SES). That service allows us to be notified about the pipeline runs process with the confirmed email whenever we run a pipeline using the Seqera platform.</p><p>Create SES Credentials:</p><pre><br>1. Go to the Amazon Simple Email Service console<br>2. Select SMTP Settings<br>3. Create and Download SMTP Credentials<br>4. Select and verify a new Email Address<br>5. You should receive a confirmation email from Amazon SES, confirm email address</pre><p><strong>Step 3: Relational Database (RDS)</strong></p><p>Seqera requires a SQL database. You can create your own MySQL database on AWS RDS Service. I will use MySQL docker image.</p><pre>image: mysql:8.0</pre><p><strong>Step 4:</strong> <strong>Redis Service</strong></p><p>Seqera Enterprise requires a Redis database for caching that makes web applications faster and more scalable by storing frequently accessed data in memory. It allows retrieving data quickly, reducing repeatedly fetching data from the database.</p><p>I will use a Redis docker image from the Seqera Registry.</p><pre>image: cr.seqera.io/public/redis:6.0</pre><p><strong>Step 5:</strong> <strong>Update configuration files based on your needs: tower.env, tower.yml, docker-compose.yml</strong></p><p>You can set configuration values using environment variables, a tower.yml configuration file, or individual values stored in the AWS Parameter Store.</p><p>You can download these files with default settings here: <a href="https://docs.seqera.io/assets/files/tower-9af14fb1c081a028d46dc56791efe25d.env"><strong>tower.env</strong></a><strong>, </strong><a href="http://tower.yml/"><strong>tower.yml</strong></a><strong>, </strong><a href="https://docs.seqera.io/assets/files/docker-compose-d00e0de8ffaf5450e7181a8f097da3f9.yml"><strong>docker-compose.yml</strong></a></p><p>You can find all the configuration details <a href="https://docs.seqera.io/platform/23.4.0/enterprise/configuration/overview">here</a>.</p><p><strong>Step 6: Set Up Okta identity provider for Seqera with OpenID Connect (OIDC)</strong></p><p>It allows you to use credentials from a trusted provider (the Identity Provider) to access the Seqera Platform securely. We will use Okta here. We will configure Seqera Platform Enterprise to integrate Okta to enable single sign-on (SSO) login. Configure the Seqera Platform to use OIDC for authentication and provide the necessary details (like client ID, client secret, authorization endpoint, token endpoint, etc.) from your Identity Provider. When logging into the Seqera Platform, you’ll be redirected to the login page of your Identity Provider, where you’ll enter your credentials. Once authenticated, you’ll be redirected back to the Seqera Platform, and you should be logged in successfully.</p><pre>1. Sign in to your Okta organization with your administrator account.<br>2. From the Admin Console side navigation, select Applications &gt; Applications.<br>3. Select Add Application, Create New App.<br>4. Select the OpenID Connect sign-on method, select Create.<br>5. Enter a name for your new app integration, e.g., Seqera.<br>6. In Configure OpenID Connect, add the following redirect URIs: <br>  Sign-in redirect URIs: https://&lt;YOUR HOST OR IP&gt;/oauth/callback/oidc <br>  Sign-out redirect URIs: https://&lt;YOUR HOST OR IP&gt;/logout </pre><p>Complete the setup in Seqera by adding the following environment variables to your configuration:</p><pre><br>o TOWER_OIDC_CLIENT: Copy the Client ID value from General &gt; Client Credentials for the corresponding app client configuration.<br>o TOWER_OIDC_SECRET: Copy the Client secret value from General &gt; Client Credentials for the corresponding app client configuration.<br>o TOWER_OIDC_ISSUER: Copy the Okta issuer URL from Sign On &gt; OpenID Connect ID Token for the corresponding app client configuration.<br>o TOWER_AUTH_&lt;PROVIDER&gt;_ALLOW_LIST: Replace &lt;PROVIDER&gt; in the snippets below with github, google, or oidc. oidc is used to specify any other authentication service based on OpenID Connect, such as Okta, Entra ID, Keycloak, etc. Include each provider separately if you specify more than one. The allow list entries are case-insensitive.</pre><h3><strong>PART 2: SEQERA PLATFORM ENTERPRISE</strong> <strong>DEPLOYMENT with DOCKER COMPOSE</strong></h3><p>The minimal Seqera Enterprise deployment requires only the frontend, backend, and database services.</p><p><strong>Step 1: Deploy the Seqera Enterprise with Docker-Compose</strong></p><p>After connecting the EC2 instance we created in the first part, we pulled the required images from the Seqera Registry, updated our configuration files and now we are ready to deploy our application running docker-compose.</p><pre>docker compose up</pre><p>After running compose we can check the running images:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QpzSUa20dIMOhcA-t-6qgA.png" /></figure><p><strong>Step 2: Open Seqera instance public IP</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*7jQ5AYaIJOJTzoGDDFgV-Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tBb4R1BW0_t6064FNS7Zlw.png" /></figure><h3><strong>PART 3: RUN a SIMPLE NEXTFLOW HELLO-WORLD PIPELINE to TEST</strong></h3><p>Nextflow is a workflow management system used to define and execute computational pipelines. Seqera Platform simplifies the deployment and management of Nextflow pipelines in complex computing environments, making it easier for organizations to use the power of Nextflow for scientific research and data analysis.</p><p>Nextflow supports the AWS Batch, which uses Docker containers to run tasks, for job submission in the cloud without managing a cluster of virtual machines.</p><p>We should set up a Batch compute environment, a Batch queue, an IAM user, and an S3 bucket before running a pipeline.</p><p>The GitHub repository for the pipeline will run: <a href="https://github.com/nextflow-io/hello.git">https://github.com/nextflow-io/hello.git</a></p><p><strong>Step 1: Create an AWS Batch Compute Environment Manually</strong></p><p>There are two ways to create a computing environment for AWS Batch:</p><p><strong>1. Tower Forge:</strong> Automatically creates the AWS Batch resources in your AWS account.</p><p><strong>2. Manual:</strong> Uses existing AWS Batch resources.</p><p>We will create an AWS Batch Compute environment manually here.</p><p>Nextflow requires Docker to execute tasks on AWS Batch. The ECS container agent is a component of Amazon Elastic Container Service (Amazon ECS) and is responsible for managing containers on behalf of ECS. AWS Batch uses ECS to execute containerized jobs, therefore it requires the agent to be installed on EC2 instances within your Compute Environments as well. Additionally, Nextflow requires the AWS CLI tool.</p><p>We will use specialized AMI for Nextflow: <strong>Amazon ECS-Optimized Amazon Linux 2 (AL2) x86_64 AMI</strong></p><p>The <strong>Amazon ECS-Optimized Amazon Linux 2 (AL2) x86_64 </strong>AMI is a specialized Amazon Machine Image designed specifically for running containerized applications on Amazon Elastic Container Service (ECS). It includes several pre-configured components and optimizations to enhance the performance and manageability of ECS tasks and clusters.</p><ul><li><strong>Amazon ECS Container Agent</strong>: This is the software agent that runs on ECS container instances and facilitates communication between the ECS service and the Docker daemon running on the instance. It manages tasks, registers the instance with the ECS cluster, and reports status back to ECS.</li><li><strong>Docker Engine</strong>: The AMI comes pre-installed with Docker Engine, the containerization platform used to create, deploy, and manage containers. Docker Engine is essential for running Docker containers, which are the building blocks of ECS tasks.</li><li><strong>Amazon ECS-Optimized Configuration</strong>: The AMI is pre-configured with optimizations specifically tailored for running ECS tasks efficiently. This includes tuning settings related to networking, storage, and resource allocation to maximize performance and stability.</li><li><strong>AWS CLI (Command Line Interface)</strong>: While the Amazon ECS-Optimized Amazon Linux 2 AMI includes various tools and utilities for managing ECS tasks and instances, it typically does not come pre-installed with the AWS CLI. However, you can easily install the AWS CLI on the ECS instances if needed to interact with other AWS services and resources.</li></ul><p><strong>Create a Launch template with your custom AMI:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KtlLDkk_NNVUVgn0vFxUNQ.png" /></figure><p>Create an AWS Batch Compute environment using this launch template.</p><p><em>In Step1:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*Vac7FDCZGEt2-aR1PWGsPw.png" /></figure><p>AWS Batch creates a Service role for us. It will create an Instance role named <em>ecsInstanceRole</em>. The <em>ecsInstanceRole </em>is an IAM role that you create to allow Amazon Elastic Container Service (ECS) container instances to make API calls to AWS services like CloudWatch Logs, S3, DynamoDB, and others as required by the tasks running on those instances. This role is typically used when you’re setting up an ECS cluster.</p><p>The AmazonEC2ContainerServiceforEC2Role policy must be attached to the instance role to be able to connect the EC2 instance created by the Compute Environment to the ECS container.</p><p>The AmazonEC2ContainerRegistryReadOnly policy should be attached to the instance role to get read-only access to Amazon EC2 Container Registry repositories.</p><p><em>In Step2:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*qPEaDaHFC2inCrCT19QxCQ.png" /></figure><p>Specify the newly created launch template in the corresponding field while creating a new compute environment in the Batch dashboard.</p><p>Our compute environment on AWS Batch is ready!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*slCzILO0ZfyZBQVCoY76mQ.png" /></figure><p><strong>Step 2: Create a Batch Head and Compute Queue</strong></p><p><strong>Head queue</strong>, which is the name of the AWS Batch queue that the Nextflow driver job will run.</p><p><strong>Compute queue</strong>, which is the name of the AWS Batch queue that tasks will be submitted to.</p><p>Associate queues with the previously created AWS Batch Compute Environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mgRt4PPJ4cLPGSUXsXgp7g.png" /></figure><p><strong>Step 3: Create an IAM user</strong></p><pre>IAM user with the following IAM permissions:<br>1. AmazonS3ReadOnlyAccess<br>2. AmazonEC2ContainerRegistryReadOnly<br>3. CloudWatchLogsReadOnlyAccess<br>4. We can use S3 to store intermediate and output data generated by pipelines.<br>   A custom policy is needed to grant the ability to submit and control Batch jobs.</pre><p>Custom policy:</p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;s3:ListBucket&quot;<br>            ],<br>            &quot;Resource&quot;: [<br>                &quot;arn:aws:s3:::YOUR-BUCKET-NAME&quot;<br>            ]<br>        },<br>        {<br>            &quot;Action&quot;: [<br>                &quot;s3:GetObject&quot;,<br>                &quot;s3:PutObject&quot;,<br>                &quot;s3:PutObjectTagging&quot;,<br>                &quot;s3:DeleteObject&quot;<br>            ],<br>            &quot;Resource&quot;: [<br>                &quot;arn:aws:s3:::YOUR-BUCKET-NAME/*&quot;<br>            ],<br>            &quot;Effect&quot;: &quot;Allow&quot;<br>        }<br>    ]<br>}</pre><p><strong>Step 4: Add Credentials to Seqera</strong></p><p>Credentials are the authentication keys Seqera uses to access compute environments, private code repositories, and external services.</p><p><strong>AWS Batch IAM user Credentials: </strong>Once the IAM user is created, navigate to the “Security credentials” tab for the user. Under the “Access keys” section, click on “Create access key” to generate a new access key pair (Access Key ID and Secret Access Key). We will add these credentials while creating a compute environment on the Seqera Platform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UcWyxpFAdnFC-9gdDLOdKA.png" /></figure><p><strong>GitHub Integration Credentials: </strong>Seqera Platform has built-in support to pull pipelines remotely from public and private Git providers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2l7tgZ87TkuU9QGp3hftQA.png" /></figure><p><strong>Quay Container Registry Integration Credential: </strong>Ensure all container images are accessible to AWS Batch.</p><p>The GitHub repository for the pipeline will run: <a href="https://github.com/nextflow-io/hello.git">https://github.com/nextflow-io/hello.git</a></p><p>You can see the nextflow.config file for our hello-world pipeline which uses a docker image hosted on Quay.io with the repository <strong>nextflow </strong>and the image name <strong>bash</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uCBPhEQ8_alIyA6eH1ltxw.png" /></figure><p>Nextflow script indicates that the process defined in the script should be executed within the Docker container specified by the image <strong>quay.io/nextflow/bash</strong>.</p><p><strong>Step 5: Create an organization and workspace</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*rx49cyPY0lFS-JtRo42I3A.png" /></figure><p><strong>Step 6:</strong> <strong>Create a Seqera compute environment</strong></p><p>Seqera Platform <strong>compute environments </strong>define where a pipeline will run.</p><p>We configured the required AWS resources and your user permissions and ready to create an AWS Batch compute environment in Seqera manually.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xet1U-K6D3F6mGiLkBe34w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xDTxdxntNUFOEKHjHyQcRQ.png" /></figure><p><strong>Step 7:</strong> <strong>Create and launch the pipeline under your organization</strong></p><p>A pipeline is a repository containing a Nextflow workflow, a compute environment, and pipeline parameters.</p><p>Use Launchpad to create and launch your pipeline. You can monitor and inspect workflow execution under the <em>Runs</em> tab after launching the pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rt4IzKJMU9G3SeIGSc9ZUA.png" /></figure><p>Execution monitoring:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*364EfWOil5sM4dD1ElpQ3A.png" /></figure><p>Jobs submitted to AWS Batch and succeeded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GyLINgWC_-23AnEIDsYrPQ.png" /></figure><p><strong>Email notifications regarding the run:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bFuj5RiWiGW3N4Bvvt5OGQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*0ZMy7ZpWwhE9ZqNajHSj-Q.png" /></figure><p>Follow me on LinkedIn</p><p><a href="https://www.linkedin.com/in/cansu-t-a5617557/">https://www.linkedin.com/in/cansu-t-a5617557/</a></p><p>REFERENCES</p><ul><li><a href="https://www.nextflow.io/docs/latest/">Nextflow&#39;s documentation! - Nextflow 23.10.1 documentation</a></li><li><a href="https://seqera.io/">Seqera | The modern biotech stack</a></li><li><a href="https://github.com/seqeralabs">Seqera</a></li><li><a href="https://docs.seqera.io/platform/23.4.0/">Introduction | Seqera Docs</a></li><li><a href="https://quay.io/">Quay</a></li><li><a href="https://www.okta.com/">Employee and Customer Identity Solutions | Okta</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc69afb87820" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 13 — HumanGov Application — Ansible-Final Project: Configuration and Deployment of HumanGov…]]></title>
            <link>https://medium.com/@cansutekin23/part-13-humangov-application-ansible-final-project-configuration-and-deployment-of-humangov-e8288cbc3132?source=rss-3599111d902f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8288cbc3132</guid>
            <category><![CDATA[ansible]]></category>
            <category><![CDATA[multicloud-management]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Cansu Tekin]]></dc:creator>
            <pubDate>Mon, 18 Mar 2024 03:45:12 GMT</pubDate>
            <atom:updated>2024-03-18T03:57:48.624Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 13 — HumanGov Application — Ansible-Final Project: Configuration and Deployment of HumanGov SaaS Application on AWS EC2 Inventory Across US States Using Ansible and Securily Storing Configuration Files on AWS CodeCommit</h3><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*eGVw0kjLtdYLss7ZeGIolQ.jpeg" /></figure><blockquote>The HumanGov Application is a Human Resources Management Cloud SaaS application for the Department of Education across all 50 states in the US. Whenever a state hired a new employee the registiration of the new employees will be done through the application. Their information will be stored inside AWS DynamoDB and their employment document will be stored inside S3 buckets. Check the first 10 parts where we focused on Terraform and then we focused on Ansible in the <a href="https://medium.com/@cansutekin23/part-11-humangov-application-ansible-1-configuration-management-with-ansible-a2f9b4339016">Part 11</a> and <a href="https://medium.com/@cansutekin23/part-12-humangov-application-ansible-2-playbooks-variables-conditionals-loops-roles-and-90d9cc8b5143">Part 12</a>. Now, we are going to finalize Ansible section and keep improving the application architecture with DevOps tools in the following sections.</blockquote><blockquote>In this following project series, we are going to transition the architecture from a traditional virtual machine architecture to a modern container-based architecture using Docker containers and Kubernetes running on AWS. In addition, we will also be responsible for automating the complete software delivery process using Pipelines CI/CD using AWS services such as AWS CodeCommit, AWS CodePipeline, AWS CodeBuild, and AWS CodeDeploy. Finally, we will learn how to monitor and observe the cloud environment in real-time using tools such as Prometheus, Grafana, and automate one-off cloud tasks using Python and the AWS SDK.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*0ZXASax8TElurrOM6Fs_ng.png" /></figure><p><strong><em>Summary: </em></strong>We already have Terraform configuration codes to deploy AWS infrastructure and run the HumanGov python application for the 50 states from previous parts. In this final project, we will write an Ansible role and Ansible playbook to run the HumanGov application on top of this infrastructure. We will commit and push these Ansible files to the AWS CodeCommit to keep our files in a Git repository. Additionally, we need to update our Terraform files because the application running inside the EC2 instance needs to connect to DynamoDB to store data and the S3 bucket to upload necessary files coming through the application. We should authenticate the phyton application to do these operations by assigning necessary security roles to EC2 instances. After that, we are going to deploy the HumanGov application inside the EC2 instance in parallel across all tenants’ infrastructure in a fully automated way.</p><p><strong>PART 1: Pre-requisites — Configuration of the Infrastructure with Terraform</strong></p><p><strong>PART 2: Deploy and Configure the HumanGov Application Manually</strong></p><p><strong>PART 3: Deploy the HumanGov application with Ansible</strong></p><h3>PART 1: Pre-requisites — <strong>Configuration of the Infrastructure with Terraform</strong></h3><p>Before starting heavily on the Ansible part we should have other infrastructure configurations ready for the HumanGov application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*quMR80b7KkTeUND-kEztjg.png" /></figure><p>When a new employee needs to be added to the system with the HumanGov Python application, the application will send a request to the NGINX web server running inside the EC2 instance. The NGINX is an intermediary between client devices (such as web browsers) and application servers that works as a reverse proxy allowing it to sit in front of application servers as a single entry point, forwards requests to the appropriate servers like the WSGI application server, in our case, and sends responses back to the clients. We will connect NGINX and the WSGI application server with the Unix socket in the configuration file. The application server will pass the request to the Python Flask web application. After that, the employee information will be written to the AWS DynomaDB table and the employee document will be uploaded to the S3 bucket by Python Flask Application.</p><p><strong>Step 1: Configure Cloud 9 with non-temporary credentials</strong></p><p>Cloud9 comes with temporary credentials that allow us to connect to the AWS services. We did not specify any keys for authentication while using Cloud9 so far because it comes with it. Cloud9 manages these access credentials for us. These credentials are obtained through IAM roles and have a limited duration.</p><p>The non-temporary credentials provide long-term access to AWS resources without time limitations. We need to create non-temporary credentials using the IAM module and disable the temporary credentials. That will allow us to create an IAM user with full privileges to configure the infrastructure to create the necessary architecture.</p><p>Create a new user on IAM with Admin privilege.</p><p>Go to AWS Services &gt; IAM &gt; Users &gt; Create user &gt; Next &gt; attach policies directly &gt; pick AdministratorAccess &gt; Create User</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dcnHNA8fuRQsEOBQGzy4Tg.png" /></figure><p>Go to inside of the <em>cloud9-user</em> we just created. We will create security credentials for this user to authenticate and authorize requests made to AWS services.</p><p>Security credentials tab&gt; Access keys &gt; Create access key</p><p>Select the use case as <em>Command Line Interface (CLI) </em>because<em> </em>this user will be used by Terraform to create resources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-kY--_xd_d6Yl89rVjxo-A.png" /></figure><p>Disable the temporary credentials on Cloud9 :</p><p>Settings &gt; AWS Settings &gt; Credentials &gt; Turning Off the option “AWS managed temporary credentials”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tsQ0a-76GF22YHTJBF4iYg.png" /></figure><p>Now, we can configure Cloud9 to use the user <em>cloud9-user </em>we have created which has all the privileges.</p><p>Configure the new IAM user credentials by running the <em>aws configure</em> command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KGNjPFiSHDJw-vq7DlHYuA.png" /></figure><p>It will ask for the access key and secret access key we created before. Go to the IAM Management Console, copy the keys, and paste them into the Cloud9 terminal. Cloud9 will use our user privileges now, which are AdministratorAccess privileges. It will allow Terraform to create the infrastructure we want.</p><p><strong>Step 2: Update the HumanGov Terraform module</strong></p><p>We should not have any infrastructure because we destroyed what we created before. Check if everything is fine with the terraform files. You can check all the details related to the Terraform configuration files we created in the <a href="https://medium.com/@cansutekin23/part-10-final-project-humangov-application-deployment-of-reusable-saas-multi-tenant-aws-0c1447b533f1">previous part</a> of the project series.</p><pre>cd human-gov-infrastructure/terraform<br>terraform show<br>terraform validate</pre><p>We first let Terraform create and attach the IAM role to the EC2 instances we will create. This will give privileges to EC2 instances to read data from DynamoDB and S3 bucket and write data to DynmoDB and S3 bucket. Add the IAM role code below after the last line of the file modules/aws_humangov_infrastructure/main.tf:</p><pre>resource &quot;aws_iam_role&quot; &quot;s3_dynamodb_full_access_role&quot; {<br>  name = &quot;humangov-${var.state_name}-s3_dynamodb_full_access_role&quot;<br><br>  assume_role_policy = &lt;&lt;EOF<br>{<br>  &quot;Version&quot;: &quot;2012-10-17&quot;,<br>  &quot;Statement&quot;: [<br>    {<br>      &quot;Action&quot;: &quot;sts:AssumeRole&quot;,<br>      &quot;Principal&quot;: {<br>        &quot;Service&quot;: &quot;ec2.amazonaws.com&quot;<br>      },<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Sid&quot;: &quot;&quot;<br>    }<br>  ]<br>}<br>EOF<br><br>  tags = {<br>        Name = &quot;humangov-${var.state_name}&quot;<br>  }  <br>  <br>}<br><br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;s3_full_access_role_policy_attachment&quot; {<br>  role       = aws_iam_role.s3_dynamodb_full_access_role.name<br>  policy_arn = &quot;arn:aws:iam::aws:policy/AmazonS3FullAccess&quot;<br>  <br>}<br><br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;dynamodb_full_access_role_policy_attachment&quot; {<br>  role       = aws_iam_role.s3_dynamodb_full_access_role.name<br>  policy_arn = &quot;arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess&quot;<br><br>}<br><br>resource &quot;aws_iam_instance_profile&quot; &quot;s3_dynamodb_full_access_instance_profile&quot; {<br>  name = &quot;humangov-${var.state_name}-s3_dynamodb_full_access_instance_profile&quot;<br>  role = aws_iam_role.s3_dynamodb_full_access_role.name<br><br>  tags = {<br>      Name = &quot;humangov-${var.state_name}&quot;<br>  }  <br>}</pre><p>Add the argument below to the EC2 instance resource in the file: modules/aws_humangov_infrastructure/main.tf</p><pre>iam_instance_profile = aws_iam_instance_profile.s3_dynamodb_full_access_instance_profile.name</pre><p>The EC2 instance resource will look like this after the update:</p><pre>resource &quot;aws_instance&quot; &quot;state_ec2&quot; {<br>    ami = &quot;ami-007855ac798b5175e&quot;<br>    instance_type = &quot;t2.micro&quot;<br>    key_name = &quot;humangov-ec2-key&quot;<br>    vpc_security_group_ids = [aws_security_group.state_ec2_sg.id]<br>    iam_instance_profile = aws_iam_instance_profile.s3_dynamodb_full_access_instance_profile.name<br>    <br>    tags = {<br>        Name = &quot;humangov-${var.state_name}&quot;<br>    }<br>}</pre><p>Update the security groups as below in the file: modules/aws_humangov_infrastructure/main.tf</p><pre>  ingress {<br>    from_port   = 80 #HTTP port, NGINX port to access to the HumanGov Application<br>    to_port     = 80<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br>  <br>  ingress {  # Port for Python Flask Application,optional, we may use for troubleshooting. Users will reach the application via NGINX port and pass the request to the Flask Application as we explained before. <br>    from_port   = 5000<br>    to_port     = 5000<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br><br>  ingress { # This port for Cloud9 to make SSH connection to the EC2 instance with private IP address to run Ansible.<br>    from_port   = 0<br>    to_port     = 0<br>    protocol    = &quot;-1&quot;<br>    security_groups = [&quot;&lt;YOUR_CLOUD9_SECGROUP&gt;&quot;]<br>  }<br>  <br>  egress { # This is the port allowing EC2 instance connecting to the internet and download packages required for our application like NGINX..<br>    from_port   = 0<br>    to_port     = 0<br>    protocol    = &quot;-1&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }</pre><p>Cloud9 Security Group:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EgCESYyYLhleAw0QxFsnbw.png" /></figure><p>Make sure you have a private key that will be used to make an SSH connection to the EC2 instance. We created it before with the name the <em>humangov-ec2-key. </em>Go to AWS EC2 instances &gt; Network &amp; Security &gt; Key pairs &gt; <em>humangov-ec2-key. </em>If you do not have create a new one with the same name and download it to your computer. If you have downloaded it to your computer before, upload it to the <em>humangov</em> folder inside the Cloud9 environment.</p><p><strong>Step 3: Provision the infrastructure on AWS using Terraform</strong></p><p>Go to the <em>environment/human-gov-infrastructure/terraform/</em></p><pre>terraform plan<br>terraform apply</pre><p>Terraform should create 9 resources per state. We have only one state in our state list in <em>variables.tf </em>file we created the <a href="https://medium.com/@cansutekin23/part-10-final-project-humangov-application-deployment-of-reusable-saas-multi-tenant-aws-0c1447b533f1">previous project series</a>.</p><p><strong>Step 4: Commit the changes to the local Git repository, CodeCommit</strong></p><p>You can read more <a href="https://medium.com/@cansutekin23/part-2-humangov-implementation-of-git-repositories-for-application-and-infrastructure-code-using-c46a95b272d1">here</a> about CodeCommit.</p><pre>git status<br>git add .<br>git status<br>git commit -m &quot;Added IAM Role to Terraform module aws_humangov_infrastructure/main.tf&quot;</pre><p>Push the changes to the CodeCommit repository.</p><pre>git push -u origin </pre><p>This command will give an error because we disabled managed credentials on Cloud9. It will also affect how Cloud9 authenticates CodeCommit. We will handle this error at the end of the project while pushing all the changes once we are done!</p><h3><strong>PART 2: Deploy and Configure the HumanGov Application on the AWS EC2 instance Manually</strong></h3><p><strong>Step 1: Download the Humangov application files</strong></p><p>First, we need to get Humangov application files. Go to the human-gov-application <em>git</em> folder that we created before to keep application files. It was empty so far. Download the files from the given directory. Create an src directory to store application files in it.</p><pre>cd ~/environment/human-gov-application<br>echo &quot;*.zip&quot; &gt;&gt; .gitignore<br>mkdir src <br>cd src<br>wget https://tcb-bootcamps.s3.amazonaws.com/tcb5001-devopscloud-bootcamp/v2/module4-ansible/humangov-app.zip<br>unzip humangov-app.zip</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*codqSmBSvRh58tIRNrvGWA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8KPDqOrhDmKKqujRFCOrNA.png" /></figure><p><strong>Step 2: Commit the recent changes in the Cloud9 local Git repository</strong></p><pre>git status<br>git add .<br>git add ../.gitignore<br>git commit -m &quot;HumanGov 1st commit&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dp0J1UJAQtpcqIwXoxZOiA.png" /></figure><p><strong>Step 3: Connect to the EC2 instance and configure to deploy the HumanGov Application</strong></p><pre># Connect to the EC2 instance with SSH <br>chmod 600 /home/ec2-user/environment/humangov-ec2-key.cer<br>ssh -i &quot;humangov-ec2-key.cer&quot; ubuntu@ec2-54-205-101-211.compute-1.amazonaws.com<br><br># Update and upgrade packages<br>sudo apt-get update<br>sudo apt-get upgrade -y<br><br># Install required packages for the app<br>sudo apt-get install -y nginx python3-pip python3-dev build-essential libssl-dev libffi-dev python3-setuptools python3-venv unzip<br><br># UFW (Uncomplicated Firewall) is a front-end for iptables on Linux systems.<br># It allowsspecific types of traffic that can reach the desired services on your server.<br># By default, UFW denies all incoming connections and allows all outgoing connections.<br># Allow Nginx HTTP traffic through the UFW (Uncomplicated Firewall)<br>sudo ufw allow &#39;Nginx HTTP&#39;</pre><pre># Set necessary environment variables<br>export project_path=/home/ubuntu/humangov<br>export username=ubuntu<br>export project_name=humangov<br><br># Create a project directory inside EC2 instance using environment variables you created<br>mkdir -p $project_path<br><br># Change the owner of the directory specified by $project_path to the user specified by the $username variable<br>sudo chown $username:$username $project_path<br><br># Sets the permissions to rwxr-xr-x, meaning the owner has read, write, and execute permissions, while others have only read and execute permissions.<br>sudo chmod 0755 $project_path<br><br># Create Python virtual environment within the directory specified by the $project_path variable<br># This virtual environment is isolated from the system&#39;s Python installation, <br># Allows you to install and manage Python packages specific to your project without affecting other projects or the system-wide Python installation<br>python3 -m venv $project_path/humangovenv</pre><pre># Copy the application zip file to the EC2 instance by exiting or opening a new terminal<br>scp -i /home/ec2-user/environment/humangov-ec2-key.cer /home/ec2-user/environment/human-gov-application/src/humangov-app.zip ubuntu@ip-172-31-30-181:/home/ubuntu/humangov<br><br># Unzip the application zip file, extract the contents of the ZIP file to the project path<br>unzip $project_path/humangov-app.zip -d $project_path</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*9Xa1CuEtoZXU2k3TKQR6Zg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zenbEbHHV6ZImzyOiFR2Ew.png" /></figure><pre># Install Python packages from requirements.txt into the virtual environment<br>$project_path/humangovenv/bin/pip install -r $project_path/requirements.txt</pre><p>Create a <em>systemd </em>service file for Gunicorn (replace values with yours in the template):</p><p>A <em>systemd </em>service file for Gunicorn is a configuration file that defines how Gunicorn, a popular WSGI HTTP server for Python web applications like Django or Flask, should be managed by the <em>systemd</em> init system on Linux systems.</p><pre>sudo tee /etc/systemd/system/$project_name.service &lt;&lt;EOL<br>[Unit]<br>Description=Gunicorn instance to serve $project_name<br>After=network.target<br><br>[Service]<br>User=$username<br>Group=www-data<br>WorkingDirectory=$project_path<br>Environment=&quot;PATH=$project_path/humangovenv/bin&quot;<br>Environment=&quot;AWS_REGION=us-east-1&quot;<br>Environment=&quot;AWS_DYNAMODB_TABLE=humangov-california-dynamodb&quot;<br>Environment=&quot;AWS_BUCKET=humangov-california-s3-pl32&quot;<br>Environment=&quot;US_STATE=california&quot;<br>ExecStart=$project_path/humangovenv/bin/gunicorn --workers 1 --bind unix:$project_path/$project_name.sock -m 007 $project_name:app<br><br>[Install]<br>WantedBy=multi-user.target<br>EOL</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rfmhKsnKMwhK_p1pIvkOkg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KBejY1hI1i_4GXbolyZV_g.png" /></figure><pre># Change permissions of the user’s home directory<br>sudo chmod 0755 /home/$username<br><br># Remove the default nginx configuration file<br>sudo rm /etc/nginx/sites-enabled/default</pre><p>Configure Nginx to proxy requests. The content will be written to the NGINX configuration file.</p><pre>sudo tee /etc/nginx/sites-available/$project_name &lt;&lt;EOL<br>server {<br>    listen 80;<br>    server_name $project_name www.$project_name;<br>location / {<br>        include proxy_params;<br>        proxy_pass http://unix:$project_path/$project_name.sock;<br>    }<br>}<br>EOL<br></pre><pre># Enable and start Gunicorn service<br>sudo systemctl enable $project_name<br>sudo systemctl start $project_name<br>sudo systemctl status $project_name<br><br># press q to return the main bash prompt</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6CmvGR0rkC8YXlz84yK1LA.png" /></figure><pre># Enable Nginx configuration, creates a symbolic link,it becomes easier to manage configurations, especially in environments with multiple NGINX sites. <br># NGINX typically reads its configuration files from the &quot;/etc/nginx/sites-enabled/&quot; directory.<br># /etc/nginx/sites-available/$project_name: This is the path to the NGINX site configuration file that you want to enable. $project_name is a placeholder for the name of your specific site configuration file.<br># /etc/nginx/sites-enabled/: This is the directory where enabled site configurations are stored. By creating a symbolic link here, NGINX will include the configuration from the source file in its active configuration.<br>sudo ln -s /etc/nginx/sites-available/$project_name /etc/nginx/sites-enabled/<br><br># Restart Nginx and the humangov service<br>sudo systemctl restart $project_name<br>sudo systemctl status $project_name<br>sudo systemctl restart nginx<br>sudo systemctl status nginx<br><br># pres q to return the main bash prompt</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zp9Iv-XmvspO6neHv9Tddw.png" /></figure><p><strong>Step 5: Test the HumanGov Application</strong></p><p>Go to the EC2 instance public IP address to connect to the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gsiPSzZQtSn7914wUAFWFw.png" /></figure><p>It is working!</p><p><strong>Step 6: Destroy the infrastructure using Terraform</strong></p><pre>cd ~/environment/human-gov-infrastructure/terraform<br>terraform destroy</pre><h3><strong>PART 3: Deploy the HumanGov application with Ansible</strong></h3><p>Terraform manages infrastructure provisioning, while Ansible is responsible for configuring and deploying applications on those resources.</p><p><strong>Step 1: Update Terraform files for infrastructure provisioning</strong></p><p>We keep using Terraform for infrastructure provisioning with some updates.</p><p>If Ansible is installed in your environment you should already have a default host inventory file under /etc/ansible/hosts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*m1TARjp93aiDCICb--nXYQ.png" /></figure><p>In the Cloud9 environment, we have Ansible pre-installed already. Otherwise, make sure it is installed:</p><pre># Verify whether Ansible is installed in your Cloud9 environment<br>ansible --version<br><br># Otherwise, install it<br>sudo yum install epel-release<br>sudo yum install ansible</pre><p>Create the empty Ansible inventory file on <em>/etc/ansible/hosts</em></p><pre>sudo touch /etc/ansible/hosts<br># Change the ownership of the &quot;hosts&quot; file to the user ec2-user to ensures that the ec2-user has the necessary permissions to modify the hosts file.<br>sudo chown ec2-user:ec2-user /etc/ansible/hosts<br># Recursively change the ownership of the entire &quot;/etc/ansible&quot; directory and its contents to ensure that the ec2-user has full control over the Ansible configuration directory.<br>sudo chown -R ec2-user:ec2-user /etc/ansible</pre><p>Update the module variable file, <em>modules/aws_humangov_infrastructure/variables.tf, by </em>adding the region variable to the</p><pre>variable &quot;state_name&quot; {<br>   description = &quot;The name of the US State&quot;<br>}<br>variable &quot;region&quot; {<br>  default = &quot;us-east-1&quot;<br>}</pre><p>Add <a href="https://medium.com/@cansutekin23/part-9-humangov-application-terraform-7-terraform-provisioners-5b73ba1e87b9">provisioners </a>to EC2 resource in <em>modules/aws_humangov_infrastructure/main.tf</em>. The provisioners will execute commands on the local machine during instance creation.</p><pre>resource &quot;aws_instance&quot; &quot;state_ec2&quot; {<br>    ami = &quot;ami-007855ac798b5175e&quot;<br>    instance_type = &quot;t2.micro&quot;<br>    key_name = &quot;humangov-ec2-key&quot;<br>    vpc_security_group_ids = [aws_security_group.state_ec2_sg.id]<br>    iam_instance_profile = aws_iam_instance_profile.s3_dynamodb_full_access_instance_profile.name<br>    <br>  # Add the EC2 instance&#39;s private IP address to the local machine&#39;s known_hosts file after waiting for 30 seconds.<br>  provisioner &quot;local-exec&quot; {<br>   command = &quot;sleep 30; ssh-keyscan ${self.private_ip} &gt;&gt; ~/.ssh/known_hosts&quot;<br>  }<br><br> # Append EC2 instance information to the /etc/ansible/hosts file, enabling Ansible to manage the instance.<br> provisioner &quot;local-exec&quot; {<br>   command = &quot;echo ${var.state_name} id=${self.id} ansible_host=${self.private_ip} ansible_user=ubuntu us_state=${var.state_name} aws_region=${var.region} aws_s3_bucket=${aws_s3_bucket.state_s3.bucket} aws_dynamodb_table=${aws_dynamodb_table.state_dynamodb.name} &gt;&gt; /etc/ansible/hosts&quot;<br> }<br><br> # Remove the information about the EC2 instance from the /etc/ansible/hosts file when the instance is destroyed.<br> provisioner &quot;local-exec&quot; {<br> provisioner &quot;local-exec&quot; {<br>   command = &quot;sed -i &#39;/${self.id}/d&#39; /etc/ansible/hosts&quot;<br>   when = destroy<br> }<br>    <br>    tags = {<br>        Name = &quot;humangov-${var.state_name}&quot;<br>    }<br>}</pre><p>Provision the infrastructure with updated Terraform files. I am going to do it for only two states for now. I updated the<em> human-gov-infrastructure/terraform/variable.tf</em> file</p><pre>variable &quot;states&quot; {<br>  description = &quot;A list of state names&quot;<br>  default     = [&quot;california&quot;, &quot;texas&quot;]<br>}</pre><pre>terraform fmt<br>terraform validate<br>terraform plan<br>terraform apply</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*kHzLzef-cFmmNb71BzBXiA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3euFjt9sJMsJ1CwcqtgPRA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z8nJkh7KCCIJIviHpl31-A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Ub0uUC8eKD1-6pdgJUpnw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qj_ay0mULcRH8pf0FKY8zw.png" /></figure><p><strong>Step 3: Commit and push changes to the Cloud9 local git repository</strong></p><pre>git status<br>git add .<br>git status<br>git commit -m &quot;Terraform files updated&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F-yga8gmXcCsyuuDftzasA.png" /></figure><p><strong>Step 4: Ping the instances</strong></p><p>Let’s check if our instances for California and Texas are up and running.</p><pre>ansible all -m ping -e &quot;ansible_ssh_private_key_file=/home/ec2-user/environment/humangov-ec2-key.cer&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EoxhuDiNRJFw55BSGhGB9A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ACrN6kMg0S9vD0bS5T8RJQ.png" /></figure><p><strong>Step 5: Create an Ansible role for the HumanGov Application</strong></p><p>First, create a folder to store Ansible files, then create the role files.</p><pre>cd ~/environment/human-gov-infrastructure <br>mkdir ansible<br>mkdir roles<br>ansible-galaxy init roles/humangov_webapp</pre><p>This command will create a directory with the specified role name and generate the standard role structure inside it including their main.yml files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*xQjQOGC0_PNpXbPoquxzMg.png" /></figure><p>Next, we can add the additional files we will use in this role.</p><pre>cd ansible<br>touch roles/humangov_webapp/templates/nginx.conf.j2<br>touch roles/humangov_webapp/templates/humangov.service.j2<br>touch deploy-humangov.yml</pre><p><strong>Step 6: Define the Ansible role under <em>roles/humangov_webapp </em>role with tasks and other configurations to deploy the HumanGov web application</strong></p><p><strong><em>defaults/main.yml</em></strong></p><pre>---<br>username: ubuntu<br>project_name: humangov<br>project_path: &quot;/home/{{ username }}/{{ project_name }}&quot;<br>source_application_path: /home/ec2-user/environment/human-gov-application/src</pre><p><strong><em>handlers/main.yml</em></strong></p><pre>---<br>- name: Restart Nginx<br>  systemd:<br>    name: nginx<br>    state: restarted<br>  become: yes<br>- name: Restart humangov<br>  systemd:<br>    name: humangov<br>    state: restarted<br>  become: yes</pre><p><strong><em>tasks/main.yml</em></strong></p><pre>---<br>- name: Update and upgrade apt packages<br>  apt:<br>    upgrade: dist<br>    update_cache: yes<br>  become: yes<br>- name: Install required packages<br>  apt:<br>    name:<br>      - nginx<br>      - python3-pip<br>      - python3-dev<br>      - build-essential<br>      - libssl-dev<br>      - libffi-dev<br>      - python3-setuptools<br>      - python3-venv<br>      - unzip<br>    state: present<br>  become: yes<br>- name: Ensure UFW allows Nginx HTTP traffic<br>  ufw:<br>    rule: allow<br>    name: &#39;Nginx HTTP&#39;<br>  become: yes<br>- name: Create project directory<br>  file:<br>    path: &quot;{{ project_path }}&quot;<br>    state: directory<br>    owner: &quot;{{ username }}&quot;<br>    group: &quot;{{ username }}&quot;<br>    mode: &#39;0755&#39;<br>  become: yes<br>- name: Create Python virtual environment<br>  command:<br>    cmd: python3 -m venv {{ project_path }}/humangovenv<br>    creates: &quot;{{ project_path }}/humangovenv&quot;<br>- name: Copy the application zip file to the destination<br>  copy:<br>    src: &quot;{{ source_application_path }}/humangov-app.zip&quot;<br>    dest: &quot;{{ project_path }}&quot;<br>    owner: &quot;{{ username }}&quot;<br>    group: &quot;{{ username }}&quot;<br>    mode: &#39;0644&#39;<br>  become: yes<br>- name: Unzip the application zip file<br>  unarchive:<br>    src: &quot;{{ project_path }}/humangov-app.zip&quot;<br>    dest: &quot;{{ project_path }}&quot;<br>    remote_src: yes<br>  notify: Restart humangov<br>  become: yes<br>- name: Install Python packages from requirements.txt into the virtual environment<br>  pip:<br>    requirements: &quot;{{ project_path }}/requirements.txt&quot;<br>    virtualenv: &quot;{{ project_path }}/humangovenv&quot;<br>- name: Create systemd service file for Gunicorn<br>  template:<br>    src: humangov.service.j2<br>    dest: /etc/systemd/system/{{ project_name }}.service<br>  notify: Restart humangov<br>  become: yes<br>- name: Enable and start Gunicorn service<br>  systemd:<br>    name: &quot;{{ project_name }}&quot;<br>    enabled: yes<br>    state: started<br>  become: yes<br>- name: Remove the default nginx configuration file<br>  file:<br>    path: /etc/nginx/sites-enabled/default<br>    state: absent<br>  become: yes<br>- name: Change permissions of the user&#39;s home directory<br>  file:<br>    path: &quot;/home/{{ username }}&quot;<br>    mode: &#39;0755&#39;<br>  become: yes<br>- name: Configure Nginx to proxy requests<br>  template:<br>    src: nginx.conf.j2<br>    dest: /etc/nginx/sites-available/{{ project_name }}<br>  become: yes<br>- name: Enable Nginx configuration<br>  file:<br>    src: /etc/nginx/sites-available/{{ project_name }}<br>    dest: /etc/nginx/sites-enabled/{{ project_name }}<br>    state: link<br>  notify: Restart Nginx<br>  become: yes</pre><p><strong><em>templates/humangov.service.j2: </em></strong>Jinja2 template for the Gunicorn systemd service.</p><pre>[Unit]<br>Description=Gunicorn instance to serve {{ project_name }}<br>After=network.target<br>[Service]<br>User={{ username }}<br>Group=www-data<br>WorkingDirectory={{ project_path }}<br>Environment=&quot;US_STATE={{ us_state }}&quot;<br>Environment=&quot;PATH={{ project_path }}/humangovenv/bin&quot;<br>Environment=&quot;AWS_REGION={{ aws_region }}&quot;<br>Environment=&quot;AWS_DYNAMODB_TABLE={{ aws_dynamodb_table }}&quot;<br>Environment=&quot;AWS_BUCKET={{ aws_s3_bucket }}&quot;<br>ExecStart={{ project_path }}/humangovenv/bin/gunicorn --workers 1 --bind unix:{{ project_path }}/{{ project_name }}.sock -m 007 {{ project_name }}:app<br>[Install]<br>WantedBy=multi-user.target</pre><p><strong><em>templates/nginx.conf.j2: </em></strong>Jinja2 template for the Nginx configuration</p><pre>server {<br>    listen 80;<br>    server_name humangov www.humangov;<br><br>location / {<br>        include proxy_params;<br>        proxy_pass http://unix:{{ project_path }}/{{ project_name }}.sock;<br>    }<br>}</pre><p><strong><em>deploy-humangov.yml</em></strong></p><pre>- hosts: all<br>  roles:<br>    - humangov_webapp</pre><p><strong>Step 7: Run the Ansible playbook to deploy the HumanGov Web Application</strong></p><pre>ansible-playbook deploy-humangov.yml -e &quot;ansible_ssh_private_key_file=/home/ec2-user/environment/humangov-ec2-key.cer&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*52Ltw3nWktyUEBLbVPdjeQ.png" /></figure><p><strong>Step 8:Test the HumanGov Application by opening up the Public DNS for both state</strong></p><pre>Outputs:<br><br>state_infrastructure_outputs = {<br>  &quot;california&quot; = {<br>    &quot;dynamodb_table&quot; = &quot;humangov-california-dynamodb&quot;<br>    &quot;ec2_public_dns&quot; = &quot;ec2-52-72-238-79.compute-1.amazonaws.com&quot;<br>    &quot;s3_bucket&quot; = &quot;humangov-california-s3-tw1b&quot;<br>  }<br>  &quot;texas&quot; = {<br>    &quot;dynamodb_table&quot; = &quot;humangov-texas-dynamodb&quot;<br>    &quot;ec2_public_dns&quot; = &quot;ec2-54-174-73-108.compute-1.amazonaws.com&quot;<br>    &quot;s3_bucket&quot; = &quot;humangov-texas-s3-7v5k&quot;<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZIzswQQAipO9C9fTlUPnsA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_3I-DzZ6xchUNvSIfb-1rg.png" /></figure><p>Add a new employee:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PYo3xhAxsh9A-znm63uxug.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*47ZyhhIVWBkvWzlrxSEI6g.png" /></figure><p>Check if you are able to write employee data to DynamoDB table and store employe documents in S3 bucket:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lMYkLDVqzw_3colgxK37rw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1hstqqzoYg8dLoEAU4WS1Q.png" /></figure><p><strong>Step 9: Commit and push the application source codes with the latest changes to the CodeCommit Git repository</strong></p><p><strong>Enable</strong> back the temporary credentials on Cloud9</p><p>Settings &gt; AWS Settings &gt; Credentials &gt; Turning Off the option “AWS managed temporary credentials”</p><pre># Commit and push changes to AWS Code Commit<br>cd ~/environment/human-gov-infrastructure<br>git status<br>git add .<br>git status<br>git commit -m &quot;Ansible configuration 1st commit for California and Texas&quot;<br><br>git push -u origin</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FZz04_BfCpVRmfcaYbeeMg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vZHIWlG7xb0sqtNTF3YP-w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kDKaagXyxgKd6k0WC3iHoQ.png" /></figure><pre># Push the application source code to the AWS CodeCommit remote repository<br>cd ~/environment/human-gov-application<br>git pull --rebase<br>git push -u origin</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8C4pldcHirNSSTLYNTSyKQ.png" /></figure><p><strong>Step 10: Destroy the infrastructure with Terraform</strong></p><p>First, fix the Ansible directory permission</p><pre>sudo chown -R ec2-user:ec2-user /etc/ansible<br>export AWS_ACCESS_KEY_ID=&quot;AKIAZDSAVGW7LGTR6LNZ&quot;<br>export AWS_SECRET_ACCESS_KEY=&quot;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&quot;<br><br>cd ~/environment/human-gov-infrastructure/terraform<br>terraform destroy</pre><p>CONGRATULATIONS!!!</p><p>Follow me on LinkedIn</p><p><a href="https://www.linkedin.com/in/cansu-t-a5617557/">https://www.linkedin.com/in/cansu-t-a5617557/</a></p><p>REFERENCES</p><ul><li><a href="https://thecloudbootcamp.com/en/?utm_source=&amp;utm_campaign=&amp;utm_medium=&amp;utm_content=&amp;utm_term=&amp;trk=">The Cloud Bootcamp Platform - EN</a></li><li><a href="https://www.digitalocean.com/community/tutorials/how-to-install-nginx-on-ubuntu-22-04">How To Install Nginx on Ubuntu 22.04 | DigitalOcean</a></li><li><a href="https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-gunicorn-and-nginx-on-ubuntu-22-04">How To Serve Flask Applications with Gunicorn and Nginx on Ubuntu 22.04 | DigitalOcean</a></li><li><a href="https://docs.ansible.com/ansible/latest/installation_guide/intro_installation.html?source=post_page-----a2f9b4339016--------------------------------#installing-and-upgrading-ansible">Installing Ansible - Ansible Documentation</a></li><li><a href="https://docs.ansible.com/ansible/latest/reference_appendices/config.html?source=post_page-----a2f9b4339016--------------------------------">Ansible Configuration Settings - Ansible Community Documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8288cbc3132" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 12 — HumanGov Application — Ansible-2: Playbooks, Variables, Conditionals, Loops, Roles, and…]]></title>
            <link>https://medium.com/@cansutekin23/part-12-humangov-application-ansible-2-playbooks-variables-conditionals-loops-roles-and-90d9cc8b5143?source=rss-3599111d902f------2</link>
            <guid isPermaLink="false">https://medium.com/p/90d9cc8b5143</guid>
            <category><![CDATA[ansible-roles]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[ansible]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Cansu Tekin]]></dc:creator>
            <pubDate>Tue, 30 Jan 2024 23:20:15 GMT</pubDate>
            <atom:updated>2024-01-30T23:20:15.046Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 12 — HumanGov Application — Ansible-2: Playbooks, Variables, Conditionals, Loops, Roles, and Dynamic Inventory</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*pO7DqMxMMD04-mdULwxxYA.png" /></figure><blockquote>The HumanGov Application is a Human Resources Management Cloud SaaS application for the Department of Education across all 50 states in the US. Check <a href="https://medium.com/@cansutekin23/part-11-humangov-application-ansible-1-configuration-management-with-ansible-a2f9b4339016">Part 11</a> to follow up the project series. In the first 10 part we focused on Terraform. Now, we are going to introduce Ansible and keep improving the application architecture with DevOps tools in the following sections.</blockquote><blockquote>In this following project series, we are going to transition the architecture from a traditional virtual machine architecture to a modern container-based architecture using Docker containers and Kubernetes running on AWS. In addition, we will also be responsible for automating the complete software delivery process using Pipelines CI/CD using AWS services such as AWS CodeCommit, AWS CodePipeline, AWS CodeBuild, and AWS CodeDeploy. Finally, we will learn how to monitor and observe the cloud environment in real-time using tools such as Prometheus, Grafana, and automate one-off cloud tasks using Python and the AWS SDK.</blockquote><h3>Ansible: Playbooks</h3><p>A playbook is a collection of plays. A play is a set of instructions. Playbooks are written in YAML that contain a series of tasks to be executed sequentially on remote hosts. Playbooks can be used for configuration management, application deployment, and various automation tasks. Ansible, Docker Compose, Kubernetes, and many more use YAML files.<strong> </strong>YAML is a human-readable data serialization language, commonly used for configuration files. YAML mainly has key-value pairs, lists, and dictionaries structure. It is case-sensitive and uses 2 spaces for indentation.</p><pre># key:value pair<br>hosts:webservers<br><br># List(ordered)<br>loop:          # key<br>  -package1    # value<br>  -package2    # value<br>  -package3    # value<br><br># Dictionary (Unordered)<br>firewall_rules: # key<br>  8080:tcp        # key:value<br>  22:tcp          # key:value</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*3n9EBdGzrhzm_udHOzzFVg.png" /><figcaption>Ansible Playbook example with one play</figcaption></figure><h3>Ansible: Playbook</h3><p><strong>Step 1: Provisioning host01 &amp; host02 using Terraform</strong></p><p>We will keep using AWS Cloud9. Go to AWS Services and open Cloud9.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hcUUneFXm11XiUy2c6TMTg.png" /></figure><p>We will provision infrastructure using Terraform and perform some tasks on this infrastructure using Ansible. Go to our Cloud9 ansible-tasks folder from the <a href="https://medium.com/@cansutekin23/part-11-humangov-application-ansible-1-configuration-management-with-ansible-a2f9b4339016">previous project</a>. Create a <em>main.tf</em> file. Check<a href="https://medium.com/@cansutekin23/part-10-final-project-humangov-application-deployment-of-reusable-saas-multi-tenant-aws-0c1447b533f1"> previous project series</a> to learn more about the Terraform file. We will focus on Ansible here and not touch Terraform in detail.</p><p><em>main.tf</em></p><pre>provider &quot;aws&quot; {<br>  region = &quot;us-east-1&quot;<br>}<br><br># We will use Red Hat Enterprise Linux AMI for both instances<br>resource &quot;aws_instance&quot; &quot;host01&quot; {<br>  ami           = &quot;ami-023c11a32b0207432&quot;<br>  instance_type = &quot;t2.micro&quot;<br>  key_name = &quot;tcb-ansible-key&quot;<br>  vpc_security_group_ids = [aws_security_group.secgroup.id]<br><br># Each time when we try to connect to the hosts with Ansible, we should confirm connection<br># Instead of doing this each time we can go to known_hosts file and add our hosts here. <br># We also give 30 second wait time before running the command. The instance need some<br># time to be up and running. Otherwise, the private IP address will not be created.<br># You can check running  &quot;tail ~/.ssh/known_hosts&quot; command  <br>  provisioner &quot;local-exec&quot; {<br>   command = &quot;sleep 30; ssh-keyscan ${self.private_ip} &gt;&gt; ~/.ssh/known_hosts&quot;<br>  }<br>}<br><br>resource &quot;aws_instance&quot; &quot;host02&quot; {<br>  ami           = &quot;ami-023c11a32b0207432&quot;<br>  instance_type = &quot;t2.micro&quot;<br>  key_name = &quot;tcb-ansible-key&quot;<br>  vpc_security_group_ids = [aws_security_group.secgroup.id]<br><br>  provisioner &quot;local-exec&quot; {<br>   command = &quot;sleep 30; ssh-keyscan ${self.private_ip} &gt;&gt; ~/.ssh/known_hosts&quot;<br>  }<br>}<br><br>resource &quot;aws_security_group&quot; &quot;secgroup&quot; {<br><br># To allow SSH connectivity<br>  ingress {<br>    from_port   = 22<br>    to_port     = 22<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;] # open connection only to the IP adresses you trust in your production environment<br>  }<br># To allow HTTP connectivity<br>  ingress {<br>    from_port   = 80<br>    to_port     = 80<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;] # open connection only to the IP adresses you trust in your production environment<br>  }<br><br># Allow connection from Cloud9 instance, <br># go to Cloud9 security group and grap its ID <br>  ingress {<br>    from_port   = 0<br>    to_port     = 0<br>    protocol    = &quot;-1&quot;<br>    security_groups = [&quot;&lt;YOUR_SEC_GROUP_ID&gt;&quot;]<br>  }<br><br># To allow the trafic from the EC2 instance to Inthernet <br># to connect to the Linux Repository to download the software<br> egress {<br>     from_port   = 0<br>     to_port     = 0<br>     protocol    = &quot;-1&quot;<br>     cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>   }<br><br>}<br># We need private IP address&#39; of the instances to establish Ansible connection <br># to these instances<br>output &quot;host01_private_ip&quot; {<br>  value = aws_instance.host01.private_ip<br>}<br><br>output &quot;host02_private_ip&quot; {<br>  value = aws_instance.host02.private_ip<br>}</pre><p>Here is how to find Cloud9 EC2 instance’ security group ID:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E1fidjKWyAvflX283XCsBg.png" /></figure><p>Run Terraform:</p><pre>terraform init<br>terraform plan <br>terraform apply</pre><p>Open our Ansible inventory file from <a href="https://medium.com/@cansutekin23/part-11-humangov-application-ansible-1-configuration-management-with-ansible-a2f9b4339016"><em>Part 11</em></a><em> </em>and update the hostname and host private IP addresses with the output of the <em>terraform apply</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PtQx-VP88d5AOFzU_5bX_A.png" /></figure><p><strong>Step 2: Test ping communication and SSH connectivity from the Cloud9 control node to created hosts; host01 and host02</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2YzFYDrxDSy6dEpYxh5BtQ.png" /></figure><p><strong>Step 3: Installing nginx via ad-hoc (RHEL Linux Distribution)</strong></p><pre># Update and Install &#39;nginx&#39;:<br> ansible -i hosts all -m yum -a &quot;update_cache=yes name=nginx state=latest&quot; -b<br><br># Check &#39;nginx&#39; service status:<br> ansible -i hosts all -m shell -a &quot;systemctl status nginx&quot;<br><br># Start &#39;nginx&#39;:<br> ansible -i hosts all -m shell -a &quot;systemctl start nginx&quot; -b</pre><p><strong>Step 4: Creating a Playbook file <em>install-webserver.yml </em>to install nginx</strong></p><p>Let’s repeat the same task using the Ansible playbook. Ad-hoc commands are suitable for simple tasks, but playbooks are better for managing complex scenarios. First, we need to remove the nginx we installed in the previous step.</p><pre># Remove &#39;nginx&#39;:<br>ansible -i hosts all -m yum -a &quot;name=nginx state=absent&quot; -b</pre><p>Inside of ansible-tasks folder create a file <em>install-webserver.yml</em></p><pre>- name: Installing &amp; starting nginx<br>  hosts: all<br>  become: yes<br>  tasks:<br>    - name: Installing nginx<br>      yum:<br>        update_cache: yes<br>        name: nginx<br>        state: latest<br><br>    - name: Starting nginx<br>      shell: systemctl start nginx<br><br>    - name: Enable the NGINX service during the boot process<br>      service:<br>        name: nginx<br>        enabled: yes</pre><p>You can find all this information inside <a href="https://docs.ansible.com/ansible/2.9/modules/modules_by_category.html?source=post_page-----a2f9b4339016--------------------------------">Ansible documentation</a>.</p><p>Run the Ansible Playbook to install the webserver.</p><pre>ansible-playbook install-webserver.yml</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qwM60F5nxuOp21AIm02cjw.png" /></figure><p>Check the public IP addresses of the hosts to see if nginx is installed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5UjOrIDKtIfZUuSN-TLxVA.png" /></figure><p>If you continue to hands-on later you can also stop instances right now and restart from the AWS dashboard later, or destroy the environment with Terraform</p><pre>terraform destroy</pre><h3>Ansible: Variables</h3><p>Variables are used to store and reference values that can be used throughout playbooks, templates, and other configuration files. We can define our variables in two places; the INI inventory file(<em>key=value</em>) and the YAML variable file (<em>key: value</em>). We can use Ansible predefined variables or we can create new ones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ZYPc6TdwSrqTyH_b_e3mQ.png" /><figcaption><a href="https://thecloudbootcamp.com/en/?utm_source=&amp;utm_campaign=&amp;utm_medium=&amp;utm_content=&amp;utm_term=&amp;trk=&amp;source=post_page-----a2f9b4339016--------------------------------">Source</a>: The Cloud Bootcamp Platform</figcaption></figure><p>The <em>ansible_host</em>, <em>ansible_connection</em>, and <em>ansible_user</em> are the predefined variables by Ansible while<em> http_port</em> and <em>db_port</em> are new.</p><p>We are already using variables in our host inventory file from the <a href="https://medium.com/@cansutekin23/part-11-humangov-application-ansible-1-configuration-management-with-ansible-a2f9b4339016">previous section</a>.</p><p>The<em> host</em> inventory file:</p><pre>host01 ansible_host=172.31.20.236 ansible_user=ec2-user<br>host02 ansible_host=172.31.31.243 ansible_user=ec2-user<br><br># The variables defined for all servers; host01 and host02 <br>[all:vars] <br>ansible_ssh_private_key_file=/home/ec2-user/environment/ansible-tasks/tcb-ansible-key.cer<br><br>[webservers]<br>host01</pre><p><strong>Step 1: Create a new Ansible playbook named <em>variables-example.yml</em></strong></p><p>Go to Cloud9 and create a new Ansible playbook named <em>variables-example.yml under the ansible-task </em>folder we used so far.</p><pre>- name: Example Playbook<br>  hosts: localhost  # Instead of connecting remotely to EC2 instance host, Ansible will run locally on Cloud9 control node<br>  vars:             # Where we define variables<br>    http_port: 80<br>    https_port: 443<br><br>    packages:      # Defining variable as a list<br>      - git<br>      - mysql-client<br>      - curl<br>      - wget<br><br>    appserver:      # Defining variables as a dictionary<br>      hostname: webapp01<br>      ipaddress: 192.168.1.202<br>      os: Windows Server 2019<br><br>  tasks:<br>    - name: Display the single variable<br>      debug:        # the module to display variable&#39;s values<br>        var: http_port, https_port<br><br>    - name: Display the list variable<br>      debug:<br>        var: packages<br><br>    - name: Display the dictionary variable<br>      debug:<br>        var: appserver</pre><p><strong>Step 2: Run this Ansible playbook on the Cloud9 console</strong></p><pre> ansible-playbook variables-example.yml </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A8UDzEudNXRDbyYdYqkTgw.png" /></figure><h3>Ansible: Conditionals</h3><p>Conditionals allow you to control the flow of your playbooks based on certain conditions. As an example, we are going to install software on a couple of EC2 instances at the same time, however, each instance has a different operating system. We should consider specific settings for different operating systems and will use the Ansible conditionals to set these settings automatically.</p><p>We already have a Terraform infrastructure with two Red Hat EC2 instances. We are going to add one more EC2 instance to this infrastructure with a different operating system, Debian.</p><p><strong>Step 1: Update the Terraform <em>main.tf</em> file to create a Debian EC2 instance</strong></p><p>Provision the infrastructure using Terraform and update the inventory file with Private IP accordingly. Add the code below inside the <em>main.tf</em> file.</p><pre>resource &quot;aws_instance&quot; &quot;host03&quot; {<br>  ami           = &quot;ami-058bd2d568351da34&quot; # may change, copy yours from AWS Debian Instance AMI<br>  instance_type = &quot;t2.micro&quot;<br>  key_name = &quot;tcb-ansible-key&quot;<br>  vpc_security_group_ids = [aws_security_group.secgroup.id]<br><br> provisioner &quot;local-exec&quot; {<br>   command = &quot;sleep 30; ssh-keyscan ${self.private_ip} &gt;&gt; ~/.ssh/known_hosts&quot;<br> }<br><br>}<br><br>output &quot;host03_private_ip&quot; {<br>  value = aws_instance.host03.private_ip<br>}</pre><p>Run Terraform</p><pre>terraform apply -auto-approve</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8jE4SmjxKk5erCM4Yl5tqg.png" /></figure><p>Go to the <em>host</em> inventory file and update private IP addresses and users with new ones as above.</p><p><strong>Step 2: Check if the connection to the hosts is working</strong></p><pre>ansible all -m ping </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uq4_hiF00dsJWx_w_6Djog.png" /></figure><p>Useful Ansible Ad hoc commands for exploring Ansible Facts:</p><pre>ansible host01 -m gather_facts # gather all information for host01<br>ansible host01 -m setup        # gather all information for host01<br><br>ansible host01 -m setup -a &quot;filter=ansible_distribution&quot; # get the distribution information host01 <br>ansible host02 -m setup -a &quot;filter=ansible_distribution&quot; # get the distribution information host02<br>ansible host03 -m setup -a &quot;filter=ansible_distribution&quot; # get the distribution information host03<br><br>ansible host01 -m setup -a &quot;filter=ansible_python_version&quot; # get the ansible python version host01<br>ansible host02 -m setup -a &quot;filter=ansible_python_version&quot; # get the ansible python version host02<br>ansible host03 -m setup -a &quot;filter=ansible_python_version&quot; # get the ansible python version host03<br><br>ansible all -m setup | grep -e &#39;ansible_os_family\\|ansible_python_version\\|ansible_pkg_mgr&#39;</pre><p><strong>Step 3: Install Apache on different EC2 instances using conditionals</strong></p><p>Let’s create a new playbook named <em>install-webserver-conditional.yml </em>to install Apache on different EC2 instances using conditionals.</p><pre>- name: Installing Apache<br>  hosts: all<br>  become: yes  # We nedd to be a root user to install software<br>  tasks:<br>    - name: Setup Apache - Debian # webserver for Debian<br>      apt:      # We use apt module to install packages for Debian<br>        update_cache: yes<br>        name: apache2<br>        state: present<br>      when: ansible_distribution == &#39;Debian&#39; # Get values from ansible_distribution variable from Ansible Facts, only if equals Debian, installs Apache<br><br>    - name: Setup Apache - RHEL<br>      yum:       # We use yum module to install packages for Red Hat<br>        name: httpd  # Apache Webserver for Red Hat<br>        state: present<br>      when: ansible_distribution == &#39;RedHat&#39; # Get values from ansible_distribution variable from Ansible Facts, only if equals RedHat, installs Apache</pre><p><strong>Step 4: Run the Ansible playbook on Cloud9</strong></p><pre>ansible-playbook install-webserver-conditional.yml </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3shygAC8IG3ZDz5H8llgUg.png" /></figure><p>As you can see host01 and host02 are skipped but host03 changed for task <em>Setup Apache — Debian</em>. The host03 is skipped for the task <em>Setup Apache — RHEL </em>while host01 and host02 are changed by installing Apache based on specified conditionals in the playbook.</p><p>When we run the playbook again no change will happen because of the idempotency feature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3fyQ6qLnvQcif0_XHNCUQQ.png" /></figure><p>Most of the modules in Ansible have this feature except the <em>shell</em> and <em>command</em> module.</p><pre># We did not add any task in playbook to start webserver. So, first command will fail<br>ansible host01 -m shell -a &quot;systemctl status httpd&quot; -b</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rbneRnM2KVNfvpO9iAJjpg.png" /></figure><pre># Start the webserver for host01<br>ansible host01 -m shell -a &quot;systemctl start httpd&quot; -b<br>ansible host02 -m shell -a &quot;systemctl start httpd&quot; -b</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*-5DUAlRx1iTzZLcESyGT-g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*85FhEt_HXOsoBtM-qsQgUQ.png" /></figure><p>As you can see when we use the <em>shell</em> module, the state has changed. If we run the <em>shell</em> start command again and again, its status will change every time even though Apache is already running. The idempotency feature is not valid for the <em>shell </em>module. Consider using the <em>service</em> module instead.</p><p><strong>Step 5: Check one of the hosts if it is up and running</strong></p><p>Go to AWS EC2 instances, pick one of the hosts, copy its public IP address, and paste it to your browser to see if it is up and running after you start using the <em>shell</em> module as above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6soB4Z_m0QZJCunIW3FJTg.png" /></figure><p>It is working!</p><p><strong>Step 6: Create a sample <em>index.html</em> file to create a simple webpage</strong></p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>    &lt;style&gt;<br>        body {<br>            background-color: #000000;<br>            color: #ffffff;<br>            font-family: Arial, sans-serif;<br>        }<br><br>        .container {<br>            display: flex;<br>            justify-content: center;<br>            align-items: center;<br>            height: 100vh;<br>            flex-direction: column;<br>            text-align: center;<br>        }<br><br>        img {<br>            max-width: 300px;<br>            margin-bottom: 20px;<br>        }<br>    &lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;div class=&quot;container&quot;&gt;<br>        &lt;img src=&quot;https://i.pinimg.com/originals/80/b9/59/80b959e1089aecb9bf3376a777032265.jpg&quot; alt=&quot;Your Image&quot;&gt;<br>        &lt;h1&gt;Congratulations!&lt;/h1&gt;<br>        &lt;p&gt;Keep up the good work!&lt;/p&gt;<br>    &lt;/div&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Copy this file to the host02.</p><pre>ansible host02 -m copy -a &quot;src=index.html dest=/var/www/html&quot; -b</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H-9ftnWdsaTdqxcn5PUOtQ.png" /></figure><p>Refresh your browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6gobuoq4klt7A23YqSf0oQ.png" /></figure><p><strong>Step 7: Remove the infrastructure if you are done and continue hands-on later</strong></p><pre>terraform destroy -auto-approve</pre><h3>Ansible: Loops</h3><p>In Ansible, loops are used to iterate over a set of values, such as a list or dictionary, and perform tasks repeatedly.</p><p><strong>Step 1: Create a new Ansible Playbook <em>create-files-folders.yml</em></strong></p><p>When we run the <em>create-files-folders.yml</em> playbook it will connect to each instance we created inside AWS and then create a folder and create a file inside this folder.</p><p>First, provision the infrastructure using Terraform again if you destroyed it in the previous section, and update the inventory file with Private IP accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZCZmQth5V_YlBJ4svAIEGg.png" /></figure><p>Run the Ansible Playbook:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uRPDWS_dboq2VfP_Xs52bw.png" /></figure><pre>ansible-playbook create-files-folders.yml</pre><p><strong>Step 2: Adjust the playbook to create multiple folders using “with_items” or “loop” directives</strong></p><pre>- hosts: all<br>  tasks:<br>    - name: Creating Folder<br>      file:<br>        path: /home/{{ ansible_user }}/{{ item }}<br>        state: directory<br>      with_items: # or &quot;loop:&quot;<br>        - folder01<br>        - folder02<br>        - folder03</pre><p>We can create all folders using the <em>“loop”</em> directive instead of <em>“with_items”</em> as well.</p><p>Run the Ansible Playbook:</p><pre>ansible-playbook create-files-folders.yml</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pfszViC85SXBsCYRzHXMFA.png" /></figure><p>It is connected to each host and created the files not already in there. As you remember we created one folder for each in the previous step.</p><p>Let’s go and check the created folders. Open a new terminal remotely connect to the host01 and list the content in this directory.</p><p>Cloud9 -&gt; Window -&gt; New Terminal</p><pre>ansible host01 -m shell -a &quot;ls /home/ec2-user/&quot; </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Alv2A_vn0Uze_X59JzOGqQ.png" /></figure><p>Our folders; folder01, folder02, and folder03 are here.</p><p>We can delete folders by simply changing the <em>state</em> from <em>directory</em> to <em>absent</em>.</p><p>Make changes and run the Ansible playbook again, then check host01 if the folders are removed.</p><pre>ansible-playbook create-files-folders.yml</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X6XaSLc1WBTJIk3EGmCqmw.png" /></figure><p><strong>Step 3: Create a file inside each folder</strong></p><pre>- hosts: all<br>  tasks:<br>    - name: Creating Folder<br>      file:<br>        path: /home/{{ ansible_user }}/{{ item }}<br>        state: directory #state: absent<br>      loop:<br>        - folder01<br>        - folder02<br>        - folder03<br><br>    - name: Creating files<br>      file:<br>        path: /home/{{ ansible_user }}/{{ item.dir }}/{{ item.file }}<br>        state: touch  #state: absent<br>      with_items:<br>        - { dir: &quot;folder01&quot;, file: &quot;file01&quot;}<br>        - { dir: &quot;folder02&quot;, file: &quot;file02&quot;}<br>        - { dir: &quot;folder03&quot;, file: &quot;file03&quot;}</pre><p>Run the Ansible Playbook:</p><pre>ansible-playbook create-files-folders.yml</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i422fZHsj1cOE5fHGpRUJw.png" /></figure><p>Check the other terminal where you connected to host01 if the file is created in it.</p><pre> ansible host01 -m shell -a &quot;ls /home/ec2-user/folder01/&quot; </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*NJUKH-5Gdx_ANVJJOdISWA.png" /></figure><p>Make both states in the playbook absent and run the Ansible playbook to remove all files and folders you created.</p><p><strong>Step 4: Destroy the environment with Terraform if you are done and continue hands-on later</strong></p><pre>terraform destroy -auto-approve</pre><h3>Ansible: Roles</h3><p>Ansible roles, similar to modules in Terraform, are a way to organize and structure your playbooks, making them more modular, reusable, and sharable across different projects. Roles are pieces of organized configuration for tasks, variables, and handlers that we can call from the main playbook. The basic components of Ansible roles are:</p><p><strong>Defaults: </strong>Includes default values for the variables.</p><p><strong>Files:</strong> Configuration files, scripts, or any other files needed by your application or system, that should be transferred to the host.</p><p><strong>Handlers</strong>: Tasks that will be triggered by other tasks like restarting a service or reloading configurations.</p><p><strong>Meta</strong>: Manages role metadata such as dependencies.</p><p><strong>Tasks</strong>: The main list of tasks to be run by the role.</p><p><strong>Templates</strong>: Used to generate configuration files dynamically using Jinja2 templating language.</p><p><strong>Vars</strong>: Contains variables that will be used in the role. The variable’s default values determined in the <em>Defaults </em>directory can be overwritten here if the same variable is defined in both directory files.</p><p>If you do not create a directory for the roles, its default directory is <em>/etc/ansible/roles. </em>You can modify its directory inside<em> /etc/ansible/ansible.cfg. </em>You can read more about roles from<a href="https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_reuse_roles.html"> Ansible documentation</a>.</p><p><strong>Step 1: Provision the infrastructure using Terraform and update the inventory file with Private IP accordingly</strong></p><p>Open the AWS Cloud9. If you destroyed infrastructure, provision it again and update Private IPs as we did before and also update the webservers group as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7MFzVmXgZbhfPtPMvvGfOQ.png" /></figure><p>We have a webservers group with <em>host01</em> and <em>host02</em>. We are going to create and configure a role with the all required files to perform the webserver configuration task. We can use this role whenever we need to perform the same task.</p><p><strong>Step 1: First, check if everything is working</strong></p><pre>ansible webservers -m ping</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*fgATx20H1ORGIJHl-AdZ9w.png" /></figure><p><strong>Step 2: Create a new Ansible Role</strong></p><p>We basically can create a role directory manually under our <em>ansible-tasks</em> directory. Additionally, we can use a template that comes with <em>ansible-galaxy </em>that will create a roles directory and then initialize a role inside it. Inside the <em>roles</em> folder, we will create a <em>webserver</em> folder that will build the whole role directory structure we discussed before.</p><pre><br>ansible-galaxy role init roles/webserver</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nZfvY3k4sNB5FjlU4o18_w.png" /></figure><p>As you can see, it created a <em>roles</em> folder with the role structure in it. Files inside folders are mostly empty. We will update this role based on our preferences.</p><p><strong>Step 3: Update the <em>files</em> folder by uploading the image <em>devops.png</em> to the <em>roles/webserver/files</em> folder</strong></p><p>We are going to create a webpage and this page will use the image we uploaded to the <em>files</em> directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XB1x9Jmloi3B_mSsF3ol0A.png" /></figure><p>We will use this image, if you want you can use something else. Go to the <em>files</em> directory and upload the image from your local directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cUvN1Q6MRYMmx9JTBbWcKA.png" /></figure><p><strong>Step 4: Update the file <em>roles/webserver/handlers/main.yml</em> and the file <em>roles/webserver/defaults/main.yml</em></strong></p><p>We can execute a handler whenever a state change occurs after completing a task. We will define a handler that will be called to restart Apache whenever we make an update inside the <em>index.html </em>file that we will use for our webpage. We will create the<em> Restarting Apache</em> handler and then call it inside our main Ansible file.</p><p>We also will create a <em>cloud_provider</em> variable and set the default provider value to AWS in <em>roles/webserver/defaults/main.yml</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oj5RSDaJNB5P_XOulf7BjQ.png" /></figure><p><strong>Step 5: Create a template file <em>index.html.j2</em> under <em>roles/webserver/templates</em></strong></p><p>Right-click on the template folder and create an <em>index.html.j2 </em>file in it. With the <strong><em>.j2</em></strong><em> </em>extension,<em> </em>Ansible accepts it as a template file.</p><p>This role will deploy a webserver. We will push an <em>index.html</em> file to the webserver to see it as a webpage. Some of the content on this webpage will be dynamic. This template will use the role variables we defined in the previous step to make it dynamic.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>  &lt;style&gt;<br>    body {<br>      background-color: #000;<br>      color: #fff;<br>      display: flex;<br>      justify-content: center;<br>      align-items: center;<br>      height: 100vh;<br>      margin: 0;<br>      font-family: Arial, sans-serif;<br>    }<br><br>    .content {<br>      text-align: center;<br>    }<br>  &lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>  &lt;div class=&quot;content&quot;&gt;<br>    &lt;b&gt; Hello!&lt;/b&gt;<br><br>    &lt;h1&gt; This is a webserver running in an EC2 Instance: {{ ansible_hostname }}&lt;/h1&gt; <br>    &lt;h4&gt; Powered by {{ cloud_provider }}&lt;/h4&gt;<br><br>    &lt;img src=&quot;devops.png&quot; alt=&quot;DevOps Image&quot;&gt;<br>  &lt;/div&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p><em>{{ ansible_hostname}}</em> grabs the value of the <em>ansible_hostname</em> variable from ansible facts.</p><p><em>{{ cloud_provider}} </em>grabs<em> </em>value of<em> </em>the<em> cloud_provider </em>variable from the file <em>roles/webserver/defaults/main.yml</em> we defined before.</p><p>Finally, this template will use the <em>devops.png</em> image we uploaded inside the file directory.</p><p><strong>Step 6: Update the file <em>roles/webserver/tasks/main.yml</em></strong></p><p>These are the tasks to be performed by role. We will define them as we did with the playbook before. You already know the <em>Installing Apache</em> and the <em>Starting Apache</em> tasks.</p><pre>- name: Installing Apache<br>  yum:<br>    name: httpd<br>    state: present<br><br>- name: Starting Apache<br>  service:<br>    name: httpd<br>    state: started<br>    enabled: true<br><br>- name: Copying files<br>  copy: src=devops.png dest=/var/www/html/ # Root directory of the Apache webserver <br><br>- name: Generating Template<br>  template:<br>    src: index.html.j2<br>    dest: /var/www/html/index.html #This template will generate a index.html file<br>  notify:<br>    - Restarting Apache</pre><p>In the <em>Copying files</em> task, we will copy our image inside the role <em>files</em> directory to the root directory of the Apache webserver.</p><p>The <em>Generating Template </em>task will generate an <em>index.html</em> file in a defined destination, the Apache root directory, using the <em>index.html.j2 </em>template. While generating this file, it will replace the dynamic variables (<em>ansible_hostname</em> and <em>cloud_provider</em>) in <em>index.html.j2 </em>inside the <em>template</em> directory with their defined values. After doing that, we need to restart Apache. Instead of determining a new task, we can simply use a handler here because we want to restart the Apache only when changes are applied to the<em> index.html</em> file. Go to the <em>handler/main.yml file</em> and copy the name of the handle we defined before for this purpose.</p><p><strong>Step 7: Create a main playbook <em>setup-webserver-roles.yml</em> to execute the role</strong></p><p>We should create a playbook outside the roles folder. Create a file named <em>setup-webserver-roles.yml</em> inside ansible-tasks directory.</p><pre>- name: Setting up Apache as Webserver<br>  hosts: webservers<br>  become: true<br>  roles:<br>    - webserver</pre><p><strong>Step 8: Run the Ansible playbook</strong></p><pre>ansible-playbook setup-webserver-roles.yml</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pGZef68xgE96Fj13A0FpCg.png" /></figure><p>Step 9: Test the website access using the host02 public IP address</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yXt_MH1WfxZRdaFRWoIwgQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_1UvTnojByRIMb_oyyx34w.png" /></figure><p>Well Done!</p><p><strong>Step 9: Destroy the infrastructure using Terraform</strong></p><pre>cd ansible-tasks<br>terraform destroy -auto-approve</pre><p>CONGRATULATIONS!</p><p>Follow me on LinkedIn: <a href="https://www.linkedin.com/in/cansu-t-a5617557/">https://www.linkedin.com/in/cansu-t-a5617557/</a></p><p>REFERENCES</p><ul><li><a href="https://docs.ansible.com/ansible/latest/collections/ansible/builtin/file_module.html">ansible.builtin.file module - Manage files and file properties - Ansible Documentation</a></li><li><a href="https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_reuse_roles.html">Roles - Ansible Documentation</a></li><li><a href="https://thecloudbootcamp.com/en/?utm_source=&amp;utm_campaign=&amp;utm_medium=&amp;utm_content=&amp;utm_term=&amp;trk=&amp;source=post_page-----a2f9b4339016--------------------------------">The Cloud Bootcamp Platform - EN</a></li><li><a href="https://galaxy.ansible.com/">Ansible Galaxy</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90d9cc8b5143" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 11 — HumanGov Application — Ansible-1: Configuration Management with Ansible]]></title>
            <link>https://medium.com/@cansutekin23/part-11-humangov-application-ansible-1-configuration-management-with-ansible-a2f9b4339016?source=rss-3599111d902f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2f9b4339016</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[multicloud-management]]></category>
            <category><![CDATA[ansible]]></category>
            <dc:creator><![CDATA[Cansu Tekin]]></dc:creator>
            <pubDate>Wed, 03 Jan 2024 19:00:10 GMT</pubDate>
            <atom:updated>2024-01-03T20:15:50.382Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 11 — HumanGov Application — Ansible-1: Configuration Management with Ansible</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*pO7DqMxMMD04-mdULwxxYA.png" /></figure><blockquote>The HumanGov Application is a Human Resources Management Cloud SaaS application for the Department of Education across all 50 states in the US. Check <a href="https://medium.com/@cansutekin23/part-10-final-project-humangov-application-deployment-of-reusable-saas-multi-tenant-aws-0c1447b533f1">Part 10</a> to follow up the project series. In the first 10 part we focused on Terraform. Now, we are going to introduce Ansible and keep improving the application architecture with DevOps tools in the following sections.</blockquote><blockquote>In this following project series, we are going to transition the architecture from a traditional virtual machine architecture to a modern container-based architecture using Docker containers and Kubernetes running on AWS. In addition, we will also be responsible for automating the complete software delivery process using Pipelines CI/CD using AWS services such as AWS CodeCommit, AWS CodePipeline, AWS CodeBuild, and AWS CodeDeploy. Finally, we will learn how to monitor and observe the cloud environment in real-time using tools such as Prometheus, Grafana, and automate one-off cloud tasks using Python and the AWS SDK.</blockquote><p>In the previous section, we used the Terraform to provision infrastructure with ease. In this section, we are going to provision the application to run inside the EC2 instances for each state and look at where Ansible fits in our HumanGov SaaS project. As you know from previous sections, each state has its own infrastructure. None of the resources are shared among the states. For example, each state has its own EC2 instance to run the application. Inside the EC2 instance, each state will have an application server to serve only the state it belongs to. Now, we need a way to deploy the application for all 50 states and configure the hosts in a scalable way that is prone to human errors. Instead of doing this manually, we will use Ansible to manage the configuration in a fully automated way.</p><h3><strong>Configuration Management</strong></h3><p>Configuration Management is a process of maintaining computer systems, servers, and software in a desired consistent state. It refers to the process of systematically handling changes to a system in a way that maintains integrity over time. Ansible as a configuration management tool is in use to automate repetitive tasks, ensure consistency across systems, and streamline the management of infrastructure and applications.</p><p>Configuration Management Benefits:</p><ul><li>Reduces the time and effort required to manage systems</li><li>Ensures test and production environment matches</li><li>Minimizes human errors</li><li>Quick restoration from failures or mistakes with the ability to roll back to a previous state</li><li>Ease of scaling such as adding new servers or resources automatically and consistently across the environment</li><li>Enforce security policies and compliance standards across the entire infrastructure</li></ul><h3>Configuration Management: Ansible</h3><p>Ansible is an open-source configuration management tool for application deployment, task automation, orchestration, cloud provisioning, security, and compliance. Ansible is agentless, meaning it doesn’t require the installation of any software. It uses SSH to connect to systems and execute tasks. It is written in a declarative language, YAML, which is easy to read and write. It also has a large collection of built-in modules to perform the tasks.</p><p><strong>Ansible Architecture:</strong></p><p>Ansible architecture is composed of Ansible’s Automation Engine which is software that runs Ansible. It has inventory, API, modules, and plugins inside.</p><ul><li>Ansible inventory file uses hosts and groups. Hosts in the inventory file specify the hosts on which Ansible connects and executes tasks. It lists the IP addresses of the target hosts. The groups can group similar servers inside a group allowing us to run Ansible commands only on these particular servers. Ansible comes with two default groups; all and ungroup. The all group includes all the hosts inside the inventory file. The ungroup group includes all the hosts that are not part of any group. You can create an inventory file in your directory. Otherwise, Ansible searches for it in the default place for the inventory file; <em>/etc/ansible/hosts</em>.</li></ul><p>Ansible inventory file:</p><pre># individual hosts<br>[webservers]<br>web1 ansible_host=192.168.1.10 ansible_user=myuser http_port=80<br><br>[dbservers]<br>db1 ansible_host=192.168.1.20 ansible_user=myuser db_port=3306<br><br># groups of hosts<br>[production]<br>web1<br>db1<br>lb1</pre><ul><li>The Ansible API(Application Programming Interface) allows external programs or scripts to interact with Ansible. For example; REST API (HTTP API) and Ansible Python API. We will talk about them in detail later.</li><li>Ansible modules are a block of reusable codes that carry specific actions, such as managing files, installing packages, or configuring services on hosts. For example, if we want to install a web server inside the host, EC2 instance, we will use a module for that. System administration and configuration modules(ping, user, cron, service), package management modules(apt, yum, homebrew), file modules(copy, templete, unarchive), user and group modules(user, group, win_user), database modules(mysql_db, postgresql_db), networking modules(ios_facts, ios_command), cloud modules(ec2, azure_tm, gcp), container modules(docker_container, docker_image), security modules(authorized_key) are the some common modules.</li><li>Ansible plugins provide additional features, integrations, or customizations that are not provided by Ansible modules.</li><li>Ansible playbook is written in YAML to perform configuration tasks. Key components of an Ansible playbook include hosts, tasks, modules, handlers, variables, conditionals, loops, and roles. Hosts specify the target hosts on which tasks will be executed. Tasks describe a series of actions to be performed on the target hosts. Modules are used within tasks to perform specific actions on the target hosts. Handlers are often used to trigger action tasks that are executed only if notified by other tasks. Variables provide a way to store and manage data more flexibly and in a reusable way. Conditionals allow you to control the execution of the task based on specific conditions. Loops allow you to repeat tasks multiple times. Roles are a way to organize and package related tasks, handlers, and variables into reusable components.</li><li>Ansible facts are collected information from managed hosts during the execution of the playbook such as operation system, IP addresses, and hostname.</li><li>ansible.cfg file is the main Ansible configuration file.</li><li>Ad-hoc commands are CLI commands used for simple one-time tasks and use the /user/bin/ansible command line tool. We run the commands directly from the command line without using playbooks. The ad-hoc command below runs on the webserver group and module yum to install the HTTPD package on all the webserver groups.</li></ul><pre># binary    inventory   module    module arguments<br>#           host/group<br>  ansible   webserver   -m yum   -a &quot;name=httpd state=latest&quot;</pre><p>Lastly, Ansible is idempotent; executing the same Ansible playbook multiple times has the same result if there are no changes to apply. It performs the same action only once.</p><h3>Hands-on: ANSIBLE</h3><h3>Part 1: Getting Started with Ansible</h3><p><strong>Step 1: Cloud9 Environment Preparation</strong></p><p>We will keep using AWS Cloud9. Go to AWS Services and open Cloud9.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fZ1MQcB8RTDXNM4Mlg6Sqg.png" /></figure><p>Cloud9 runs on an EC2 instance. We first need to install Ansible on the Cloud9 EC2 instance. We will create two EC2 instances on AWS. We will use those EC2 instances as managed nodes.</p><p>Go to EC2 instances on AWS and make sure you have only Cloud9 the EC2 instance running. Clean up EC2 instances and Security Groups (if any) except the ones below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Es8-D2aJBDr64taaeR2PnQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jTUHdtQQ61TU-nlOXVdrjQ.png" /></figure><p>Create 2 AWS EC2:</p><pre>**Instances specifications:**<br><br>- `host01`: Debian [based on Debian Linux Distribution] - &#39;admin&#39; user<br>- `host02`: RHEL [based on Red Hat Enterprise Linux Distribution] - &#39;ec2-user&#39; user<br><br>- SSH Key: &#39;tcb-ansible-key&#39;<br>- VPC Default<br>- Security group: launch-wizard-1 (SSH/22)</pre><ul><li>host01:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BDnYA5XLTRmgBjchL55dMQ.png" /></figure><p>Create a key pair on the same page: We will use this SSH to connect to the EC2 instance. Ansible will use this key to establish a remote connection to these instances.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aE9dDZg_XTVPDwNCaKPLFA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*Vw3D-6Vtm9L5xfYwYT9XTQ.png" /></figure><p>We will allow access to this instance from anywhere, just for hands-on purposes here. Do not do this for your production environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5u10V76p9ByyvJ1mi51KUA.png" /></figure><p>Then launch the first instance.</p><ul><li>host02:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j_KdCSh8FnJOGwUiAr8Htg.png" /></figure><p>For this time, we will not create a new key pair and security group. Instead, we will use the one that we created for host01.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f_O3cW5OzHGIbxpxKwy3bw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ovj3scPphexHdf9N5kMAsA.png" /></figure><p>Launch instance. Now, we have two EC2 instances created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dVF8BomeIBZfkdoOoW3hwg.png" /></figure><p><strong>Step 2: Installing Python3, Pip3 and Ansible at Cloud9 control node</strong></p><p>Before we install Ansible onto Cloud9, we first should install the prerequisites because we will use Cloud9 to run Ansible. Ansible is created in Python. Python3 should be installed on Cloud9 to be able to run Ansible. Check the Python and PIP versions on the control node (Cloud9). Python must be present across all nodes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gXeJHp-sod2IMOmuddExDg.png" /></figure><p>As you can see, Python3 and pip3 are installed already but Ansible is not. Update the OS and install Python and PIP if needed:</p><pre>sudo yum update -y<br>sudo yum install python<br>sudo yum install pip</pre><p>Install Ansible:</p><p>We will use Ansible <a href="https://docs.ansible.com/">documentation</a> for everything here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uul8yNtCqZWlDUOpxEI-nQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_4rCsJ43GlEYtY8y0s6ZPg.png" /></figure><p><strong>Step 3: Testing EC2 ping communication and EC2 SSH connectivity from the Cloud9 control node to the managed targets</strong></p><p>Now, we are going to connect from the Cloud9 host to the target hosts, host01 and host02, to perform some tasks using Ansible. Before we work with Ansible we need to test ping communication and SSH connectivity. The ping checks the reachability of hosts and verifies that Ansible can communicate with them.</p><p>Go to host01 and host02, copy their private IP address, and test ping communication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KefUoSlgPeFLavpckTFBKw.png" /><figcaption>host01</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IMUIPU5s1qeP9O7-NFG2JA.png" /><figcaption>host02</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*bH9BheamMP-_zoE9EPqxxQ.png" /></figure><p>Instances are not answering ping requests because Cloud9 and instances are not able to talk to each other. The security group does not have a rule allowing the Cloud9 to reach the host01 and host02 instances. We need to add a security rule to the security group for that. We will allow the traffic coming from Cloud9 to host01 and host02.</p><p>Under the security, only port 22 is allowed. No internal traffic coming from Cloud9 is allowed yet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QlB9THVEShkKaYQIuzIiwQ.png" /></figure><p>Click the security groups,<em> launch-wizard-1</em>, and edit the inbound rules:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lxlhfaQRrv8-HXeI7pN83A.png" /></figure><p>We will add a new rule that allows all the inbound traffic on host01 and host02 from the security group associated with Cloud9.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1GLSVcLYClS0_AY7Qx4kKw.png" /></figure><p>Now, we should be able to ping and connect over SSH. Let&#39;s go and check.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NM2yPnLAbeQFhsAzUL2sFw.png" /></figure><p>It is working! The same thing should apply to host02 as well because both of them use the same security group. You can stop the ping command with <em>control + C.</em></p><p>Let&#39;s check if SSH connectivity is also working. Upload the private key to Cloud9 under <em>/home/ec2-user/environment</em>.</p><p>Cloud9 -&gt; File -&gt; Upload Local Files -&gt; upload the certificate we created (<em>tcb-ansible-key.pem</em>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MpzBBwp2AgjqEHpuMcL52g.png" /></figure><p>Test the SSH connection with host01 and host02 private IP addresses.</p><pre>ssh -i tcb-ansible-key.pem admin@PRIVATE-IP_host01</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4YnJcMzmdgESR81BN5ldAQ.png" /></figure><p>You can find how to connect to the host01 EC2 instance under the <em>Connect</em> tab as shown above. We should permit the key file first. Otherwise, we will get a warning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vjpONot1V0NrgjXTJ8sh4g.png" /></figure><p>We got a warning! Let&#39;s do it again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TUwGI9BQY4UkKggPA9F9yQ.png" /></figure><p>It worked. We are in! Repeat the same process for host02 as well. host01 is a Debian instance, host02 is a Red Hat instance. Therefore, the SSH connectivity command is not the same. Our user names are different; host01 user name -&gt; <em>admin</em> and host02 user name -&gt; <em>root </em>or <em>ec2-user.</em></p><pre>chmod 400 tcb-ansible-key.cer<br>ssh -i tcb-ansible-key.cer admin@172.31.86.156<br>ssh -i tcb-ansible-key.cer ec2-user@172.31.90.116</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rXQmISSAVsHafBrlGlpRrw.png" /></figure><h3>Part 2: Ansible Inventory, Ad-hoc &amp; Configuration</h3><p><strong>Step 1: Create an Inventory File</strong></p><p>Open Cloud9, create a folder ansible-tasks, create an inventory file called <em>hosts</em> inside of ansible-tasks folder, and insert the Private IPs of the Hosts (host01 and host02) inside of the hosts file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aVL-MD9bkvd-Cmzzx-N2tw.png" /></figure><p><strong>Step 2: Test ‘ping’ module using Ansible ‘Ad-hoc Command’</strong></p><p>Let’s test the connectivity to the managed hosts using Ansible module ping:</p><pre>ansible -i hosts all -m ping</pre><p>You will see a permission denied error. We are not able to connect the hosts because we did not specify the username and the SSH key. The ping module is not only checking if instances are alive but also trying to establish SSH connectivity. It does not know how to connect without an SSH key and user name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eIa-SXNpxlULcZr1tZm4YQ.png" /></figure><p>Let’s inform the SSH Key:</p><pre># move the key first to the current directory<br>mv ../tcb-ansible-key.cer .<br>ansible -i hosts all -m ping -e &quot;ansible_ssh_private_key_file=tcb-ansible-key.cer&quot;</pre><p>We will still get the same error but only for one instance for this time. We are trying to connect two different hosts at the same time. The SSH key is the same for both but the user name is different. The user name is <em>admin</em> for the Debian instance and <em>ec2-user</em> for the Red Hat instance. As you can see, our Cloud9 user name is also <em>ec2-user. </em>Therefore, it successfully connects to the Red Hat instance with ping but the Debian instance does not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iL8irvXUP1GSFdwuJkMxYA.png" /></figure><p>Let&#39;s edit the inventory file. We can specify the SSH key here for all hosts instead of specifying it on the command line. We can also create a webservers group with host01:</p><pre>host01 ansible_host=172.31.86.156 ansible_user=admin<br>host02 ansible_host=172.31.90.116 ansible_user=ec2-user<br><br>[all:vars]<br>ansible_ssh_private_key_file=/home/ec2-user/environment/ansible-tasks/tcb-ansible-key.cer<br><br>[webservers]<br>host01</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-T2PsxIW6HbMnJFWcjZmfw.png" /><figcaption>ping over all hosts vs ping over the webservers group</figcaption></figure><p><strong>Step 3: Ansible Configuration file</strong></p><p>You can read <a href="https://docs.ansible.com/ansible/latest/reference_appendices/config.html">here</a> about the Ansible configuration file.</p><p>Generate a sample ansible.cfg file under the same directory and copy-paste the content of the <a href="https://github.com/ansible/ansible/blob/stable-2.9/examples/ansible.cfg">GitHub example file</a> content here. As an example, we can remove warnings by modifying the configuration file. Everything is commented out for now. We can uncomment related place. Change <em>deprecation_warnings = True</em> to <em>deprecation_warnings = False.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L1KNN3CwWLpG2Q_Cnf6-uw.png" /></figure><p>As you can see, the deprecation warning disappeared!</p><p>Let&#39;s set up the ‘ping’ module as the default module and the ‘host’ inventory file path:</p><pre>[defaults]<br>module_name=ping<br><br>[defaults]<br>inventory=/etc/ansible/hosts, /home/ec2-user/environment/ansible-tasks</pre><p>It runs the ping module on the command line as default without specifying:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FngZ0TF08Q04rLSmzoFMKQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qp_c5bYMmE1taN3ZrQEX4w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iBCnBRsNNTGltV7VY-hh8A.png" /></figure><h3>Part 3: Ansible Modules</h3><p>You can read <a href="https://docs.ansible.com/ansible/2.9/modules/modules_by_category.html">here</a> more about modules using Ansible documentation. Always refer to the <a href="https://docs.ansible.com/ansible/2.9/index.html">official Ansible documentation</a> for the most up-to-date and accurate information.</p><p>First, we need to make sure that our instances are working. Run ping module commands below to check as we did before:</p><pre>ansible -i hosts host01 -m ping<br>ansible -i hosts host02 -m ping</pre><p><strong>Step 1: Exploring the command module</strong></p><p>You can check the command module documentation <a href="https://docs.ansible.com/ansible/2.9/modules/command_module.html#command-module">here</a>. We will use this module frequently. Ansible will connect to the target hosts via SSH and run commands that allow the execution of shell commands on those targets.</p><p>date: The current date of the remote host</p><p>df -kh: Disk space information of the remote hosts</p><p>/etc/os-release: Retrieve the operating system information from/etc/os-release</p><pre># -i:inventory file name, -m:module name -a:argument of the module<br>ansible -i hosts host01 -m command -a &quot;date&quot;<br>ansible -i hosts host01 -m command -a &quot;df -kh&quot;<br>ansible -i hosts host01 -m command -a &quot;cat /etc/os-release&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AB99NB4B961kaoIR1I5_JA.png" /></figure><p><strong>Step 2: Exploring the apt module</strong></p><p>The apt module is specifically designed to manage packages, repositories, and package-related tasks on Debian and Ubuntu-based systems. Let&#39;s use this module to install the web server Apache to one of our hosts as an example. Before installing any package we should update the cache first. Every time we install a package or update the cache, we need to run the command as a root user for permission to perform this task.</p><pre># -become or -b is to run command as a root user<br>ansible -i hosts host01 -m apt -a &quot;update_cache=yes name=apache2 state=latest&quot; -b</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g7r_Rr-WzNx2ien6Pbp1zg.png" /></figure><p>We can do the same thing for many machines. This is an extremely useful and powerful way for installing and managing packages.</p><p>Get the public IP address of the host01 from instances under AWS and access the instance to check if Apache is installed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QsLg_uHIcbvVSERwTZ02wQ.png" /></figure><p>In the first place, we will not be able to access to the web server. First, we need to add port 80 to the Security Group we created before (<em>launch-wizard-1</em>). Otherwise, HTTP access stays blocked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dRtatJKnIOSwZPqqxX-g1A.png" /></figure><p>Now can access and check if Apache is installed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GET8WQnPttCG1LHbN9hNxw.png" /></figure><p><strong>Step 3: Exploring the module service and shell</strong></p><pre># Checking, Stopping and Starting the Apache service<br>ansible -i hosts host01 -m shell -a &quot;systemctl status apache2&quot;<br>ansible -i hosts host01 -m shell -a &quot;systemctl stop apache2&quot; -b</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0JZaad8FUHKFGANSbzxIEA.png" /></figure><p>We cannot connect to the server anymore because we stopped.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NIrmgHpZRj1pwDjduoou7Q.png" /></figure><pre># restart the Apache Service<br>ansible -i hosts host01 -m service -a &quot;name=apache2 state=started&quot; -b</pre><p><strong>Step 4: Exploring the copy and file module</strong></p><pre># Create a dummy file inside ansible-tasks folder<br>echo &quot;This is an example file&quot; &gt;&gt; dump</pre><p>Copy this dump file to all instances with Ansible.</p><pre>#check if the files is already inside hosts, we do not want to overwrite anything<br>ansible -i hosts all -m command -a &#39;ls /tmp/dump&#39;<br>#copy the file to all hosts<br>ansible -i hosts all -m copy -a &quot;src=dump dest=/tmp&quot;<br>#check again<br>ansible -i hosts all -m command -a &#39;ls /tmp/dump&#39;<br>#print file content inside host01<br>ansible -i hosts host01 -m command -a &quot;cat /tmp/dump&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qqT7Xg6NcX3QpqJU0oGIvA.png" /></figure><pre># Delete the &#39;dump&#39; file <br>ansible -i hosts all -m file -a &#39;path=/tmp/dump state=absent&#39;</pre><p><strong>Step 5: Destroy the resources</strong></p><p>If you are doing only for learning practices do not forget to destroy the resources you created. Otherwise, AWS keeps you charging for running resources. Terminate host01 and host02 instances on the AWS management console.</p><p>CONGRATULATIONS!!!</p><p>Follow me on LinkedIn</p><p><a href="https://www.linkedin.com/in/cansu-t-a5617557/">https://www.linkedin.com/in/cansu-t-a5617557/</a></p><p>REFERENCES</p><ul><li><a href="https://thecloudbootcamp.com/en/?utm_source=&amp;utm_campaign=&amp;utm_medium=&amp;utm_content=&amp;utm_term=&amp;trk=">The Cloud Bootcamp Platform - EN</a></li><li><a href="https://docs.ansible.com/ansible/latest/installation_guide/intro_installation.html#installing-and-upgrading-ansible">Installing Ansible - Ansible Community Documentation</a></li><li><a href="https://docs.ansible.com/ansible/latest/reference_appendices/config.html">Ansible Configuration Settings - Ansible Documentation</a></li><li><a href="https://github.com/ansible/ansible/blob/stable-2.9/examples/ansible.cfg">ansible/examples/ansible.cfg at stable-2.9 · ansible/ansible</a></li><li><a href="https://docs.ansible.com/ansible/2.9/modules/modules_by_category.html">Using Ansible modules and plugins - Ansible Documentation</a></li><li><a href="https://docs.ansible.com/ansible/2.9/modules/apt_module.html#apt-module">ansible.builtin.apt module - Manages apt-packages - Ansible Documentation</a></li><li><a href="https://docs.ansible.com/ansible/2.9/modules/service_module.html#service-module">ansible.builtin.service module - Manage services - Ansible Documentation</a></li><li><a href="https://docs.ansible.com/ansible/latest/collections/ansible/builtin/copy_module.html">ansible.builtin.copy module - Copy files to remote locations - Ansible Documentation</a></li><li><a href="https://docs.ansible.com/ansible/latest/collections/ansible/builtin/file_module.html">ansible.builtin.file module - Manage files and file properties - Ansible Documentation</a></li><li><a href="https://docs.ansible.com/ansible/2.9/modules/command_module.html#command-module">ansible.builtin.command module - Execute commands on targets - Ansible Documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2f9b4339016" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>