<?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 Soham Valsangkar on Medium]]></title>
        <description><![CDATA[Stories by Soham Valsangkar on Medium]]></description>
        <link>https://medium.com/@sohamvs1999?source=rss-47660f9e2e4e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*y8UHOx_ER1Yru_r4BrCGtg.png</url>
            <title>Stories by Soham Valsangkar on Medium</title>
            <link>https://medium.com/@sohamvs1999?source=rss-47660f9e2e4e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 06:05:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sohamvs1999/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[Updating AMI in Autoscaling Group with Zero Downtime using Terraform]]></title>
            <link>https://awstip.com/updating-ami-in-autoscaling-group-with-zero-downtime-using-terraform-0cc9c7e42b8b?source=rss-47660f9e2e4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/0cc9c7e42b8b</guid>
            <category><![CDATA[high-availability]]></category>
            <category><![CDATA[devsecops]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Soham Valsangkar]]></dc:creator>
            <pubDate>Tue, 06 Aug 2024 10:29:47 GMT</pubDate>
            <atom:updated>2024-08-07T17:28:30.045Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0iKrPcCB7sIUxFOtQd9QgQ.png" /></figure><h3>Introduction</h3><p>Updating the Amazon Machine Image (AMI) in an Auto Scaling Group (ASG) can be challenging, especially if you need to ensure zero downtime. This guide walks you through the process using Terraform, ensuring your application remains available throughout the update.</p><p><strong>Prerequisites:</strong></p><p>Before we begin, ensure you have the following:</p><ul><li>AWS Account</li><li>Terraform Installed on your local machine</li><li>Basic knowledge of AWS and Terraform</li></ul><p><strong>Terraform Configuration</strong></p><p>First, we’ll set up the Terraform configuration for the ASG and Launch Template. The Launch Template defines the configuration of our EC2 instances, including the AMI.</p><p>you can find the complete source code for this project in this <a href="https://github.com/SohamV1/Terraform-Autoscaling-Instance-refresh.git">GitHub repo</a>.</p><pre>resource &quot;aws_launch_template&quot; &quot;my-lt&quot; {<br>  name            = &quot;my-launch-template&quot;<br>  image_id        = &quot;ami-04a81a99f5ec58529&quot;<br>  instance_type   = &quot;t2.micro&quot;<br>  key_name        = &quot;key_name&quot;<br>  vpc_security_group_ids = [&quot;${aws_security_group.sg.id}&quot;]<br>  user_data       = base64encode(&lt;&lt;EOF<br>#!/bin/bash<br>sudo apt update <br>sudo apt install nginx -y<br>sudo systemctl enable nginx<br>sudo systemctl start nginx<br>EOF<br>  )<br>}</pre><p><strong>Auto Scaling Group Configuration</strong></p><pre>resource &quot;aws_autoscaling_group&quot; &quot;ag&quot; {<br>  name                 = &quot;my-ag&quot;<br>  max_size             = 3<br>  min_size             = 1<br>  health_check_type    = &quot;ELB&quot;<br>  desired_capacity     = 2<br>  target_group_arns    = [aws_lb_target_group.test.arn]<br>  launch_template {<br>    id = aws_launch_template.my-lt.id<br>    version = aws_launch_template.my-lt.latest_version<br>  }<br>  force_delete         = true<br>  vpc_zone_identifier  = [&quot;subnet-id1&quot;, &quot;subnet-id2&quot;]<br><br>  instance_refresh {<br>    strategy = &quot;Rolling&quot;<br>    preferences {<br>      min_healthy_percentage = 50<br>      skip_matching = true<br>    }<br>    triggers = [&quot;launch_template&quot;]<br>  }<br><br>  tag {<br>    key                 = &quot;Name&quot;<br>    value               = &quot;autoscaling-ec2&quot;<br>    propagate_at_launch = true<br>  }<br><br>}</pre><h3>Instance Refresh</h3><p>Instance Refresh is a feature in ASG that allows you to replace instances with a new launch template or configuration without manual intervention.</p><h3>Adding Instance Refresh</h3><p>The instance refresh is already included in the ASG configuration above. The key elements are:</p><ul><li><strong>Strategy</strong>: Defines how instances are replaced. In this example, we use “Rolling.”</li><li><strong>Min Healthy Percentage</strong>: Ensures at least 50% of instances are healthy during the update.</li><li><strong>Triggers</strong>: Specifies the launch template as a trigger for the refresh.</li></ul><h3>Zero Downtime Strategy</h3><p>To achieve zero downtime during the AMI update, follow these steps:</p><ol><li><strong>Update Launch Template</strong>: Change the AMI in the launch template and apply the Terraform configuration. This action will trigger the instance refresh.</li><li><strong>Instance Refresh Process</strong>:</li></ol><ul><li>New instances with the updated AMI will be launched.</li><li>Old instances will be terminated once the new instances are healthy and registered with the Load Balancer.</li></ul><p><strong>3. Monitoring</strong>: Ensure the new instances are properly registered and healthy before the old instances are terminated.</p><p>Code to update AMI for launch template</p><pre>resource &quot;aws_launch_template&quot; &quot;my-lt&quot; {<br>  name            = &quot;my-launch-template&quot;<br>  image_id        = &quot;New_AMI_ID&quot;<br>  instance_type   = &quot;t2.micro&quot;<br>  key_name        = &quot;key_name&quot;<br>  vpc_security_group_ids = [&quot;${aws_security_group.sg.id}&quot;]<br>  user_data       = base64encode(&lt;&lt;EOF<br>#!/bin/bash<br>sudo apt update <br>sudo apt install nginx -y<br>sudo systemctl enable nginx<br>sudo systemctl start nginx<br>EOF<br>  )<br>}</pre><p>After updating the image_id, run terraform apply to start the instance refresh.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-aAvmBhLPXV-jz9tyHH7XQ.png" /></figure><h3>Conclusion</h3><p>Updating the AMI in an Auto Scaling Group using Terraform can be seamlessly achieved by leveraging instance refresh. This ensures that your applications remain available without downtime during the update process. By following the steps outlined in this guide, you can maintain a resilient and up-to-date infrastructure.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0cc9c7e42b8b" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/updating-ami-in-autoscaling-group-with-zero-downtime-using-terraform-0cc9c7e42b8b">Updating AMI in Autoscaling Group with Zero Downtime using Terraform</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Three-Tier Terraform Project with Modular Approach for Multiple Environments — Part 1]]></title>
            <link>https://awstip.com/advanced-three-tier-terraform-project-with-modular-approach-for-multiple-environments-part-1-763a5e721fc9?source=rss-47660f9e2e4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/763a5e721fc9</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[devsecops]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Soham Valsangkar]]></dc:creator>
            <pubDate>Thu, 06 Jun 2024 15:48:58 GMT</pubDate>
            <atom:updated>2024-06-11T19:19:44.330Z</atom:updated>
            <content:encoded><![CDATA[<h3>Advanced Three-Tier Terraform Project with Modular Approach for Multiple Environments — Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*8XfGFUhrtKSkdokYbjlyOA.gif" /><figcaption>Three-Tier-Architecture on AWS</figcaption></figure><p><strong>Project Introduction: </strong>In this project, we will create a Three-Tier Infrastructure on AWS using the Modular approach for multiple environments using best practices like S3 backend and DynamoDB table for state locking.</p><p><strong>Project Overview:</strong></p><ul><li>Create modules for ALB, ASG, VPC, RDS, and Security Group.</li><li>Create an S3 bucket for the Terraform backend and a DynamoDB table for state locking for the dev environment.</li><li>Create a dev folder, source the modules, and write the configuration.</li><li>Create an S3 bucket and DynamoDB for other environments like prod and qa, and create a prod folder.</li><li>In the prod folder, call the needed modules and write the configuration.</li></ul><p><strong>Step 1</strong>: Creating Modules for ALB, ASG, VPC, etc.</p><p>I have stored my access key ID and secret key ID in the environment so that we don’t have to use them in the code.</p><p>You can check the git repo for the whole code</p><pre>https://github.com/SohamV1/Terraform-Three-tier.git</pre><p>Create a Modules folder</p><p>In the Load-Balancer folder create main.tf</p><pre>resource &quot;aws_lb&quot; &quot;my-lb&quot; {<br>  name               = var.load_balancer_name<br>  internal           = var.internal<br>  load_balancer_type = var.load_balancer_type<br>  security_groups    = var.security_groups<br>  subnets            = var.subnets<br><br>  tags = {<br>    &quot;Name&quot; = var.load_balancer_name<br>    &quot;Enviornment&quot; = var.Environment<br>  }<br>}<br><br>resource &quot;aws_lb_target_group&quot; &quot;test&quot; {<br>  name     = var.target_group_name<br>  port     = var.target_group_port<br>  protocol = var.protocol<br>  vpc_id   = var.vpc_id<br>}<br><br>resource &quot;aws_lb_listener&quot; &quot;front_end&quot; {<br>  load_balancer_arn = aws_lb.my-lb.arn<br>  port              = var.target_group_port<br>  protocol          = var.protocol<br><br>  default_action {<br>    type             = &quot;forward&quot;<br>    target_group_arn = aws_lb_target_group.test.arn<br>  }<br>}</pre><p>create variables.tf as well in the same folder</p><pre>variable &quot;load_balancer_name&quot; {<br>  description = &quot;load_balancer_name&quot;<br>  type = string<br>}<br><br>variable &quot;internal&quot; {<br>  description = &quot;internal lb&quot;<br>  type = bool<br>}<br><br>variable &quot;load_balancer_type&quot; {<br>  description = &quot;load_balancer_type application, network&quot;<br>  type = string<br>}<br><br>variable &quot;security_groups&quot; {<br>    description = &quot;security_groups&quot;<br>    type = list(string)<br>}<br><br>variable &quot;subnets&quot; {<br>  description = &quot;subnets&quot;<br>  type = list(string)<br>}<br><br>variable &quot;Environment&quot; {<br>  description = &quot;Environment&quot;<br>  type = string<br>}<br><br>variable &quot;target_group_name&quot; {<br>  description = &quot;target_group_name&quot;<br>  type = string<br>}<br><br>variable &quot;target_group_port&quot; {<br>  description = &quot;target_group_port&quot;<br>  type = string<br>}<br><br><br>variable &quot;protocol&quot; {<br>  description = &quot;protocol&quot;<br>  type = string<br>}<br><br>variable &quot;vpc_id&quot; {<br>  description = &quot;vpc_id&quot;<br>  type = string<br>}</pre><p>Create output.tf as we need to use load balancer arn in other places</p><pre>output &quot;target_group_arn&quot; {<br>  description = &quot;target_group_arn&quot;<br>  value = aws_lb_target_group.test.arn<br>}</pre><p>In this way create a module for ALB, ASG, RDS, VPC, and Security-Groups</p><p>We have used user_data in launch_template to install nginx to clear the health check of the load balancer.</p><p>Alternatively, you can create an ami of your code or increase the health check grace period to 300 and configure the Code within that time also you can change the parameters like health check port and other things according to your code.</p><p>In VPC, I have created two public and two private subnets and configured nat and other things accordingly.</p><p>In RDS, I have created a primary RDS instance and one read replica in the subnet group.</p><p><strong>Step 2: Create AWS Secrets manager secret</strong></p><p>For storing the Password for RDS we will need to use the AWS secrets manager by following the command</p><pre>aws secretsmanager create-secret --name my_rds_password_1 --secret-string &quot;Test1234&quot;</pre><p>Make sure you don’t use @, / or special characters as the rds password according to rds policy we will call this using a data block to fetch it in our config.</p><pre>data &quot;aws_secretsmanager_secret&quot; &quot;rds_password&quot; {<br>  name = var.rds_password_secret_name<br>}<br><br>data &quot;aws_secretsmanager_secret_version&quot; &quot;secret-version&quot; {<br>  secret_id = data.aws_secretsmanager_secret.rds_password.id<br>}</pre><p><strong>Step 3: Create an S3 bucket for terraform backend and DynamoDB table</strong></p><p>Go on AWS Console and create an S3 bucket for storing the terraform state file remotely.</p><p>Make sure to keep versioning enabled in the s3 bucket</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uxmsG77OKtHDIAQehnbbOA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0l9ewPbu0blJlYNW_An-qA.png" /></figure><p>Now create a DynamoDB table for state-locking so that multiple individuals make changes to our state file at once</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Z0x9jyzMIE_hRsxEIS4RA.png" /></figure><p>Use the Partition key <strong>as LockID</strong></p><p><strong>Step 3: Create a dev folder and write the config for the dev</strong></p><p>Create provider.tf and give the s3 bucket name and DynamDB table we just created</p><pre>terraform {<br>  backend &quot;s3&quot; {<br>    bucket         = &quot;three-tier-backend-dev&quot;<br>    key            = &quot;terraform.tfstate&quot;<br>    region         = &quot;us-east-1&quot;<br>    dynamodb_table = &quot;three-tier-dev&quot;<br>  }<br>}<br><br>provider &quot;aws&quot; {<br>  region = &quot;us-east-1&quot;<br>}</pre><p>You will need to provide values for all variables and use the outputs wherever required</p><pre>module &quot;frontend-lb&quot; {<br>  source             = &quot;../Modules/Load-Balancer&quot;<br>  load_balancer_name = &quot;frontend-three-tier-lb&quot;<br>  internal           = false<br>  load_balancer_type = &quot;application&quot;<br>  security_groups    = [module.sg.id]<br>  subnets            = [module.vpc.public_subnet_id, module.vpc.public_subnet_id_2]<br>  Environment        = &quot;dev&quot;<br>  target_group_name  = &quot;frontend-lb-tg&quot;<br>  target_group_port  = &quot;80&quot;<br>  protocol           = &quot;HTTP&quot;<br>  vpc_id             = module.vpc.vpc_id<br>}<br><br><br>module &quot;frontend-ALB&quot; {<br>  source                 = &quot;../Modules/ASG&quot;<br>  ami                    = &quot;ami-04b70fa74e45c3917&quot;<br>  instance_type          = &quot;t2.micro&quot;<br>  key_name               = &quot;Soham&quot;<br>  instance_name          = &quot;frontend-dev-instances&quot;<br>  Environment            = &quot;dev&quot;<br>  security_groups        = [module.sg.id]<br>  alb_group_name         = &quot;three-tier-asg-frontend&quot;<br>  max_size               = 2<br>  min_size               = 1<br>  desired_capacity       = 1<br>  lb_target_group_arns   = [module.frontend-lb.target_group_arn]<br>  subnets_alb            = [module.vpc.public_subnet_id, module.vpc.public_subnet_id_2]<br>  asg_policy_name        = &quot;three-tier-asg-policy-frontend&quot;<br>  policy_type            = &quot;TargetTrackingScaling&quot;<br>  predefined_metric_type = &quot;ASGAverageCPUUtilization&quot;<br>  target_value           = 50<br>  health_check_type      = &quot;ELB&quot;<br>}<br><br>module &quot;backend-lb&quot; {<br>  source             = &quot;../Modules/Load-Balancer&quot;<br>  load_balancer_name = &quot;backend-three-tier-lb&quot;<br>  internal           = true<br>  load_balancer_type = &quot;application&quot;<br>  security_groups    = [module.sg.id]<br>  subnets            = [module.vpc.private_subnet_id, module.vpc.private_subnet_id_2]<br>  Environment        = &quot;dev&quot;<br>  target_group_name  = &quot;backend-lb-tg&quot;<br>  target_group_port  = &quot;80&quot;<br>  protocol           = &quot;HTTP&quot;<br>  vpc_id             = module.vpc.vpc_id<br>}<br><br>module &quot;backend-ALB&quot; {<br>  source                 = &quot;../Modules/ASG&quot;<br>  ami                    = &quot;ami-04b70fa74e45c3917&quot;<br>  instance_type          = &quot;t2.micro&quot;<br>  key_name               = &quot;Soham&quot;<br>  instance_name          = &quot;backend-dev-instances&quot;<br>  Environment            = &quot;dev&quot;<br>  security_groups        = [module.sg.id]<br>  alb_group_name         = &quot;three-tier-asg-backend&quot;<br>  max_size               = 2<br>  min_size               = 1<br>  desired_capacity       = 1<br>  lb_target_group_arns   = [module.backend-lb.target_group_arn]<br>  subnets_alb            = [module.vpc.private_subnet_id, module.vpc.private_subnet_id_2]<br>  asg_policy_name        = &quot;three-tier-asg-policy-backend&quot;<br>  policy_type            = &quot;TargetTrackingScaling&quot;<br>  predefined_metric_type = &quot;ASGAverageCPUUtilization&quot;<br>  target_value           = 50<br>  health_check_type      = &quot;ELB&quot;<br>}<br><br>module &quot;sg&quot; {<br>  source      = &quot;../Modules/Security_groups&quot;<br>  vpc_id      = module.vpc.vpc_id<br>  name        = &quot;test-sg&quot;<br>  description = &quot;a test sg&quot;<br><br>  ingress_rules = [<br>    {<br>      description = &quot;HTTP Port&quot;<br>      from_port   = &quot;80&quot;<br>      to_port     = &quot;80&quot;<br>      protocol    = &quot;tcp&quot;<br>      cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>    },<br>    {<br>      description = &quot;SSH Port&quot;<br>      from_port   = &quot;22&quot;<br>      to_port     = &quot;22&quot;<br>      protocol    = &quot;tcp&quot;<br>      cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>    },<br>    {<br>      description = &quot;MYSQL Port&quot;<br>      from_port   = &quot;3306&quot;<br>      to_port     = &quot;3306&quot;<br>      protocol    = &quot;tcp&quot;<br>      cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>    },<br>    {<br>      description = &quot;Backend Port&quot;<br>      from_port   = &quot;3000&quot;<br>      to_port     = &quot;3000&quot;<br>      protocol    = &quot;tcp&quot;<br>      cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>    }<br>  ]<br>  egress_rules = [<br>    {<br>      description = &quot;Allow all outbound traffic&quot;<br>      from_port   = 0<br>      to_port     = 0<br>      protocol    = &quot;-1&quot;<br>      cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>    }<br>  ]<br>}<br><br>module &quot;vpc&quot; {<br>  source                          = &quot;../Modules/VPC&quot;<br>  vpc_cidr                        = &quot;10.0.0.0/16&quot;<br>  vpc_name                        = &quot;three-tier-VPC&quot;<br>  public_subnet_cidr_block        = &quot;10.0.0.0/24&quot;<br>  public_subnet_name              = &quot;Three-tier-Public-Subnet&quot;<br>  public_sub_availability_zone    = &quot;us-east-1a&quot;<br>  private_subnet_cidr_block       = &quot;10.0.1.0/24&quot;<br>  private_subnet_name             = &quot;Three-tier-Private-subnet&quot;<br>  private_sub_availability_zone   = &quot;us-east-1b&quot;<br>  public_subnet_cidr_block_2      = &quot;10.0.2.0/24&quot;<br>  public_subnet_name_2            = &quot;Three-tier-Public-Subnet-2&quot;<br>  public_sub_availability_zone_2  = &quot;us-east-1b&quot;<br>  private_subnet_cidr_block_2     = &quot;10.0.3.0/24&quot;<br>  private_subnet_name_2           = &quot;Three-tier-Private-subnet-2&quot;<br>  private_sub_availability_zone_2 = &quot;us-east-1a&quot;<br>}<br><br>module &quot;rds&quot; {<br>  source                   = &quot;../Modules/RDS&quot;<br>  identifier               = &quot;three-tier-db-dev&quot;<br>  allocated_storage        = 10<br>  db_name                  = &quot;ThreeTierDb&quot;<br>  db_engine                = &quot;mysql&quot;<br>  db_engine_version        = &quot;8.0&quot;<br>  instance_type            = &quot;db.t3.micro&quot;<br>  rds_username             = &quot;soham&quot;<br>  subnet_group_name        = &quot;three-tier-subnet-group&quot;<br>  subnet_ids               = [module.vpc.private_subnet_id, module.vpc.private_subnet_id_2]<br>  skip_final_snapshot      = true<br>  security_group_ids       = [module.sg.id]<br>  Environment              = &quot;dev&quot;<br>  rds_password_secret_name = &quot;my_rds_password_1&quot;<br>  identifier_replica       = &quot;three-tier-db-dev-replica&quot;<br>  backup_retention_period  = 7<br>}</pre><p>We have tagged the environment as dev and also used dev in the name so that duplicate resources are not created.</p><p><strong>Step 4: Create an S3 bucket and DynamoDB table for prod or other environments</strong></p><p>Create an S3 bucket and DynamoDB table similar to the above step</p><p><strong>Step 5:</strong> <strong>Create a prod folder and write the config for the prod</strong></p><p>Create provider.tf as follows:</p><pre>terraform {<br>  backend &quot;s3&quot; {<br>    bucket = &quot;three-tier-backend-prod&quot;<br>    key    = &quot;terraform.tfstate&quot;<br>    region = &quot;us-east-1&quot;<br>    dynamodb_table = &quot;three-tier-prod&quot;<br>  }<br>}<br><br>provider &quot;aws&quot; {<br>  region = &quot;us-east-1&quot;<br>}</pre><p>You need to make changes in the names of the resources and add the prod or environment name in the name. You can also make changes in infrastructure for prod accordingly.</p><pre>module &quot;frontend-lb&quot; {<br>  source = &quot;../Modules/Load-Balancer&quot;<br>  load_balancer_name = &quot;frontend-three-tier-lb-prod&quot;<br>  internal = false<br>  load_balancer_type = &quot;application&quot;<br>  security_groups = [module.sg.id]<br>  subnets = [module.vpc.public_subnet_id,module.vpc.public_subnet_id_2]<br>  Environment = &quot;prod&quot;<br>  target_group_name = &quot;frontend-lb-tg-prod&quot;<br>  target_group_port = &quot;80&quot;<br>  protocol = &quot;HTTP&quot;<br>  vpc_id = module.vpc.vpc_id<br>}<br><br><br>module &quot;frontend-ALB&quot; {<br>  source = &quot;../Modules/ASG&quot;<br>  ami = &quot;ami-04b70fa74e45c3917&quot;<br>  instance_type = &quot;t2.micro&quot;<br>  key_name = &quot;Soham&quot;<br>  instance_name = &quot;frontend-prod-instances&quot;<br>  Environment = &quot;prod&quot;<br>  security_groups = [module.sg.id]<br>  alb_group_name = &quot;three-tier-asg-frontend-prod&quot;<br>  max_size = 2<br>  min_size = 1<br>  desired_capacity = 1<br>  lb_target_group_arns = [module.frontend-lb.target_group_arn]<br>  subnets_alb = [module.vpc.public_subnet_id,module.vpc.public_subnet_id_2]<br>  asg_policy_name = &quot;three-tier-asg-policy-frontend-prod&quot;<br>  policy_type = &quot;TargetTrackingScaling&quot;<br>  predefined_metric_type = &quot;ASGAverageCPUUtilization&quot;<br>  target_value = 50<br>  health_check_type = &quot;ELB&quot;<br>}<br><br>module &quot;backend-lb&quot; {<br>  source = &quot;../Modules/Load-Balancer&quot;<br>  load_balancer_name = &quot;backend-three-tier-lb-prod&quot;<br>  internal = true<br>  load_balancer_type = &quot;application&quot;<br>  security_groups = [module.sg.id]<br>  subnets = [module.vpc.private_subnet_id,module.vpc.private_subnet_id_2]<br>  Environment = &quot;prod&quot;<br>  target_group_name = &quot;backend-lb-tg-prod&quot;<br>  target_group_port = &quot;80&quot;<br>  protocol = &quot;HTTP&quot;<br>  vpc_id = module.vpc.vpc_id<br>}<br><br>module &quot;backend-ALB&quot; {<br>  source = &quot;../Modules/ASG&quot;<br>  ami = &quot;ami-04b70fa74e45c3917&quot;<br>  instance_type = &quot;t2.micro&quot;<br>  key_name = &quot;Soham&quot;<br>  instance_name = &quot;backend-prod-instances-prod&quot;<br>  Environment = &quot;prod&quot;<br>  security_groups = [module.sg.id]<br>  alb_group_name = &quot;three-tier-asg-backend-prod&quot;<br>  max_size = 2<br>  min_size = 1<br>  desired_capacity = 1<br>  lb_target_group_arns = [module.backend-lb.target_group_arn]<br>  subnets_alb = [module.vpc.private_subnet_id,module.vpc.private_subnet_id_2]<br>  asg_policy_name = &quot;three-tier-asg-policy-backend-prod&quot;<br>  policy_type = &quot;TargetTrackingScaling&quot;<br>  predefined_metric_type = &quot;ASGAverageCPUUtilization&quot;<br>  target_value = 50<br>  health_check_type = &quot;ELB&quot;<br>}<br><br>module &quot;sg&quot; {<br>  source = &quot;../Modules/Security_groups&quot;<br>  vpc_id = module.vpc.vpc_id<br>  name = &quot;test-sg-prod&quot;<br>  description= &quot;a test sg&quot;<br><br>  ingress_rules = [<br>  {<br>    description = &quot;HTTP Port&quot;<br>    from_port = &quot;80&quot;<br>    to_port = &quot;80&quot;<br>    protocol = &quot;tcp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  },<br>  {<br>    description = &quot;SSH Port&quot;<br>    from_port = &quot;22&quot;<br>    to_port = &quot;22&quot;<br>    protocol = &quot;tcp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  },<br>  {<br>    description = &quot;MYSQL Port&quot;<br>    from_port = &quot;3306&quot;<br>    to_port = &quot;3306&quot;<br>    protocol = &quot;tcp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  },<br>  {<br>    description = &quot;Backend Port&quot;<br>    from_port = &quot;3000&quot;<br>    to_port = &quot;3000&quot;<br>    protocol = &quot;tcp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br>  ]<br>  egress_rules = [<br>    {<br>      description = &quot;Allow all outbound traffic&quot;<br>      from_port   = 0<br>      to_port     = 0<br>      protocol    = &quot;-1&quot;<br>      cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>    }<br>  ]<br>}<br><br>module &quot;vpc&quot; {<br>  source = &quot;../Modules/VPC&quot;<br>  vpc_cidr = &quot;10.0.0.0/16&quot;<br>  vpc_name = &quot;three-tier-VPC-prod&quot;<br>  public_subnet_cidr_block = &quot;10.0.0.0/24&quot;<br>  public_subnet_name = &quot;Three-tier-Public-Subnet-prod&quot;<br>  public_sub_availability_zone = &quot;us-east-1a&quot;<br>  private_subnet_cidr_block = &quot;10.0.1.0/24&quot;<br>  private_subnet_name = &quot;Three-tier-Private-subnet-prod&quot;<br>  private_sub_availability_zone = &quot;us-east-1b&quot;<br>  public_subnet_cidr_block_2 = &quot;10.0.2.0/24&quot;<br>  public_subnet_name_2 = &quot;Three-tier-Public-Subnet-prod-2&quot;<br>  public_sub_availability_zone_2 = &quot;us-east-1b&quot;<br>  private_subnet_cidr_block_2 = &quot;10.0.3.0/24&quot;<br>  private_subnet_name_2 = &quot;Three-tier-Private-subnet-prod-2&quot;<br>  private_sub_availability_zone_2 = &quot;us-east-1a&quot;<br>}<br><br>module &quot;rds&quot; {<br>  source = &quot;../Modules/RDS&quot;<br>  identifier = &quot;three-tier-db-prod&quot;<br>  allocated_storage = 10<br>  db_name              = &quot;ThreeTierDbProd&quot;<br>  db_engine               = &quot;mysql&quot;<br>  db_engine_version       = &quot;8.0&quot;<br>  instance_type       = &quot;db.t3.micro&quot;<br>  rds_username             = &quot;soham&quot;<br>  subnet_group_name    = &quot;three-tier-subnet-group-prod&quot;<br>  subnet_ids           = [module.vpc.private_subnet_id,module.vpc.private_subnet_id_2]<br>  skip_final_snapshot  = true<br>  security_group_ids = [module.sg.id]<br>  Environment = &quot;prod&quot;<br>  rds_password_secret_name = &quot;my_rds_password_1&quot;<br>  identifier_replica = &quot;three-tier-db-prod-replica&quot;<br>  backup_retention_period  = 7<br>} </pre><p>To run this configuration we will run the following commands:</p><pre>terraform init //to install modules and aws plugin<br>terraform fmt // to format the terraform code<br>terraform validate // to validate code<br>terraform plan // check what terraform will create exactly<br>terraform apply --auto-approve // create the infrastructure<br>terraform destroy --auto-approve // to destroy the current infrastructure</pre><p>You can also use tools like Chekov to check if the terraform code is following best practices or not</p><p>In this Part, we have used a simple approach of creating separate folders for each environment.</p><p>Some other options are can use terraform workspaces keep a single configuration and create multiple workspaces for different environments.</p><p>Terraform workspaces are useful only if the infrastructure is not very complex and the config remains the same more or less in most environments.</p><p>In next part will be creating a git branch for each environment and deploying the terraform code with a complete pipeline following all the security best practices.</p><p>Or else you can use third-party tools like Terragrunt.</p><p><strong>Conclusion: </strong>We have successfully created a three-tier infrastructure using the modular approach for multiple environments!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=763a5e721fc9" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/advanced-three-tier-terraform-project-with-modular-approach-for-multiple-environments-part-1-763a5e721fc9">Advanced Three-Tier Terraform Project with Modular Approach for Multiple Environments — Part 1</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced DevSecOps Multiple Microservices Kubernetes Project Using AWS EKS, Jenkins, and ArgoCD]]></title>
            <link>https://medium.com/@sohamvs1999/advanced-devsecops-multiple-microservices-kubernetes-project-using-aws-eks-jenkins-and-argocd-87f98c6d69a2?source=rss-47660f9e2e4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/87f98c6d69a2</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[devsecops]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[jenkins]]></category>
            <dc:creator><![CDATA[Soham Valsangkar]]></dc:creator>
            <pubDate>Wed, 22 May 2024 10:56:31 GMT</pubDate>
            <atom:updated>2024-05-22T10:56:31.353Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8cleDKyFxRUdEwEML12fhQ.png" /></figure><p><strong>Project Introduction: </strong>In this project, we leverage the power of AWS EKS, Jenkins, and ArgoCD to build, test, secure, and deploy multiple microservices. Our goal is to demonstrate a comprehensive DevSecOps pipeline that integrates state-of-the-art tools and practices for continuous integration and continuous deployment (CI/CD) within a microservices architecture.</p><p><strong>Project Overview:</strong></p><ol><li><strong>Jenkins Server Configuration: </strong>Install and configure essential tools on the Jenkins server, including Jenkins itself, Docker, Sonarqube, Kubectl, AWS CLI, and Trivy.</li><li><strong>Sonarqube Integration</strong>: Integrate Sonarqube for code quality analysis in the DevSecOps pipeline.</li><li><strong>Docker Script:</strong> Create a Script for Building and Pushing docker images in the ECR Repositories for all microservices.</li><li><strong>Release script:</strong> Create a Script to change the Manifest file for every microservice and push the changes to git Repo</li><li><strong>Jenkins Pipelines</strong>: Create Jenkins pipelines for deploying code to the EKS cluster.</li><li><strong>EKS Cluster Deployment</strong>: Using the eksctl command we will create an EKS cluster to deploy this project it is a managed kubernetes cluster on AWS.</li><li><strong>ECR Repositories: </strong>Create an ECR Repository for all services in the src folder and make sure to keep the images private</li><li><strong>ArgoCD Installation</strong>: Install and set up ArgoCD for continuous delivery and GitOps.</li><li><strong>Jenkins Pipeline: </strong>Creating a Jenkins pipeline for deploying microservices to an EKS cluster involves automating steps like code checkout, code quality analysis, security scans, Docker image building, and Kubernetes deployment.</li><li><strong>ArgoCD Application Deployment: </strong>Use ArgoCD to deploy all the microservices to the EKS Cluster<strong>.</strong></li></ol><p><strong>Prerequisites</strong>:</p><p>Install and Configure Jenkins, Docker, AWS CLI, Trivy, kubectl, and eksctl</p><p><strong>Step 1: Configure Jenkins Server:</strong></p><p>Install and login into the Jenkins server</p><p>We will store some credentials in Jenkins for this project</p><p>We will need AWS_ACCOUNT_ID to Save it as a secret text</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lcqYuIJA_Jvk9qSbAICr1g.png" /></figure><p>We will also need GitHub credentials</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Je6ib0F1w9hDY-66Lcp6Q.png" /></figure><p><strong>Step 2: Install and Configure Sonarqube using the docker image</strong></p><pre>docker run -itd -p 9000:9000 sonarqube:latest</pre><p>Run this command to start the Sonarqube server as a docker container</p><p>Go to localhost:9000 and username: admin and password: admin to get into the server, you might need to set up a new password as prompted. We will create a project called Multiple-Microservice-Deployment.</p><p>Click on <strong>Administration</strong> then <strong>Security</strong>, and select <strong>Users</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UACRJlnCuTbMn1kjhkKTAg.png" /></figure><p>Click on Tokens and Generate a new token, Copy this token somewhere safe</p><p>Now create webhooks for Quality Gate</p><p>Click on <strong>Administration</strong> then, Configuration and select <strong>Webhooks</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HpshUyACAA1hHexINe2Lfg.png" /></figure><p>We will need to add a URL as</p><p><a href="http://jenkins-server-ip:8080/sonarqube-webhook/">http://jenkins-server-ip:8080/sonarqube-webhook/</a></p><p>I have given my private IP of the Jenkins server</p><p>Now we need to create the project Multiple-Microservices-Deployment</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hg5B-PB57pIa3_T9C141gQ.png" /></figure><p>click on Locally and Use the existing token</p><p>Select Linux as OS and Others</p><p>After performing the above steps, you will get the command which you can use in the Jenkins Pipeline</p><p>We will need to create a secret in Jenkins for the Sonarqube token</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u4U05qAeDM2ALW7oZhnDiw.png" /></figure><p>Then head to Manage Jenkins&gt; System</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RzvwmuORVpeKJlJ1VCNiUA.png" /></figure><p>Github Repo: You can clone this repo for the source code</p><pre>https://github.com/SohamV1/Multiple-Microservices-Deployment.git</pre><p><strong>Step 3: Create a Script for building docker images and pushing it into ECR:</strong></p><pre>#!/bin/bash<br><br>set -euo pipefail<br>SCRIPTDIR=&quot;$(cd &quot;$( dirname &quot;$BASH_SOURCE[0]&quot;)&quot; &amp;&amp; pwd )&quot;<br>echo $SCRIPTDIR<br>BUILD_NUMBER=&quot;${BUILD_NUMBER}&quot;<br>AWS_DEFAULT_REGION=&quot;${AWS_DEFAULT_REGION}&quot;<br>REPO_PREFIX=&quot;${REPO_PREFIX}&quot;<br><br>log() { echo &quot;$1&quot; &gt;&amp;2; }<br><br>TAG=${BUILD_NUMBER}<br>echo $TAG<br>REPO_PREFIX=${REPO_PREFIX}<br>echo $REPO_PREFIX<br><br>while IFS= read -d $&#39;\0&#39; -r dir; do<br>    echo $IFS<br>    svcname=&quot;$(basename &quot;${dir}&quot;)&quot;<br>    if [[ $svcname == .* ]]<br>    then<br>        echo &quot;Skipping hidden directory: $svcname&quot;<br>        continue<br>    fi<br>    builddir=&quot;${dir}&quot;<br>    image=&quot;$REPO_PREFIX$svcname:$TAG&quot;<br>    (<br>        if [ $svcname == &quot;cartservice&quot; ] <br>        then<br>            builddir=&quot;${dir}/src&quot;<br>        fi<br>        cd &quot;${builddir}&quot;<br>        docker system prune -f <br>        docker container prune -f<br>        log &quot;Building and pushing: ${image}&quot;<br>        aws ecr get-login-password --region &quot;${AWS_DEFAULT_REGION}&quot; | docker login --username AWS --password-stdin &quot;${REPO_PREFIX}&quot;<br>        docker build -t &quot;${svcname}&quot; .<br>        docker tag &quot;$svcname&quot; &quot;${image}&quot;<br>        docker push &quot;${image}&quot;<br>    )<br>done &lt; &lt;(find &quot;${SCRIPTDIR}/../src&quot; -mindepth 1 -maxdepth 1 -type d -print0)<br><br>log &quot;Successfully built and pushed all the images&quot;</pre><p>I have saved this in Scripts/make-docker.sh with the source code</p><p>In this script, we enter each directory of the microservice create the docker image of that microservice tag that image with the ECR repo of that microservice, and push it as well.</p><p><strong>Step 4: Create a script to edit the kubernetes-manifest for each microservice and push the changes to GitHub</strong></p><pre>#!/bin/bash<br><br><br>set -euo pipefail<br><br>SCRIPTDIR=&quot;$(cd &quot;$(dirname &quot;$BASH_SOURCE[0]&quot;)&quot; &amp;&amp; pwd )&quot;<br>echo $SCRIPTDIR<br><br>log() { echo &quot;$1&quot; &gt;&amp;2; }<br><br><br>REPO_PREFIX=&quot;${REPO_PREFIX}&quot;<br>GITHUB_TOKEN=&quot;${GITHUB_TOKEN}&quot;<br>GIT_USER_NAME=&quot;${GIT_USER_NAME}&quot;<br>GIT_REPO_NAME=&quot;${GIT_REPO}&quot;<br>TAG=${BUILD_NUMBER}<br><br><br>edit_k8s() {<br><br>    for dir in ../src/*/; <br>    do<br>        svcname=&quot;$(basename &quot;${dir}&quot;)&quot;<br>        if [[ $svcname == .* ]]<br>        then<br>            echo &quot;Skipping hidden directory: $svcname&quot;<br>            continue<br>        fi<br>        image=&quot;$REPO_PREFIX$svcname:$TAG&quot;<br>        echo $image<br>        file=&quot;${SCRIPTDIR}/../kubernetes-manifests/${svcname}.yaml&quot;<br>        sed -i &quot;s|image:.*$svcname.*|image: ${image}|g&quot; &quot;$file&quot;<br>    done<br>    cd ..<br>    git add kubernetes-manifests/<br>    git commit -m &quot;updates manifest files to ${TAG} version&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>}<br><br>edit_k8s</pre><p>I have saved this in Scripts/make-release.sh with the source code</p><p>We are editing the image and tag with Jenkins Build Number for each microservice in the kubernetes-manifest file and pushing the changes to GitHub via this script</p><p><strong>Step 5: Create ECR Repos</strong></p><p>We will need to create ECR Repo for Each microservice as we will need to maintain the image for each microservice</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J5bsyE9Zxeaq4pkdbgUebw.png" /></figure><p>Create an ECR Repo for each folder in src keep these repos private as it is the industry standards</p><p><strong>Step 6: Create a Jenkins Pipeline</strong></p><p>Check if all the necessary tools are installed with the following command</p><pre>jenkins --version<br>docker --version<br>trivy --version<br>aws --version<br>eksctl --version</pre><p>We need to install the following plugins from <strong>Dashboard &gt; manage Jenkins&gt; available plugins</strong></p><pre>Docker<br>Docker Commons<br>Docker Pipeline<br>Docker API<br>docker-build-step<br>OWASP Dependency-Check<br>SonarQube Scanner</pre><p>We will need to store some credentials as follows:</p><p>We will need to store the AWS Account ID</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gnpb8xkP609UcAxLfS4bFg.png" /></figure><p>You will need to store github credentials as well</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fPCFOQprlgAX9Q1vzd4l5w.png" /></figure><p>You can copy the Jenkinsfile from</p><pre>https://github.com/SohamV1/Multiple-Microservices-Deployment/blob/master/Jenkinsfile</pre><p>You can paste this as a pipeline script</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CX8PwwslXsxIlhhZqyN-oQ.png" /></figure><p><strong>Step 7: Create an EKS cluster using eksctl</strong></p><p>Create an EKS cluster using the below commands.</p><pre>eksctl create cluster --name Multiple-Microservices-Cluster--region us-east-1 --node-type t2.medium --nodes-min 2 --nodes-max 2<br>aws eks update-kubeconfig --region us-east-1 --name Multiple-Microservices-Cluster</pre><p>As the ECR Repos will be private we need</p><p>We will also need secret as the ECR Repo is private</p><pre>kubectl create secret generic ecr-registry-secret \<br>  --from-file=.dockerconfigjson=${HOME}/.docker/config.json \<br>  --type=kubernetes.io/dockerconfigjson <br>kubectl get secrets </pre><p><strong>Step 8: Install &amp; Configure ArgoCD</strong></p><p>create a separate namespace for it and apply the argocd configuration for installation.</p><pre>kubectl create namespace argocd<br>kubectl apply -n argocd -f https://raw.githubusercontent.com/argoproj/argo-cd/v2.4.7/manifests/install.yaml</pre><p>All pods must be running, to validate run the below command</p><pre>kubectl get pods -n argocd</pre><p>Now, expose the argoCD server as LoadBalancer using the below command</p><pre>kubectl patch svc argocd-server -n argocd -p &#39;{&quot;spec&quot;: {&quot;type&quot;: &quot;LoadBalancer&quot;}}&#39;</pre><p>To access the argoCD, copy the LoadBalancer DNS and hit on your favorite browser.</p><p>Now, we need to get the password for our argoCD server to perform the deployment.</p><p>To do that, we have a pre-requisite which is <strong>jq.</strong> Install it by the command below.</p><pre>sudo apt install jq -y</pre><p>We need to get the password of argocd using the following command</p><pre>export ARGOCD_SERVER=&#39;kubectl get svc argocd-server -n argocd -o json | jq - raw-output &#39;.status.loadBalancer.ingress[0].hostname&#39;&#39;<br>export ARGO_PWD=&#39;kubectl -n argocd get secret argocd-initial-admin-secret -o jsonpath=&quot;{.data.password}&quot; | base64 -d&#39;<br>echo $ARGO_PWD</pre><p>We will get the command if you run it we will get argocd password</p><p>Log into ArgoCD using the DNS of the load balancer and username as admin and the received password from the above command</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mYfxc4Rlj-6xGUxhmQZKlA.png" /></figure><p>Now connect the git repo</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HWzQby_oBvAFci12hrmyfg.png" /></figure><p>Create the project in argocd</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TmfdqcVEK-gSt2xhV-_0BA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QDeduCfkTUcXRb4jhVnKjw.png" /></figure><p>Use directory as the option and select the kubernetes-manifests folder</p><p>Once it is completely synced and healthy a load balancer for frontend external service will be created</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gkz5XKx4KZvUreBA8S5Szg.png" /></figure><p>If you hit the Load balancer DNS of the frontend external service you can see the application working</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mYfxc4Rlj-6xGUxhmQZKlA.png" /></figure><p>The application will look like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B57FoBj0oWfTPsrvlhsb_A.png" /></figure><p>In this microservices project, gRPC facilitates efficient communication between services like emailservice, checkoutservice, recommendationservice, paymentservice, and shippingservice. Each service uses gRPC to expose methods that other services can call remotely, ensuring fast and reliable inter-service communication.</p><p>Here we have used multiple microservices with different languages which is a major advantage of using microservices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*fan4uNpzwFMLqcf84MiBCA.png" /></figure><p>I have used the Google GKE microservices demo for the source code you can check that full repository here:</p><pre>https://github.com/GoogleCloudPlatform/microservices-demo?tab=readme-ov-file</pre><p>Finally, we have managed to deploy Multiple-Microservices using EKS, Jenkins, and Argocd</p><p>Thanks for reading my article!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87f98c6d69a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monitoring Nodejs Application Using Elasticsearch APM(Application Process Manager) with Nodejs…]]></title>
            <link>https://medium.com/@sohamvs1999/monitoring-nodejs-application-using-elasticsearch-apm-application-process-manager-with-nodejs-754658cd6e6b?source=rss-47660f9e2e4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/754658cd6e6b</guid>
            <category><![CDATA[apm]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[elk-stack]]></category>
            <dc:creator><![CDATA[Soham Valsangkar]]></dc:creator>
            <pubDate>Fri, 26 Apr 2024 14:10:54 GMT</pubDate>
            <atom:updated>2024-04-26T14:36:54.580Z</atom:updated>
            <content:encoded><![CDATA[<h3>Monitoring Nodejs Application Using Elasticsearch APM(Application Process Manager) with Nodejs Agent</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dP-ypwyiUlAzGvzu7lMGaw.png" /></figure><p>In this article, We will be installing ELK with Filebeat and Setting the APM server for Node js API monitoring. Logging transactions and Errors is necessary and visualization is a very nice plus.</p><p>In this case, Elasticsearch has the Application Performance Monitor with Nodejs Agent to keep track of applications in real-time, by collecting performance information on response time for incoming requests, database queries, and more. This makes it easy to pinpoint and fix performance problems quickly.</p><p>We get out-of-the-box visualization and can also allow you to create and measure custom transactions (tasks) and spans (subtasks inside transactions). We will follow these steps:</p><ol><li>Install and Setup ELK</li><li>Install the APM Server</li><li>Nodejs Application to Monitor</li><li>APM Agent which is Nodejs Agent in our case</li></ol><p><strong>Installation</strong></p><p>We will start with installing and setting up ELK, firstly we will install Elasticsearch</p><p><strong>Step 1 Elasticsearch Installation Script:</strong></p><pre>curl -fsSL https://artifacts.elastic.co/GPG-KEY-elasticsearch |sudo gpg --dearmor -o /usr/share/keyrings/elastic.gpg<br>echo &quot;deb [signed-by=/usr/share/keyrings/elastic.gpg] https://artifacts.elastic.co/packages/7.x/apt stable main&quot; | sudo tee -a /etc/apt/sources.list.d/elastic-7.x.list<br>sudo apt update <br>sudo apt install elasticsearch</pre><p>We will edit the Elasticsearch main configuration find the line that specifies network.host, uncomment it, and replace its value with localhost like this:</p><pre>sudo vim /etc/elasticsearch/elasticsearch.yml</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jo_fVS4iAv40uBla_Z8f8w.png" /></figure><p>Start the Elasticsearch service with systemctl. Give Elasticsearch a few moments to start up. Otherwise, you may get errors about not being able to connect.</p><pre>sudo systemctl start elasticsearch<br>sudo systemctl enable elasticsearch</pre><p>To check the Elasticsearch Installation</p><pre>curl -X GET &quot;localhost:9200&quot;</pre><p>You will see a similar response</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*QGsnL-mwui4HWZM43hWwwQ.png" /></figure><p><strong>Step 2 Installing and Configuring Kibana:</strong></p><p>Use the following script to install kibana</p><pre>sudo apt install kibana <br>sudo systemctl enable kibana<br>sudo systemctl start kibana</pre><p>edit the kibana configuration and uncomment and add the following:</p><pre>sudo su<br>sudo vim /etc/kibana/kibana.yml</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I_QQEotEgYp4Ab2YIzinAA.png" /></figure><p>You can access the Kibana dashboard at <a href="http://yourip:5601/">http://YourIP:5601</a></p><p>If you are using an AWS EC2 instance then make sure to open 5601 in security group of the instance.Also, you can check the status of Kibana at</p><pre>http://yourIP:5601/status</pre><p><strong>Step 3 Install and configure Logstash:</strong></p><pre>sudo apt install logstash</pre><p>Logstash is used to process the data and we can collect the data from multiple sources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fVXNY3sKeU6OZ6nI.png" /></figure><p>Open /etc/logstash/conf.d and add following</p><pre>sudo vim /etc/logstash/conf.d/02-beats-input.conf</pre><p>Insert the following input configuration. This specifies a beats input that will listen on TCP port 5044</p><pre>input {<br>  beats {<br>    port =&gt; 5044<br>  }<br>}</pre><pre>sudo vim /etc/logstash/conf.d/30-elasticsearch-output.conf</pre><pre>output {<br>  if [@metadata][pipeline] {<br> elasticsearch {<br>   hosts =&gt; [&quot;localhost:9200&quot;]<br>   manage_template =&gt; false<br>   index =&gt; &quot;%{[@metadata][beat]}-%{[@metadata][version]}-%{+YYYY.MM.dd}&quot;<br>   pipeline =&gt; &quot;%{[@metadata][pipeline]}&quot;<br> }<br>  } else {<br> elasticsearch {<br>   hosts =&gt; [&quot;localhost:9200&quot;]<br>   manage_template =&gt; false<br>   index =&gt; &quot;%{[@metadata][beat]}-%{[@metadata][version]}-%{+YYYY.MM.dd}&quot;<br> }<br>  }<br>}</pre><p>Save and close the file.</p><p>Test your Logstash configuration with this command:</p><pre>sudo -u logstash /usr/share/logstash/bin/logstash --path.settings /etc/logstash -t</pre><p>Now we can start the logstash service</p><pre>sudo systemctl start logstash<br>sudo systemctl enable logstash</pre><p><strong>Step 4 Installing APM Server</strong></p><pre>sudo apt-get install apm-server</pre><p>Start APM server</p><pre>sudo systemctl status apm-server</pre><p>In the browser</p><pre>http://YourIP:5601/app/home#/tutorial/apm</pre><p>If everything is working you should see this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UjueMPGONYW6fm2hZQHTgQ.png" /></figure><p><strong>Node Application</strong></p><p>Now the ELK Part is completed and we have to run the Nodejs Application and connect the APM server</p><p>Clone the repo</p><pre>git clone https://github.com/SohamV1/ELK-Nodejs-APM.git</pre><p>Run the following commands and make sure you have node, npm, and yarn installed</p><pre>cd ELK-Nodejs-APM/<br>cd server<br>yarn install<br>yarn start</pre><p>We need to edit the host in public/utils and the IP and port of your machine where the backend is running</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*Jj8hIaF4KPpnHkZJds_-pg.png" /></figure><p>We have started the backend of the application at 5000 port. Now open another terminal and CD into the public folder</p><pre>cd ELK-Nodejs-APM/<br>cd public<br>yarn install<br>yarn start</pre><p>Your node application will be running at <a href="http://yourip:3000/">http://YourIP:3000/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KwFWAkytuMb7X-oM" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nGyAxHseVPAvxLkT" /></figure><p><strong>Install Nodejs APM Agent</strong></p><pre>npm install elastic-apm-node --save</pre><p>Add this line to the very beginning of server/index.js</p><pre>const apm = require(&#39;elastic-apm-node&#39;).start({serviceName: &quot;node-app&quot;});</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*d_yNNWf0UketUTXKtvFtaw.png" /></figure><p>You can register a couple of users and hit the APIs for testing.</p><p>Here you go your node app is sending logs to ELK once you hit a couple of APIs you can check the APM dashboard the events must be created</p><pre>http://YourIP:5601/app/apm</pre><p>Your app must be showing up</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qOxrkdr79oWSZAiMGP-FXQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dP-ypwyiUlAzGvzu7lMGaw.png" /></figure><p><strong>Conclusion:</strong></p><p>We can finally check all the transactions and errors, and get detailed information on response time for incoming requests, database queries, calls to caches, external HTTP requests, and more. We can also create custom transactions.</p><p>Using this information we can easily pinpoint and fix the performance problems easily!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/889/1*lAAuVH9jynZ7dX6yrkfNRQ.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=754658cd6e6b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>