<?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 manojkumar on Medium]]></title>
        <description><![CDATA[Stories by manojkumar on Medium]]></description>
        <link>https://medium.com/@akulamanojkumar988?source=rss-100b6452cd9c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*zrIS5rlpePQTTCv9</url>
            <title>Stories by manojkumar on Medium</title>
            <link>https://medium.com/@akulamanojkumar988?source=rss-100b6452cd9c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 10:34:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@akulamanojkumar988/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[CI/CD for our Fullstack Project with Jenkins(Basics)]]></title>
            <link>https://medium.com/@akulamanojkumar988/ci-cd-for-our-fullstack-project-with-jenkins-basics-bb33f51f3e56?source=rss-100b6452cd9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb33f51f3e56</guid>
            <category><![CDATA[full-stack]]></category>
            <category><![CDATA[pipeline]]></category>
            <category><![CDATA[jenkins]]></category>
            <dc:creator><![CDATA[manojkumar]]></dc:creator>
            <pubDate>Fri, 21 Mar 2025 11:33:52 GMT</pubDate>
            <atom:updated>2025-03-21T11:33:52.875Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/316/1*taihP7EIdsl4SCnQn-Z4Jw.jpeg" /><figcaption><strong>CI\CD End to End Pipeline</strong></figcaption></figure><p>In the fast-paced world of software development, ensuring that your code is always in a deployable state is crucial. Continuous Integration and Continuous Deployment (CI/CD) practices help achieve this by automating the build, test, and deployment processes. For a fullstack project, which includes both frontend and backend components, setting up a Jenkins pipeline can significantly enhance your workflow. This article will guide you through creating an attractive and efficient Jenkinsfile for a fullstack project using Next.js for the frontend and Node.js for the backend.</p><h3>Why CI/CD Matters</h3><p>CI/CD pipelines are the backbone of modern development practices. They ensure that every change to your codebase is automatically tested and deployed, reducing the risk of integration issues and speeding up the delivery process. By automating these steps, you can focus more on writing code and less on manual deployment tasks.</p><h3>Project Structure</h3><p>Let’s assume your project has the following structure:</p><pre>/your-fullstack-project<br>|-- /frontend<br>|   |-- package.json<br>|   |-- next.config.js<br>|-- /backend<br>|   |-- package.json<br>|   |-- server.js<br>|-- Jenkinsfile</pre><h3>Crafting the Perfect Jenkinsfile</h3><p>Here’s a Jenkinsfile that covers the CI/CD pipeline for both the frontend and backend parts of your project:</p><pre>pipeline {<br>    agent any</pre><pre>    environment {<br>        NODE_ENV = &#39;production&#39;<br>    }</pre><pre>    stages {<br>        stage(&#39;Checkout&#39;) {<br>            steps {<br>                // Checkout the code from the repository<br>                git &#39;https://github.com/your-repo/your-fullstack-project.git&#39;<br>            }<br>        }<br>        stage(&#39;Install Frontend Dependencies&#39;) {<br>            steps {<br>                dir(&#39;frontend&#39;) {<br>                    sh &#39;npm install&#39;<br>                }<br>            }<br>        }<br>        stage(&#39;Install Backend Dependencies&#39;) {<br>            steps {<br>                dir(&#39;backend&#39;) {<br>                    sh &#39;npm install&#39;<br>                }<br>            }<br>        }<br>        stage(&#39;Build Frontend&#39;) {<br>            steps {<br>                dir(&#39;frontend&#39;) {<br>                    sh &#39;npm run build&#39;<br>                }<br>            }<br>        }<br>        stage(&#39;Test Frontend&#39;) {<br>            steps {<br>                dir(&#39;frontend&#39;) {<br>                    sh &#39;npm test&#39;<br>                }<br>            }<br>        }<br>        stage(&#39;Test Backend&#39;) {<br>            steps {<br>                dir(&#39;backend&#39;) {<br>                    sh &#39;npm test&#39;<br>                }<br>            }<br>        }<br>        stage(&#39;Deploy&#39;) {<br>            steps {<br>                // Deploy the frontend and backend<br>                dir(&#39;frontend&#39;) {<br>                    sh &#39;npm run deploy&#39;<br>                }<br>                dir(&#39;backend&#39;) {<br>                    sh &#39;npm run deploy&#39;<br>                }<br>            }<br>        }<br>    }<br>}</pre><h3>Breaking Down the Jenkinsfile</h3><ol><li>Checkout: This stage checks out the code from your Git repository.</li><li>Install Frontend Dependencies: Installs the necessary Node.js dependencies for the frontend.</li><li>Install Backend Dependencies: Installs the necessary Node.js dependencies for the backend.</li><li>Build Frontend: Builds the Next.js application.</li><li>Test Frontend: Runs tests for the frontend.</li><li>Test Backend: Runs tests for the backend.</li><li>Deploy: Deploys both the frontend and backend applications.</li></ol><h3>Customizing Your Pipeline</h3><ul><li>Repository URL: Replace &#39;https://github.com/your-repo/your-fullstack-project.git&#39; with your actual repository URL.</li><li>Deployment Steps: Customize the deployment steps according to your deployment strategy. This could involve copying files to a server, running Docker commands, or using a cloud service.</li></ul><h3>The Benefits of Automation</h3><p>By setting up a Jenkins pipeline with a well-defined Jenkinsfile, you can automate the CI/CD process for your fullstack project. This ensures that every code change is automatically built, tested, and deployed, leading to faster and more reliable software delivery. Automation not only saves time but also reduces the risk of human error, making your development process more efficient and robust.</p><h3>Conclusion</h3><p>Implementing a CI/CD pipeline with Jenkins for your fullstack project can transform your development workflow. With automated builds, tests, and deployments, you can ensure that your application is always in a deployable state. This Jenkinsfile serves as a starting point, and you can adapt it to fit the specific needs of your project. Embrace the power of automation and watch your productivity soar!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb33f51f3e56" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SSL vs TLS]]></title>
            <link>https://medium.com/@akulamanojkumar988/ssl-vs-tls-20b72cef303f?source=rss-100b6452cd9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/20b72cef303f</guid>
            <category><![CDATA[tls]]></category>
            <category><![CDATA[ssl-certificate]]></category>
            <dc:creator><![CDATA[manojkumar]]></dc:creator>
            <pubDate>Fri, 07 Jun 2024 16:13:51 GMT</pubDate>
            <atom:updated>2024-06-07T16:13:51.325Z</atom:updated>
            <content:encoded><![CDATA[<p>Transport Layer Security (TLS) and Secure Sockets Layer (SSL) are cryptographic protocols designed to provide secure communication over a computer network. Although SSL is the predecessor to TLS, both are commonly referred to in the context of securing web communications. Here’s a breakdown of their differences and similarities:</p><h3>SSL (Secure Sockets Layer)</h3><ul><li><strong>Developed By</strong>: Netscape</li><li><strong>Versions</strong>: SSL 1.0, SSL 2.0, SSL 3.0 (SSL 1.0 was never publicly released)</li><li><strong>Status</strong>: Deprecated</li><li><strong>Security</strong>: Known to have several vulnerabilities; therefore, it’s not recommended for use</li><li><strong>Usage</strong>: SSL was widely used in the early days of the internet but has since been replaced by TLS</li></ul><h3>TLS (Transport Layer Security)</h3><ul><li><strong>Developed By</strong>: Internet Engineering Task Force (IETF)</li><li><strong>Versions</strong>: TLS 1.0, TLS 1.1, TLS 1.2, TLS 1.3</li><li><strong>Status</strong>: Actively maintained and updated</li><li><strong>Security</strong>: Considered secure when using the latest versions (especially TLS 1.2 and TLS 1.3)</li><li><strong>Usage</strong>: Currently the standard for securing web communications, such as HTTPS, email, and other protocols</li></ul><h3>Key Differences</h3><ol><li><strong>Development and Standardization</strong>:</li></ol><ul><li>SSL was developed by Netscape.</li><li>TLS is developed and maintained by the IETF.</li></ul><ol><li><strong>Protocol Versions</strong>:</li></ol><ul><li>SSL has older versions (SSL 1.0, 2.0, 3.0) which are now obsolete.</li><li>TLS versions start from TLS 1.0 up to the current TLS 1.3.</li></ul><ol><li><strong>Security Enhancements</strong>:</li></ol><ul><li>TLS includes more robust security measures and encryption algorithms.</li><li>TLS 1.2 and 1.3 have significant improvements over previous versions, offering better performance and stronger security.</li></ul><ol><li><strong>Handshake Process</strong>:</li></ol><ul><li>While the handshake processes in SSL and TLS are conceptually similar, TLS has more secure and optimized processes.</li></ul><h3>Certificates</h3><ul><li><strong>SSL Certificates</strong>: Historically, certificates issued to secure websites were called SSL certificates. However, this term persists out of tradition, even though these certificates are used with TLS.</li><li><strong>TLS Certificates</strong>: Technically, all modern “SSL certificates” are TLS certificates because they use TLS protocols.</li></ul><h3>Modern Usage</h3><ul><li><strong>SSL/TLS Certificates</strong>: Regardless of whether they are called SSL or TLS certificates, modern certificates support TLS protocols.</li><li><strong>Adoption</strong>: Most servers and browsers have moved to support TLS, and using anything lower than TLS 1.2 is generally not recommended.</li></ul><h3>Conclusion</h3><p>While SSL and TLS are often mentioned together, it’s important to use the latest TLS versions (1.2 or 1.3) to ensure secure communications. When people refer to “SSL certificates” today, they are actually referring to certificates that support the TLS protocol.</p><p>The structure of SSL and TLS protocols can be understood through their layered architecture and the steps involved in their handshake processes. Here’s a detailed overview of the structure of SSL and TLS:</p><h3>SSL/TLS Protocol Architecture</h3><ol><li><strong>Application Layer</strong>:</li></ol><p>The layer where application protocols like HTTP, FTP, SMTP, etc., operate. SSL/TLS works to secure these application protocols.</p><p><strong>2. Record Layer</strong>:</p><ul><li><strong>Fragmentation</strong>: Messages are fragmented into manageable blocks.</li><li><strong>Compression</strong> (optional): Data can be compressed to save bandwidth.</li><li><strong>MAC (Message Authentication Code)</strong>: Ensures data integrity.</li><li><strong>Encryption</strong>: Fragments are encrypted before transmission.</li><li><strong>Record Protocol</strong>: Manages the communication of messages.</li></ul><ol><li><strong>Handshake Layer</strong>:Handles the negotiation of security parameters and establishment of a secure session.</li><li><strong>Change Cipher Spec Layer</strong>:A simple protocol to signal that the following records will be protected under a newly negotiated CipherSpec and keys.</li><li><strong>Alert Protocol</strong>:Communicates alerts for errors or other conditions that require attention.</li></ol><h3>SSL/TLS Handshake Process</h3><h4>SSL Handshake Process</h4><p>The SSL handshake involves the following steps:</p><ol><li><strong>ClientHello</strong>:</li></ol><ul><li>The client sends a “ClientHello” message to the server, initiating the handshake. This message includes:</li><li>SSL version</li><li>Cipher suites supported by the client</li><li>Randomly generated data</li><li>Compression methods</li></ul><p><strong>2.ServerHello</strong>:</p><ul><li>The server responds with a “ServerHello” message, which includes:</li><li>SSL version selected</li><li>Cipher suite chosen by the server</li><li>Randomly generated data</li><li>Session ID</li></ul><p><strong>3.Server Certificate</strong>:</p><ul><li>The server sends its digital certificate to the client for authentication.</li></ul><p><strong>4.Server Key Exchange</strong> (if necessary):</p><ul><li>The server sends key exchange information if the selected cipher suite requires it.</li></ul><p><strong>5.Certificate Request</strong> (optional):</p><ul><li>The server requests a certificate from the client to authenticate the client (for mutual authentication).</li></ul><p><strong>6.ServerHello Done</strong>:</p><ul><li>The server signals the end of the “ServerHello” phase.</li></ul><p><strong>7.Client Certificate</strong> (if requested):</p><ul><li>The client sends its certificate to the server.</li></ul><p><strong>8.Client Key Exchange</strong>:</p><ul><li>The client sends key exchange information (such as the pre-master secret).</li></ul><p><strong>9.Certificate Verify</strong> (if client certificate was sent):</p><ul><li>The client sends a digitally signed message to verify its certificate.</li></ul><p><strong>10.Change Cipher Spec</strong>:</p><ul><li>Both the client and server send a “Change Cipher Spec” message to indicate that subsequent messages will be encrypted.</li></ul><p><strong>11.Finished</strong>:</p><ul><li>Both the client and server send a “Finished” message, indicating the completion of the handshake.</li></ul><h4>TLS Handshake Process</h4><p>The TLS handshake is similar to the SSL handshake but with some enhancements:</p><ol><li><strong>ClientHello</strong>:</li></ol><ul><li>The client sends a “ClientHello” message with additional supported extensions and cipher suites.</li></ul><p><strong>2.ServerHello</strong>:</p><ul><li>The server responds with a “ServerHello” message, similar to SSL, but may include additional extensions.</li></ul><p><strong>3.Server Certificate</strong>:</p><ul><li>The server sends its certificate to the client.</li></ul><p><strong>4.Server Key Exchange</strong>:</p><ul><li>Required for some key exchange algorithms.</li></ul><p><strong>5.Certificate Request</strong> (optional):</p><ul><li>For mutual authentication, the server may request a client certificate.</li></ul><p><strong>6.ServerHello Done</strong>:</p><ul><li>Signals the end of the server hello phase.</li></ul><p><strong>7.Client Certificate</strong> (if requested):</p><ul><li>The client sends its certificate.</li></ul><p><strong>8.Client Key Exchange</strong>:</p><ul><li>The client sends the pre-master secret.</li></ul><ol><li><strong>9.Certificate Verify</strong> (if client certificate was sent):</li></ol><ul><li>The client verifies its certificate.</li></ul><p><strong>10.Change Cipher Spec</strong>:</p><ul><li>Indicates that subsequent messages will be encrypted with the negotiated cipher suite.</li></ul><p><strong>11.Finished</strong>:</p><ul><li>Both the client and server send a “Finished” message, completing the handshake.</li></ul><h3>Key Differences in SSL and TLS Handshake</h3><ul><li><strong>Message Integrity</strong>: TLS uses HMAC for message integrity, which is more secure compared to the MAC used in SSL.</li><li><strong>Key Material Generation</strong>: TLS improves the generation of key material.</li><li><strong>Alert Messages</strong>: TLS has more detailed alert messages.</li><li><strong>Supported Algorithms</strong>: TLS supports more modern and secure cryptographic algorithms.</li></ul><h3>Diagram</h3><pre>+--------------------+<br>|    Application     |<br>+--------------------+<br>|      Handshake     |<br>+--------------------+<br>|   Change Cipher    |<br>|       Spec         |<br>+--------------------+<br>|       Alerts       |<br>+--------------------+<br>|       Record       |<br>+--------------------+<br>|       TCP/IP       |<br>+--------------------+</pre><p>In summary, while SSL and TLS share similar structures, TLS offers enhanced security features and improvements over SSL, making it the preferred protocol for secure communications.</p><p>#DevOps #AWS #kubernetes</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20b72cef303f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Step-by-Step on Deploying a Kubernetes application using Terraform, EKS Cluster and Jenkins.]]></title>
            <link>https://medium.com/@akulamanojkumar988/a-step-by-step-on-deploying-a-kubernetes-application-using-terraform-eks-cluster-and-jenkins-5b04fd9cf6ac?source=rss-100b6452cd9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b04fd9cf6ac</guid>
            <dc:creator><![CDATA[manojkumar]]></dc:creator>
            <pubDate>Sat, 18 May 2024 04:20:34 GMT</pubDate>
            <atom:updated>2024-05-18T04:20:34.904Z</atom:updated>
            <content:encoded><![CDATA[<p>This is an end-to-end project to deploy a Nginx web server through Jenkins and Kubernetes, using Terraform. What we will build will have this structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/0*6Webs7_wNXVXVXiH.jpeg" /></figure><p>To do this, we will follow several steps:</p><ol><li>Create an EC2 key pair</li><li>Create a Jenkins server and install all the dependencies</li><li>Access and setup the Jenkins server</li><li>Run the Jenkins pipeline to deploy to EKS. In particular it will create a Kubernetes cluster and then we will create a deployment in that cluster, to deploy the Kubernetes Services, in particular we will deploy just Nginx and run it as a Service</li><li>Test the application to make sure it’s running</li><li>Clean up and destroy all resources</li></ol><p>In the real world usually the deployment happens in multiple environments, typically in 3 environments:</p><ul><li>a dev environment</li><li>a test environment</li><li>a production environment</li></ul><p>This project is just one environment deployment, so we will have just a dev environment. Here is the repository with the source code:</p><p><a href="https://github.com/manoj9885762348/jenkins-pipeline">GitHub - manoj9885762348/jenkins-pipeline</a></p><h3>Step 1: create a keypair</h3><p>The first thing you have to do is to create a new keypair. So in the AWS management console go to “EC2” and select “Key pairs” in the listed overview of your resources:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nkKAU2CBPL68wnbh.png" /></figure><p>Then select “Create key pair” on the top-right corner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/0*jNhC7EiNEMhrWLjq.png" /></figure><p>Give a name to the keypair and select as key file format “.pem”, then select “Create key pair” and save it in a new folder for this project, if you haven’t created it yet.</p><h3>Step 2: create the projects folders</h3><p>In your project folder you can follow the structure of the code of my repository, you can also directly fork the repository if you prefer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/0*6H7HhiCwOw0wstnF.png" /></figure><p>The structure is the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eReXFNahiLjUUPn-.png" /></figure><p>Now I will dive in and explain the content each folder.</p><h3>Step 3: setup Jenkins server</h3><p>Here I will explain what the code inside “1-terraform-jenkins-server” does.</p><p>However the first thing that we need to do is to create an S3 bucket that will be used as the Terraform state file storage. Make sure to be consistent with the AWS region you choose, for example for all the project I will always use “eu-west-3”, so I’m creating an S3 bucket on this region. If you plan to use another AWS region, ensure to replace “eu-west-3” anywhere in the code with your region.</p><p>So we create the bucket and ensure that we choose a unique name for the bucket, I will call it “jenkins-app-kub-2024-v2” but choose a different name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/0*UPjR3kl0ykfrFtX1.png" /></figure><p>Now let’s go back to the folder ““1-terraform-jenkins-server”.</p><p>In the file “provider.tf” we ensure that Terraform uses the specified version of the AWS provider and operates within the “eu-west-3” region when interacting with AWS resources. Choose the same AWS region of the backend S3 bucket. Here is the snippet:</p><pre># provider.tf</pre><pre>terraform {<br>  required_providers {<br>    aws = {<br>      source  = &quot;hashicorp/aws&quot;<br>      version = &quot;4.52.0&quot;<br>    }<br>  }<br>}</pre><pre>provider &quot;aws&quot; {<br>  region = &quot;eu-west-3&quot;<br>}</pre><p>In “variables.tf” we define all the variables that we need throughout the proget:</p><pre># variables.tf</pre><pre>variable &quot;vpc_cidr_block&quot; {}<br>variable &quot;subnet_cidr_block&quot; {}<br>variable &quot;avail_zone&quot; {}<br>variable &quot;env_prefix&quot; {}<br>variable &quot;instance_type&quot; {}</pre><p>And then in “terraform.tfvars” we provide the values that we want to assign to the variables:</p><pre># terraform.tfvars<br>vpc_cidr_block      = &quot;10.0.0.0/16&quot; # VPC address<br>subnet_cidr_block   = &quot;10.0.10.0/24&quot; # subnet address<br>availability_zone   = &quot;eu-west-3a&quot; # availability zone (change it according to your AWS region)<br>env_prefix          = &quot;dev&quot; # prefix for tags<br>instance_type       = &quot;t2.small&quot; # EC2 instance type</pre><p>In the file “backend.tf” we configure the backend to use the S3 bucket created before, where Terraform can store its state file centrally. The state file keeps track of the resources that Terraform manages and their current state. This is also important for collaboration among team members and ensuring consistent infrastructure management:</p><pre># backend.tf</pre><pre>terraform {<br>  # Configuring Terraform backend to store state file in an S3 bucket<br>  backend &quot;s3&quot; {<br>    # Specify the name of the S3 bucket to store the state file<br>    bucket = &quot;jensins-kubernetes-app-2024-v2&quot;<br>    # Specify the AWS region where the bucket is located<br>    region = &quot;eu-west-3&quot;<br>    # Specify the path within the bucket to store the state file<br>    key = &quot;jenkins-server/terraform.tfstate&quot;<br>  }<br>}</pre><p>In “server.tf” we define an Amazon Linux Image (AMI) and the EC2 instance that will use it. The EC2 instance is our Jenkins server:</p><pre># server.tf</pre><pre># Fetch the latest Amazon Linux Image (AMI) owned by AWS<br>data &quot;aws_ami&quot; &quot;latest-amazon-linux-image&quot; {<br>  most_recent = true<br>  owners      = [&quot;amazon&quot;]<br>  filter {<br>    name   = &quot;name&quot;<br>    values = [&quot;amzn2-ami-hvm-*-x86_64-gp2&quot;]<br>  }<br>  filter {<br>    name   = &quot;virtualization-type&quot;<br>    values = [&quot;hvm&quot;]<br>  }<br>}</pre><pre># Define the Jenkins server<br>resource &quot;aws_instance&quot; &quot;jenkins-server&quot; {<br>  # Specify the AMI id defined above<br>  ami                         = data.aws_ami.latest-amazon-linux-image.id<br>  instance_type               = var.instance_type<br>  key_name                    = &quot;jenkins-server-demo&quot;<br>  subnet_id                   = aws_subnet.jenkins-subnet-1.id<br>  vpc_security_group_ids      = [aws_default_security_group.jenkins-sg.id]<br>  availability_zone           = var.availability_zone<br>  associate_public_ip_address = true<br>  # Specify a script to be executed when the instance is launched<br>  user_data                   = file(&quot;jenkins-script.sh&quot;)<br>  tags = {<br>    Name = &quot;${var.env_prefix}-server&quot;<br>  }<br>}</pre><p>In “jenkins-script.sh” we define a list of commands to install and start all the required services and packages:</p><pre>#!/bin/bash</pre><pre># install jenkins</pre><pre>sudo yum update<br>sudo wget -O /etc/yum.repos.d/jenkins.repo \<br>    <a href="https://pkg.jenkins.io/redhat-stable/jenkins.repo">https://pkg.jenkins.io/redhat-stable/jenkins.repo</a><br>sudo rpm --import <a href="https://pkg.jenkins.io/redhat-stable/jenkins.io-2023.key">https://pkg.jenkins.io/redhat-stable/jenkins.io-2023.key</a><br>sudo yum upgrade -y<br>sudo amazon-linux-extras install java-openjdk11 -y<br>sudo yum install jenkins -y<br>sudo systemctl enable jenkins<br>sudo systemctl start jenkins</pre><pre># install git<br>sudo yum install git -y</pre><pre># install terraform</pre><pre>sudo yum install -y yum-utils<br>sudo yum-config-manager --add-repo <a href="https://rpm.releases.hashicorp.com/AmazonLinux/hashicorp.repo">https://rpm.releases.hashicorp.com/AmazonLinux/hashicorp.repo</a><br>sudo yum -y install terraform</pre><pre># install kubectl</pre><pre>sudo curl -LO <a href="https://storage.googleapis.com/kubernetes-release/release/v1.23.6/bin/linux/amd64/kubectl">https://storage.googleapis.com/kubernetes-release/release/v1.23.6/bin/linux/amd64/kubectl</a><br>sudo chmod +x ./kubectl<br>sudo mkdir -p $HOME/bin &amp;&amp; sudo cp ./kubectl $HOME/bin/kubectl &amp;&amp; export PATH=$PATH:$HOME/bin</pre><p>In “outputs.tf” we tell Terraform that we want to print to the console the address of the EC2 instance once it is launched:</p><pre># Output in the terminal the address of the Jenkins server, once it&#39;s created<br>output &quot;ec2_public_ip&quot; {<br>  value = aws_instance.myapp-server.public_ip<br>}</pre><p>In “vpc.tf” we define the VPC and a private subnet:</p><pre>resource &quot;aws_vpc&quot; &quot;my-vpc&quot; {<br>  cidr_block = var.vpc_cidr_block<br>  tags = {<br>    Name = &quot;${var.env_prefix}-vpc&quot;<br>  }<br>}</pre><pre>resource &quot;aws_subnet&quot; &quot;jenkins-subnet-1&quot; {<br>  vpc_id            = aws_vpc.my-vpc.id<br>  cidr_block        = var.subnet_cidr_block<br>  availability_zone = var.availability_zone<br>  map_public_ip_on_launch = false # this makes the subnet private<br>  tags = {<br>    Name = &quot;${var.env_prefix}-subnet-1&quot;<br>  }<br>}</pre><p>In “route.tf” we define an Internet Gateway and the default route table for our VPC:</p><ul><li>The Internet Gateway allows communication between the EC2 instance (the Jenkins server) in your VPC and the Internet, without this your EC2 instance in your subnet would not have access to the Internet</li><li>A default route table is automatically created for our VPC, here we are associating the Internet Gateway with the default route (route block) which states: “Any traffic destined to the Internet (0.0.0.0/0) will be routed through the Internet Gateway”.</li></ul><pre># route.tf</pre><pre># Internet Gateway<br>resource &quot;aws_internet_gateway&quot; &quot;my-igw&quot; {<br>  vpc_id = aws_vpc.myapp-vpc.id<br>  tags = {<br>    Name = &quot;${var.env_prefix}-igw&quot;<br>  }<br>}</pre><pre># Default Route Table<br>resource &quot;aws_default_route_table&quot; &quot;my-route-table&quot; {<br>  default_route_table_id = aws_vpc.my-vpc.default_route_table_id<br>  route {<br>    cidr_block = &quot;0.0.0.0/0&quot;<br>    gateway_id = aws_internet_gateway.my-igw.id<br>  }<br>  tags = {<br>    Name = &quot;${var.env_prefix}-route-table&quot;<br>  }<br>}</pre><p>In “security.tf” we define a Security Group for our Jenkins server, allowing SSH access and :</p><pre># security.tf</pre><pre># Security Group of the Jenkins server<br>resource &quot;aws_default_security_group&quot; &quot;jenkins-sg&quot; {<br>  vpc_id = aws_vpc.my-vpc.id</pre><pre>  # Allow inbound TCP traffic on port 22 (SSH) from any source <br>  ingress {<br>    from_port   = 22<br>    to_port     = 22<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>    ipv6_cidr_blocks = [&quot;::/0&quot;]<br>  }<br>  <br>  # Allow inbound TCP traffic on port 8080 (Jenkins) from any source.<br>  # This is the default port for Jenkins, so we open it to the Internet<br>  # because we will access it from a web browser<br>  ingress {<br>    from_port   = 8080<br>    to_port     = 8080<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>    ipv6_cidr_blocks = [&quot;::/0&quot;]<br>  }</pre><pre>  # Allow all outbound traffic to any destination<br>  egress {<br>    from_port   = 0<br>    to_port     = 0<br>    protocol    = &quot;-1&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>    ipv6_cidr_blocks = [&quot;::/0&quot;]<br>  }<br>  tags = {<br>    Name = &quot;${var.env_prefix}-default-sg&quot;<br>  }<br>}</pre><p>We have finished commenting this part of the project. Now, if you haven’t already done it, deploy this infrastructure by running these commands in the terminal, make sure you are in the right folder (jenkins-server):</p><pre>terraform init<br>terraform plan<br>terraform apply</pre><p>After running all the commands, make a note of the public IP address of your Jenkins server, which will be printed in the console.</p><p>Now, paste this IP address into your web browser’s address bar, followed by ‘:8080’. The Jenkins server welcome page should show up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PwvHKbuNfRCeK0B_.png" /></figure><p>To access to our Jenkins server, we need a password. So we first connect to our EC2 instance through SSH, make sure that your terminal is opened in the same folder as the key you downloaded before (.pem file) when creating the key pair. So, run the following command to connect to the EC2 instance:</p><pre>ssh -i &quot;jenkins-server.pem&quot; ec2-user@1.234.567.89</pre><p>In the above command, ensure that you replace ‘jenkins-server.pem’ with the name of your key pair and “1.234.567.89” with the public IP you noted earlier.</p><p>After running it, type “yes” and press Enter.</p><p>Once you are connected to the EC2 instance, run:</p><pre>sudo cat /var/lib/jenkins/secrets/initialAdminPassword</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JmNzKTDlXArUWH3S.png" /></figure><p>You will get a password. Copy it and then paste it in the field “Administrator password” in the Jenkins welcome screen and then click on Continue:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OIC-pr0CUVTA7eGa.png" /></figure><p>Then, select “Install suggested plugins”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*L4ef7oeWv15xHBsH.png" /></figure><p>It will take a while, but it will install everything you need.</p><p>Next it will ask you to create the first admin user: assign a username, a password, a full name and your e-mail address.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yeL6s8ufoD1ImtGZ.png" /></figure><p>Then click on “Save and Continue”.</p><p>Now it will show the Jenkins URL, the field is already filled in so we click on “Save and Finish” and we are done!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*F2cFoHoF-PAfe2Aq.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WnAQ7uuYU479NWXI.png" /></figure><p>The next thing is to add our GitHub credentials to the Jenkins server. So click on “Manage Jenkins” on the left. Then select “Manage Credentials” under Security:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RR4IeJpKuetNDJK7.png" /></figure><p>Then select “(global)”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/0*GpdNdjkdSWDqPFP0.png" /></figure><p>Then click on the button “Add Credentials”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ow9cfmfIF_vJoRQi.png" /></figure><p>In this form you need to select “Username with password” in the kind field and insert your GitHub username and password and give a random ID that can be your username as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sZMUJVgulRY1pX2w.png" /></figure><p>Then we want to allow Jenkins to access our AWS environment, so we need to add the credentials to our AWS account, in particular the AWS Access Key and AWS Secret Key. If you don’t have them, follow this guide to generate them easily:</p><h3><a href="https://medium.com/@mohasina.clt/how-to-generate-access-keys-in-aws-af1a303dde42?source=post_page-----332b91e90be1--------------------------------">How to Generate Access Keys in AWS</a></h3><h3><a href="https://medium.com/@mohasina.clt/how-to-generate-access-keys-in-aws-af1a303dde42?source=post_page-----332b91e90be1--------------------------------">Welcome to the gateway of AWS empowerment! In the vast realm of Amazon Web Services (AWS), the magic of programmatic…</a></h3><p><a href="https://medium.com/@mohasina.clt/how-to-generate-access-keys-in-aws-af1a303dde42?source=post_page-----332b91e90be1--------------------------------">medium.com</a></p><p>If you already have them but you don’t remember them, go on the directory located in “C:\Users\your-PC-username\.aws” and open “credentials”. If you’re on Windows you can open a terminal anywhere and simply run:</p><pre>cd\<br>cd Users\your-PC-username\.aws<br>type credentials</pre><p>Ensure that you replace your-PC-username with your actual username.</p><p>Once you have the access keys, we are now ready to add them in Jenkins but we can do it only one at a time, so first of all we want to specify our AWS Access Key. So click again on “Add Credentials” and as kind select “Secret text”. It will ask you for a Secret and an ID. In ID specify “AWS_ACCESS_KEY_ID” and in Secret paste your AWS Access Key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9aZVgS5A0ta2g9cz.png" /></figure><p>Once you’re done, click again on “Add Credentials” and do the same for your AWS Secret Key. In ID type “AWS_SECRET_ACCESS_KEY”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TVvFPXBz8RS-a3fH.png" /></figure><p>Now all the credentials are set up:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jWSQgzqkf8jWMd_4.png" /></figure><h3>Step 4: Jenkins pipeline</h3><p>Here I will explain the other folder “2-terraform-eks-deployment”, that we have not discussed about yet and also the folder “kubernetes”.</p><p>We want to create an Elastic Kubernetes Service (EKS) cluster and deploy Kubernetes manifest files inside it using Jenkins.</p><p>First we start from “2-terraform-eks-deployment”.</p><p>In “backend.tf” we configure the same backend as before, it just changes the key:</p><pre>terraform {<br>  backend &quot;s3&quot; {<br>    bucket = &quot;jensins-kubernetes-app-2024-v2&quot;<br>    region = &quot;eu-west-3&quot;<br>    key = &quot;eks/terraform.tfstate&quot;<br>  }<br>}</pre><p>In “eks.tf” we are defining a module to create an EKS cluster. We are using the same VPC we created earlier. The source is a module published in the Terraform registry, if you are curious and want to see what it does go and check it out on:</p><h3><a href="https://registry.terraform.io/modules/terraform-aws-modules/eks/aws/latest?source=post_page-----332b91e90be1--------------------------------">EKS (Terraform Registry)</a></h3><h3><a href="https://registry.terraform.io/modules/terraform-aws-modules/eks/aws/latest?source=post_page-----332b91e90be1--------------------------------">Terraform module to create AWS Elastic Kubernetes (EKS) resources</a></h3><p>It is widely used and it will basically create several resources for us, such as EKS nodes and a Load Balancer. This one is important because we will be able to access to our application through the Load Balancer DNS name.</p><pre># eks.tf</pre><pre>module &quot;eks&quot; {<br>    source  = &quot;terraform-aws-modules/eks/aws&quot;<br>    version = &quot;~&gt; 19.0&quot;<br>    cluster_name = &quot;eks-cluster&quot;<br>    cluster_version = &quot;1.24&quot;</pre><pre>    cluster_endpoint_public_access  = true</pre><pre>    vpc_id = module.my-vpc.vpc_id<br>    subnet_ids = module.my-vpc.private_subnets</pre><pre>    tags = {<br>        environment = &quot;development&quot;<br>        application = &quot;myapp&quot;<br>    }</pre><pre>    eks_managed_node_groups = {<br>        dev = {<br>            min_size = 1<br>            max_size = 3<br>            desired_size = 2</pre><pre>            instance_types = [&quot;t2.small&quot;]<br>        }<br>    }<br>}</pre><p>In “vpc.tf” we specify the VPC with a module but again we take the code from a module of the Terraform registry, so we don’t create it from scratch</p><pre># vpc.tf</pre><pre>data &quot;aws_availability_zones&quot; &quot;azs&quot; {}</pre><pre>module &quot;my-vpc&quot; {<br>  source          = &quot;terraform-aws-modules/vpc/aws&quot;<br>  version         = &quot;5.8.1&quot;<br>  name            = &quot;my-vpc&quot;<br>  cidr            = var.vpc_cidr_block<br>  private_subnets = var.private_subnet_cidr_blocks<br>  public_subnets  = var.public_subnet_cidr_blocks<br>  azs             = data.aws_availability_zones.azs.names</pre><pre>  enable_nat_gateway   = true<br>  single_nat_gateway   = true<br>  enable_dns_hostnames = true</pre><pre>  tags = {<br>    &quot;kubernetes.io/cluster/myapp-eks-cluster&quot; = &quot;shared&quot;<br>  }</pre><pre>  public_subnet_tags = {<br>    &quot;kubernetes.io/cluster/myapp-eks-cluster&quot; = &quot;shared&quot;<br>    &quot;kubernetes.io/role/elb&quot;                  = 1<br>  }</pre><pre>  private_subnet_tags = {<br>    &quot;kubernetes.io/cluster/myapp-eks-cluster&quot; = &quot;shared&quot;<br>    &quot;kubernetes.io/role/internal-elb&quot;         = 1<br>  }<br>}</pre><p>And then in “variables.tf” and “terraform.tfvars” we specify the ranges of IP addresses that the VPC and the subnets can take</p><pre># variables.tf</pre><pre>variable &quot;vpc_cidr_block&quot; {}<br>variable &quot;private_subnet_cidr_blocks&quot; {}<br>variable &quot;public_subnet_cidr_blocks&quot; {}</pre><pre># terraform.tfvars</pre><pre>vpc_cidr_block = &quot;10.0.0.0/16&quot;<br>private_subnet_cidr_blocks=[&quot;10.0.1.0/24&quot;,&quot;10.0.2.0/24&quot;,&quot;10.0.3.0/24&quot;]<br>public_subnet_cidr_blocks=[&quot;10.0.4.0/24&quot;,&quot;10.0.5.0/24&quot;,&quot;10.0.6.0/24&quot;]</pre><p>In the root folder there is a Jenkinsfile written in Groovy. This is the main file that Jenkins will use to do the deployment process for us in stages. So we will not need to deploy ourselves with the usual Terraform commands, but the Jenkins server will do that for us, as you can also see from the Jenkinsfile.</p><pre>#!/usr/bin/env groovy<br>pipeline {<br>    agent any<br>    environment {<br>        # Jenkins will use the credentials added earlier<br>        AWS_ACCESS_KEY_ID = credentials(&#39;AWS_ACCESS_KEY_ID&#39;)<br>        AWS_SECRET_ACCESS_KEY = credentials(&#39;AWS_SECRET_ACCESS_KEY&#39;)<br>        AWS_DEFAULT_REGION = &quot;eu-west-3&quot;<br>    }<br>    stages {<br>        # Stage 1<br>        stage(&quot;Create an EKS Cluster&quot;) {<br>            steps {<br>                script {<br>                    dir(&#39;2-terraform-eks-deployment&#39;) {<br>                        # Jenkins will run these commands for us<br>                        sh &quot;terraform init&quot;<br>                        sh &quot;terraform apply -auto-approve&quot;<br>                    }<br>                }<br>            }<br>        }<br>        # Stage 2<br>        stage(&quot;Deploy to EKS&quot;) {<br>            steps {<br>                script {<br>                    dir(&#39;kubernetes&#39;) {<br>                        # Update packages inside the cluster<br>                        sh &quot;aws eks update-kubeconfig --name eks-cluster&quot;<br>                        # Deploy an application<br>                        sh &quot;kubectl apply -f nginx-deployment.yaml&quot;<br>                        # Deploy a service<br>                        sh &quot;kubectl apply -f nginx-service.yaml&quot;<br>                    }<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>As you can see, we have two stages.</p><p>In the first stage, it initializes and applies a Terraform configuration to create an EKS cluster.</p><p>In the second stage, it updates the kubeconfig with the EKS cluster information and applies Kubernetes YAML files (nginx-deployment.yaml and nginx-service.yaml) to deploy Nginx to the EKS cluster. These two files are located in the “kubernetes” folder.</p><p>So, in nginx-deployment.yamlit is described a Kubernetes deployment for deploying a simple Nginx web server:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: nginx # Deployment name<br>spec:<br>  selector:<br>    matchLabels:<br>      app: nginx # Select pods with label &#39;app: nginx&#39;<br>  replicas: 1 # Number of pod replicas<br>  template:<br>    metadata:<br>      labels:<br>        app: nginx # Label for pods<br>    spec:<br>      containers:<br>      - name: nginx # Container name<br>        image: nginx # Nginx Docker image<br>        ports:<br>        - containerPort: 80 # Port on which the container listens</pre><p>In nginx-service.yaml instead we are setting up a Kubernetes Service for exposing the Nginx deployment:</p><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: nginx # Service name<br>  labels:<br>    app: nginx # Label for Service<br>spec:<br>  ports:<br>  - name: http # Port name<br>    port: 80 # Port on which the Service listens<br>    protocol: TCP # Protocol used<br>    targetPort: 80 # Port to forward traffic to in the pods<br>  selector:<br>    app: nginx # Selects pods with label &#39;app: nginx&#39;<br>  type: LoadBalancer # Exposes the Service outside the cluster as a LoadBalancer</pre><p><strong>Again:</strong> we do not have to run the usual Terraform commands to deploy this code, because Jenkins will do that for us. We will host this code in a GitHub repository and then Jenkins will connect to it and pull it down following the deployment process described in the Jenkinsfile.</p><h3>Step 5: Create a GitHub repository</h3><p>So Jenkins need to access to this code to do the deployment for us, so create a new GitHub repository and name it “my-jenkins-pipeline” or call it whatever you want. Leave it public and do not add a README.md file.</p><p>Then pull down the repository with “git clone” and move the following files to the cloning folder:</p><ul><li>Jenkinsfile</li><li>The folder “2-terraform-eks-deployment”</li><li>The folder “kubernetes”</li></ul><p>Then push your changes to the main branch</p><h3>Step 6: create a Jenkins pipeline</h3><p>On the Jenkins homepage, click on “New Item” on the left.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*u7-qpsootQyjMUlN.png" /></figure><p>Then select “Pipeline” and give it a name, I call it jenkins-pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UiPMnem-6F7HrkY2.png" /></figure><p>Click OK and then scroll to the bottom of the page and under Pipeline select “Pipeline script from SCM” and as SCM choose “Git” and then you want to give your GitHub Repository URL and select the credentials we defined before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vJKCY5vsjpQ8wCPl.png" /></figure><p>In branch, specify */main instead of */master.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fDuh4BtnXWF5_o-G.png" /></figure><p>Then click on Save.</p><p>Now that it is all set it up we just need to run it by clicking on “Build Now” on the left.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wTJY4rFeavNVpuKF.png" /></figure><p>You will see the process of creation and deployment defined with the two stages that we have defined before in the code. Jenkins will take about 10–15 minutes to create the EKS cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*duJogYE0uIyWo_t2.png" /></figure><p>In the bottom-left in “Build History” you should see your build running, if you click on it and then click on “Console output” in the menu on the left you should see the logs and you can see that it is creating several resources, and you can follow all the process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*k3Z9nK6t785VMrTy.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*v4x2esWekSlGUTbj.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cxezojIxE0TPvJbH.png" /></figure><p>Those are the same logs that you would see if you run the usual Terraform commands to deploy the infrastructure using Visual Studio Code.</p><p>Now wait until the whole deployment process is finished. I guess you have time to take a coffee or to go to the bathroom</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/0*iO4-ST9J_QGrDQnC.gif" /></figure><h3>Step 7: Test the application</h3><p>Alright! Now it’s time to test the application. In the AWS management console go to the “Elastic Kubernetes Service” and you should see that the cluster is running:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*O94QaQGA0w_JiYBn.png" /></figure><p>If you go to the tab “Resources” you can see what resources it has created (Pods, Deployment, ..).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aF6q678jgeSSLCqd.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-qydjLLtOewE3a-z.png" /></figure><p>If you don’t see them, there should be a message above that says that your user doesn’t have the permissions to get Kubernetes objects. Click on “Learn more” and follow the guide to grant the access to your resources. Anyway, this is just to see what happens behind the scenes.</p><p>Now, if you go to the “EC2” AWS service and select “Load balancers” you should see the Application Load Balancer created by Kubernetes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5NFIC-DxI0NiRTO7.png" /></figure><p>If you click on it you can see its DNS name:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hP-NoXbYnPlUGcKI.png" /></figure><p>Copy it and navigate to it in a new tab and you should see the Nginx welcome page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tcl2Ug7g9ne7Mi4F.png" /></figure><h3>Step 8: Clean up the resources</h3><p>Now I will show you how to delete all the resources.</p><p>Go to the “2-terraform-eks-deployment” folder in your project and run:</p><pre>terraform init<br>terraform destroy -auto-approve</pre><p>Now go to the “1-terraform-jenkins-server” and run:</p><pre>terraform destroy -auto-approve</pre><p>That’s it! I hope you liked this project, please leave a thumbs up and see you in the next project</p><p>REMEMBER TO CHANGE THE VERSION OF THE MODULE OF VPC TO 5.8.1 IN NEW FOLDER (2) / 2-terraform-deploy-to-eks / vpc.tf — → THEN PUSH</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/148/1*YgD8dI1P6tc7YL0B9ie5aw.jpeg" /></figure><p>A Slp Thanks to you man (Mattiamazzari)……………………</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b04fd9cf6ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Set Up an Application Load Balancer with AWS 2-EC2 Instances]]></title>
            <link>https://medium.com/@akulamanojkumar988/how-to-set-up-an-application-load-balancer-with-aws-2-ec2-instances-4ae1cc875818?source=rss-100b6452cd9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ae1cc875818</guid>
            <dc:creator><![CDATA[manojkumar]]></dc:creator>
            <pubDate>Wed, 20 Mar 2024 17:37:16 GMT</pubDate>
            <atom:updated>2024-03-20T17:37:16.662Z</atom:updated>
            <content:encoded><![CDATA[<ul><li>Understand what load balancing is and why it is important for your applications</li><li>Understand what ELB is and how it works in AWS EC2</li><li>Launch two EC2 instances with an Ubuntu AMI and use User Data to install the Apache Web Server</li><li>Modify the index.html file to include your name and a message</li><li>Create an Application Load Balancer (ALB) in EC2 using the AWS Management Console</li><li>Add EC2 instances to the ALB as target groups</li><li>Verify that the ALB is working properly by checking the health status of the target instances and testing the load balancing capabilities</li></ul><p>Load balancing is the distribution of workloads across multiple servers to ensure consistent and optimal resource utilization. It is an essential aspect of any large-scale and scalable computing system, as it helps you to improve the reliability and performance of your applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/0*lPjFdr6tht1a4qRI.png" /></figure><p>Load balancing can help you to achieve the following benefits:</p><ul><li>High availability: Load balancing can prevent your applications from becoming unavailable due to server failures or overloading. By distributing the traffic across multiple servers, load balancing can ensure that your applications can handle the requests even if one or more servers go down or become slow.</li><li>Fault tolerance: Load balancing can also help you to recover from server failures or errors. By detecting the unhealthy or unresponsive servers, load balancing can automatically redirect the traffic to the healthy or available servers, minimizing the impact on your applications and users.</li><li>Scalability: Load balancing can also help you to scale your applications according to the demand or traffic. By adding or removing servers from the load balancing pool, you can adjust the capacity and performance of your applications without affecting the user experience.</li></ul><h3>What is Elastic Load Balancing?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/0*jqHzfPup-2iXRte-.png" /></figure><p>Elastic Load Balancing (ELB) is a service provided by Amazon Web Services (AWS) that automatically distributes incoming traffic across multiple EC2 instances. ELB provides three types of load balancers:</p><ul><li>Application Load Balancer (ALB): ALB operates at layer 7 of the OSI model and is ideal for applications that require advanced routing and microservices. ALB can route the traffic based on the content of the request, such as the URL path, the host header, the query parameters, etc. ALB can also support multiple protocols, such as HTTP, HTTPS, HTTP/2, WebSocket, and gRPC. ALB can also integrate with other AWS services, such as Amazon ECS, Amazon EKS, AWS Lambda, AWS WAF, etc.</li><li>Network Load Balancer (NLB): NLB operates at layer 4 of the OSI model and is ideal for applications that require high throughput and low latency. NLB can route the traffic based on the TCP or UDP port and the IP address of the destination. NLB can also support static or elastic IP addresses, long-lived TCP connections, and TLS termination. NLB can also integrate with other AWS services, such as Amazon VPC, Amazon EC2, AWS CloudFormation, etc.</li><li>Classic Load Balancer (CLB): CLB operates at layer 4 of the OSI model and is ideal for applications that require basic load balancing features. CLB can route the traffic based on the TCP or SSL port and the IP address of the destination. CLB can also support HTTP, HTTPS, SSL, and TCP protocols, health checks, sticky sessions, and cross-zone load balancing. CLB can also integrate with other AWS services, such as Amazon EC2, Amazon CloudWatch, etc.</li></ul><p>To illustrate how to use ELB in AWS EC2, we’ll use an example of setting up an ALB with two EC2 instances that run the Apache Web Server.</p><h3>How to Launch Two EC2 Instances with an Ubuntu AMI and Use User Data to Install the Apache Web Server</h3><p>To launch two EC2 instances with an Ubuntu AMI and use User Data to install the Apache Web Server, we’ll use the following steps:</p><p>1. Go to the AWS console and navigate to the EC2 service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*5uD0onvMDQXLAMtO.png" /></figure><p>2. Click on <strong>Launch Instance</strong> button and select <strong>Ubuntu Server 22.04 LTS (HVM), SSD Volume Type</strong> from the list of available AMIs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*B5P81YiNJ2XZR3TP" /></figure><p>3. Choose <strong>t2.micro</strong> from the list of available instance types.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/0*EMWUx9x_HDDC154H" /></figure><p>4. Choose an existing key pair or create a new one if you don’t have one already. You’ll need this key pair to SSH into your instance later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/0*7UMzF7m8xIgrpPvO.png" /></figure><p>5. In the <strong>Configure Instance Details</strong> page, scroll down to the <strong>Advanced Details</strong> section and expand the <strong>User data</strong> field.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/0*ylcUltd01g_FbB34.png" /></figure><p>6. In the <strong>User data</strong> field, enter the following commands to install and start the Apache Web Server:</p><pre>#!/bin/bash<br># Update packages<br>sudo apt-get update -y<br># Install Apache<br>sudo apt-get install -y apache2<br># Start Apache service<br>sudo systemctl start apache2<br># Enable Apache service<br>sudo systemctl enable apache2<br># Modify index.html file<br>sudo echo &quot;&lt;h1&gt;Welcome to AWS EC2&lt;/h1&gt;&quot; &gt; /var/www/html/index.html<br>sudo echo &quot;&lt;p&gt;My name is Ajit&lt;/p&gt;&quot; &gt;&gt; /var/www/html/index.html</pre><p>7. Expand Network settings<strong>: </strong>Create a new security group or select an existing one. Make sure to allow inbound traffic on port 80 for HTTP protocol from anywhere. This will allow us to access the Apache web page from our browser.</p><p>8. Click on <strong>Launch instance</strong> button and wait for your instance to launch.</p><p>9. Repeat steps 2–8 to launch another instance with the same configuration, but modify the user data script as follows:</p><pre>#!/bin/bash<br># Update packages<br>sudo apt-get update -y<br># Install Apache<br>sudo apt-get install -y apache2<br># Start Apache service<br>sudo systemctl start apache2<br># Enable Apache service<br>sudo systemctl enable apache2<br># Modify index.html file<br>sudo echo &quot;&lt;h1&gt;Welcome to AWS EC2&lt;/h1&gt;&quot; &gt; /var/www/html/index.html<br>sudo echo &quot;&lt;p&gt;TrainWithShubham Community is Super Awesome :)&lt;/p&gt;&quot; &gt;&gt; /var/www/html/index.html</pre><p>This will change the message in the index.html file for the second instance.</p><p>You have successfully launched two EC2 instances with an Ubuntu AMI and used User Data to install the Apache Web Server.</p><h3>How to Create an Application Load Balancer (ALB) in EC2 using the AWS Management Console and Add the EC2 Instances to the ALB as Target Groups</h3><p>An Application Load Balancer (ALB) is a type of load balancer that operates at layer 7 of the OSI model and is ideal for applications that require advanced routing and microservices. ALB can route the traffic based on the content of the request, such as the URL path, the host header, the query parameters, etc. ALB can also support multiple protocols, such as HTTP, HTTPS, HTTP/2, WebSocket, and gRPC. ALB can also integrate with other AWS services, such as Amazon ECS, Amazon EKS, AWS Lambda, AWS WAF, etc.</p><p>To create an ALB in EC2 using the AWS Management Console and add the EC2 instances to the ALB as target groups, we’ll use the following steps:</p><p>1.Go to the AWS console and navigate to the EC2 service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*x0GbEjoepY9KymDh.png" /></figure><p>2. Click on <strong>Load Balancers</strong> in the left navigation pane and then click the <strong>Create Load Balancer</strong> button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*OGRoYeFOZWIOCxGm.png" /></figure><p>3. Select <strong>Create Application Load Balancer</strong> as the load balancer type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*WNJ3TOUU-27sI2hz.png" /></figure><p>4. In the <strong>Basic Configuration</strong> section, enter a name for your load balancer, such as <strong>ALB-Demo</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*Vc_tQfXrhKbqOiJ6.png" /></figure><p>5. In the Network mapping section, review VPC and subnet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*WQhSPYbblk4eTyTn.png" /></figure><p>6. In the<strong> Security Groups</strong> section, create a new security group or select an existing one for your load balancer. Make sure to allow inbound traffic on port 80 for HTTP protocol from anywhere. This will allow us to access the load balancer from our browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*-2IokOMLxsU9Ds25.png" /></figure><p>7. In the <strong>Listeners and Routing</strong> section, create a new target group or select an existing one for your load balancer. A target group is a group of targets, such as EC2 instances, that receive the traffic from the load balancer. For example, you can create a new target group with the following settings:</p><ul><li>For <strong>Name</strong>, enter a name for your target group, such as <strong>ALB-Demo-TG</strong>.</li><li>For <strong>Target type</strong>, select the <strong>instance</strong> to specify targets by instance ID.</li><li>For <strong>Protocol</strong>, select <strong>HTTP</strong>.</li><li>For <strong>Port</strong>, enter <strong>80</strong>.</li><li>For <strong>Health checks</strong>, modify the default settings as needed. For example, you can change the <strong>Path</strong> to <strong>/index.html</strong> to check the index.html file on each target.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*CapxE-C3qKQNH-Fh.png" /></figure><p>8. Click on the <strong>Create load balancer</strong> button and wait for your load balancer to be created.</p><p>You have successfully created an ALB in EC2 using the AWS Management Console and added the EC2 instances to the ALB as target groups.</p><h3>How to Verify that the ALB is Working Properly by Checking the Health Status of the Target Instances and Testing the Load Balancing Capabilities</h3><p>To verify that the ALB is working properly, we’ll use the following steps:</p><p>1.Go to the AWS console and navigate to the EC2 service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*yAxcOQuBhry7KoBc.png" /></figure><p>2. Click on <strong>Load Balancers</strong> in the left navigation pane and select your load balancer, such as <strong>ALB-Demo</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*A0qWb2M6e94iRneZ.png" /></figure><p>3. Copy the DNS name of your load balancer from the details panel. This is the address that you can use to access your load balancer from your browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*pwWtm3hI7vvlzzhy.png" /></figure><p>4. Open a web browser and paste the DNS name into the address bar. You should see a webpage displaying information about your apache2 installation and your name or message, such as “Welcome to AWS EC2” and “My name is Ajit”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*-f42W0zItcqZ9OtC.png" /></figure><p>5. Refresh the web page several times and observe the changes. You should see different names or messages on each refresh, such as “Welcome to AWS EC2” and “TrainWithShubham Community is Super Awesome :)”. This means that the load balancer is distributing the traffic across your two EC2 instances and displaying the index.html file from each instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*iV7YHGkc6E4Wl-nr.png" /></figure><p>6. Go back to the AWS console and navigate to the EC2 service.</p><p>7. Click on <strong>Target Groups</strong> in the left navigation pane and select your target group, such as <strong>ALB-Demo-TG</strong>.</p><p>8. Click on the <strong>Targets</strong> tab and observe the health status of your target instances. You should see that both instances are healthy and in service. This means that the load balancer is able to communicate with your instances and perform health checks on them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*AJIsyv1RwukXgTV7.png" /></figure><p>9. To test the fault tolerance of your load balancer, you can stop or terminate one of your instances and see how the load balancer handles the situation. For example, you can select one of your instances, such as <strong>ALB-Demo-1</strong>, and click on <strong>Actions</strong> button and choose <strong>Instance State</strong> and then <strong>Stop</strong> or <strong>Terminate</strong> option from the drop-down menu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*Z6ZiRMNSTQT1Ev4L.png" /></figure><p>10. Wait for the instance to stop or terminate and then refresh the web page in your browser. You should see that the web page is still accessible and displaying the name or message from the other instance, such as “Welcome to AWS EC2” and “TrainWithShubham Community is Super Awesome :)”. This means that the load balancer is able to detect the unhealthy or unavailable instance and redirect the traffic to the healthy or available instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*DgQVYEgumGoxai6h.png" /></figure><p>You have successfully verified that the ALB is working properly by checking the health status of the target instances and testing the load balancing capabilities.</p><h3>Conclusion</h3><p>In this blog post, I have explained what load balancing is and how to use Elastic Load Balancing (ELB) in AWS EC2, a service that automatically distributes incoming traffic across multiple EC2 instances. I have also shown you how to create and use an Application Load Balancer (ALB) in EC2 using the AWS Management Console and add the EC2 instances to the ALB as target groups. I have also shown you how to verify that the ALB is working properly by checking the health status of the target instances and testing the load balancing capabilities.</p><p>I hope you found this blog post informative and engaging.</p><p>This is the end of the blog post for Day 41 of 90 Days of DevOps.</p><p>Thank you for reading and stay tuned for more posts in this series!</p><p><a href="https://medium.com/tag/devops?source=post_page-----30542b5deaa4---------------devops-----------------">DevOps</a></p><p><a href="https://medium.com/tag/aws?source=post_page-----30542b5deaa4---------------aws-----------------">AWS</a></p><p><a href="https://medium.com/tag/load-balancing?source=post_page-----30542b5deaa4---------------load_balancing-----------------">Load Balancing</a></p><p><a href="https://medium.com/tag/ec2?source=post_page-----30542b5deaa4---------------ec2-----------------">Ec2</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ae1cc875818" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Step-by-step process for installing Docker on Ubuntu in AWS]]></title>
            <link>https://medium.com/@akulamanojkumar988/step-by-step-process-for-installing-docker-on-ubuntu-in-aws-7a45cd27cc2a?source=rss-100b6452cd9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a45cd27cc2a</guid>
            <dc:creator><![CDATA[manojkumar]]></dc:creator>
            <pubDate>Wed, 20 Mar 2024 15:56:23 GMT</pubDate>
            <atom:updated>2024-03-20T15:56:23.740Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*Z4Dzt--Y8ZT4MN5x.jpeg" /></figure><p>Installing Docker on Ubuntu Machine</p><ul><li><strong><em>AWS Prerequisites</em></strong></li><li><strong><em>Updating package index</em></strong></li><li><strong><em>Installing docker</em></strong></li><li><strong><em>Starting the Docker service</em></strong></li><li><strong><em>Verifying the installation</em></strong></li><li><strong><em>Enabling the Docker service</em></strong></li><li><strong><em>Check the Docker version</em></strong></li><li><strong><em>Add User to Docker Group</em></strong></li><li><strong><em>Conclusion</em></strong></li></ul><p><strong>AWS Prerequisites</strong></p><ul><li><em>Set up an EC2 instance in an Amazon VPC.</em></li><li><em>An Ubuntu EC2 instance with an internet connection.</em></li></ul><p>Here’s how to create and configure the VPC, as well as launch the EC2 instance within it. Check out the link below.</p><blockquote><a href="https://medium.com/@srijaanaparthy/create-an-ec2-instance-in-an-amazon-vpc-ea72f8c3cd8f"><em>Create an EC2 instance in an Amazon VPC</em></a></blockquote><p><strong>Note</strong>: Instead of using an Amazon Linux machine, choose to launch an Ubuntu system because this blog will demonstrate the Docker installation part of an Ubuntu system.</p><p><strong>Updating package index</strong></p><p>Before installing Docker, you should update the package index:</p><pre>sudo apt-get update</pre><p><strong>Installing docker</strong></p><p>To install Docker on Ubuntu, you can use the following command:</p><pre>sudo apt-get install docker.io -y</pre><p><strong>Starting the Docker service</strong></p><p>After installing Docker, you will need to start the Docker service:</p><pre>sudo systemctl start docker</pre><p><strong>Verifying the installation</strong></p><p>Once you have started the Docker service, you can verify that it is running by running the following command in your terminal:</p><pre>sudo docker run hello-world</pre><p>If the installation is successful, you will see a message indicating that Docker is working correctly.</p><p><strong>Enabling the Docker service</strong></p><p>To start the Docker service automatically when the instance starts, you can use the following command:</p><pre>sudo systemctl enable docker</pre><p><strong>Check the Docker version</strong></p><p>Verify the Docker installation by running the Docker version command:</p><pre>docker --version</pre><p><strong>Add User to Docker Group</strong></p><p>(Optional) Add your user to the Docker group to run Docker commands without &#39;sudo&#39;</p><pre>sudo usermod -a -G docker $(whoami)</pre><p>After executing this command, the user will be added to the docker group and will have the necessary permissions to run Docker commands without sudo.</p><p>Note that the change to the user’s group membership will not take effect until the next time the user logs in. You can log out and log back in to apply the changes or use the following command to activate the changes without logging out:</p><pre>newgrp docker</pre><p>After following these steps, Docker should be installed and running on your Ubuntu machine.</p><p><strong>Conclusion</strong></p><p>Installing Docker on Ubuntu in AWS is a straightforward procedure that requires only a few steps. By following these steps, you should be able to install Docker and start using it to build, ship, and run your applications on your Ubuntu instance.</p><p>#DevOps #AWS #Docker</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a45cd27cc2a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3-Tier Application Deployment in K8 Cluster]]></title>
            <link>https://medium.com/@akulamanojkumar988/3-tier-application-deployment-in-k8-cluster-9689acc72bde?source=rss-100b6452cd9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9689acc72bde</guid>
            <dc:creator><![CDATA[manojkumar]]></dc:creator>
            <pubDate>Tue, 19 Mar 2024 17:20:55 GMT</pubDate>
            <atom:updated>2024-03-19T17:20:55.074Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*jrmkYMfNl1MH8N1p.png" /></figure><p>T<a href="https://medium.com/p/41ab1995d6ac/">hree-tier Application Deployment</a></p><p>We have divided it into different phases . Each phase play a very important role and i must insure you will understand in easy way.</p><p><strong><em>First Phase:-</em></strong></p><p>i) First of all we need to create a ec2 instance .</p><p>ii)Go to the AWS dashboard and click on the EC2 service.<br>iii) Click on “Launch Instance.”</p><p>iv) Select an AMI.<br>v) Choose an instance type and set the Key Pair name.<br>vi) Create the Security Group.<br>vii)Click on “Launch Instance.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*EHY_qhGzwoBVw8WX.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*v1LYKFrUp5sGdfvl.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*l0LXIuy8ZDxME5aA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*9z6E2ZuSA5r9mQpv.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*sTgFqiiAAvldYEh-.png" /></figure><p><strong>Phase 2:-</strong></p><p>After creating ec2 instance , now we need to connect with it and need to install docker .</p><p><strong>Step 1:-</strong> First of all you need to perform update command to update the server</p><pre>apt-get update -y</pre><p><strong>Step 2:-</strong> Copy and Paste the given command to create a script and run it .</p><pre>#!/bin/bash</pre><pre># Update the apt package index<br>sudo apt update</pre><pre># Install necessary dependencies<br>sudo apt install -y apt-transport-https ca-certificates curl software-properties-common</pre><pre># Add Docker&#39;s official GPG key<br>curl -fsSL <a href="https://download.docker.com/linux/ubuntu/gpg">https://download.docker.com/linux/ubuntu/gpg</a> | sudo apt-key add -</pre><pre># Determine the Ubuntu version<br>ubuntu_version=$(lsb_release -cs)</pre><pre># Add the Docker repository to the system based on the Ubuntu version<br>if [ &quot;$ubuntu_version&quot; = &quot;focal&quot; ] || [ &quot;$ubuntu_version&quot; = &quot;jammy&quot; ]; then<br>    sudo add-apt-repository &quot;deb [arch=amd64] <a href="https://download.docker.com/linux/ubuntu">https://download.docker.com/linux/ubuntu</a> focal stable&quot;<br>elif [ &quot;$ubuntu_version&quot; = &quot;bionic&quot; ]; then<br>    sudo add-apt-repository &quot;deb [arch=amd64] <a href="https://download.docker.com/linux/ubuntu">https://download.docker.com/linux/ubuntu</a> bionic stable&quot;<br>else<br>    echo &quot;Unsupported Ubuntu version: $ubuntu_version&quot;<br>    exit 1<br>fi</pre><pre># Update the apt package index again<br>sudo apt update</pre><pre># Install Docker CE<br>sudo apt install -y docker-ce</pre><pre># Verify Docker installation<br>docker --version</pre><pre># Optionally, add the current user to the docker group<br>sudo usermod -aG docker $USER</pre><pre>echo &quot;Docker has been successfully installed.&quot;<br>echo &quot;You may need to log out and log back in for group changes to take effect.&quot;</pre><p><strong>Step 2:-</strong> After creating the script , you need to provide the executable permission to file</p><pre>sudo chmod +x docker.sh<br>sudo mv docker.sh /usr/local/bin</pre><p>Now question arise why we are moving the .sh file to bin because if we move it to bin then in next time we dont need to use or apply (sh or ./ ) before shell script file</p><p><strong>Step 3:- </strong>After installing the docker file we need to clone the github repo , where our code is located .</p><p><strong>Step 4:-</strong> So we are working on project where frontend is written in reactjs and backend is written in node js . We are also using the Mongodb database for it.</p><p><strong>Step 5:-</strong> First of all we need to create a dockerfile for frontend application. Lets create a docker file for it</p><pre># Use the official Node.js version 14 image from Docker Hub as the base image<br>FROM node:14</pre><pre># Set the working directory inside the container to /usr/src/app<br>WORKDIR /usr/src/app</pre><pre># Copy package.json and package-lock.json from the host machine into the container&#39;s working directory<br>COPY package*.json ./</pre><pre># Install npm dependencies inside the container based on the package.json files<br>RUN npm install</pre><pre># Copy all application files from the host machine into the container&#39;s working directory<br>COPY . .</pre><pre># Specify the command to run when the container starts<br>CMD [ &quot;npm&quot;, &quot;start&quot; ]</pre><p><strong>Step 6:- </strong>After created a dockerfile we need to perform to create a image which help us to create container.</p><pre>#command to create a docker image is <br>docker build -t frontend .<br># command to create a container from image is <br>docker run -d -p  3500:3500 --name frontend frontend <br>#here we are exposing it on port 3500</pre><p><strong>Step 7:-</strong> We are going to push the image on ecr , so we need to create ecr repo in aws . Before doing that we required to create an <strong>IAM users</strong> , where we provide the Permission to read &amp; access ecr image to IAM .</p><p>We also need to install awscli on our terminal.</p><p><strong>Step 8:- </strong>Command to <strong>install awscli</strong> on terminal.</p><pre>curl &quot;https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip&quot; -o &quot;awscliv2.zip&quot;<br>sudo apt install unzip<br>unzip awscliv2.zip<br>sudo ./aws/install -i /usr/local/aws-cli -b /usr/local/bin --update<br>aws configure</pre><p><strong>Step 9:-</strong> Now we need to push the image on ecr , for that we will get the command on ecr, just crate a repo and click on push command options as shown in <strong>below screenshot.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*oEUSMdWlLhWsQf4R.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*Xya-b9kQggqLpSEc.png" /></figure><p><strong>Phase 3:-</strong> After pushing image on ecr , we need to install kubernetes , so here we are using eks . So i am providing the command to connect &amp; install eks on <strong>terminal below </strong>.</p><p><strong>First of all we need to kubectl , command is given below:-</strong></p><pre>curl -o kubectl https://amazon-eks.s3.us-west-2.amazonaws.com/1.19.6/2021-01-05/bin/linux/amd64/kubectl<br>chmod +x ./kubectl<br>sudo mv ./kubectl /usr/local/bin<br>kubectl version --short --client</pre><p><strong>Now we need to install eksctl:-</strong></p><pre>curl --silent --location &quot;https://github.com/weaveworks/eksctl/releases/latest/download/eksctl_$(uname -s)_amd64.tar.gz&quot; | tar xz -C /tmp<br>sudo mv /tmp/eksctl /usr/local/bin<br>eksctl version</pre><p><strong>Step 2:- </strong>Now we need to Setup<strong> EKS Cluster :-</strong></p><pre>eksctl create cluster --name three-tier-cluster --region us-west-2 --node-type t2.medium --nodes-min 2 --nodes-max 2<br>aws eks update-kubeconfig --region us-west-2 --name three-tier-cluster<br>kubectl get nodes</pre><p>This command will create a eks on aws.</p><p><strong>Step 3:- </strong>Now we need to create deployment for frontend , backend and database.</p><p>Let’s start with <strong>database first</strong>.</p><p>Create deployment_mongo.yaml(menifest file) for mongodb (because we are using the mongodb)</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata: <br>  namespace: three-tier<br>  name: mongodb<br>spec: <br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: mongodb<br>  template:<br>    metadata:<br>      labels: <br>        app: mongodb<br>    spec: <br>      containers:<br>      - name: mon<br>        image: mongo:4.4.6<br>        command:<br>            - &quot;numactl&quot;<br>            - &quot;--interleave=all&quot;<br>            - &quot;mongod&quot;<br>            - &quot;--wiredTigerCacheSizeGB&quot;<br>            - &quot;0.1&quot;<br>            - &quot;--bind_ip&quot;<br>            - &quot;0.0.0.0&quot;<br>        ports:<br>        - containerPort: 27017<br>        env: <br>          - name: MONGO_INITDB_ROOT_USERNAME<br>            valueFrom:<br>              secretKeyRef:<br>                name: mongo-sec<br>                key: username<br>          - name: MONGO_INITDB_ROOT_PASSWORD<br>            valueFrom:<br>              secretKeyRef:<br>                name: mongo-sec<br>                key: password<br>        volumeMounts:<br>          - name: mongo-volume<br>            mountPath: /data/db<br>      volumes: <br>      - name: mongo-volume<br>        persistentVolumeClaim:<br>          claimName: mongo-volume-claim</pre><blockquote><em>By Default mongodb work on </em><strong><em>port 27017.</em></strong></blockquote><p>Step 4:- Now we need to create a service.yaml , secrets.yaml .</p><p><strong>Service .yaml:-</strong>The service.yaml file in Kubernetes is used to define a service object, which directs network traffic to a group of pods. This includes specifications such as the service name, selectors to identify pods, ports to listen on, and the type of service. This file is required to configure network access to applications running in a Kubernetes cluster.</p><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  namespace: three-tier<br>  name: mongodb-svc<br>spec:<br>  selector:<br>    app: mongodb<br>  ports:<br>  - name: mongodb-svc<br>    protocol: TCP<br>    port: 27017<br>    targetPort: 27017</pre><p><strong>Secrets.yaml:- </strong>A <strong><em>`secrets.yaml`</em></strong> file in Kubernetes is used to define secret objects, which securely store sensitive information such as passwords, API keys, or certificates within the cluster. These secrets can be securely accessed by applications running in Kubernetes pods as files or environment variables, enabling secure configuration, communication, and authentication.</p><pre>apiVersion: v1<br>kind: Secret<br>metadata: <br>  namespace: three-tier<br>  name: mongo-sec<br>type: Opaque<br>data:  <br>  password: cGFzc3dvcmQxMjM=   #Three-Tier-Project<br>  username: YWRtaW4= #admin</pre><p><strong>Step5:-</strong> We also need to create <strong>pv.yaml and pvc.yaml</strong> .</p><p><strong><em>i)pv.yaml :-</em></strong> It defines a <strong><em>PersistentVolume (PV)</em></strong> object that represents storage in a cluster that is provisioned by an administrator or dynamically.</p><pre>apiVersion: v1<br>kind: PersistentVolume<br>metadata:<br>  name: mongo-pv<br>  namespace: three-tier<br>spec:<br>  capacity: <br>    storage: 1Gi<br>  volumeMode: Filesystem<br>  accessModes:<br>    - ReadWriteOnce<br>  hostPath:<br>    path: /data/db</pre><p><strong><em>ii)pvc.yaml :- It defines d</em></strong>efines <strong><em>PersistentVolumeClaim (PVC)</em></strong> objects that are requests for storage by pods, separating storage details from applications.</p><pre>apiVersion: v1<br>kind: PersistentVolumeClaim<br>metadata:<br>  name: mongo-volume-claim<br>  namespace: three-tier<br>spec: <br>  accessModes:  <br>    - ReadWriteOnce<br>  storageClassName: &quot;&quot;<br>  resources:<br>    requests:<br>      storage: 1Gi</pre><blockquote><strong><em>PV and PVC enable dynamic provisioning</em></strong><em> and consumption of persistent storage in a Kubernetes cluster.</em></blockquote><p><strong>Step6:-</strong> Now we need to apply command to deploy the cluster .</p><p>Use command which is given below:-</p><pre>## It is used to apply the configuration defined in the deployment_mongo.yaml file to a Kubernetes cluster<br>kubectl apply -f deployment_mongo.yaml</pre><pre>## It is used to apply the configuration defined in the services.yaml file to a Kubernetes cluster<br>kubectl apply -f service.yaml</pre><pre>## It is used to apply the configuration defined in the secrets.yaml file to a Kubernetes cluster<br>kubectl apply -f secets.yaml</pre><pre>## It is used to apply the configuration defined in the pv.yaml file to a Kubernetes cluster<br>kubectl apply -f pv.yaml</pre><pre>## It is used to apply the configuration defined in the pvc.yaml file to a Kubernetes cluster<br>kubectl apply -f pvc.yaml</pre><p><strong>Step 7:- </strong>Now create a deployment.yaml file for backend.</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata: <br>  name: api<br>  namespace: three-tier<br>  labels: <br>    role: api<br>    env: demo<br>spec: <br>  replicas: 2<br>  strategy: <br>    type: RollingUpdate<br>    rollingUpdate:<br>      maxSurge: 1<br>      maxUnavailable: 25%<br>  selector: <br>    matchLabels:<br>      role: api<br>  template:<br>    metadata:<br>      labels:<br>        role: api<br>    spec:<br>      imagePullSecrets:<br>      - name: ecr-registry-secret<br>      containers:<br>      - name: api<br>        image: 407622020962.dkr.ecr.us-east-1.amazonaws.com/backend:latest<br>        imagePullPolicy: Always<br>        env:<br>          - name: MONGO_CONN_STR<br>            value: mongodb://mongodb-svc:27017/todo?directConnection=true<br>          - name: MONGO_USERNAME<br>            valueFrom:<br>              secretKeyRef:<br>                name: mongo-sec<br>                key: username<br>          - name: MONGO_PASSWORD<br>            valueFrom:<br>              secretKeyRef:<br>                name: mongo-sec<br>                key: password<br>        ports:<br>        - containerPort: 3500<br>        livenessProbe: <br>          httpGet:<br>            path: /ok<br>            port: 3500<br>          initialDelaySeconds: 2<br>          periodSeconds: 5<br>        readinessProbe:<br>          httpGet:<br>            path: /ok<br>            port: 3500<br>          initialDelaySeconds: 5<br>          periodSeconds: 5<br>          successThreshold: 1</pre><p>Also need to create a service.yaml file for backend.</p><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: api<br>  namespace: three-tier<br>spec: <br>  ports:<br>  - port: 3500<br>    protocol: TCP<br>  type: ClusterIP<br>  selector:<br>    role: api</pre><p>Now we need to create deployment.yaml and service.yaml for frontend too.</p><p><strong><em>deployment.yaml file code is given below: —</em></strong></p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: frontend<br>  namespace: three-tier<br>  labels:<br>    role: frontend<br>    env: demo<br>spec: <br>  replicas: 1<br>  strategy:<br>    type: RollingUpdate<br>    rollingUpdate:<br>      maxSurge: 1<br>      maxUnavailable: 25%<br>  selector:<br>    matchLabels: <br>      role: frontend<br>  template:<br>    metadata:<br>      labels:<br>        role: frontend<br>    spec: <br>      imagePullSecrets:<br>      - name: ecr-registry-secret<br>      containers:<br>      - name: frontend<br>        image: 407622020962.dkr.ecr.us-east-1.amazonaws.com/frontend:latest<br>        imagePullPolicy: Always<br>        env:<br>          - name: REACT_APP_BACKEND_URL<br>            value: &quot;http://backend.amanpathakdevops.study/api/tasks&quot;<br>        ports:<br>        - containerPort: 3000</pre><p><strong><em>Service.yaml file is given below:-</em></strong></p><pre>apiVersion: v1<br>kind: Service<br>metadata: <br>  name: frontend<br>  namespace: three-tier<br>spec:<br>  ports:<br>  - port: 3000<br>    protocol: TCP<br>  type: ClusterIP<br>  selector:<br>    role: frontend</pre><p>After creating the yaml files , we need to apply it as same as we have done in database sections.</p><p><strong>Step 8:-</strong></p><p>We will use ingress controller for internal routing .</p><p>#<strong><em>What is Ingress controller ?</em></strong></p><p>The ingress controller in Kubernetes is a component responsible for managing inbound HTTP(S) traffic to services within the cluster. It acts as a Layer 7 load balancer, routing traffic based on rules defined in ingress resources. Ingress controllers support features such as HTTP/HTTPS routing, TLS expiration, and dynamic configuration updates based on Kubernetes service discovery. Popular implementations include NGINX Ingress Controller, Traffic, and HAProxy Ingress.</p><p>Create a ingress.yaml file with the given below yaml code .</p><pre>apiVersion: networking.k8s.io/v1<br>kind: Ingress<br>metadata:<br>  name: mainlb<br>  namespace: three-tier<br>  annotations:<br>    alb.ingress.kubernetes.io/scheme: internet-facing<br>    alb.ingress.kubernetes.io/target-type: ip<br>    alb.ingress.kubernetes.io/listen-ports: &#39;[{&quot;HTTP&quot;: 80}]&#39;<br>spec:<br>  ingressClassName: alb<br>  rules:<br>    - host: backend.amanpathakdevops.study<br>      http:<br>        paths:<br>          - path: /api<br>            pathType: Prefix<br>            backend:<br>              service:<br>                name: api<br>                port:   <br>                  number: 3500<br>          - path: /<br>            pathType: Prefix<br>            backend:<br>              service:<br>                name: frontend<br>                port: <br>                  number: 3000</pre><p>Step 9:- Install AWS Load Balancer with the given command .</p><pre>#!/bin/bash</pre><pre># Download IAM Policy Document<br>curl -O <a href="https://raw.githubusercontent.com/kubernetes-sigs/aws-load-balancer-controller/v2.5.4/docs/install/iam_policy.json">https://raw.githubusercontent.com/kubernetes-sigs/aws-load-balancer-controller/v2.5.4/docs/install/iam_policy.json</a></pre><pre># Create IAM Policy<br>aws iam create-policy --policy-name AWSLoadBalancerControllerIAMPolicy --policy-document file://iam_policy.json</pre><pre># Associate OIDC Provider with EKS Cluster<br>eksctl utils associate-iam-oidc-provider --region=us-west-2 --cluster=three-tier-cluster --approve</pre><pre># Create IAM Service Account<br>eksctl create iamserviceaccount --cluster=three-tier-cluster --namespace=kube-system --name=aws-load-balancer-controller --role-name AmazonEKSLoadBalancerControllerRole --attach-policy-arn=arn:aws:iam::626072240565:policy/AWSLoadBalancerControllerIAMPolicy --approve --region=us-west-2</pre><p>Step 10:- Deploy AWS Load Balancer Controller</p><pre>#!/bin/bash</pre><pre># Install Helm<br>sudo snap install helm --classic</pre><pre># Add EKS Helm repository<br>helm repo add eks <a href="https://aws.github.io/eks-charts">https://aws.github.io/eks-charts</a></pre><pre># Update Helm repositories<br>helm repo update eks</pre><pre># Install AWS Load Balancer Controller using Helm<br>helm install aws-load-balancer-controller eks/aws-load-balancer-controller \<br>  -n kube-system \<br>  --set clusterName=my-cluster \<br>  --set serviceAccount.create=false \<br>  --set serviceAccount.name=aws-load-balancer-controller</pre><pre># Check the deployment status of AWS Load Balancer Controller<br>kubectl get deployment -n kube-system aws-load-balancer-controller</pre><pre># Apply the Kubernetes manifest file for the full stack LB (full_stack_lb.yaml)<br>kubectl apply -f full_stack_lb.yaml</pre><p>So here we have deploy three tier application by using docker , kubernetes, aws ec2 , ecr, eks.</p><p>If you want to integrate it with jenkins then i am sharing jenkins script file below you can use it .</p><p>For Backend :- Backend_jenkins script</p><pre>pipeline {<br>    agent any <br>    tools {<br>        jdk &#39;jdk&#39;<br>        nodejs &#39;nodejs&#39;<br>    }<br>    environment  {<br>        SCANNER_HOME=tool &#39;sonar-scanner&#39;<br>        AWS_ACCOUNT_ID = credentials(&#39;ACCOUNT_ID&#39;)<br>        AWS_ECR_REPO_NAME = credentials(&#39;ECR_REPO2&#39;)<br>        AWS_DEFAULT_REGION = &#39;us-east-1&#39;<br>        REPOSITORY_URI = &quot;${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com/&quot;<br>    }<br>    stages {<br>        stage(&#39;Cleaning Workspace&#39;) {<br>            steps {<br>                cleanWs()<br>            }<br>        }<br>        stage(&#39;Checkout from Git&#39;) {<br>            steps {<br>                git credentialsId: &#39;GITHUB&#39;, url: &#39;https://github.com/thakurrajeshPathak-DevOps/End-to-End-Kubernetes-Three-Tier-DevSecOps-Project.git&#39;<br>            }<br>        }<br>        stage(&#39;Sonarqube Analysis&#39;) {<br>            steps {<br>                dir(&#39;Application-Code/backend&#39;) {<br>                    withSonarQubeEnv(&#39;sonar-server&#39;) {<br>                        sh &#39;&#39;&#39; $SCANNER_HOME/bin/sonar-scanner \<br>                        -Dsonar.projectName=three-tier-backend \<br>                        -Dsonar.projectKey=three-tier-backend &#39;&#39;&#39;<br>                    }<br>                }<br>            }<br>        }<br>        stage(&#39;Quality Check&#39;) {<br>            steps {<br>                script {<br>                    waitForQualityGate abortPipeline: false, credentialsId: &#39;sonar-token&#39; <br>                }<br>            }<br>        }<br>        stage(&#39;OWASP Dependency-Check Scan&#39;) {<br>            steps {<br>                dir(&#39;Application-Code/backend&#39;) {<br>                    dependencyCheck additionalArguments: &#39;--scan ./ --disableYarnAudit --disableNodeAudit&#39;, odcInstallation: &#39;DP-Check&#39;<br>                    dependencyCheckPublisher pattern: &#39;**/dependency-check-report.xml&#39;<br>                }<br>            }<br>        }<br>        stage(&#39;Trivy File Scan&#39;) {<br>            steps {<br>                dir(&#39;Application-Code/backend&#39;) {<br>                    sh &#39;trivy fs . &gt; trivyfs.txt&#39;<br>                }<br>            }<br>        }<br>        stage(&quot;Docker Image Build&quot;) {<br>            steps {<br>                script {<br>                    dir(&#39;Application-Code/backend&#39;) {<br>                            sh &#39;docker system prune -f&#39;<br>                            sh &#39;docker container prune -f&#39;<br>                            sh &#39;docker build -t ${AWS_ECR_REPO_NAME} .&#39;<br>                    }<br>                }<br>            }<br>        }<br>        stage(&quot;ECR Image Pushing&quot;) {<br>            steps {<br>                script {<br>                        sh &#39;aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | docker login --username AWS --password-stdin ${REPOSITORY_URI}&#39;<br>                        sh &#39;docker tag ${AWS_ECR_REPO_NAME} ${REPOSITORY_URI}${AWS_ECR_REPO_NAME}:${BUILD_NUMBER}&#39;<br>                        sh &#39;docker push ${REPOSITORY_URI}${AWS_ECR_REPO_NAME}:${BUILD_NUMBER}&#39;<br>                }<br>            }<br>        }<br>        stage(&quot;TRIVY Image Scan&quot;) {<br>            steps {<br>                sh &#39;trivy image ${REPOSITORY_URI}${AWS_ECR_REPO_NAME}:${BUILD_NUMBER} &gt; trivyimage.txt&#39; <br>            }<br>        }<br>        stage(&#39;Checkout Code&#39;) {<br>            steps {<br>                git credentialsId: &#39;GITHUB&#39;, url: &#39;https://github.com/thakurrajeshPathak-DevOps/End-to-End-Kubernetes-Three-Tier-DevSecOps-Project.git&#39;<br>            }<br>        }<br>        stage(&#39;Update Deployment file&#39;) {<br>            environment {<br>                GIT_REPO_NAME = &quot;End-to-End-Kubernetes-Three-Tier-DevSecOps-Project&quot;<br>                GIT_USER_NAME = &quot;thakurrajesh-DevOps&quot;<br>            }<br>            steps {<br>                dir(&#39;Kubernetes-Manifests-file/Backend&#39;) {<br>                    withCredentials([string(credentialsId: &#39;github&#39;, variable: &#39;GITHUB_TOKEN&#39;)]) {<br>                        sh &#39;&#39;&#39;<br>                            git config user.email &quot;thakurrajesh@gmail.com&quot;<br>                            git config user.name &quot;thakurrajesh-DevOps&quot;<br>                            BUILD_NUMBER=${BUILD_NUMBER}<br>                            echo $BUILD_NUMBER<br>                            imageTag=$(grep -oP &#39;(?&lt;=backend:)[^ ]+&#39; deployment.yaml)<br>                            echo $imageTag<br>                            sed -i &quot;s/${AWS_ECR_REPO_NAME}:${imageTag}/${AWS_ECR_REPO_NAME}:${BUILD_NUMBER}/&quot; deployment.yaml<br>                            git add deployment.yaml<br>                            git commit -m &quot;Update deployment Image to version \${BUILD_NUMBER}&quot;<br>                            git push @github.com/${GIT_USER_NAME}/${GIT_REPO_NAME&quot;&gt;https://${GITHUB_TOKEN}@github.com/${GIT_USER_NAME}/${GIT_REPO_NAME} HEAD:master<br>                        &#39;&#39;&#39;<br>                    }<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>For frontend , the jenkins file is given below</p><pre>pipeline {<br>    agent any <br>    tools {<br>        jdk &#39;jdk&#39;<br>        nodejs &#39;nodejs&#39;<br>    }<br>    environment  {<br>        SCANNER_HOME=tool &#39;sonar-scanner&#39;<br>        AWS_ACCOUNT_ID = credentials(&#39;ACCOUNT_ID&#39;)<br>        AWS_ECR_REPO_NAME = credentials(&#39;ECR_REPO1&#39;)<br>        AWS_DEFAULT_REGION = &#39;us-east-1&#39;<br>        REPOSITORY_URI = &quot;${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com/&quot;<br>    }<br>    stages {<br>        stage(&#39;Cleaning Workspace&#39;) {<br>            steps {<br>                cleanWs()<br>            }<br>        }<br>        stage(&#39;Checkout from Git&#39;) {<br>            steps {<br>                git credentialsId: &#39;GITHUB&#39;, url: &#39;https://github.com/thakurrajeshPathak-DevOps/End-to-End-Kubernetes-Three-Tier-DevSecOps-Project.git&#39;<br>            }<br>        }<br>        stage(&#39;Sonarqube Analysis&#39;) {<br>            steps {<br>                dir(&#39;Application-Code/frontend&#39;) {<br>                    withSonarQubeEnv(&#39;sonar-server&#39;) {<br>                        sh &#39;&#39;&#39; $SCANNER_HOME/bin/sonar-scanner \<br>                        -Dsonar.projectName=three-tier-frontend \<br>                        -Dsonar.projectKey=three-tier-frontend &#39;&#39;&#39;<br>                    }<br>                }<br>            }<br>        }<br>        stage(&#39;Quality Check&#39;) {<br>            steps {<br>                script {<br>                    waitForQualityGate abortPipeline: false, credentialsId: &#39;sonar-token&#39; <br>                }<br>            }<br>        }<br>        stage(&#39;OWASP Dependency-Check Scan&#39;) {<br>            steps {<br>                dir(&#39;Application-Code/frontend&#39;) {<br>                    dependencyCheck additionalArguments: &#39;--scan ./ --disableYarnAudit --disableNodeAudit&#39;, odcInstallation: &#39;DP-Check&#39;<br>                    dependencyCheckPublisher pattern: &#39;**/dependency-check-report.xml&#39;<br>                }<br>            }<br>        }<br>        stage(&#39;Trivy File Scan&#39;) {<br>            steps {<br>                dir(&#39;Application-Code/frontend&#39;) {<br>                    sh &#39;trivy fs . &gt; trivyfs.txt&#39;<br>                }<br>            }<br>        }<br>        stage(&quot;Docker Image Build&quot;) {<br>            steps {<br>                script {<br>                    dir(&#39;Application-Code/frontend&#39;) {<br>                            sh &#39;docker system prune -f&#39;<br>                            sh &#39;docker container prune -f&#39;<br>                            sh &#39;docker build -t ${AWS_ECR_REPO_NAME} .&#39;<br>                    }<br>                }<br>            }<br>        }<br>        stage(&quot;ECR Image Pushing&quot;) {<br>            steps {<br>                script {<br>                        sh &#39;aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | docker login --username AWS --password-stdin ${REPOSITORY_URI}&#39;<br>                        sh &#39;docker tag ${AWS_ECR_REPO_NAME} ${REPOSITORY_URI}${AWS_ECR_REPO_NAME}:${BUILD_NUMBER}&#39;<br>                        sh &#39;docker push ${REPOSITORY_URI}${AWS_ECR_REPO_NAME}:${BUILD_NUMBER}&#39;<br>                }<br>            }<br>        }<br>        stage(&quot;TRIVY Image Scan&quot;) {<br>            steps {<br>                sh &#39;trivy image ${REPOSITORY_URI}${AWS_ECR_REPO_NAME}:${BUILD_NUMBER} &gt; trivyimage.txt&#39; <br>            }<br>        }<br>        stage(&#39;Checkout Code&#39;) {<br>            steps {<br>                git credentialsId: &#39;GITHUB&#39;, url: &#39;https://github.com/thakurrajeshPathak-DevOps/End-to-End-Kubernetes-Three-Tier-DevSecOps-Project.git&#39;<br>            }<br>        }<br>        stage(&#39;Update Deployment file&#39;) {<br>            environment {<br>                GIT_REPO_NAME = &quot;End-to-End-Kubernetes-Three-Tier-DevSecOps-Project&quot;<br>                GIT_USER_NAME = &quot;thakurrajeshPathak-DevOps&quot;<br>            }<br>            steps {<br>                dir(&#39;Kubernetes-Manifests-file/Frontend&#39;) {<br>                    withCredentials([string(credentialsId: &#39;github&#39;, variable: &#39;GITHUB_TOKEN&#39;)]) {<br>                        sh &#39;&#39;&#39;<br>                            git config user.email &quot;thakurrajesh07@gmail.com&quot;<br>                            git config user.name &quot;thakurrajesh-DevOps&quot;<br>                            BUILD_NUMBER=${BUILD_NUMBER}<br>                            echo $BUILD_NUMBER<br>                            imageTag=$(grep -oP &#39;(?&lt;=frontend:)[^ ]+&#39; deployment.yaml)<br>                            echo $imageTag<br>                            sed -i &quot;s/${AWS_ECR_REPO_NAME}:${imageTag}/${AWS_ECR_REPO_NAME}:${BUILD_NUMBER}/&quot; deployment.yaml<br>                            git add deployment.yaml<br>                            git commit -m &quot;Update deployment Image to version \${BUILD_NUMBER}&quot;<br>                            git push @github.com/${GIT_USER_NAME}/${GIT_REPO_NAME&quot;&gt;https://${GITHUB_TOKEN}@github.com/${GIT_USER_NAME}/${GIT_REPO_NAME} HEAD:master<br>                        &#39;&#39;&#39;<br>                    }<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>To delete the EKS cluster :-</p><pre>eksctl delete cluster --name three-tier-cluster --region us-west-2</pre><p>K<strong><em>eyPoint :-</em></strong></p><p>Q1 :- What is difference between package.json and package-lock.json</p><p><strong><em>package.json:</em> </strong>Manifest file containing project metadata and list of dependencies. Developers modify it directly to manage project configuration, metadata, and dependencies.</p><p><strong><em>package-lock.json:</em></strong> Automatically generated file that records the exact versions of installed dependencies. This ensures consistency across different environments and builds by providing a detailed snapshot of dependencies, their versions, and their dependencies.</p><p>Q2. Difference Between <strong><em>RUN and CMD</em></strong> in docker file?</p><p><strong><em>RUN</em></strong> :- Used in the Dockerfile to execute commands during the image build process. This is to set up the environment inside the image by installing dependencies, configuring software, etc. <strong><em>Each RUN instruction creates a new layer in the image.</em></strong></p><p><strong><em>cmd :</em></strong> specifies the default command to run when the container is started from the image. A Dockerfile can contain only one CMD directive, and it defines the command to execute by default. <strong><em>This can be overridden at runtime by providing a command when running the container.</em></strong></p><p>Q3:- What is <strong>Rolling Update?</strong></p><p>It means , if any new build occur/created , then it will replace old build. So to replace it fast, we used rolling update.</p><p>Q4:- What is <strong>Headless Service ?</strong></p><p>It is type of K8S service that does not allocate a cluster ip address .Instead headless service uses <strong>DNS to expose the IP addresses</strong> of the pods that are associated with the service. This allows you to connect directly to the pods <strong><em>instead of going through a proxy.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9689acc72bde" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[THE ULTIMATE CICD AWS CLOUD &DEVOPS PIPELINE PROJECT END to END..]]></title>
            <link>https://medium.com/@akulamanojkumar988/the-ultimate-cicd-aws-cloud-devops-pipeline-project-end-to-end-79977bbb869e?source=rss-100b6452cd9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/79977bbb869e</guid>
            <dc:creator><![CDATA[manojkumar]]></dc:creator>
            <pubDate>Tue, 19 Mar 2024 11:13:21 GMT</pubDate>
            <atom:updated>2024-03-19T11:13:21.709Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yVWbGJx6JE5W2L7o.png" /></figure><p><strong>CHAPTER-1 | Setup Infra</strong></p><p>To create an Ubuntu EC2 instance in AWS, follow these steps:</p><p><strong>1. Sign in to the AWS Management Console:</strong></p><p>Go to the AWS Management Console at <a href="https://aws.amazon.com/console/">https://aws.amazon.com/console/.</a></p><p>Sign in with your AWS account credentials.</p><p><strong>2. Navigate to EC2:</strong></p><p>Once logged in, navigate to the EC2 dashboard by typing “EC2” in the search bar at the top or by selecting “Services” and then “EC2” under the “Compute” section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LncRvJhx98fUqLUd.png" /></figure><p><strong>3. Launch Ec2 Instance:</strong></p><p>Click on the “Instances” link in the EC2 dashboard sidebar.</p><p>Click the “Launch Instance” button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wtvP0kcmYKr1Jw1G.png" /></figure><p><strong>4. Choose an Amazon Machine Image (AMI):</strong></p><p>In the “Step 1: Choose an Amazon Machine Image (AMI)” section, select “Ubuntu” from the list of available AMIs.</p><p>Choose the Ubuntu version you want to use. For example, “Ubuntu Server 20.04 LTS”.</p><p>Click “Select”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-92CHynF2BHkEcf2.png" /></figure><p><strong>5. Choose an Instance Type:</strong></p><p>In the “Step 2: Choose an Instance Type” section, select the instance type that fits your requirements. The default option (usually a t2.micro instance) is suitable for testing and small workloads.</p><p>Click “Next: Configure Instance Details”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VwKtPLdM_OZlgS0p.png" /></figure><p><strong>6. Configure Instance Details:</strong></p><p>Optionally, configure instance details such as network settings, subnets, IAM role, etc. You can leave these settings as default for now.</p><p>Click “Next: Add Storage”.</p><p><strong>7. Add Storage:</strong></p><p>Specify the size of the root volume (default is usually fine for testing purposes).</p><p>Click “Next: Add Tags”.</p><p><strong>8. Add Tags:</strong></p><p>Optionally, add tags to your instance for better organization and management.</p><p>Click “Next: Configure Security Group”.</p><p><strong>9. Configure Security Group:</strong></p><p>In the “Step 6: Configure Security Group” section, configure the security group to allow SSH access (port 22) from your IP address.</p><p>You may also want to allow other ports based on your requirements (e.g., HTTP, HTTPS) as in this pic</p><p>Click “Review and Launch”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wWsWNycZ3ifSAyeT.png" /></figure><p><strong>10. Review and Launch:</strong></p><p>Review the configuration of your instance.</p><p>Click “Launch”.</p><p><strong>11. Select Key Pair:</strong></p><p>In the pop-up window, select an existing key pair or create a new one.</p><p>Check the acknowledgment box.</p><p>Click “Launch Instances”.</p><p><strong>12. Access Your Instance:</strong></p><p>Use Mobaxterm</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cod4gcAVPbD3Ofvo.png" /></figure><h3>Setup K8-Cluster using kubeadm [K8 Version →1.28.1]</h3><p>1. Update System Packages [On Master &amp; Worker Node]</p><p>sudo apt-get update</p><p>2. Install Docker[On Master &amp; Worker Node]</p><pre>sudo apt update<br>#Install Required Packages for Docker: Install packages to allow apt to use a repository over HTTPS:<br>sudo apt install apt-transport-https ca-certificates curl software-properties-common -y</pre><pre>#Add Docker’s Official GPG Key: Add Docker’s official GPG key to ensure the authenticity of the software package:<br>curl -fsSL <a href="https://download.docker.com/linux/ubuntu/gpg">https://download.docker.com/linux/ubuntu/gpg</a> | sudo apt-key add -</pre><pre>#Set Up the Docker Repository: Add the Docker repository to your system&#39;s APT sources<br>sudo add-apt-repository &quot;deb [arch=amd64] <a href="https://download.docker.com/linux/ubuntu">https://download.docker.com/linux/ubuntu</a> $(lsb_release -cs) stable&quot;</pre><pre>#Update the Package Database with Docker Packages: Update the apt package index again:<br>sudo apt update</pre><pre>#Install Docker: Now, you can install Docker from the Docker repository:<br>sudo apt install docker-ce -y</pre><pre>#Check Docker Version: To verify that Docker is installed correctly, you can check its version:<br>docker --version</pre><pre>#Manage Docker as a Non-root User (Optional): If you want to run Docker commands without using sudo, add your user to the docker group:<br>sudo usermod -aG docker ${USER}</pre><p><strong>3. Install Required Dependencies for Kubernetes[On Master &amp; Worker Node]</strong></p><pre># disable swap<br>sudo swapoff -a</pre><pre># Create the .conf file to load the modules at bootup<br>cat &lt;&lt;EOF | sudo tee /etc/modules-load.d/k8s.conf<br>overlay<br>br_netfilter<br>EOF</pre><pre>sudo modprobe overlay<br>sudo modprobe br_netfilter</pre><pre># sysctl params required by setup, params persist across reboots<br>cat &lt;&lt;EOF | sudo tee /etc/sysctl.d/k8s.conf<br>net.bridge.bridge-nf-call-iptables  = 1<br>net.bridge.bridge-nf-call-ip6tables = 1<br>net.ipv4.ip_forward                 = 1<br>EOF</pre><pre># Apply sysctl params without reboot<br>sudo sysctl --system</pre><pre>## Install CRIO Runtime<br>sudo apt-get update -y<br>sudo apt-get install -y software-properties-common curl apt-transport-https ca-certificates gpg</pre><pre>sudo curl -fsSL <a href="https://pkgs.k8s.io/addons:/cri-o:/prerelease:/main/deb/Release.key">https://pkgs.k8s.io/addons:/cri-o:/prerelease:/main/deb/Release.key</a> | sudo gpg --dearmor -o /etc/apt/keyrings/cri-o-apt-keyring.gpg<br>echo &quot;deb [signed-by=/etc/apt/keyrings/cri-o-apt-keyring.gpg] <a href="https://pkgs.k8s.io/addons:/cri-o:/prerelease:/main/deb/">https://pkgs.k8s.io/addons:/cri-o:/prerelease:/main/deb/</a> /&quot; | sudo tee /etc/apt/sources.list.d/cri-o.list</pre><pre>sudo apt-get update -y<br>sudo apt-get install -y cri-o</pre><pre>sudo systemctl daemon-reload<br>sudo systemctl enable crio --now<br>sudo systemctl start crio.service</pre><pre>echo &quot;CRI runtime installed successfully&quot;</pre><pre># Add Kubernetes APT repository and install required packages<br>curl -fsSL <a href="https://pkgs.k8s.io/core:/stable:/v1.29/deb/Release.key">https://pkgs.k8s.io/core:/stable:/v1.29/deb/Release.key</a> | sudo gpg --dearmor -o /etc/apt/keyrings/kubernetes-apt-keyring.gpg<br>echo &#39;deb [signed-by=/etc/apt/keyrings/kubernetes-apt-keyring.gpg] <a href="https://pkgs.k8s.io/core:/stable:/v1.29/deb/">https://pkgs.k8s.io/core:/stable:/v1.29/deb/</a> /&#39; | sudo tee /etc/apt/sources.list.d/kubernetes.list</pre><pre>sudo apt-get update -y<br>sudo apt-get install -y kubelet=&quot;1.29.0-*&quot; kubectl=&quot;1.29.0-*&quot; kubeadm=&quot;1.29.0-*&quot;<br>sudo apt-get update -y<br>sudo apt-get install -y jq</pre><pre>sudo systemctl enable --now kubelet<br>sudo systemctl start kubelet</pre><p>N<strong>ote :- </strong>If you are getting the error which is given below , then use command .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*iCf8Lq0BF7RW68sU.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/0*rcYRXP3epUUlcd1t.png" /></figure><p><strong>4. Update Package List[On Master &amp; Worker Node]</strong></p><p>sudo apt update</p><p><strong>5. Initialize Kubernetes Master Node [On MasterNode]</strong></p><p>sudo kubeadm init — pod-network-cidr=10.244.0.0/16</p><p>8. Configure Kubernetes Cluster [On MasterNode]</p><p>mkdir -p $HOME/.kube</p><p>sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config sudo chown $(id -u):$(id -g) $HOME/.kube/config</p><p>9. Deploy Networking Solution (Calico) [On MasterNode]</p><p>kubectl apply -f <a href="https://docs.projectcalico.org/v3.20/manifests/calico.yaml">https://docs.projectcalico.org/v3.20/manifests/calico.yaml</a></p><p>10. Deploy Ingress Controller (NGINX) [On MasterNode]</p><p>kubectl apply -f <a href="https://raw.githubusercontent.com/kubernetes/ingress-">https://raw.githubusercontent.com/kubernetes/ingress-</a> nginx/controller-v0.49.0/deploy/static/provider/baremetal/deploy.yaml</p><h3>Installing Jenkins on Ubuntu</h3><pre>#!/bin/bash<br># Install OpenJDK 17 JRE Headless<br>sudo apt install openjdk-17-jre-headless -y<br># Download Jenkins GPG key<br>sudo wget -O /usr/share/keyrings/jenkins-keyring.asc \ https://pkg.jenkins.io/debian-stable/jenkins.io-2023.key<br># Add Jenkins repository to package manager sources<br>echo deb [signed-by=/usr/share/keyrings/jenkins-keyring.asc] \ https://pkg.jenkins.io/debian-stable binary/ | sudo tee \<br>/etc/apt/sources.list.d/jenkins.list &gt; /dev/null<br># Update package manager repositories sudo apt-get update<br># Install Jenkins<br>sudo apt-get install jenkins -y</pre><p>Save this script in a file, for example, install_jenkins.sh, and make it executable using:</p><p>chmod +x install_jenkins.sh</p><p>Then, you can run the script using:</p><p>./install_jenkins.sh</p><p>This script will automate the installation process of OpenJDK 17 JRE Headless and Jenkins.</p><p><strong>Install docker for future use</strong></p><pre>#!/bin/bash<br># Update package manager repositories sudo apt-get update<br># Install necessary dependencies<br>sudo apt-get install -y ca-certificates curl<br># Create directory for Docker GPG key sudo install -m 0755 -d /etc/apt/keyrings<br># Download Docker&#39;s GPG key<br>sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o<br>/etc/apt/keyrings/docker.asc<br># Ensure proper permissions for the key sudo chmod a+r /etc/apt/keyrings/docker.asc<br># Add Docker repository to Apt sources<br>echo &quot;deb [arch=$(dpkg - print-architecture) signed- by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu \<br>$(. /etc/os-release &amp;&amp; echo &quot;$VERSION_CODENAME&quot;) stable&quot; | \ sudo tee /etc/apt/sources.list.d/docker.list &gt; /dev/null<br># Update package manager repositories sudo apt-get update<br>sudo apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin</pre><p><strong>Save this script in a file, for example</strong>, install_docker.sh, <strong>and make it executable using</strong>:</p><p>chmod +x install_docker.sh</p><p>Then, you can run the script using:</p><p>./install_docker.sh</p><h3>SetUp Nexus</h3><pre>#!/bin/bash<br># Update package manager repositories sudo apt-get update<br># Install necessary dependencies<br>sudo apt-get install -y ca-certificates curl<br># Create directory for Docker GPG key sudo install -m 0755 -d /etc/apt/keyrings<br># Download Docker&#39;s GPG key<br>sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o<br>/etc/apt/keyrings/docker.asc<br># Ensure proper permissions for the key sudo chmod a+r /etc/apt/keyrings/docker.asc<br># Add Docker repository to Apt sources<br>echo &quot;deb [arch=$(dpkg - print-architecture) signed- by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu \<br>$(. /etc/os-release &amp;&amp; echo &quot;$VERSION_CODENAME&quot;) stable&quot; | \ sudo tee /etc/apt/sources.list.d/docker.list &gt; /dev/null<br># Update package manager repositories sudo apt-get update<br>sudo apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin</pre><p><strong>Save this script in a file, for example</strong>, install_docker.sh, <strong>and make it executable using:</strong></p><p>chmod +x install_docker.sh</p><p>Then, you can run the script using:</p><p>./install_docker.sh</p><p>Create Nexus using docker container</p><p>To create a Docker container running Nexus 3 and exposing it on port 8081, you can use the following command:</p><p>docker run -d — name nexus -p 8081:8081 sonatype/nexus3:latest</p><p>This command does the following:</p><p>· -d: Detaches the container and runs it in the background.</p><p>· — name nexus: Specifies the name of the container as “nexus”.</p><p>· -p 8081:8081: Maps port 8081 on the host to port 8081 on the container, allowing access to Nexus through port 8081.</p><p>· sonatype/nexus3:latest: Specifies the Docker image to use for the container, in this case, the latest version of Nexus 3 from the Sonatype repository.</p><p>After running this command, Nexus will be accessible on your host machine at <a href="http://ip:8081./">http://IP:8081.</a></p><p>Get Nexus initial password</p><p>Your provided commands are correct for accessing the Nexus password stored in the container. Here’s a breakdown of the steps:</p><p>1. <strong>Get Container ID</strong>: You need to find out the ID of the Nexus container. You can do this by running:</p><p>docker ps</p><p>This command lists all running containers along with their IDs, among other information.</p><p>2. <strong>Access Container’s Bash Shell</strong>: Once you have the container ID, you can execute the docker exec command to access the container’s bash shell: docker exec -it &lt;container_ID&gt; /bin/bash</p><p>Replace &lt;container_ID&gt; with the actual ID of the Nexus container.</p><p>3. <strong>Navigate to Nexus Directory</strong>: Inside the container’s bash shell, navigate to the directory where Nexus stores its configuration:</p><p>cd sonatype-work/nexus3</p><p>4. <strong>View Admin Password</strong>: Finally, you can view the admin password by displaying the contents of the admin.password file:</p><p>cat admin.password</p><p>5. <strong>Exit the Container Shell</strong>: Once you have retrieved the password, you can exit the container’s bash shell:</p><p>exit</p><p>This process allows you to access the Nexus admin password stored within the container. Make sure to keep this password secure, as it grants administrative access to your Nexus instance.</p><h3>SetUp SonarQube</h3><pre>#!/bin/bash<br># Update package manager repositories sudo apt-get update<br># Install necessary dependencies<br>sudo apt-get install -y ca-certificates curl<br># Create directory for Docker GPG key sudo install -m 0755 -d /etc/apt/keyrings<br># Download Docker&#39;s GPG key<br>sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o<br>/etc/apt/keyrings/docker.asc<br># Ensure proper permissions for the key sudo chmod a+r /etc/apt/keyrings/docker.asc<br># Add Docker repository to Apt sources<br>echo &quot;deb [arch=$(dpkg - print-architecture) signed- by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu \<br>$(. /etc/os-release &amp;&amp; echo &quot;$VERSION_CODENAME&quot;) stable&quot; | \ sudo tee /etc/apt/sources.list.d/docker.list &gt; /dev/null<br># Update package manager repositories sudo apt-get update<br>sudo apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin</pre><p><strong>Save this script in a file, for example</strong>, install_docker.sh, <strong>and make it executable using:</strong></p><p>chmod +x install_docker.sh</p><p>Then, you can run the script using:</p><p>./install_docker.sh</p><p>Create Sonarqube Docker container</p><p>To run SonarQube in a Docker container with the provided command, you can follow these steps:</p><p>1. Open your terminal or command prompt.</p><p>2. Run the following command:</p><p>docker run -d — name sonar -p 9000:9000 sonarqube:lts-community</p><p>This command will download the sonarqube:lts-community Docker image from Docker Hub if it’s not already available locally. Then, it will create a container named “sonar”</p><p>from this image, running it in detached mode (-d flag) and mapping port 9000 on the host machine to port 9000 in the container (-p 9000:9000 flag).</p><p>3. Access SonarQube by opening a web browser and navigating to <a href="http://vmip:9000./">http://VmIP:9000.</a></p><p>This will start the SonarQube server, and you should be able to access it using the provided URL. If you’re running Docker on a remote server or a different port, replace localhost with the appropriate hostname or IP address and adjust the port accordingly.</p><h3>CHAPTER-2 | Private Git Setup</h3><p>Steps to create a private Git repository, generate a personal access token, connect to the repository, and push code to it:</p><p>1. Create a Private Git Repository:</p><p>Go to your preferred Git hosting platform (e.g., GitHub, GitLab, Bitbucket).</p><p>Log in to your account or sign up if you don’t have one.</p><p>Create a new repository and set it as private.</p><p>2 Generate a Personal Access Token:</p><p>Navigate to your account settings or profile settings.</p><p>Look for the “Developer settings” or “Personal access tokens” section.</p><p>Generate a new token, providing it with the necessary permissions (e.g., repo access).</p><p>3. Clone the Repository Locally:</p><p>Open Git Bash or your terminal.</p><p>Navigate to the directory where you want to clone the repository.</p><p>Use the git clone command followed by the repository’s URL. For example:</p><p>git clone &lt;repository_URL&gt;</p><p>4. Replace &lt;repository_URL&gt; with the URL of your private repository.</p><p>5. Add Your Source Code Files:</p><p>Navigate into the cloned repository directory.</p><p>Paste your source code files or create new ones inside this directory.</p><p>6. Stage and Commit Changes:</p><p>Use the git add command to stage the changes:</p><p>git add .</p><p>Use the git commit command to commit the staged changes along with a meaningful message:</p><p>git commit -m “Your commit message here”</p><p>7. Push Changes to the Repository:</p><p>Use the git push command to push your committed changes to the remote repository:</p><p>git push</p><p>If it’s your first time pushing to this repository, you might need to specify the remote and branch:</p><p>git push -u origin master</p><p>8. Replace master with the branch name if you’re pushing to a different branch.</p><p>9. Enter Personal Access Token as Authentication:</p><p>When prompted for credentials during the push, enter your username (usually your email) and use your personal access token as the password.</p><p>By following these steps, you’ll be able to create a private Git repository, connect to it using Git Bash, and push your code changes securely using a personal access token for authentication.</p><h3>CHESTER-4| CICD</h3><p>Install below Plugins in Jenkins</p><p>1. Eclipse Temurin Installer:</p><p>This plugin enables Jenkins to automatically install and configure the Eclipse Temurin JDK (formerly known as AdoptOpenJDK).</p><p>To install, go to Jenkins dashboard -&gt; Manage Jenkins -&gt; Manage Plugins -&gt; Available tab.</p><p>Search for “Eclipse Temurin Installer” and select it.</p><p>Click on the “Install without restart” button.</p><p>2. Pipeline Maven Integration:</p><p>This plugin provides Maven support for Jenkins Pipeline.</p><p>It allows you to use Maven commands directly within your Jenkins Pipeline scripts.</p><p>To install, follow the same steps as above, but search for “Pipeline Maven Integration” instead.</p><p>3. Config File Provider:</p><p>This plugin allows you to define configuration files (e.g., properties, XML, JSON) centrally in Jenkins.</p><p>These configurations can then be referenced and used by your Jenkins jobs.</p><p>Install it using the same procedure as mentioned earlier.</p><p>4. SonarQube Scanner:</p><p>SonarQube is a code quality and security analysis tool.</p><p>This plugin integrates Jenkins with SonarQube by providing a scanner that analyzes code during builds.</p><p>You can install it from the Jenkins plugin manager as described above.</p><p>5. Kubernetes CLI:</p><p>This plugin allows Jenkins to interact with Kubernetes clusters using the Kubernetes command-line tool (kubectl).</p><p>It’s useful for tasks like deploying applications to Kubernetes from Jenkins jobs.</p><p>Install it through the plugin manager.</p><p>6. Kubernetes:</p><p>This plugin integrates Jenkins with Kubernetes by allowing Jenkins agents to run as pods within a Kubernetes cluster.</p><p>It provides dynamic scaling and resource optimization capabilities for Jenkins builds.</p><p>Install it from the Jenkins plugin manager.</p><p>7. Docker:</p><p>This plugin allows Jenkins to interact with Docker, enabling Docker builds and integration with Docker registries.</p><p>You can use it to build Docker images, run Docker containers, and push/pull images from Docker registries.</p><p>Install it from the plugin manager.</p><p>8. Docker Pipeline Step:</p><p>This plugin extends Jenkins Pipeline with steps to build, publish, and run Docker containers as part of your Pipeline scripts.</p><p>It provides a convenient way to manage Docker containers directly from Jenkins Pipelines.</p><p>Install it through the plugin manager like the others.</p><p>After installing these plugins, you may need to configure them according to your specific environment and requirements. This typically involves setting up credentials, configuring paths, and specifying options in Jenkins global configuration or individual job configurations. Each plugin usually comes with its own set of documentation to guide you through the configuration process.</p><p>Configure Above Plugins in Jenkins Pipeline</p><pre>pipeline { agent any<br>tools {<br>jdk &#39;jdk17&#39;<br>maven &#39;maven3&#39;<br>}<br>enviornment {<br>SCANNER_HOME= tool &#39;sonar-scanner&#39;<br>}<br>stages {<br>stage(&#39;Git Checkout&#39;) {<br>steps {<br>git branch: &#39;main&#39;, credentialsId: &#39;git-cred&#39;, url: &#39;https://github.com/jaiswaladi246/Boardgame.git&#39;<br>}<br>}<br>stage(&#39;Compile&#39;) { steps {<br>sh &quot;mvn compile&quot;<br>}<br>}<br>stage(&#39;Test&#39;) { steps {<br>sh &quot;mvn test&quot;<br>}<br>}<br>stage(&#39;File System Scan&#39;) { steps {<br>sh &quot;trivy fs - format table -o trivy-fs-report.html .&quot;<br>}<br>}<br>stage(&#39;SonarQube Analsyis&#39;) { steps {<br>withSonarQubeEnv(&#39;sonar&#39;) {<br>sh &#39;&#39;&#39; $SCANNER_HOME/bin/sonar-scanner - Dsonar.projectName=BoardGame -Dsonar.projectKey=BoardGame \<br>-Dsonar.java.binaries=. &#39;&#39;&#39;<br>}<br>}<br>}<br>stage(&#39;Quality Gate&#39;) { steps {<br>script {<br>waitForQualityGate abortPipeline: false, credentialsId: &#39;sonar-token&#39;<br>}<br>}<br>}<br>stage(&#39;Build&#39;) { steps {<br>sh &quot;mvn package&quot;<br>}<br>}<br>stage(&#39;Publish To Nexus&#39;) { steps {<br>withMaven(globalMavenSettingsConfig: &#39;global-settings&#39;, jdk: &#39;jdk17&#39;, maven: &#39;maven3&#39;, mavenSettingsConfig: &#39;&#39;, traceability: true) {<br>sh &quot;mvn deploy&quot;<br>}<br>}<br>}<br>stage(&#39;Build &amp; Tag Docker Image&#39;) { steps {<br>script {<br>withDockerRegistry(credentialsId: &#39;docker-cred&#39;, toolName: &#39;docker&#39;) { sh &quot;docker build -t adijaiswal/boardshack:latest .&quot;<br>}<br>}<br>}<br>}<br>stage(&#39;Docker Image Scan&#39;) { steps {<br>sh &quot;trivy image - format table -o trivy-image-report.html adijaiswal/boardshack:latest &quot;<br>}<br>}<br>stage(&#39;Push Docker Image&#39;) { steps {<br>script {<br>withDockerRegistry(credentialsId: &#39;docker-cred&#39;, toolName: &#39;docker&#39;) { sh &quot;docker push adijaiswal/boardshack:latest&quot;<br>}<br>}<br>}<br>}<br>stage(&#39;Deploy To Kubernetes&#39;) { steps {<br>withKubeConfig(caCertificate: &#39;&#39;, clusterName: &#39;kubernetes&#39;, contextName: &#39;&#39;, credentialsId: &#39;k8-cred&#39;, namespace: &#39;webapps&#39;, restrictKubeConfigAccess: false, serverUrl: &#39;https://172.31.8.146:6443&#39;) {<br>sh &quot;kubectl apply -f deployment-service.yaml&quot;<br>}<br>}<br>}<br>stage(&#39;Verify the Deployment&#39;) { steps {<br>withKubeConfig(caCertificate: &#39;&#39;, clusterName: &#39;kubernetes&#39;, contextName: &#39;&#39;, credentialsId: &#39;k8-cred&#39;, namespace: &#39;webapps&#39;, restrictKubeConfigAccess: false, serverUrl: &#39;https://172.31.8.146:6443&#39;) {<br>sh &quot;kubectl get pods -n webapps&quot;<br>sh &quot;kubectl get svc -n webapps&quot;<br>}<br>}<br>}<br>}<br>post { always {<br>script {<br>def jobName = env.JOB_NAME<br>def buildNumber = env.BUILD_NUMBER<br>def pipelineStatus = currentBuild.result ?: &#39;UNKNOWN&#39;<br>def bannerColor = pipelineStatus.toUpperCase() == &#39;SUCCESS&#39; ? &#39;green&#39; : &#39;red&#39;<br>def body = &quot;&quot;&quot;<br>&lt;html&gt;<br>&lt;body&gt;<br>&lt;div style=&quot;border: 4px solid ${bannerColor}; padding:<br>10px;&quot;&gt;<br>10px;&quot;&gt;<br>&lt;h2&gt;${jobName} - Build ${buildNumber}&lt;/h2&gt;<br>&lt;div style=&quot;background-color: ${bannerColor}; padding:<br>&lt;h3 style=&quot;color: white;&quot;&gt;Pipeline Status:<br>${pipelineStatus.toUpperCase()}&lt;/h3&gt;<br>&lt;/div&gt;<br>&lt;p&gt;Check the &lt;a href=&quot;${BUILD_URL}&quot;&gt;console<br>output&lt;/a&gt;.&lt;/p&gt;<br>&quot;&quot;&quot;<br>&lt;/div&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;<br>emailext (<br>subject: &quot;${jobName} - Build ${buildNumber} -<br>${pipelineStatus.toUpperCase()}&quot;, body: body,<br>to: &#39;thakurrajesh22293@gmail.com&#39;, from: &#39;jenkins@example.com&#39;, replyTo: &#39;jenkins@example.com&#39;, mimeType: &#39;text/html&#39;,<br>attachmentsPattern: &#39;trivy-image-report.html&#39;<br>)<br>}<br>}<br>}<br>}</pre><h3>PHASE-5 | Monitoring</h3><h3>Highly recommended to follow the steps shown in video</h3><p><strong>Links to download Prometheus, Node_Exporter &amp; black Box exporter </strong><a href="https://prometheus.io/download/"><strong>https://prometheus.io/download/</strong></a></p><h3>Links to download</h3><p><strong>Grafana </strong><a href="https://grafana.com/grafana/download"><strong>https://grafana.com/grafana/download</strong></a></p><h3>Other link from</h3><p><strong>video </strong><a href="https://github.com/prometheus/blackbox_exporter"><strong>https://github.com/prometheus/blackbox_exporter</strong></a></p><p><a href="https://medium.com/tag/jenkins?source=post_page-----05fda4220812---------------jenkins-----------------">Jenkins</a> <a href="https://medium.com/tag/jenkins-pipeline?source=post_page-----05fda4220812---------------jenkins_pipeline-----------------">Jenkins Pipeline</a> <a href="https://medium.com/tag/maven?source=post_page-----05fda4220812---------------maven-----------------">Maven</a> <a href="https://medium.com/tag/devops?source=post_page-----05fda4220812---------------devops-----------------">DevOps</a> <a href="https://medium.com/tag/devops-project?source=post_page-----05fda4220812---------------devops_project-----------------">Devops Project</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79977bbb869e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solace’s SEMPv2 to integrate with CI/CD pipelines using Ansible and Jenkins]]></title>
            <link>https://medium.com/@akulamanojkumar988/solaces-sempv2-to-integrate-with-ci-cd-pipelines-using-ansible-and-jenkins-43b8ab3f60d1?source=rss-100b6452cd9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/43b8ab3f60d1</guid>
            <dc:creator><![CDATA[manojkumar]]></dc:creator>
            <pubDate>Thu, 14 Mar 2024 06:23:36 GMT</pubDate>
            <atom:updated>2024-03-14T06:23:36.602Z</atom:updated>
            <content:encoded><![CDATA[<h3>Using Solace’s SEMPv2 to integrate with CI/CD pipelines using Ansible and Jenkins</h3><p>This sample demostrates how you can use Solace’s SEMPv2 management API to perform automated provisioning of Solace configuration, as well as integrate the automated provisioning of your Solace environment with your CI/CD Pipeline.</p><p>There are two ways you can get started:</p><ul><li>If your company has Solace message routers deployed, contact your middleware team to obtain the host name or IP address of a Solace message router to test against, a username and password to access it, and a VPN in which you can produce and consume messages.</li><li>If you do not have access to a Solace message router, you will need to go through the “<a href="http://docs.solace.com/Solace-VMR-Set-Up/Setting-Up-VMRs.htm">Set up a VMR</a>” tutorial to download and install the software.</li></ul><p>Ensure that you are running a version of SolOS that supports the SEMPv2 management API. SEMPv2 was introduced in the following releases:</p><ul><li>Virtual Message Router: SolOS 7.2.1</li><li>Message Router Appliance: SolOS 7.2.2</li></ul><p>NOTE: The sample has been created to illustrate how SEMPv2 can be used to integrate Solace with a CI/CD pipeline. You may need to modify the samples to align with your custom environment, as well as apply security, hardening and other production readiness considerations as necessary.</p><h3>Contents</h3><p><a href="https://www.ansible.com/">Ansible</a> is an open source tool for automating tasks such as application deployment, IT service orchestration, cloud provisioning and many more. Ansible is easy to deploy, does not use any agents, and has a simple learning curve. Ansible uses “playbooks” to describe its automation jobs, known as “tasks” and the playbooks are described using YAML.</p><p>This repository contains an ansible playbook which uses the Solace SEMPv2 RESTful administration API to create a new messaging environment on an existing Solace message router. Ansible’s <a href="http://docs.ansible.com/ansible/latest/uri_module.html">URI</a> module is used to interact with the SEMPv2 API.</p><p>For a nice introduction to the SEMPv2 Management API , check out this <a href="https://solace.com/blog/products-tech/introducing-semp-v2-solace-message-routers-configuration-reinvented">blog</a>, as well as the <a href="http://dev.solace.com/get-started/semp-tutorials/">SEMP tutorials home page</a></p><p>The sample can be used for automated deployment of your Solace messaging environments for Continuous Integration. Additionally, you can integrate this into your pipeline for Continuous Deployments. This is explained in the subsequent sections.</p><h3>Automated provisioning in a CI environment using Ansible</h3><p>Using Ansible, you can automatically provision configuration on the Solace router. The Ansible playbook consists of a number of tasks, and each task uses Solace’s SEMPv2 Management API to create a new Solace message-vpn on an existing Solace message router along with associated objects:</p><ul><li>Client Profiles</li><li>ACL Profiles</li><li>Client Usernames</li><li>Queue Endpoints</li></ul><p>If the objects already exist, this is indicated in the playbook run’s output. It is not treated as a failure of the Ansible task, and the playbook execution continues to to the next task. Object properties can be specified in a configuration files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/0*abmGJnUUc6YuRAqZ.jpg" /></figure><h3>Pre-requisites</h3><ol><li>Install <a href="https://www.ansible.com/">Ansible</a></li><li>The host running the samples should have network connectivity to the management IP of the Solace Router</li><li>A Management user must be created on the Solace router and given a global-access-level of read-write.</li></ol><h3>Checking out and building</h3><p>To check out the project and build it, do the following:</p><ol><li>clone this GitHub repository</li><li>cd solace-ci-cd-demo</li></ol><h3>Configuring the CI Demo:</h3><ol><li>Edit the Ansible inventory: Edit the inventory.ini to specify the Solace routers on which the messaging environment is to be created. You can create one or more host groups against which the Ansible playbook will be run.</li></ol><p>For example:</p><pre>[solace]<br>sgdemo mgmt_host=192.168.42.11 mgmt_port=80 semp_username=ansible semp_password=ansible</pre><p>NOTE: Do not edit the solace-vars group or its contents</p><ol><li>Edit the configuration files: The configuration for Solace environments to be created is specified in vars/solace-env.yml. Edit the configuration objects as necessary. The current version of the sample supports the creation of:</li></ol><ul><li>A single message-vpn</li><li>One or more client profiles within the message-vpn</li><li>One or more ACL profiles within the message-vpn</li><li>One or more Client Usernames within the message-vpn</li><li>One or more Queues within the message-vpn, with topic subscriptions on these queues</li></ul><p>NOTE:</p><ul><li>The current version of this sample does not support the externalization of all the configuration properties for the Solace environment. Only some properties are specified in the configuration files, and more properties can be added along with appropriate changes to your ansible playbook, depending on your environment.</li><li>The sample currently does not have the feature to remove any message-vpns when they are removed from the configuration file.This operation will have to be performed manually.</li></ul><h3>Running the CI Demo:</h3><p>In order to run the Ansible playbook, use:</p><p>ansible-playbook create-solace-vpn.yml -i inventory.ini</p><h3>Integrating with a Continuous Delivery System</h3><p>The Continuous Integration demo can now be integrated with Jenkins and Git for setting up a Continuous Delivery System. The below figure shows a sample CD pipeline, using Git, Jenkins and Ansible — I’ve chosen them as they are the common DevOps tools for CD, but you can replace parts or all of these with whatever tooling you use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/0*ZSo0mk62fgw_rwjT.jpg" /></figure><p>I’ve set up a job in Jenkins for this project, which will be triggered every time code is checked in to the Git repository, using a Githuub Webhook. The Jenkins job runs the Ansible playbook, which uses SEMPv2 to create the messaging environment as specified in the config files.</p><p>Finally, after the creation of the messaging environment, Jenkins triggers another job to pull the Solace Javascript Samples and deploys them to our web server. You can then run the Solace Javascript samples against your newly provisioned messaging environment!</p><p>In summary, when I do a Git push, this will trigger Jenkins to create my messaging environment on Solace, and then deploy my app (Solace Javascript samples, in my case) — As Jürgen Klopp says, BOOM!</p><h3>Live Demo</h3><p>Visit <a href="http://sgdemo.solace.com/jenkins/job/solace-ci-cd-demo/">Solace SGDemo Jenkins</a> — A Jenkins job (‘solace-ci-cd-demo’) has been created and configured such that any changes to the configuration in GitHub (such as adding new queues/users) will trigger the job to create the corresponding Solace configuration. As indicated previously, the Ansible playbook does not attempt to re-create existing objects — they will simply be logged as “ALREADY_EXISTS”</p><p>Once the Solace environment has been created, this triggers a second job which will pull the solclient JS samples from Github and deploy them to the sgdemo web server. Click <a href="http://sgdemo.solace.com/solclientjs">here</a> to try out the newly deployed Solclient samples.</p><p>Contact your Solace Account Manager for a Live Demo!</p><p>NOTE: If any configuration is removed, the Ansible playbook does not delete the corresponding configurations from the Solace router</p><h3>Reproducing the CD Demo:</h3><p>As the material for setting up the CD demo is publicly available, here are some references:</p><ol><li>Trigger a Jenkins Job using a GIT push: <a href="https://wiki.jenkins.io/display/JENKINS/GitHub+Integration+Plugin">GIT Integration plugin</a></li><li>Run Ansible playbooks in Jenkins: <a href="https://wiki.jenkins.io/display/JENKINS/Ansible+Plugin">Ansible Plugin for Jenkins</a></li></ol><h3>Built With</h3><ul><li><a href="https://www.ansible.com/">Ansible</a> — Simple IT Automation, Configuration Management and Orchestration</li><li><a href="https://docs.solace.com/SEMP/SEMP-Home.htm">SEMPv2</a> — Solace’s RESTful Administration API</li><li><a href="https://jenkins.io/">Jenkins</a> — Open Source Automation Server</li></ul><p>For more information try these resources:</p><ul><li>The Solace Developer Portal website at: <a href="http://dev.solace.com/">http://dev.solace.com</a></li><li>Get a better understanding of <a href="http://dev.solace.com/tech/">Solace technology</a>.</li><li>Get your hands dirty with <a href="http://dev.solace.com/get-started/semp-tutorials/">SEMP Tutorials</a></li><li>Check out the <a href="http://dev.solace.com/blog/">Solace blog</a> for other interesting discussions around Solace technology</li><li>Ask the <a href="http://dev.solace.com/community/">Solace community.</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43b8ab3f60d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Project: Setting Up GraphQL-Based Serverless Architecture]]></title>
            <link>https://medium.com/@akulamanojkumar988/project-setting-up-graphql-based-serverless-architecture-04c3c64475d0?source=rss-100b6452cd9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/04c3c64475d0</guid>
            <dc:creator><![CDATA[manojkumar]]></dc:creator>
            <pubDate>Sat, 09 Mar 2024 17:22:33 GMT</pubDate>
            <atom:updated>2024-03-09T17:22:33.523Z</atom:updated>
            <content:encoded><![CDATA[<p>Project Summary:</p><p>In this hands-on assessment, you will be evaluated based on your ability to set up a GraphQL-based serverless architecture. The project involves the following tasks:</p><p>Setting up a React application for a real-time project involves several steps. Below is a guide to help you get started. This assumes you have Node.js and npm installed on your machine.</p><h3>Step 1: Create a React App</h3><p>Use Create React App to set up a new React project. Open your terminal and run:</p><pre>npx create-react-app my-real-time-app<br>cd my-real-time-app</pre><p>Replace “my-real-time-app” with your desired project name.</p><h3>Step 2: Install Dependencies</h3><p>For real-time functionality, you might want to use a library like Socket.io for handling WebSocket connections. Install it by running:</p><pre>npm install socket.io-client</pre><h3>Step 3: Create a WebSocket Service</h3><p>Create a service to manage WebSocket connections. For example, create a file socketService.js:</p><pre>javascriptCopy code</pre><pre>import io from &#39;socket.io-client&#39;;</pre><pre>const socket = io(&#39;http://localhost:3001&#39;); // Replace with your server URL</pre><pre>export default socket;</pre><h3>Step 4: Integrate WebSocket Service into Components</h3><p>In your React components, use the WebSocket service to connect to the server. For example, in App.js:</p><pre>import React, { useEffect } from &#39;react&#39;;<br>import socket from &#39;./socketService&#39;;</pre><pre>function App() {<br>  useEffect(() =&gt; {<br>    socket.on(&#39;connect&#39;, () =&gt; {<br>      console.log(&#39;Connected to server&#39;);<br>    });</pre><pre>    // Add more event listeners as needed</pre><pre>    return () =&gt; {<br>      socket.disconnect();<br>    };<br>  }, []);</pre><pre>  return (<br>    &lt;div className=&quot;App&quot;&gt;<br>      {/* Your React components */}<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>export default App;</pre><h3>Step 5: Set Up the Backend</h3><p>You’ll need a backend server to handle WebSocket connections. You can use Node.js with Express and Socket.io. Create a new directory for the server, navigate to it, and run:</p><pre>npm init -y<br>npm install express socket.io</pre><p>Create a server.js file for your backend:</p><pre>const express = require(&#39;express&#39;);<br>const http = require(&#39;http&#39;);<br>const socketIo = require(&#39;socket.io&#39;);</pre><pre>const app = express();<br>const server = http.createServer(app);<br>const io = socketIo(server);</pre><pre>const PORT = process.env.PORT || 3001;</pre><pre>io.on(&#39;connection&#39;, (socket) =&gt; {<br>  console.log(&#39;Client connected&#39;);</pre><pre>  // Add more event listeners as needed</pre><pre>  socket.on(&#39;disconnect&#39;, () =&gt; {<br>    console.log(&#39;Client disconnected&#39;);<br>  });<br>});</pre><pre>server.listen(PORT, () =&gt; {<br>  console.log(`Server is running on <a href="http://localhost:${PORT}`);">http://localhost:${PORT}`);</a><br>});</pre><h3>Step 6: Start the Application</h3><p>In separate terminals, start your React app and the backend server:</p><pre># Terminal 1<br>cd my-real-time-app<br>npm start</pre><pre># Terminal 2<br>cd your-server-directory<br>node server.js</pre><p>Your React app should now be set up with real-time functionality using Socket.io. Customize the backend to handle your specific real-time requirements, and update the frontend components accordingly.</p><p>Setting up AWS Lambda functions that use TypeScript and Node.js.</p><p>Setting up AWS Lambda functions with TypeScript and Node.js involves several steps. Here’s a step-by-step guide to help you get started:</p><h3>Step 1: Prerequisites</h3><p>Ensure you have the following installed:</p><ul><li>Node.js</li><li>npm (Node Package Manager)</li><li>AWS CLI (Command Line Interface)</li><li>Serverless Framework (optional but recommended)</li></ul><h3>Step 2: Create a New TypeScript Lambda Project</h3><p>Create a new directory for your Lambda project and navigate into it:</p><pre>mkdir my-lambda-project<br>cd my-lambda-project</pre><p>Initialize a new Node.js project with TypeScript:</p><pre>npm init -y<br>npm install typescript</pre><h3>Step 3: Configure TypeScript</h3><p>Create a tsconfig.json file in the root of your project:</p><pre>{<br>  &quot;compilerOptions&quot;: {<br>    &quot;target&quot;: &quot;ES2020&quot;,<br>    &quot;module&quot;: &quot;commonjs&quot;,<br>    &quot;outDir&quot;: &quot;./dist&quot;,<br>    &quot;rootDir&quot;: &quot;./src&quot;,<br>    &quot;strict&quot;: true<br>  },<br>  &quot;include&quot;: [&quot;src/**/*.ts&quot;],<br>  &quot;exclude&quot;: [&quot;node_modules&quot;, &quot;dist&quot;]<br>}</pre><p>Create a src folder and add your TypeScript files inside it.</p><h3>Step 4: Install Serverless Framework (Optional)</h3><p>The Serverless Framework simplifies the deployment and management of AWS Lambda functions. Install it globally:</p><pre>npm install -g serverless</pre><h3>Step 5: Install AWS SDK</h3><p>Install the AWS SDK for Node.js to interact with AWS services:</p><pre>npm install aws-sdk</pre><h3>Step 6: Create a Simple Lambda Function</h3><p>Create a TypeScript file in the src folder, e.g., handler.ts:</p><pre>// src/handler.ts<br>import { APIGatewayProxyHandler } from &#39;aws-lambda&#39;;</pre><pre>export const hello: APIGatewayProxyHandler = async (event, _context) =&gt; {<br>  return {<br>    statusCode: 200,<br>    body: JSON.stringify({<br>      message: &#39;Hello from Lambda!&#39;,<br>      input: event,<br>    }),<br>  };<br>};</pre><h3>Step 7: Serverless Configuration (Optional)</h3><p>If you’re using the Serverless Framework, create a serverless.yml file in the root of your project:</p><pre>yamlCopy code</pre><pre>service: my-lambda-service</pre><pre>provider:<br>  name: aws<br>  runtime: nodejs14.x<br>  region: your-region</pre><pre>functions:<br>  hello:<br>    handler: dist/handler.hello<br>    events:<br>      - http:<br>          path: /<br>          method: get</pre><p>Replace your-region with your AWS region.</p><h3>Step 8: Build and Deploy</h3><p>Build your TypeScript project:</p><pre>tsc</pre><p>If using the Serverless Framework:</p><pre>serverless deploy</pre><p>If not using the Serverless Framework, manually zip your dist folder and upload it to AWS Lambda using the AWS Management Console or AWS CLI.</p><h3>Step 9: Test Your Lambda Function</h3><p>Once deployed, test your Lambda function either through the AWS Management Console, AWS CLI, or by triggering it through an event source (e.g., API Gateway).</p><p>Your AWS Lambda function using TypeScript and Node.js is now set up and ready for deployment.</p><p>Deploying a private GraphQL server on AWS ECS Fargate within a serverless environment involves several steps. In this example, we’ll use AWS App Runner to create a serverless environment and AWS ECS Fargate for deploying the GraphQL server. Ensure you have the AWS CLI installed and configured with the necessary permissions.</p><h3>Step 1: Set Up Your GraphQL Server</h3><p>Create a GraphQL server using a framework like Apollo Server, and configure it to run on a private network. Ensure that your GraphQL server exposes the necessary endpoints for GraphQL operations.</p><h3>Step 2: Dockerize Your GraphQL Server</h3><p>Create a Dockerfile in the root of your GraphQL server project:</p><pre>DockerfileCopy code</pre><pre># Use an official Node.js runtime as a parent image<br>FROM node:14</pre><pre># Set the working directory<br>WORKDIR /usr/src/app</pre><pre># Copy package.json and package-lock.json to the working directory<br>COPY package*.json ./</pre><pre># Install dependencies<br>RUN npm install</pre><pre># Copy the rest of the application code<br>COPY . .</pre><pre># Expose the port your app will run on<br>EXPOSE 4000</pre><pre># Command to run your application<br>CMD [&quot;npm&quot;, &quot;start&quot;]</pre><h3>Step 3: Build and Push Docker Image to Amazon ECR</h3><ol><li>Build your Docker image:</li></ol><ul><li>bashCopy code</li><li>docker build -t your-ecr-repository-url/your-graphql-server:latest .</li></ul><ol><li>Push the image to Amazon ECR:</li></ol><ul><li>bashCopy code</li><li>aws ecr get-login-password --region your-region | docker login --username AWS --password-stdin your-ecr-repository-url docker push your-ecr-repository-url/your-graphql-server:latest</li></ul><h3>Step 4: Set Up AWS App Runner</h3><ol><li>Navigate to the AWS Management Console and open the App Runner service.</li><li>Click “Create Service.”</li><li>Choose “Container registry” as the source, and select Amazon ECR. Choose your ECR repository and image.</li><li>Configure your service settings. Set the service name, choose the VPC, and set the subnets and security groups. Ensure that the security groups allow the necessary inbound and outbound traffic.</li><li>Click “Next” and configure the runtime settings. Specify the port your GraphQL server is running on (e.g., 4000).</li><li>Click “Next” and configure the deployment settings. You can choose the deployment trigger and set up auto-deployment from a source (e.g., GitHub).</li><li>Review your settings and click “Create &amp; Deploy.”</li></ol><h3>Step 5: Set Up AWS ECS Fargate</h3><ol><li>Navigate to the AWS Management Console and open the ECS service.</li><li>Click “Create Cluster” and choose “Networking only” as the cluster template.</li><li>Configure your cluster settings, VPC, subnets, and security groups.</li><li>Create a task definition:</li></ol><ul><li>Choose Fargate as the launch type.</li><li>Configure your task definition with the necessary container settings.</li><li>Specify environment variables, including any configuration your GraphQL server requires.</li></ul><ol><li>Create a service:</li></ol><ul><li>Choose the task definition you created.</li><li>Set the number of tasks to run.</li><li>Configure your service with the desired network settings.</li></ul><ol><li>Update the security groups to allow traffic between your App Runner service and ECS Fargate service.</li></ol><h3>Step 6: Test Your GraphQL Server</h3><p>Once both AWS App Runner and ECS Fargate are set up, you can test your GraphQL server by accessing the provided endpoints. Ensure that your security groups, network settings, and container configurations allow communication between services.</p><p>By following these steps, you should have a private GraphQL server deployed on AWS ECS Fargate within a serverless environment. Adjust configurations and security settings based on your specific requirements.</p><p>To configure and deploy multiple AWS Lambda functions for handling GraphQL queries, mutations, and subscriptions using the Serverless Application Model (SAM) or the Serverless Framework, you can follow the steps below. We’ll use the Serverless Framework in this example, but the concepts are similar for SAM.</p><h3>Prerequisites:</h3><ol><li>Node.js and npm: Ensure you have Node.js and npm installed on your machine.</li><li>Serverless Framework: Install the Serverless Framework globally:</li></ol><ul><li>bashCopy code</li><li>npm install -g serverless</li></ul><ol><li>AWS CLI: Make sure you have the AWS CLI installed and configured with the necessary permissions.</li></ol><h3>Step 1: Create a New Serverless Project</h3><p>Create a new directory for your project and navigate into it:</p><pre>mkdir my-graphql-lambda<br>cd my-graphql-lambda</pre><p>Initialize a new Serverless project:</p><pre>serverless create --template aws-nodejs</pre><h3>Step 2: Install Dependencies</h3><p>Install the necessary npm packages for your project:</p><pre>npm init -y<br>npm install aws-sdk graphql graphql-lambda</pre><h3>Step 3: Define Your GraphQL Schema and Resolvers</h3><p>Create a file named schema.js in your project. Define your GraphQL schema and resolvers. For example:</p><pre>// schema.js<br>const { buildSchema } = require(&#39;graphql&#39;);</pre><pre>const schema = buildSchema(`<br>  type Query {<br>    hello: String<br>  }</pre><pre>  type Mutation {<br>    setMessage(message: String!): String<br>  }</pre><pre>  type Subscription {<br>    messageUpdated: String<br>  }<br>`);</pre><pre>const resolvers = {<br>  Query: {<br>    hello: () =&gt; &#39;Hello, world!&#39;,<br>  },<br>  Mutation: {<br>    setMessage: ({ message }) =&gt; {<br>      // Handle the mutation logic here<br>      return message;<br>    },<br>  },<br>  Subscription: {<br>    messageUpdated: {<br>      subscribe: () =&gt; pubsub.asyncIterator(&#39;messageUpdated&#39;),<br>    },<br>  },<br>};</pre><pre>module.exports = { schema, resolvers };</pre><h3>Step 4: Create Serverless Function Handlers</h3><p>Create Lambda function handlers in the handler.js file. Each function will correspond to a GraphQL query, mutation, or subscription.</p><pre>// handler.js<br>const { graphqlLambda } = require(&#39;graphql-server-lambda&#39;);<br>const { makeExecutableSchema } = require(&#39;graphql-tools&#39;);<br>const { schema, resolvers } = require(&#39;./schema&#39;);</pre><pre>const executableSchema = makeExecutableSchema({<br>  typeDefs: schema,<br>  resolvers,<br>});</pre><pre>module.exports.queryHandler = graphqlLambda({ schema: executableSchema });<br>module.exports.mutationHandler = graphqlLambda({ schema: executableSchema });<br>module.exports.subscriptionHandler = graphqlLambda({ schema: executableSchema });</pre><h3>Step 5: Configure Serverless Framework</h3><p>Update the serverless.yml file to define your serverless functions and specify the events (HTTP endpoints for GraphQL queries, mutations, and subscriptions):</p><pre># serverless.yml<br>service: my-graphql-lambda</pre><pre>provider:<br>  name: aws<br>  runtime: nodejs14.x</pre><pre>functions:<br>  queryHandler:<br>    handler: handler.queryHandler<br>    events:<br>      - http:<br>          path: query<br>          method: post</pre><pre>  mutationHandler:<br>    handler: handler.mutationHandler<br>    events:<br>      - http:<br>          path: mutation<br>          method: post</pre><pre>  subscriptionHandler:<br>    handler: handler.subscriptionHandler<br>    events:<br>      - http:<br>          path: subscription<br>          method: post</pre><h3>Step 6: Deploy Your Serverless Functions</h3><p>Deploy your Lambda functions using the Serverless Framework:</p><pre>serverless deploy</pre><h3>Step 7: Test Your GraphQL Endpoints</h3><p>Once the deployment is successful, you can find the HTTP endpoints for your GraphQL queries, mutations, and subscriptions in the output. Test these endpoints using a tool like cURL or a GraphQL client.</p><p>For example, if your query endpoint is https://your-api-gateway-url/dev/query, you can use cURL:</p><pre>curl -X POST -H &quot;Content-Type: application/json&quot; -d &#39;{&quot;query&quot;:&quot;{ hello }&quot;}&#39; https://your-api-gateway-url/dev/query</pre><p>Make sure to adapt the endpoint URLs according to your deployment.</p><p>By following these steps, you’ll have multiple Lambda functions handling GraphQL queries, mutations, and subscriptions deployed using the Serverless Framework. Adjust the GraphQL schema, resolvers, and Serverless configuration to fit your specific use case.</p><p>The Serverless Framework is a powerful tool for deploying serverless applications. It simplifies the process of building, deploying, and managing serverless architectures on various cloud providers, including AWS, Azure, Google Cloud, and more. Here’s a step-by-step guide to implementing the Serverless Framework for streamlined application deployment:</p><h3>Prerequisites:</h3><ol><li>Node.js and npm: Ensure you have Node.js and npm installed on your machine.</li><li>Serverless Framework: Install the Serverless Framework globally:</li></ol><ul><li>bashCopy code</li><li>npm install -g serverless</li></ul><ol><li>AWS CLI: Make sure you have the AWS CLI installed and configured with the necessary permissions.</li></ol><h3>Step 1: Create a New Serverless Project</h3><p>Create a new directory for your project and navigate into it:</p><pre>mkdir my-serverless-app<br>cd my-serverless-app</pre><p>Initialize a new Serverless project:</p><pre>serverless create --template aws-nodejs</pre><h3>Step 2: Configure Serverless Framework</h3><p>Edit the serverless.yml file to configure your serverless application. Specify the service name, provider, runtime, and functions. Here&#39;s a basic example:</p><pre>service: my-serverless-app</pre><pre>provider:<br>  name: aws<br>  runtime: nodejs14.x</pre><pre>functions:<br>  hello:<br>    handler: handler.hello<br>    events:<br>      - http:<br>          path: /<br>          method: any</pre><h3>Step 3: Create Serverless Functions</h3><p>In the handler.js file, define your serverless functions. For example:</p><pre>// handler.js<br>&#39;use strict&#39;;</pre><pre>module.exports.hello = async (event) =&gt; {<br>  return {<br>    statusCode: 200,<br>    body: JSON.stringify({<br>      message: &#39;Hello, Serverless World!&#39;,<br>      input: event,<br>    }),<br>  };<br>};</pre><h3>Step 4: Deploy Your Serverless Application</h3><p>Deploy your serverless application using the following command:</p><pre>serverless deploy</pre><h3>Step 5: Test Your Serverless Function</h3><p>Once the deployment is complete, you’ll see the endpoint URL in the output. Test your serverless function using a tool like cURL or a web browser. For example:</p><pre>curl https://your-api-gateway-url/dev</pre><h3>Step 6: Monitor and Troubleshoot</h3><p>The Serverless Framework provides commands for monitoring and troubleshooting. Use the following commands:</p><ul><li>View logs: serverless logs -f &lt;function-name&gt;</li><li>Stream logs: serverless logs -f &lt;function-name&gt; -t</li><li>Invoke a function: serverless invoke -f &lt;function-name&gt;</li></ul><h3>Step 7: Update Your Serverless Application</h3><p>If you make changes to your serverless application, update and redeploy using the following command:</p><pre>serverless deploy</pre><h3>Step 8: Remove Your Serverless Application</h3><p>When you no longer need your serverless application, you can remove the deployed resources using the following command:</p><pre>serverless remove</pre><p>This guide provides a basic overview of setting up and deploying a serverless application using the Serverless Framework. Customize the configuration, functions, and deployment process based on your application’s requirements. Explore the Serverless Framework documentation for more advanced features and integrations.</p><h3>Establishing a CI/CD pipeline using GitHub Actions to automate deployments.</h3><p>Setting up a Continuous Integration/Continuous Deployment (CI/CD) pipeline using GitHub Actions involves creating workflows that define the steps to build, test, and deploy your application automatically. Below is a general guide on how to establish a basic CI/CD pipeline for a Node.js application on AWS using GitHub Actions.</p><h3>Prerequisites:</h3><ol><li>AWS Account: Ensure you have an AWS account and configure AWS credentials in GitHub Secrets.</li><li>GitHub Repository: Have a GitHub repository for your Node.js application.</li></ol><h3>Step 1: Add GitHub Actions Workflow</h3><p>Create a .github/workflows/main.yml file in your repository to define the GitHub Actions workflow. This example assumes you have a Node.js application using the Serverless Framework for deployment.</p><pre>name: CI/CD Pipeline<br><br>on:<br>  push:<br>    branches:<br>      - main<br><br>jobs:<br>  build:<br>    runs-on: ubuntu-latest<br><br>    steps:<br>    - name: Checkout Repository<br>      uses: actions/checkout@v2<br><br>    - name: Setup Node.js<br>      uses: actions/setup-node@v3<br>      with:<br>        node-version: &#39;14&#39;<br><br>    - name: Install Dependencies<br>      run: npm install<br><br>    - name: Run Tests<br>      run: npm test<br><br>  deploy:<br>    runs-on: ubuntu-latest<br><br>    needs: build<br><br>    steps:<br>    - name: Checkout Repository<br>      uses: actions/checkout@v2<br><br>    - name: Setup Node.js<br>      uses: actions/setup-node@v3<br>      with:<br>        node-version: &#39;14&#39;<br><br>    - name: Deploy to AWS<br>      run: |<br>        npx serverless deploy --stage production<br>      env:<br>        AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}<br>        AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}</pre><h3>Step 2: Configure GitHub Secrets</h3><p>In your GitHub repository, go to Settings &gt; Secrets &gt; New repository secret and add the following secrets:</p><ul><li>AWS_ACCESS_KEY_ID: Your AWS access key.</li><li>AWS_SECRET_ACCESS_KEY: Your AWS secret access key.</li></ul><h3>Step 3: Update Serverless Configuration</h3><p>Make sure your Serverless Framework configuration (serverless.yml) includes the necessary configurations for AWS deployment.</p><h3>Step 4: Test Your Workflow</h3><p>Push changes to your repository to trigger the GitHub Actions workflow. GitHub Actions will automatically build, test, and deploy your application to AWS.</p><h3>Additional Considerations:</h3><ol><li>Branch Protection Rules: Consider setting up branch protection rules on your main branch to require status checks from your CI/CD workflow before merging.</li></ol><p>2.Environment-Specific Configurations: Adjust your Serverless Framework configuration to use environment-specific variables based on the GitHub Actions environment.</p><p>3.Monitoring and Logging: Implement monitoring and logging solutions to track the performance and behavior of your deployed application.</p><p>4.Artifact Storage: If your application generates deployment artifacts, consider storing them in an artifact storage solution for traceability.</p><p>5.Notification and Alerts: Configure notifications or alerts to be informed about the success or failure of your CI/CD pipeline.</p><p>6.Additional GitHub Actions: Explore other GitHub Actions for your workflow, such as code quality checks, security scans, or custom actions.</p><h3>Monitoring Lambda function metrics and logs with AWS CloudWatch and setting up CloudWatch Alarms for alerts.</h3><p>Monitoring AWS Lambda functions involves using AWS CloudWatch to collect and analyze metrics and logs. Additionally, setting up CloudWatch Alarms allows you to receive alerts based on specific conditions. Here’s a guide on how to monitor Lambda function metrics and logs, as well as how to set up CloudWatch Alarms:</p><h3>Monitoring Lambda Metrics with CloudWatch:</h3><ol><li>View Basic Metrics:</li></ol><ul><li>Open the AWS Management Console and navigate to CloudWatch.</li><li>In the CloudWatch dashboard, go to “Metrics” and choose “Lambda” in the “Browse” section.</li><li>Select the specific function and metric you want to monitor, such as “Invocations,” “Duration,” “Errors,” etc.</li></ul><ol><li>Create Dashboards:</li></ol><ul><li>In CloudWatch, you can create custom dashboards to monitor multiple metrics at once.</li><li>Go to the CloudWatch dashboard, choose “Dashboards,” and click “Create Dashboard.”</li><li>Add widgets for Lambda metrics relevant to your application.</li></ul><h3>Viewing Lambda Logs with CloudWatch Logs:</h3><ol><li>View Logs:</li></ol><ul><li>In the AWS Management Console, navigate to CloudWatch.</li><li>Under “Logs,” choose “Log groups” and find the log group for your Lambda function.</li><li>Select the log stream to view the logs generated by your Lambda function.</li></ul><ol><li>Log Retention and Storage:</li></ol><ul><li>Configure log retention settings to control how long CloudWatch retains your logs.</li><li>Go to the CloudWatch console, select “Log groups,” choose the log group, and click “Retention.”</li></ul><h3>Setting Up CloudWatch Alarms:</h3><ol><li>Create an Alarm:</li></ol><ul><li>In the CloudWatch console, navigate to “Alarms” and click “Create alarm.”</li><li>Choose the metric and conditions for your alarm (e.g., “Errors” exceeding a threshold).</li><li>Define the actions to take when the alarm state changes (e.g., send a notification).</li></ul><ol><li>Set Up SNS Topic for Notifications:</li></ol><ul><li>Before creating alarms, set up an Amazon Simple Notification Service (SNS) topic.</li><li>In the AWS Management Console, navigate to SNS and create a new topic.</li><li>Configure subscriptions to receive notifications.</li></ul><ol><li>Associate Alarm Actions with SNS Topic:</li></ol><ul><li>While creating or editing an alarm, choose the SNS topic to receive notifications.</li><li>Define actions for the alarm, such as sending an email or triggering a Lambda function.</li></ul><h3>Using AWS SAM for Alarms in Serverless Applications:</h3><p>If you’re using the Serverless Application Model (SAM) to deploy Lambda functions, you can define CloudWatch Alarms directly in your template.yaml:</p><pre>Resources:<br>  MyFunction:<br>    Type: AWS::Serverless::Function<br>    Properties:<br>      Handler: index.handler<br>      Runtime: nodejs14.x</pre><pre>  MyErrorAlarm:<br>    Type: AWS::CloudWatch::Alarm<br>    Properties:<br>      AlarmName: MyErrorAlarm<br>      ComparisonOperator: GreaterThanThreshold<br>      EvaluationPeriods: 1<br>      MetricName: Errors<br>      Namespace: AWS/Lambda<br>      Period: 60<br>      Statistic: Sum<br>      Threshold: 1<br>      ActionsEnabled: true<br>      AlarmActions:<br>        - !Ref MySNSTopic</pre><pre>  MySNSTopic:<br>    Type: AWS::SNS::Topic<br>    Properties:<br>      DisplayName: &quot;My SNSTopic&quot;<br>      TopicName: &quot;MySNSTopic&quot;</pre><p>In this example, an alarm is created for the Errors metric, and the MySNSTopic SNS topic is used for notifications.</p><h3>Note:</h3><ul><li>Adjust the thresholds and conditions in alarms based on your specific requirements.</li><li>Consider using AWS Lambda Insights and custom CloudWatch Logs Insights queries for more advanced monitoring.</li></ul><p>By following these steps, you can effectively monitor Lambda function metrics and logs using AWS CloudWatch and set up CloudWatch Alarms for proactive alerting. Adjust the configurations based on your application’s needs and the level of granularity required for monitoring.</p><h3>Implementing AWS Identity and Access Management (IAM) for access control and secure handling of sensitive data.</h3><p>AWS Identity and Access Management (IAM) is a crucial service for access control and secure handling of sensitive data in AWS. It allows you to manage access to AWS resources securely. Here’s a guide on implementing IAM best practices for secure access management:</p><h3>1. Principle of Least Privilege (PoLP):</h3><p>Grant users and roles the minimum permissions necessary to perform their tasks. Avoid providing broad, unnecessary permissions.</p><h3>2. Use IAM Roles for EC2 Instances:</h3><p>Assign IAM roles to EC2 instances instead of using access keys. This helps in managing credentials securely without embedding them in the code or configuration files.</p><h3>3. User and Group Management:</h3><p>Organize users into groups based on their roles and responsibilities. Assign policies to groups rather than individual users for easier management.</p><h3>4. Rotate Access Keys Regularly:</h3><p>Rotate access keys for IAM users periodically. AWS provides an option to automate key rotation.</p><h3>5. Enable MFA (Multi-Factor Authentication):</h3><p>Enable MFA for IAM users, especially for users with elevated privileges. This adds an extra layer of security.</p><h3>6. Use IAM Roles for Cross-Account Access:</h3><p>When granting access between AWS accounts, use IAM roles with cross-account access instead of sharing access keys or using long-term credentials.</p><h3>7. Use IAM Policies with Conditions:</h3><p>Apply conditions in IAM policies to control when and how IAM permissions are granted. Conditions can be based on factors such as IP address, time, or a specific request parameter.</p><h3>8. Audit IAM Policies:</h3><p>Regularly review and audit IAM policies to ensure they adhere to the principle of least privilege and align with your security policies.</p><h3>9. Use IAM Policy Simulator:</h3><p>Leverage the IAM Policy Simulator to test and validate the effects of IAM policies before applying them.</p><h3>10. CloudTrail Logging:</h3><p>Enable AWS CloudTrail to log API calls for your AWS account. This provides an audit trail and helps in tracking user activity.</p><h3>11. Encrypt Sensitive Data:</h3><p>For services like Amazon S3, enable server-side encryption to protect sensitive data. IAM policies can be used to control access to encryption keys.</p><h3>12. IAM Access Analyzer:</h3><p>Use IAM Access Analyzer to analyze resource policies and identity-based policies to identify and fix unintended public or cross-account access.</p><h3>13. Use IAM Conditions for S3 Buckets:</h3><p>Leverage IAM conditions for S3 bucket policies to control access based on various conditions such as VPC endpoint usage or SSL/TLS requirements.</p><h3>14. IAM Roles for AWS Lambda:</h3><p>When invoking Lambda functions from other AWS services, use IAM roles to grant the necessary permissions. Avoid using access keys embedded in the function’s code.</p><h3>15. Monitor IAM Events:</h3><p>Set up CloudWatch Alarms to monitor specific IAM events, such as changes to IAM roles or user policies, to detect potential security incidents.</p><h3>16. Periodic Access Reviews:</h3><p>Conduct periodic access reviews to ensure that users and roles have only the necessary permissions. Remove any unnecessary or outdated permissions.</p><p>By following these best practices, you can enhance the security of your AWS environment by ensuring proper access control and handling sensitive data securely. Regularly review and update your IAM configurations to adapt to changes in your organization’s structure and security requirements.</p><h3>Managing environment variables using AWS Secret Manager and GitHub Actions.</h3><p>Managing environment variables securely is crucial for applications, and AWS Secrets Manager provides a secure and scalable solution for storing and retrieving sensitive information. Combining AWS Secrets Manager with GitHub Actions allows you to securely manage and use environment variables in your CI/CD workflows. Here’s a guide on how to achieve this:</p><h3>Step 1: Store Secrets in AWS Secrets Manager:</h3><ol><li>Create a Secret:</li></ol><ul><li>Open the AWS Secrets Manager console.</li><li>Choose “Store a new secret.”</li><li>Enter key-value pairs for your sensitive information (e.g., database credentials, API keys).</li><li>Choose a name for your secret.</li></ul><ol><li>Add Tags (Optional):</li></ol><ul><li>Optionally, add tags to your secret for better organization and management.</li></ul><h3>Step 2: Set Up GitHub Secrets:</h3><ol><li>GitHub Repository:</li></ol><ul><li>Open your GitHub repository.</li></ul><ol><li>Navigate to Settings:</li></ol><ul><li>Go to “Settings” &gt; “Secrets” in your GitHub repository.</li></ul><ol><li>Add Secrets:</li></ol><ul><li>Click on “New repository secret.”</li><li>Add the key-value pairs corresponding to the secrets stored in AWS Secrets Manager.</li></ul><h3>Step 3: GitHub Actions Workflow:</h3><p>Create or update your GitHub Actions workflow file (e.g., .github/workflows/main.yml). Use the GitHub Secrets as input for the AWS Secrets Manager API calls.</p><pre>name: CI/CD Pipeline</pre><pre>on:<br>  push:<br>    branches:<br>      - main</pre><pre>jobs:<br>  deploy:<br>    runs-on: ubuntu-latest</pre><pre>    steps:<br>    - name: Checkout Repository<br>      uses: actions/checkout@v2</pre><pre>    - name: Set Up Node.js<br>      uses: actions/setup-node@v3<br>      with:<br>        node-version: &#39;14&#39;</pre><pre>    - name: Install Dependencies<br>      run: npm install</pre><pre>    - name: Retrieve Secrets from AWS Secrets Manager<br>      run: |<br>        aws secretsmanager get-secret-value --secret-id your-secret-id --query SecretString --output json &gt; secrets.json<br>        echo &quot;::set-output name=SECRETS::$(cat secrets.json)&quot;<br>      env:<br>        AWS_REGION: ${{ secrets.AWS_REGION }}<br>        AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}<br>        AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}</pre><pre>    - name: Run Deployment<br>      run: |<br>        npm run deploy --secrets=&quot;${{ env.SECRETS }}&quot;<br>      env:<br>        NODE_ENV: production</pre><p>In this example, the GitHub Actions workflow:</p><ul><li>Checks out the repository.</li><li>Sets up Node.js.</li><li>Installs dependencies.</li><li>Retrieves secrets from AWS Secrets Manager using the AWS CLI.</li><li>Runs the deployment script, passing the retrieved secrets as an environment variable.</li></ul><p>Make sure to replace your-secret-id with the actual ID or name of your secret in AWS Secrets Manager.</p><h3>Step 4: Application Code:</h3><p>Update your application code to handle the secrets passed through environment variables. For example, in a Node.js application:</p><pre>// Use the &#39;secrets&#39; environment variable in your application code<br>const secrets = JSON.parse(process.env.secrets);</pre><pre>// Access individual secrets<br>const dbUsername = secrets.dbUsername;<br>const dbPassword = secrets.dbPassword;</pre><pre>// Use the secrets in your application logic<br>// ...</pre><h3>Important Considerations:</h3><ol><li>IAM Role Permissions:</li></ol><ul><li>Ensure that the IAM role associated with your GitHub Actions workflow has the necessary permissions to retrieve secrets from AWS Secrets Manager.</li></ul><ol><li>Secrets Rotation:</li></ol><ul><li>Consider implementing a strategy for secrets rotation and updating your GitHub Secrets accordingly.</li></ul><ol><li>Limit Access to Secrets:</li></ol><ul><li>Limit access to AWS Secrets Manager and GitHub Secrets to only the necessary individuals or systems.</li></ul><ol><li>Monitoring and Auditing:</li></ol><ul><li>Implement monitoring and auditing to track who accesses or modifies secrets.</li></ul><p>By following these steps, you can securely manage environment variables using AWS Secrets Manager and GitHub Actions in your CI/CD workflows. This approach helps protect sensitive information and ensures that only authorized processes can access and use the secrets.</p><h3>Designing the GraphQL architecture for scalability with AWS Auto Scaling capabilities.</h3><p>Designing a scalable GraphQL architecture on AWS involves leveraging various AWS services to ensure high availability, fault tolerance, and the ability to handle increased load through automatic scaling. Below is a high-level architecture design for a scalable GraphQL setup:</p><h3>1. Amazon API Gateway:</h3><p>Use Amazon API Gateway to expose your GraphQL API to clients. API Gateway acts as a front door, enabling you to create, publish, maintain, monitor, and secure APIs at any scale.</p><ul><li>Set up API Gateway with a GraphQL API, specifying your GraphQL endpoint.</li></ul><h3>2. AWS AppSync:</h3><p>Consider using AWS AppSync as a managed service to simplify the development of scalable GraphQL APIs. AppSync integrates with various data sources, including AWS Lambda, DynamoDB, and more.</p><ul><li>Configure AppSync to connect to your backend data sources and resolvers.</li></ul><h3>3. AWS Lambda:</h3><p>Leverage AWS Lambda for serverless execution of your GraphQL resolvers. Lambda automatically scales based on demand, and you only pay for the compute time consumed.</p><ul><li>Deploy your GraphQL resolvers as Lambda functions.</li><li>Ensure that your Lambda functions handle concurrent executions efficiently.</li></ul><h3>4. Amazon DynamoDB:</h3><p>For storing and retrieving data, use Amazon DynamoDB, a fully managed NoSQL database. DynamoDB is designed for high scalability and low-latency access.</p><ul><li>Design your data model to optimize for DynamoDB’s capabilities.</li><li>Consider using Global Tables for multi-region deployments.</li></ul><h3>5. Amazon RDS or Aurora Serverless (Optional):</h3><p>For relational databases, use Amazon RDS or Aurora Serverless. Aurora Serverless automatically adjusts database capacity based on actual consumption.</p><ul><li>Choose the appropriate database engine based on your requirements.</li><li>Consider Aurora Serverless for a serverless relational database.</li></ul><h3>6. Amazon CloudFront:</h3><p>Implement Amazon CloudFront for content delivery. CloudFront caches your GraphQL API responses globally, reducing latency and improving the overall performance.</p><ul><li>Set up CloudFront with your API Gateway as the origin.</li></ul><h3>7. AWS Auto Scaling:</h3><p>For automatic scaling, use AWS Auto Scaling to adjust the number of instances in your backend based on demand. You can use Auto Scaling with Lambda, EC2, or ECS depending on your architecture.</p><ul><li>Configure Auto Scaling policies based on metrics such as CPU usage or the number of requests.</li><li>Set up a target tracking scaling policy for predictable scaling.</li></ul><h3>8. Amazon CloudWatch:</h3><p>Implement Amazon CloudWatch for monitoring and logging. CloudWatch allows you to collect and track metrics, collect and monitor log files, and set alarms.</p><ul><li>Create CloudWatch Alarms for key metrics to trigger Auto Scaling actions.</li><li>Use CloudWatch Logs for centralized logging.</li></ul><h3>9. Amazon ECS (Optional):</h3><p>For containerized applications, use Amazon ECS with Fargate. ECS allows you to run containers without managing the underlying infrastructure.</p><ul><li>Containerize your GraphQL application using Docker.</li><li>Deploy containers with ECS Fargate for serverless container orchestration.</li></ul><h3>10. Amazon Elasticache (Optional):</h3><p>Consider using Amazon ElastiCache for caching query responses and reducing the load on your backend.</p><ul><li>Set up ElastiCache with Redis or Memcached.</li><li>Integrate caching logic in your resolvers to utilize ElastiCache.</li></ul><h3>11. Cross-Region Replication (Optional):</h3><p>For global scalability and fault tolerance, consider replicating your architecture across multiple AWS regions.</p><ul><li>Implement cross-region replication for critical services.</li><li>Use Route 53 for global DNS-based load balancing.</li></ul><h3>12. Security Best Practices:</h3><p>Implement security best practices such as AWS Identity and Access Management (IAM), encryption in transit and at rest, and VPC security groups.</p><ul><li>Follow the principle of least privilege in IAM roles and policies.</li><li>Encrypt sensitive data using AWS Key Management Service (KMS).</li></ul><p>By combining these AWS services and best practices, you can design a scalable GraphQL architecture that can handle increased loads and provide a reliable and performant experience for your users. Adjust the architecture based on your specific requirements and performance goals.</p><h3>Developing and implementing a rollback strategy in case of deployment failures.</h3><p>Implementing a rollback strategy is crucial for handling deployment failures and ensuring that your system can quickly revert to a stable state when issues arise. Here’s a guide on developing and implementing a rollback strategy:</p><h3>1. Automated Testing:</h3><p>Before discussing rollback strategies, emphasize the importance of automated testing. A robust testing suite, including unit tests, integration tests, and end-to-end tests, can catch potential issues early in the development process.</p><h3>2. Feature Toggles (Feature Flags):</h3><p>Use feature toggles to enable or disable specific features in production. By toggling off a problematic feature, you can quickly mitigate issues without a full rollback.</p><ul><li>Implement a feature toggle system in your application code.</li><li>Use feature toggles to control the activation of specific features.</li></ul><h3>3. Blue-Green Deployment:</h3><p>Implement a blue-green deployment strategy where you maintain two production environments: one with the current stable version (blue) and the other with the new version (green). If issues occur in the green environment, you can switch back to the blue environment.</p><ul><li>Deploy the new version to a separate environment (green).</li><li>Test and validate the green environment.</li><li>Route traffic to the green environment gradually.</li><li>Monitor for issues, and if problems arise, switch back to the blue environment.</li></ul><h3>4. Rolling Deployment:</h3><p>A rolling deployment involves gradually updating instances in a production environment, reducing the impact of deployment failures.</p><ul><li>Deploy the new version to a subset of instances.</li><li>Monitor the subset for issues.</li><li>If problems occur, stop or rollback the deployment.</li><li>Continue the process until all instances are updated.</li></ul><h3>5. Canary Deployment:</h3><p>Canary deployment is similar to blue-green deployment, but it involves releasing the new version to a small subset of users before a full release.</p><ul><li>Deploy the new version to a small percentage of users.</li><li>Monitor user experience and system metrics.</li><li>If issues arise, roll back the deployment.</li><li>Gradually increase the percentage of users receiving the new version.</li></ul><h3>6. Automated Rollback Scripts:</h3><p>Develop automated rollback scripts that can revert the database schema, configurations, and application code to the previous version.</p><ul><li>Write scripts that can quickly undo the changes made during the deployment.</li><li>Test rollback scripts in a controlled environment.</li></ul><h3>7. Rollback Plan:</h3><p>Document a rollback plan detailing the steps to be taken in case of a deployment failure. Include specific instructions for each component of your application.</p><ul><li>Specify which commands or scripts should be run to execute the rollback.</li><li>Define the order of steps and dependencies.</li></ul><h3>8. Monitoring and Alerts:</h3><p>Implement comprehensive monitoring and alerting to detect issues early. Set up alerts for key metrics, error rates, and user experience.</p><ul><li>Use monitoring tools like AWS CloudWatch, Datadog, or New Relic.</li><li>Configure alerts for abnormal behavior or performance degradation.</li></ul><h3>9. Communication Plan:</h3><p>Define a communication plan to inform stakeholders and team members about deployment status and any rollbacks.</p><ul><li>Establish communication channels and protocols.</li><li>Provide clear and timely updates during deployment and rollback processes.</li></ul><h3>10. Post-Mortem Analysis:</h3><p>Conduct a post-mortem analysis after a deployment failure or rollback to identify the root cause and prevent similar issues in the future.</p><ul><li>Document the incident, actions taken, and lessons learned.</li><li>Implement improvements based on the post-mortem analysis.</li></ul><h3>11. Continuous Improvement:</h3><p>Regularly review and improve your rollback strategy based on feedback, lessons learned, and changes in your application architecture.</p><ul><li>Continuously refine deployment processes.</li><li>Encourage a culture of learning and adaptability.</li></ul><p>By incorporating these strategies into your deployment process, you can minimize the impact of deployment failures and ensure a quick and reliable rollback when needed. Choose the strategies that best fit your application architecture and deployment pipeline.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=04c3c64475d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Argo CD]]></title>
            <link>https://medium.com/@akulamanojkumar988/argo-cd-a909b5c62acb?source=rss-100b6452cd9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a909b5c62acb</guid>
            <category><![CDATA[argo-cd]]></category>
            <dc:creator><![CDATA[manojkumar]]></dc:creator>
            <pubDate>Wed, 06 Mar 2024 17:28:47 GMT</pubDate>
            <atom:updated>2024-03-06T17:28:47.677Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Complete Overview of ArgoCD with a Practical Example……………</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/0*VCEyv5SL8UbKYiP2.png" /></figure><h3>Content:</h3><h3>01, Introduction to Argo CD</h3><h3>02, Key Features and Benefits</h3><h3>03,Practical Implementation and Case Studies</h3><h3>Introduction to Argo CD</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L2QozZIcqGF2wHGHIDfp7A.png" /></figure><h3>What is ArgoCD?</h3><p>Argo CD is a Kubernetes-native continuous deployment (CD) tool. Unlike external CD tools that only enable push-based deployments, Argo CD can pull updated code from Git repositories and deploy it directly to Kubernetes resources.</p><h3>What is GitOps?</h3><p>GitOps is a way of implementing Continuous Deployment for cloud-native applications. It focuses on a developer-centric experience when operating infrastructure, by using tools developers are already familiar with, including Git and Continuous Deployment tools.</p><p>The core idea of GitOps is to have a Git repository that always contains declarative descriptions of the infrastructure currently desired in the production environment and an automated process to make the production environment match the described state in the repository. If you want to deploy a new application or update an existing one, you only need to update the repository — the automated process handles everything else. It’s like having cruise control for managing your applications in production.</p><h3>Core Functionality of Argo CD</h3><h3>01)Continuous Monitoring</h3><p>Argo CD continuously monitors running applications and compares the current state with the desired state defined in the Git repository. Any variances are automatically reconciled to maintain the desired state.</p><h3>02)Declarative Application Management</h3><p>It enables declarative definitions of applications and their configurations, ensuring that the desired state is maintained without the need for manual intervention.</p><h3>03)GitOps Approach</h3><p>Argo CD follows the GitOps methodology, where application definitions, configurations, and environments are versioned in a Git repository, providing a clear audit trail and ensuring consistency.</p><h3>Use Cases and Adoption</h3><h3>01)Enterprise Adoption</h3><p>Argo CD has gained significant traction in enterprise environments due to its ability to streamline and automate the deployment and management of complex Kubernetes applications.</p><h3>02)Community Support</h3><p>The tool benefits from a vibrant and active community, contributing to its evolution and the development of best practices for continuous delivery in Kubernetes.</p><h3>03)Integration Flexibility</h3><p>Argo CD integrates seamlessly with various CI/CD tools, version control systems, and Kubernetes distributions, making it a versatile choice for organizations with diverse tech stacks.</p><h3>Argo CD Architecture</h3><h3>01)Controller and API Server</h3><p>The core of Argo CD’s architecture consists of the controller and API server, responsible for managing the application deployment and providing the user interface.</p><h3>02)Application Set Controller</h3><p>This component enables the management of multiple applications as a single entity, allowing for efficient and scalable management of complex application landscapes.</p><h3>03)Repository and Synchronization</h3><p>Argo CD interacts directly with the Git repository to synchronize the desired state with the live state of applications, ensuring consistency and reliability.</p><h3>Key efits Features and Ben</h3><h3>GitOps Principles and Best Practices</h3><h3>01)Declarative Configuration</h3><p>Argo CD enforces the GitOps principle of declarative configuration, ensuring that the desired state of applications is explicitly defined and versioned in a Git repository.</p><h3>02)Automated Synchronization</h3><p>The tool automates the synchronization of the live state with the desired state, reducing the risk of configuration drift and ensuring consistency across environments.</p><h3>03)Auditability and Traceability</h3><p>By leveraging Git as the source of truth, Argo CD provides a transparent audit trail and traceability for all changes made to application configurations.</p><h3>Application Health and Rollback</h3><h3>01)Health Status Monitoring</h3><p>Argo CD continuously monitors the health and status of applications, providing real-time insights into their operational state and performance.</p><h3>02)Automated Rollback</h3><p>In the event of application failures or deviations from the desired state, Argo CD facilitates automated rollbacks to restore the application to a stable and consistent state.</p><h3>03)Customizable Health Checks</h3><p>It offers customizable health checks and validation mechanisms, allowing organizations to define specific criteria for application health and performance.</p><h3>Scalability and Multi-Tenancy</h3><h3>01)Scalable Application Management</h3><p>Argo CD supports the management of large-scale, complex application landscapes, providing the scalability required for enterprise-grade continuous delivery.</p><h3>02)Multi-Tenancy Support</h3><p>It offers robust multi-tenancy capabilities, allowing organizations to manage and deploy applications across diverse teams and environments with distinct access controls and permissions.</p><h3>03)Resource Quotas and Limits</h3><p>Argo CD enables the enforcement of resource quotas and limits, ensuring efficient resource utilization and allocation across applications and environments.</p><h3>Security and Compliance</h3><h3>01)Role-Based Access Control (RBAC)</h3><p>The tool provides fine-grained RBAC, allowing organizations to define granular access controls and permissions for different user roles and responsibilities.</p><h3>02)Secrets Management</h3><p>Argo CD offers secure and centralized secrets management, ensuring that sensitive information such as credentials and API tokens are handled with the utmost security.</p><h3>03)Compliance Automation</h3><p>It facilitates compliance automation by enforcing best practices, security policies, and regulatory requirements through automated configuration management and validation.</p><h3>Practical Implementation and Case Studies</h3><h3>GitOps Principles and Best Practices</h3><h3>01)Declarative Configuration</h3><p>Argo CD enforces the GitOps principle of declarative configuration, ensuring that the desired state of applications is explicitly defined and versioned in a Git repository.</p><h3>02)Automated Synchronization</h3><p>The tool automates the synchronization of the live state with the desired state, reducing the risk of configuration drift and ensuring consistency across environments.</p><h3>03)Auditability and Traceability</h3><p>By leveraging Git as the source of truth, Argo CD provides a transparent audit trail and traceability for all changes made to application configurations.</p><h3>Application Health and Rollback</h3><h3>01)Health Status Monitoring</h3><p>Argo CD continuously monitors the health and status of applications, providing real-time insights into their operational state and performance.</p><h3>02)Automated Rollback</h3><p>In the event of application failures or deviations from the desired state, Argo CD facilitates automated rollbacks to restore the application to a stable and consistent state.</p><h3>03)Customizable Health Checks</h3><p>It offers customizable health checks and validation mechanisms, allowing organizations to define specific criteria for application health and performance.</p><h3>Scalability and Multi-Tenancy</h3><h3>01)Scalable Application Management</h3><p>Argo CD supports the management of large-scale, complex application landscapes, providing the scalability required for enterprise-grade continuous delivery.</p><h3>02)Multi-Tenancy Support</h3><p>It offers robust multi-tenancy capabilities, allowing organizations to manage and deploy applications across diverse teams and environments with distinct access controls and permissions.</p><h3>03)Resource Quotas and Limits</h3><p>Argo CD enables the enforcement of resource quotas and limits, ensuring efficient resource utilization and allocation across applications and environments.</p><h3>Security and Compliance</h3><h3>01)Role-Based Access Control (RBAC)</h3><p>The tool provides fine-grained RBAC, allowing organizations to define granular access controls and permissions for different user roles and responsibilities.</p><h3>02)Secrets Management</h3><p>Argo CD offers secure and centralized secrets management, ensuring that sensitive information such as credentials and API tokens are handled with the utmost security.</p><h3>03)Compliance Automation</h3><p>It facilitates compliance automation by enforcing best practices, security policies, and regulatory requirements through automated configuration management and validation.</p><h3>Practical Implementation and Case Studies</h3><h3>Implementing Argo CD in a Kubernetes Environment</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/0*gYUDPEWAye1VXus4" /></figure><h3>01)Installation and Configuration</h3><p>A step-by-step guide to installing and configuring Argo CD in a Kubernetes cluster, including the setup of applications and repositories.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*fA8RAJkymPGFkp2d" /></figure><h3>02)Best Practices</h3><p>Practical recommendations and best practices for leveraging Argo CD to achieve efficient and reliable continuous delivery in Kubernetes environments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/0*Xq_ERxqsgKvBDGfV" /></figure><h3>03)Demonstration</h3><p>A live demonstration showcasing the deployment and management of applications using Argo CD, highlighting its key features and capabilities.</p><h3>Case Study: Streamlining Continuous Delivery with Argo CD</h3><h3>01)Organizational Context</h3><p>An overview of how a hypothetical organization implemented Argo CD to streamline its continuous delivery processes and enhance application deployment efficiency.</p><h3>02)Challenges and Solutions</h3><p>A detailed exploration of the challenges faced by the organization and how Argo CD provided solutions to address these challenges effectively.</p><h3>03)Outcomes and Benefits</h3><p>Insights into the tangible outcomes and benefits realized by the organization after adopting Argo CD, including improvements in deployment speed, reliability, and scalability.</p><h3>Real-World Applications and Success Stories</h3><h3>01)Industry Use Cases</h3><p>An analysis of real-world applications of Argo CD across diverse industries, showcasing how organizations have leveraged the tool to achieve their continuous delivery goals.</p><h3>02)Success Stories</h3><p>Case studies highlighting the success stories of organizations that have embraced Argo CD, illustrating the transformative impact of the tool on their application deployment and management practices.</p><h3>03)Lessons Learned</h3><p>Key lessons and insights drawn from the experiences of organizations that have implemented Argo CD, providing valuable takeaways for the audience.</p><h3>Future Trends and Innovations in Argo CD</h3><h3>01)Evolution of Argo CD</h3><p>A glimpse into the future of Argo CD, exploring potential advancements, feature enhancements, and innovations that are poised to shape the tool’s evolution.</p><h3>02)Community Contributions</h3><p>Insights into the role of the community in driving the evolution of Argo CD, including contributions, feedback mechanisms, and collaborative initiatives.</p><h3>03)Opportunities for Innovation</h3><p>An exploration of the emerging trends and opportunities for innovation in the realm of continuous delivery, with a focus on how Argo CD is positioned to embrace these developments.</p><h3>Example:</h3><h3>How to achieve GitOps using Argo CD?</h3><p>Every enterprise uses Git as its source code management software to store code. Developers can commit their infrastructure configurations, such as Kubernetes resources definition, in Git to create environments needed for application deployment.</p><p>Once a developer implements a feature ( with a new application and K8S configurations) and merges with the main branch, the CI process is initiated for generating and testing an image.</p><p>After the review and approval of the application, the pull request in Git is merged with the main branch. With the help of the GitOps agent, Argo CD will immediately identify the new versions of a configuration that was recently merged and compare it with the running application in the destination environment (it can be pre-prod or prod).</p><p>In case of a mismatch, it highlights out-of-sync status, and in the backend, Argo CD uses the Kubernetes controller to reconcile the new changes to cluster resources. Once the Kubernetes resources are ready, it informs the user the application is in sync.</p><p>Argo CD also uses an agent to constantly monitor the end environment and check its status with Git. Argo CD synchronizes the current state with the declared state of configurations and ensures that new configurations are correctly deployed to a Kubernetes cluster.</p><p>As all the records of all changes, including all details of the environment, at every stage of the process are stored in Git, Argo CD helps roll back applications to previous states in a single click.</p><h3>Benefits of Argo CD:</h3><ol><li><strong>Improve developer productivity</strong></li></ol><p>Argo CD provides developers with a self-service environment for application deployment. Software development teams can focus on creativity and writing business logic instead of time and energy on manual and remedial deployments.</p><p><strong>2. Improved software delivery compliance</strong></p><p>Allow your developers, Ops, and DevOps teams to use a single platform for infrastructure change management. Apply organizational policies to restrict access to Kubernetes resources and minimize your application downtime and outages.</p><p><strong>3. Increased collaboration in SDLC</strong></p><p>While working on Argo CD, every team member can work from the same system to achieve GitOps and understand the status of individual processes. The single Git repository fosters collaboration amongst team members by assigning tasks to individuals and deploying code from each person as necessary.</p><p><strong>4. Faster deployments</strong></p><p>Argo CD allows teams to perform more rapid deployments into Kubernetes clusters across multi-cloud. Quicker releases of application changes mean shorter time to market and more flexibility in responding to customer demand.</p><h3>Prerequisites:</h3><ul><li>A running Kubernetes cluster</li></ul><h3>How to install ArgoCD?</h3><ul><li>For this tutorial, you must have a running kubernetes cluster like I have minikube running on my server.</li><li><strong>Create the namespace for argoCD</strong></li></ul><pre>kubectl create namespace argocd</pre><ul><li><strong>Install ArgoCD using the below command</strong></li></ul><pre>kubectl apply -n argocd -f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml</pre><ul><li><strong>After installing the ArgoCD, you can run the below command to check what resources it has created.</strong></li></ul><pre>ubuntu@ip-172-31-7-106:~$ kubectl get all -n argocd<br>NAME                                                    READY   STATUS    RESTARTS   AGE<br>pod/argocd-application-controller-0                     1/1     Running   0          106m<br>pod/argocd-applicationset-controller-787bfd9669-4mxq6   1/1     Running   0          106m<br>pod/argocd-dex-server-bb76f899c-slg7k                   1/1     Running   0          106m<br>pod/argocd-notifications-controller-5557f7bb5b-84cjr    1/1     Running   0          106m<br>pod/argocd-redis-b5d6bf5f5-482qq                        1/1     Running   0          106m<br>pod/argocd-repo-server-56998dcf9c-c75wk                 1/1     Running   0          106m<br>pod/argocd-server-5985b6cf6f-zzgx8                      1/1     Running   0          106m<br><br>NAME                                              TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)                      AGE<br>service/argocd-applicationset-controller          ClusterIP   10.102.163.101   &lt;none&gt;        7000/TCP,8080/TCP            106m<br>service/argocd-dex-server                         ClusterIP   10.101.227.215   &lt;none&gt;        5556/TCP,5557/TCP,5558/TCP   106m<br>service/argocd-metrics                            ClusterIP   10.111.59.189    &lt;none&gt;        8082/TCP                     106m<br>service/argocd-notifications-controller-metrics   ClusterIP   10.96.102.185    &lt;none&gt;        9001/TCP                     106m<br>service/argocd-redis                              ClusterIP   10.97.229.117    &lt;none&gt;        6379/TCP                     106m<br>service/argocd-repo-server                        ClusterIP   10.102.16.58     &lt;none&gt;        8081/TCP,8084/TCP            106m<br>service/argocd-server                             ClusterIP   10.98.71.135     &lt;none&gt;        80/TCP,443/TCP               106m<br>service/argocd-server-metrics                     ClusterIP   10.109.248.207   &lt;none&gt;        8083/TCP                     106m<br><br>NAME                                               READY   UP-TO-DATE   AVAILABLE   AGE<br>deployment.apps/argocd-applicationset-controller   1/1     1            1           106m<br>deployment.apps/argocd-dex-server                  1/1     1            1           106m<br>deployment.apps/argocd-notifications-controller    1/1     1            1           106m<br>deployment.apps/argocd-redis                       1/1     1            1           106m<br>deployment.apps/argocd-repo-server                 1/1     1            1           106m<br>deployment.apps/argocd-server                      1/1     1            1           106m<br><br>NAME                                                          DESIRED   CURRENT   READY   AGE<br>replicaset.apps/argocd-applicationset-controller-787bfd9669   1         1         1       106m<br>replicaset.apps/argocd-dex-server-bb76f899c                   1         1         1       106m<br>replicaset.apps/argocd-notifications-controller-5557f7bb5b    1         1         1       106m<br>replicaset.apps/argocd-redis-b5d6bf5f5                        1         1         1       106m<br>replicaset.apps/argocd-repo-server-56998dcf9c                 1         1         1       106m<br>replicaset.apps/argocd-server-5985b6cf6f                      1         1         1       106m<br><br>NAME                                             READY   AGE<br>statefulset.apps/argocd-application-controller   1/1     106m<br>ubuntu@ip-172-31-7-106:~$</pre><ul><li><strong>Now in order to access the UI of ArgoCD, you need to run the below command</strong></li></ul><pre>kubectl port-forward --address 0.0.0.0 svc/argocd-server -n argocd 8080:443</pre><ul><li>The above command will forward port 8080 and map it with the argocd-server service’s 443 port.</li><li>You can check the UI of ArgoCD by visiting localhost:8080 or ip-of-server:8080</li><li>Now, in order to log into the UI you need the credentials. So, for a username, you can write admin and the password is stored in the secret called argocd-initial-admin-secret in the cluster.</li><li>You need to run the below command to get the value of the secret.</li></ul><pre>kubectl get secret argocd-initial-admin-secret -n argocd -o yaml</pre><ul><li>The secret base64 encoded so, you have to decode the secret by running the below command.</li></ul><pre>echo &quot;secret&quot; | base64 decode</pre><ul><li>After running the above command you can have the decoded value of the secret and using that as a password you can log in to the UI.</li><li>Now, the installation has been completed.</li></ul><p>Now, the installation is completed.</p><p>So, now I have an application running on my kubernetes cluster. Below are the manifest files for that.</p><ol><li><strong>Deployment file</strong></li></ol><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: myapp-deployment<br>spec:<br>  selector:<br>    matchLabels:<br>      app: myapp<br>  replicas: 4<br>  template:<br>    metadata:<br>      labels:<br>        app: myapp<br>    spec:<br>      containers:<br>      - name: myapp<br>        image: dhruvin30/dhsoniweb</pre><ul><li>I am using dhsoniweb which is my portfolio website’s docker image.</li></ul><p><strong>2. Service file</strong></p><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: myapp-service<br>spec:<br>  selector:<br>    app: myapp<br>  ports:<br>  - port: 80<br>    protocol: TCP<br>    targetPort: 8080</pre><p>And I have stored the code in <a href="https://github.com/DhruvinSoni30/ArgoCD-Demo"><strong>this</strong></a> repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*e0a563SrY8yvp_XU.png" /></figure><p>Repository</p><p>So, now in order for argoCD to sync with this repository we need to write some manifest file for that. Here is the manifest file for that.</p><pre>apiVersion: argoproj.io/v1alpha1<br>kind: Application<br>metadata:<br>  name: myapp-argo-application<br>  namespace: argocd<br>spec:<br>  project: default<br><br>  source:<br>    repoURL: https://github.com/DhruvinSoni30/ArgoCD-Demo.git<br>    targetRevision: HEAD<br>    path: dev<br>  destination: <br>    server: https://kubernetes.default.svc<br>    namespace: myapp<br><br>  syncPolicy:<br>    syncOptions:<br>    - CreateNamespace=true<br><br>    automated:<br>      selfHeal: true<br>      prune: true</pre><ul><li>argoproj.io/v1alpha1 is an API version of argoCD. The API Version might get changed once argoCD has some new release. Always refer to the documentation for the latest information.</li><li>I am defining my repository URL in repoURL section.</li><li>targetRevision is set to HEAD so that it will always fetch the latest commit.</li><li>path is set to dev because I have my application’s manifest files in dev folder.</li><li>In the destination section we have server section and it is set to https://kubernetes.default.svc which is the internal service of the kubernetes API Server.</li></ul><pre>ubuntu@ip-172-31-7-106:~$ kubectl get svc <br>NAME         TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)   AGE<br>kubernetes   ClusterIP   10.96.0.1    &lt;none&gt;        443/TCP   137m<br>ubuntu@ip-172-31-7-106:~$</pre><ul><li>namespace is set to myapp , because we want to create our application in that namespace. Now, we actually don’t have the namespace already created because we want argoCD to create that automatically.</li><li>In order for argoCD to create the namespace automatically we need to define the below attributes.</li></ul><pre>syncPolicy:<br>    syncOptions:<br>    - CreateNamespace=true</pre><ul><li>We want argoCD to automatically sync any changes in the git repository but by default, it is turned off. So in order to enable that we need to define the below attributes.</li></ul><pre>automated:<br>  selfHeal: true<br>  prune: true</pre><ul><li>If you apply any changes from the backend using kubectl utility then we want to override that with whatever we have in our git repository in order to do that we have selfHeal: true for that.</li><li>If we rename any component or delete the entire component then we want argoCD to delete that component in the cluster as well and in order to do that we have prune: true for that.</li><li>argoCD will check the changes in the git repository every 3 minutes. If you want argoCD to check the changes as soon as it has done then you can implement the webhook for that.</li><li>Now, that we have our file ready we need to run the below command to apply that.</li></ul><pre>kubectl apply -f application.yaml</pre><ul><li>Once you apply the file you can check your application in the UI.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ocrj3J53nr5DhYv0.png" /></figure><p>Application</p><ul><li>You can click on your application and check the various details.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cHVxc4EpmYAg9Joc.png" /></figure><p>Workflow</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5Fnzfj8orUgiJLQu.png" /></figure><p>Manifest file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mKbHSiirlodonQzw.png" /></figure><p>Manifest file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sy6x49Ower52mgV2.png" /></figure><p>Events of pod creation</p><ul><li>Now let’s say you want to increase the replica for your application. You just need to commit your changes in the git repository like below and argoCD will take care of the further actions.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*klBDq7Fbw32i8fcV.png" /></figure><p>Changes</p><ul><li>As soon as you commit the changes in the repository, argoCD will look for the changes and apply the changes in the cluster.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8dby7abWLnT83rIx.png" /></figure><p>Changes in cluster</p><ul><li>As you can see, now we have a total of 4 pods in the cluster.</li></ul><pre>ubuntu@ip-172-31-7-106:~$ kubectl get pods -n myapp<br>NAME                                READY   STATUS    RESTARTS   AGE<br>myapp-deployment-544dd58bc4-4sntz   1/1     Running   0          13h<br>myapp-deployment-544dd58bc4-wkf5j   1/1     Running   0          13h<br>myapp-deployment-544dd58bc4-xt7hb   1/1     Running   0          13h<br>myapp-deployment-544dd58bc4-zjmn8   1/1     Running   0          13h<br>ubuntu@ip-172-31-7-106:~$</pre><ul><li>Now you can perform different changes as per your need and argoCD will take care of the further action.</li></ul><h3>Thank You</h3><p>Contact: akulamanojkumar988@gmail.com</p><p>Linkedin ID: <a href="http://www.linkedin.com/in/manoj-kumar-akula-792706241">www.linkedin.com/in/manoj-kumar-akula-792706241</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a909b5c62acb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>