<?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 Rabin bhandari on Medium]]></title>
        <description><![CDATA[Stories by Rabin bhandari on Medium]]></description>
        <link>https://medium.com/@rabinbhandari44?source=rss-61e80e7fd9fc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*vIjmnOeJK1fcGUkg</url>
            <title>Stories by Rabin bhandari on Medium</title>
            <link>https://medium.com/@rabinbhandari44?source=rss-61e80e7fd9fc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 13:48:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rabinbhandari44/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[Stop Drowning in Spreadsheets: Architecting the Ultimate Serverless Data Pipeline on AWS]]></title>
            <link>https://medium.com/@rabinbhandari44/stop-drowning-in-spreadsheets-architecting-the-ultimate-serverless-data-pipeline-on-aws-ddcfd76031fd?source=rss-61e80e7fd9fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/ddcfd76031fd</guid>
            <dc:creator><![CDATA[Rabin bhandari]]></dc:creator>
            <pubDate>Sun, 30 Nov 2025 10:38:48 GMT</pubDate>
            <atom:updated>2025-11-30T10:38:48.997Z</atom:updated>
            <content:encoded><![CDATA[<p>Data is a strategic asset in today’s digital economy, not merely a byproduct. However, turning unprocessed application data into useful insights is far from simple for the majority of businesses, from retail and fintech to healthcare and SaaS.</p><p>“Excel Fatigue” is probably what you’re experiencing. Just 20% of analysts’ time is spent on actual analysis, with the remaining 80% being devoted to cleaning, reconciling, and moving data.</p><p>Three serious issues result from this broken flow:</p><p><strong>Stuck in the Past</strong>: You lack a realtime pulse. You drag the sales figures you are examining the last month with by hand, and you know that it is not the trends of this morning.</p><p><strong>The Scattered Mess:</strong> The operational data have been dispersed in transactional systems and stored in formats. Single Source of Truth does not exist.</p><p><strong>The Scale Nightmare:</strong> Your system fails as data increases in gigabytes to petabytes.</p><h4><strong>Solution</strong></h4><p>We should have a well-designed pipeline, with the ratio reversed, so that your team is analysing, not cleaning.</p><p><strong>The Architecture Diagram</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T1Cx9TDGADJ4hVhMK4CVVA.png" /><figcaption><strong><em>Fig</em></strong><em>: Architecture Diagram</em></figcaption></figure><p>We are creating a unidirectional flow of your data on Amazon Web Services-native services:</p><p><strong>Operational Data → Data Lake → ETL Transformation → Curated Warehouse → Visual Intelligence</strong>.</p><ol><li><strong>The Extraction Engine: AWS DMS (The High-Speed Scoop)</strong></li></ol><p>The initial one is the difficulty in retrieving data out of your transactional databases (MySQL or SQL server) without slowing them down.</p><ul><li><strong>The Tool:</strong> <strong>AWS Database Migration Service (DMS)</strong>.</li><li><strong>The Magic:</strong> DMS uses Change Data Capture (CDC) to avoid complex queries. It instantly streams individual changes (such as a new purchase) while listening to the database logs.</li><li><strong>The Landing Pad (Raw Zone):</strong> Amazon S3 is where the raw data is kept. Our unchangeable, inexpensive “Raw Zone” is S3.</li></ul><p><strong>2. The Alchemy Chamber: AWS Glue + AWS Lambda (The Clean Machine)</strong></p><p>Raw data is hardly business ready. It has embedded JSON, redundant records and dates in unformatted form. This layer cleanses it.</p><ul><li><strong>The Toolset:</strong> <strong>AWS Glue</strong> (our serverless ETL engine) and <strong>AWS Lambda</strong>.</li><li><strong>The Powerful Twist:</strong> <strong>AWS Glue</strong> manages the bulk lifting (reading huge files, partitioning). However, in more complicated, sensitive business logic such as masking PII or converting currency we invoke custom AWS Lambda functions as part of the Glue job.</li><li><strong>The Output:</strong> This hybrid technique causes the pipeline to be more updatable and maintainable. The result is clean</li></ul><h3>3. The Golden Vault: Amazon RDS for PostgreSQL (The Reporting Rocket)</h3><p>BI tools need to be organized and high performance so that they can load dashboards within milliseconds, however, S3 is the most suitable to store large amounts of data..</p><ul><li><strong>The Tool:</strong> <strong>Amazon RDS for PostgreSQL</strong>.</li><li><strong>The Role (The “Gold Layer”):</strong> Here we feed the transformed and cleaned data. Your reports use RDS which is the Data Mart.</li><li><strong>Why PostgreSQL?</strong> It is open-source and extremely compatible with all BI tools and can be used to make complex queries.</li></ul><h3>4. The Data Explorer: Athena + Glue Data Catalog (The Safety Net)</h3><p>What does a data scientist do when he or she wants to pose an ad-hoc query not on a dashboard?</p><ul><li><strong>The Tool:</strong> <strong>Amazon Athena</strong>.</li><li><strong>The Power:</strong> Without first loading the files into a database, Athena enables your team to write standard SQL queries directly against the S3 raw files.</li><li><strong>The GPS:</strong> Athena is informed about the location and structure of the data by the Glue Data Catalog, which serves as a map. This layer guarantees that no query is too difficult to respond to.</li></ul><h3>5. The Moment of Truth: Amazon QuickSight (Value Delivered)</h3><p>This is the last layer, where value is provided and technology fades.</p><ul><li><strong>The Tool:</strong> <strong>Amazon QuickSight</strong>.</li><li><strong>The Outcome:</strong> Our RDS PostgreSQL is directly connected to QuickSight. It enables you to create secure, interactive dashboards that facilitate practical applications, such as monitoring inventory turnover in retail, identifying anomalies in fintech, or displaying ER wait times in healthcare.</li></ul><p><strong>Conclusion</strong>:</p><p>A well-designed data pipeline is a modern company’s nervous system, not just its infrastructure. By utilizing serverless, scalable AWS services like QuickSight, Glue, and DMS, you are building a system for ongoing improvement rather than merely storing data. The technology is ready, scalable, and serverless.</p><p>What hidden patterns are currently lurking in your data is the only unanswered question.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ddcfd76031fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CI/CD and Infrastructure as Code for a PHP Application on AWS Using Bitbucket Pipelines, Docker…]]></title>
            <link>https://medium.com/@rabinbhandari44/ci-cd-and-infrastructure-as-code-for-a-php-application-on-aws-using-bitbucket-pipelines-docker-f0cc43d6b218?source=rss-61e80e7fd9fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0cc43d6b218</guid>
            <dc:creator><![CDATA[Rabin bhandari]]></dc:creator>
            <pubDate>Wed, 23 Apr 2025 10:17:23 GMT</pubDate>
            <atom:updated>2025-04-23T10:17:23.804Z</atom:updated>
            <content:encoded><![CDATA[<h3>CI/CD and Infrastructure as Code for a PHP Application on AWS Using Bitbucket Pipelines, Docker, and Terraform</h3><p>This blog will demonstrate how to use Terraform to manage infrastructure and Bitbucket Pipelines to automate deployments while containerizing a PHP application and deploying it to AWS ECS Fargate. Code and infrastructure are version-controlled, reproducible, and automatically deployed thanks to this full DevOps flow . I will walk through building a production-ready CI/CD pipeline that automates:</p><ul><li>Docker image builds and pushes to Amazon ECR</li><li>Infrastructure provisioning using Terraform</li><li>Deployment to AWS ECS Fargate</li></ul><p>We’ll be using the following technologies:</p><ul><li><strong>Bitbucket Pipelines</strong> for CI/CD</li><li><strong>Terraform</strong> for IaC (Infrastructure as Code)</li><li><strong>Docker</strong> to containerize the application</li><li><strong>Amazon ECS Fargate</strong> to run containers</li><li><strong>Amazon ECR</strong> for storing Docker images</li><li><strong>ALB (Application Load Balancer)</strong> for traffic routing</li><li><strong>IAM</strong>, <strong>VPC</strong>, <strong>Nginx</strong>, <strong>Supervisor</strong></li></ul><h3>Project Structure</h3><pre>.<br>├── bitbucket-pipelines.yml         <br>├── Dockerfile                      <br>├── nginx.conf                     <br>├── supervisord.conf               <br>├── main.tf                         <br>├── modules/                        <br>│   ├── alb/<br>│   ├── ecr/<br>│   ├── ecs-cluster/<br>│   ├── ecs-service/<br>│   ├── ecs-task-definition/<br>│   ├── iam/<br>│   └── vpc/<br>└── src/<br>    └── index.php                  # PHP application</pre><h3>Dockerizing the Application</h3><p>We need a Docker image that runs both PHP and Nginx inside the same container. This setup is managed by Supervisor, which ensures both services stay alive.</p><h3>Dockerfile</h3><pre># Use the official Alpine-based PHP image with FPM<br>FROM php:8.2.10-fpm-alpine<br><br># Install Nginx and dependencies for running PHP<br>RUN apk --no-cache add \<br>    nginx \<br>    bash \<br>    curl \<br>    supervisor \<br>    &amp;&amp; rm -rf /var/cache/apk/*<br><br># Copy the Nginx configuration file into the container<br>COPY ./nginx.conf /etc/nginx/nginx.conf<br><br># Copy the supervisor configuration file to manage Nginx and PHP-FPM<br>COPY ./supervisord.conf /etc/supervisord.conf<br><br># Set the working directory for your application inside the container<br>WORKDIR /var/www/html<br><br># Copy the PHP application files into the container<br>COPY ./src /var/www/html<br><br># Expose port 80 to access the web server<br>EXPOSE 80<br><br># Start the supervisor to manage nginx and php-fpm<br>CMD [&quot;/usr/bin/supervisord&quot;, &quot;-c&quot;, &quot;/etc/supervisord.conf&quot;]</pre><h3>index.php</h3><pre>&lt;?php<br>echo &quot;Hello, World!&quot;;<br>?&gt;</pre><h3>Ngnx.conf</h3><pre>user  nginx;<br>worker_processes  1;<br><br>events {<br>    worker_connections  1024;<br>}<br><br>http {<br>    include       /etc/nginx/mime.types;<br>    default_type  application/octet-stream;<br><br>    server {<br>        listen 80;<br>        server_name localhost;<br><br>        root /var/www/html;<br><br>        index index.php index.html index.htm;<br><br>        location / {<br>            try_files $uri $uri/ =404;<br>        }<br><br>        location ~ \.php$ {<br>            include fastcgi_params;<br>            fastcgi_pass 127.0.0.1:9000;<br>            fastcgi_param SCRIPT_FILENAME /var/www/html$fastcgi_script_name;<br>            include /etc/nginx/fastcgi_params;<br>        }<br>    }<br>}</pre><h3>supervisord.conf</h3><pre>[supervisord]<br>user=root<br>nodaemon=true<br><br>[program:nginx]<br>command=/usr/sbin/nginx -g &quot;daemon off;&quot;<br>autostart=true<br>autorestart=true<br><br>[program:php-fpm]<br>command=/usr/local/sbin/php-fpm -F  <br>autostart=true<br>autorestart=true</pre><h3>Bitbucket Pipeline for CI/CD</h3><p>The pipeline does <strong>two main steps</strong>:</p><ol><li><strong>Build and push the Docker image to Amazon ECR</strong></li><li><strong>Deploy the infrastructure with Terraform</strong></li></ol><h3>bitbucket-pipelines.yml</h3><pre>image: atlassian/default-image:3<br><br>pipelines:<br>  default:<br>    - step:<br>        name: Build and Push Docker Image<br>        services:<br>          - docker  <br>        caches:<br>          - docker-cache  <br>        script:<br>          - echo &quot;Installing AWS CLI&quot;<br>          - apt-get update &amp;&amp; apt-get install -y awscli<br><br>          - echo &quot;Authenticating Docker with AWS ECR&quot;<br>          - aws ecr get-login-password --region ap-south-1 | docker login --username AWS --password-stdin 417095947002.dkr.ecr.ap-south-1.amazonaws.com<br><br>          - echo &quot;Building Docker image&quot;<br>          - docker build -t php-application-repo .<br><br>          - echo &quot;Tagging Docker image&quot;<br>          - docker tag php-application-repo:latest 417095947002.dkr.ecr.ap-south-1.amazonaws.com/php-application-repo:latest<br><br><br>          - echo &quot;Pushing Docker image to ECR&quot;<br>          - docker push XXXXXXX.dkr.ecr.ap-south-1.amazonaws.com/php-application-repo:latest<br><br>    - step:<br>        name: Deploy with Terraform<br>        caches:<br>          - terraform  <br>        script:<br>          - echo &quot;Installing Terraform&quot;<br>          - apt-get update &amp;&amp; apt-get install -y curl unzip<br>          - curl -LO https://releases.hashicorp.com/terraform/1.5.0/terraform_1.5.0_linux_amd64.zip<br>          - unzip terraform_1.5.0_linux_amd64.zip &amp;&amp; mv terraform /usr/local/bin/<br><br><br>          - echo &quot;Initializing Terraform&quot;<br>          - terraform init<br>          - terraform validate<br>          - terraform plan -out=tfplan<br><br><br>          - echo &quot;Saving Terraform plan&quot;<br>          - mkdir -p artifacts<br>          - terraform show -json tfplan &gt; artifacts/tfplan.json<br>        artifacts:<br>          - artifacts/tfplan.json<br><br>definitions:<br>  caches:<br>    docker-cache: /tmp/docker  <br>    terraform: /tmp/terraform</pre><h3>Infrastructure with Terraform</h3><p>We’ve modularized the Terraform codebase to manage the following:</p><h3>Main.tf</h3><pre>provider &quot;aws&quot; {<br>  region = &quot;ap-south-1&quot;<br>}<br><br># VPC Module<br>module &quot;vpc&quot; {<br>  source = &quot;./modules/vpc&quot;<br>}<br><br># ECR Module<br>module &quot;ecr&quot; {<br>  source = &quot;./modules/ecr&quot;<br>}<br><br># IAM Module<br>module &quot;iam&quot; {<br>  source = &quot;./modules/iam&quot;<br>}<br><br># ALB Module <br>module &quot;alb&quot; {<br>  source = &quot;./modules/alb&quot;<br>  vpc_id = module.vpc.vpc_id<br>  subnets = module.vpc.subnet_ids<br>  lb_sg_id = module.vpc.lb_sg_id<br>}<br><br># ECS Cluster Module<br>module &quot;ecs-cluster&quot; {<br>  source = &quot;./modules/ecs-cluster&quot;<br>}<br><br># ECS Task Definition Module<br>module &quot;ecs-task-definition&quot; {<br>  source             = &quot;./modules/ecs-task-definition&quot;<br>  docker_image       = module.ecr.ecr_repo_url<br>  execution_role_arn = module.iam.ecs_execution_role_arn<br>  task_role_arn      = module.iam.ecs_task_role_arn<br>}<br><br># ECS Service Module - ECS service is dependent on ALB <br>module &quot;ecs-service&quot; {<br>  source             = &quot;./modules/ecs-service&quot;<br>  cluster_id         = module.ecs-cluster.cluster_id<br>  task_definition_arn = module.ecs-task-definition.task_definition_arn<br>  subnets            = module.vpc.subnet_ids<br>  ecs_sg_id          = module.vpc.ecs_sg_id<br>  desired_count      = 2<br>  target_group_arn   = module.alb.php_target_group_arn  # Target Group ARN is from ALB<br>}</pre><h3>VPC (Virtual Private Cloud)</h3><p>Creates subnets, internet gateway, route tables, and security groups.</p><pre># Create a new VPC<br>resource &quot;aws_vpc&quot; &quot;main&quot; {<br>  cidr_block = &quot;10.0.0.0/16&quot;<br>  enable_dns_support = true<br>  enable_dns_hostnames = true<br><br>  tags = {<br>    Name = &quot;php-vpc&quot;<br>  }<br>}<br><br><br># Create subnets<br>resource &quot;aws_subnet&quot; &quot;subnet_a&quot; {<br>  vpc_id                  = aws_vpc.main.id<br>  cidr_block              = &quot;10.0.1.0/24&quot;<br>  availability_zone       = &quot;ap-south-1a&quot;<br>  map_public_ip_on_launch = true<br>  tags = {<br>    Name = &quot;php-subnet-a&quot;<br>  }<br>}<br><br>resource &quot;aws_subnet&quot; &quot;subnet_b&quot; {<br>  vpc_id                  = aws_vpc.main.id<br>  cidr_block              = &quot;10.0.2.0/24&quot;<br>  availability_zone       = &quot;ap-south-1b&quot;<br>  map_public_ip_on_launch = true<br>  tags = {<br>    Name = &quot;php-subnet-b&quot;<br>  }<br>}<br><br><br># Create Internet Gateway<br>resource &quot;aws_internet_gateway&quot; &quot;main&quot; {<br>  vpc_id = aws_vpc.main.id<br><br>  tags = {<br>    Name = &quot;php-igw&quot;<br>  }<br>}<br><br># Create Security Group for ECS<br>resource &quot;aws_security_group&quot; &quot;ecs_sg&quot; {<br>  name        = &quot;php-ecs-sg&quot;<br>  description = &quot;Allow inbound HTTP traffic to ECS&quot;<br>  vpc_id      = aws_vpc.main.id<br><br>  ingress {<br>    from_port   = 80<br>    to_port     = 80<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br><br>  egress {<br>    from_port   = 0<br>    to_port     = 0<br>    protocol    = &quot;-1&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br><br>  tags = {<br>    Name = &quot;php-ecs-sg&quot;<br>  }<br>}<br><br># Create Security Group for Load Balancer<br>resource &quot;aws_security_group&quot; &quot;lb_sg&quot; {<br>  name        = &quot;php-lb-sg&quot;<br>  description = &quot;Allow inbound HTTP traffic to Load Balancer&quot;<br>  vpc_id      = aws_vpc.main.id<br><br>  ingress {<br>    from_port   = 80<br>    to_port     = 80<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br><br>  egress {<br>    from_port   = 0<br>    to_port     = 0<br>    protocol    = &quot;-1&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br><br>  tags = {<br>    Name = &quot;php-lb-sg&quot;<br>  }<br>}<br><br><br># Create Route Table for Public Subnet<br>resource &quot;aws_route_table&quot; &quot;public_rt&quot; {<br>  vpc_id = aws_vpc.main.id<br><br>  route {<br>    cidr_block = &quot;0.0.0.0/0&quot;<br>    gateway_id = aws_internet_gateway.main.id<br>  }<br><br>  tags = {<br>    Name = &quot;Public Route Table&quot;<br>  }<br>}<br><br># Associate Route Table with Subnets<br>resource &quot;aws_route_table_association&quot; &quot;public_rt_assoc_a&quot; {<br>  subnet_id      = aws_subnet.subnet_a.id<br>  route_table_id = aws_route_table.public_rt.id<br>}<br><br>resource &quot;aws_route_table_association&quot; &quot;public_rt_assoc_b&quot; {<br>  subnet_id      = aws_subnet.subnet_b.id<br>  route_table_id = aws_route_table.public_rt.id<br>}<br><br><br># Output VPC details<br>output &quot;vpc_id&quot; {<br>  value = aws_vpc.main.id<br>}<br><br>output &quot;subnet_ids&quot; {<br>  value = [aws_subnet.subnet_a.id, aws_subnet.subnet_b.id]<br>}<br><br>output &quot;ecs_sg_id&quot; {<br>  value = aws_security_group.ecs_sg.id<br>}<br><br>output &quot;lb_sg_id&quot; {<br>  value = aws_security_group.lb_sg.id<br>}</pre><h3>Amazon ECR</h3><pre>resource &quot;aws_ecr_repository&quot; &quot;php_repo&quot; {<br>  name = &quot;php-application-repo&quot;<br><br>  lifecycle {<br>    prevent_destroy = false<br>  }<br><br>  tags = {<br>    Name = &quot;php-application-repo&quot;<br>  }<br>}<br><br>output &quot;ecr_repo_url&quot; {<br>  value = aws_ecr_repository.php_repo.repository_url<br>}</pre><h3>ECS Cluster</h3><pre>resource &quot;aws_ecs_cluster&quot; &quot;php_cluster&quot; {<br>  name = &quot;php-ecs-cluster&quot;<br><br>  tags = {<br>    Name = &quot;php-ecs-cluster&quot;<br>  }<br>}<br><br>output &quot;cluster_id&quot; {<br>  value = aws_ecs_cluster.php_cluster.id<br>}</pre><h3>IAM Roles</h3><p>Provides ecsTaskExecutionRole and taskRole with required policies.</p><pre>resource &quot;aws_iam_role&quot; &quot;ecs_execution_role&quot; {<br>  name = &quot;ecs-execution-role&quot;<br><br>  assume_role_policy = jsonencode({<br>    Version = &quot;2012-10-17&quot;<br>    Statement = [{<br>      Action    = &quot;sts:AssumeRole&quot;<br>      Effect    = &quot;Allow&quot;<br>      Principal = {<br>        Service = &quot;ecs-tasks.amazonaws.com&quot;<br>      }<br>    }]<br>  })<br>}<br><br>resource &quot;aws_iam_role&quot; &quot;ecs_task_role&quot; {<br>  name = &quot;ecs-task-role&quot;<br><br>  assume_role_policy = jsonencode({<br>    Version = &quot;2012-10-17&quot;<br>    Statement = [{<br>      Action    = &quot;sts:AssumeRole&quot;<br>      Effect    = &quot;Allow&quot;<br>      Principal = {<br>        Service = &quot;ecs-tasks.amazonaws.com&quot;<br>      }<br>    }]<br>  })<br>}<br><br>output &quot;ecs_execution_role_arn&quot; {<br>  value = aws_iam_role.ecs_execution_role.arn<br>}<br><br>output &quot;ecs_task_role_arn&quot; {<br>  value = aws_iam_role.ecs_task_role.arn<br>}<br><br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;ecs_execution_policy&quot; {<br>  role       = aws_iam_role.ecs_execution_role.name<br>  policy_arn = &quot;arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy&quot;<br>}<br><br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;ecs_s3_full_access&quot; {<br>  role       = aws_iam_role.ecs_execution_role.name<br>  policy_arn = &quot;arn:aws:iam::aws:policy/AmazonS3FullAccess&quot;<br>}<br><br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;ecs_ecr_pull_policy&quot; {<br>  role       = aws_iam_role.ecs_execution_role.name<br>  policy_arn = &quot;arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly&quot;<br>}<br><br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;ecs_cloudwatch_logs&quot; {<br>  role       = aws_iam_role.ecs_execution_role.name<br>  policy_arn = &quot;arn:aws:iam::aws:policy/CloudWatchLogsFullAccess&quot;<br>}</pre><h3>Application Load Balancer</h3><pre>variable &quot;vpc_id&quot; {<br>  description = &quot;The ID of the VPC&quot;<br>  type        = string<br>}<br><br>variable &quot;subnets&quot; {<br>  description = &quot;A list of subnet IDs&quot;<br>  type        = list(string)<br>}<br><br>variable &quot;lb_sg_id&quot; {<br>  description = &quot;The ID of the security group for the Load Balancer&quot;<br>  type        = string<br>}<br><br>resource &quot;aws_lb&quot; &quot;php_alb&quot; {<br>  name               = &quot;php-alb&quot;<br>  internal           = false<br>  load_balancer_type = &quot;application&quot;<br>  security_groups    = [var.lb_sg_id]<br>  subnets            = var.subnets<br>  enable_deletion_protection = false<br>}<br><br>resource &quot;aws_lb_target_group&quot; &quot;php_target_group&quot; {<br>  name     = &quot;php-target-group&quot;<br>  port     = 80<br>  protocol = &quot;HTTP&quot;<br>  vpc_id   = var.vpc_id<br><br>  # Set the target type to &quot;ip&quot; for Fargate compatibility<br>  target_type = &quot;ip&quot;<br><br>  health_check {<br>    protocol = &quot;HTTP&quot;<br>    path     = &quot;/&quot;<br>    port     = &quot;80&quot;<br>  }<br>}<br><br>resource &quot;aws_lb_listener&quot; &quot;php_listener&quot; {<br>  load_balancer_arn = aws_lb.php_alb.arn<br>  port              = &quot;80&quot;<br>  protocol          = &quot;HTTP&quot;<br><br>  # Forward traffic to the target group instead of fixed-response<br>  default_action {<br>    type             = &quot;forward&quot;<br>    target_group_arn = aws_lb_target_group.php_target_group.arn<br>  }<br>}<br><br>output &quot;alb_url&quot; {<br>  value = aws_lb.php_alb.dns_name<br>}</pre><h3>ECS Task Definition</h3><pre>variable &quot;docker_image&quot; {<br>  description = &quot;Docker image for ECS&quot;<br>  default     = &quot;417095947002.dkr.ecr.ap-south-1.amazonaws.com/php-application-repo:latest&quot;<br>}<br><br>variable &quot;execution_role_arn&quot; {<br>  description = &quot;Execution role ARN for ECS&quot;<br>  type        = string<br>}<br><br>variable &quot;task_role_arn&quot; {<br>  description = &quot;Task role ARN for ECS&quot;<br>  type        = string<br>}<br><br>resource &quot;aws_ecs_task_definition&quot; &quot;ecs_task&quot; {<br>  family                   = &quot;php-app&quot;<br>  network_mode             = &quot;awsvpc&quot;<br>  execution_role_arn       = var.execution_role_arn<br>  task_role_arn            = var.task_role_arn<br>  requires_compatibilities = [&quot;FARGATE&quot;] <br>  cpu                      = &quot;256&quot;          # Minimum CPU for Fargate<br>  memory                   = &quot;512&quot;          # Minimum memory for Fargate<br>  container_definitions    = jsonencode([<br>    {<br>      name      = &quot;php-container&quot;<br>      image     = var.docker_image<br>      essential = true<br>      portMappings = [<br>        {<br>          containerPort = 80<br>          hostPort      = 80<br>        }<br>      ]<br>      memory           = 512        # Set the memory in MiB<br>      cpu              = 256        # Set the CPU units<br>      logConfiguration = {<br>        logDriver = &quot;awslogs&quot;<br>        options = {<br>          &quot;awslogs-create-group&quot;  = &quot;true&quot;<br>          &quot;awslogs-group&quot;         = &quot;/ecs/php-app-logs&quot;    # CloudWatch Log Group<br>          &quot;awslogs-region&quot;        = &quot;ap-south-1&quot;            # Region<br>          &quot;awslogs-stream-prefix&quot; = &quot;ecs&quot;                   # Prefix for streams (container name or task)<br>        }<br>      }<br>    }<br>  ])<br>}<br><br>output &quot;task_definition_arn&quot; {<br>  value = aws_ecs_task_definition.ecs_task.arn<br>}</pre><h3>ECS Service</h3><pre>variable &quot;cluster_id&quot; {<br>  description = &quot;ECS Cluster ID&quot;<br>  type        = string<br>}<br><br>variable &quot;task_definition_arn&quot; {<br>  description = &quot;Task Definition ARN&quot;<br>  type        = string<br>}<br><br>variable &quot;subnets&quot; {<br>  description = &quot;Subnets for ECS Service&quot;<br>  type        = list(string)<br>}<br><br>variable &quot;ecs_sg_id&quot; {<br>  description = &quot;Security Group ID for ECS Service&quot;<br>  type        = string<br>}<br><br>variable &quot;desired_count&quot; {<br>  description = &quot;Desired number of ECS tasks&quot;<br>  type        = number<br>  default     = 1<br>}<br><br>variable &quot;target_group_arn&quot; {<br>  description = &quot;Target group ARN for load balancing&quot;<br>  type        = string<br>}<br><br>resource &quot;aws_ecs_service&quot; &quot;php_service&quot; {<br>  name            = &quot;php-service&quot;<br>  cluster         = var.cluster_id<br>  task_definition = var.task_definition_arn<br>  desired_count   = var.desired_count<br>  launch_type     = &quot;FARGATE&quot;<br>  network_configuration {<br>    subnets         = var.subnets<br>    security_groups = [var.ecs_sg_id]<br>    assign_public_ip = true<br>  }<br>  load_balancer {<br>    #target_group_arn = aws_lb_target_group.php_target_group.arn  # Reference new target group<br>    target_group_arn = var.target_group_arn <br>    container_name   = &quot;php-container&quot;<br>    container_port   = 80<br>  }<br>}</pre><h3>Testing the Deployment</h3><p>Once you push to Bitbucket:</p><blockquote>Docker image gets built and uploaded to ECR</blockquote><blockquote>Terraform provisions all infrastructure on AWS</blockquote><blockquote>ECS pulls the latest image and runs the container</blockquote><blockquote>ALB routes traffic to your app at http://&lt;alb-dns-name&gt;</blockquote><h3>Conclusion</h3><p>With this setup:</p><ul><li>Your <strong>PHP application is containerized and deployed to ECS Fargate</strong></li><li>All infrastructure is <strong>managed through Terraform modules</strong></li><li>Deployments are triggered automatically from <strong>Bitbucket Pipelines</strong></li><li>You achieve <strong>complete automation</strong> from code to production</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0cc43d6b218" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Launch a Kubernetes Cluster on AWS EC2 with Ubuntu Using Kubeadm and Ansible for…]]></title>
            <link>https://medium.com/@rabinbhandari44/how-to-launch-a-kubernetes-cluster-on-aws-ec2-with-ubuntu-using-kubeadm-and-ansible-for-c4f076e2c10c?source=rss-61e80e7fd9fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4f076e2c10c</guid>
            <dc:creator><![CDATA[Rabin bhandari]]></dc:creator>
            <pubDate>Mon, 30 Sep 2024 08:55:14 GMT</pubDate>
            <atom:updated>2024-09-30T08:55:14.663Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Launch a Kubernetes Cluster on AWS EC2 with Ubuntu Using Kubeadm and Ansible for Configuration Management</h3><h3>Prerequisites</h3><p>Before you start, ensure you have the following:</p><ul><li>An AWS account.</li><li>Basic knowledge of AWS services and the AWS Management Console.</li><li>A key pair to access your EC2 instances.</li><li>A minimum of one EC2 instance for the master node and at least one for a worker node.</li></ul><h3>Launch EC2 Instances</h3><p>Log in to the AWS Management Console.</p><p>Navigate to the EC2 Dashboard.</p><p>Click on “Launch Instances.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WiDuEHMa7DshD_wa" /></figure><p>Select an Amazon Machine Image (AMI):</p><ul><li>Choose the latest Ubuntu Server.</li></ul><p>Choose an Instance Type:</p><ul><li>Select an instance type (e.g., t2.medium or t2.large) based on your workload needs.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/0*RS1E8acXcN44sKEE" /></figure><p>Configure Instance Details:</p><ul><li>Ensure the number of instances is set to at least one for the master and one for a worker.</li><li>Set the network settings as needed (default VPC and subnet is usually sufficient).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/0*CpiaHIzj9dG3yrX-" /></figure><p>Add Storage:</p><ul><li>The default storage size is typically sufficient, but you can increase it if needed.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LUt50PfyrlgFZzYm" /></figure><p>Configure Security Group:</p><ul><li>Allow the following ports:</li><li>TCP 22 (SSH)</li><li>TCP 6443 (Kubernetes API server)</li><li>TCP 10250 (Kubelet API)</li><li>TCP 30000–32767 (NodePort services)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dZjQW83-4WqR-q8K" /></figure><p>Review and launch the instance, ensuring you select your key pair for SSH access.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FKiG4CkcEvknOg4k" /></figure><p>Create Ansible Server:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eWCk770V1xzeBbFm" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UwkWtxZnKgZn6oKw" /></figure><p>Login to ansible server</p><p>Install ansible:</p><blockquote>sudo apt update<br>sudo apt install software-properties-common<br>sudo add-apt-repository ppa:ansible/ansible<br>sudo apt install ansible<br>ansible — version</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aNsCvQGIm6ccQiAS" /></figure><p>Create a directory named ~/kube-cluster in the home directory</p><blockquote>mkdir ~/kube-cluster<br>cd ~/kube-cluster</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/0*t0WXEV6367sDuBF3" /></figure><p>Create a file named ~/kube-cluster/hosts using vi</p><blockquote>vi ~/kube-cluster/hosts</blockquote><pre>ubuntu@ip-172–31–85–190:~/kube-cluster$ cat hosts <br>[masters]<br>master ansible_host=54.242.87.248 ansible_user=ubuntu<br>[workers]<br>worker1 ansible_host=50.17.103.250 ansible_user=ubuntu<br>worker2 ansible_host=54.196.131.219 ansible_user=ubuntu<br>[all:vars]<br>ansible_python_interpreter=/usr/bin/python3<br>ansible_ssh_private_key_file=/home/ubuntu/kube-cluster/rabin-server.pem<br>ansible_ssh_common_args=’-o StrictHostKeyChecking=no’</pre><h3>Creating a Non-Root User on All Remote Servers</h3><p>Create non-root user named rabin with sudo privileges and set up SSH key-based authentication</p><blockquote>vi initial.yml</blockquote><pre>- hosts: all<br> become: yes<br> tasks:<br> — name: Create the ‘rabin’ user<br> user:<br> name: rabin<br> append: yes<br> state: present<br> create_home: yes<br> shell: /bin/bash</pre><pre> — name: Allow ‘rabin’ to have passwordless sudo<br> lineinfile:<br> dest: /etc/sudoers<br> line: ‘rabin ALL=(ALL) NOPASSWD: ALL’<br> validate: ‘visudo -cf %s’</pre><pre> — name: Ensure the .ssh directory exists for the rabin user<br> file:<br> path: /home/rabin/.ssh<br> state: directory<br> mode: ‘0700’<br> owner: rabin<br> group: rabin</pre><pre> — name: Copy the public key from Ansible server to the rabin user’s authorized_keys<br> authorized_key:<br> user: rabin<br> state: present<br> key: “{{ lookup(‘file’, ‘/home/ubuntu/.ssh/id_rsa.pub’) }}”</pre><pre> — name: Ensure correct permissions on the authorized_keys file <br> file:<br> path: /home/rabin/.ssh/authorized_keys<br> mode: ‘0600’<br> owner: rabin<br> group: rabin</pre><p><strong>- hosts: all:</strong></p><ul><li>This playbook will target all hosts defined in the Ansible inventory file. It will apply the following tasks to all the specified servers (master and worker nodes in your AWS setup).</li></ul><p><strong>become: yes:</strong></p><ul><li>This tells Ansible to run all tasks as the root user using sudo. This is necessary because some tasks, such as creating users and modifying system files, require elevated privileges.</li></ul><p><strong>Creating the ‘rabin’ User:</strong></p><ul><li><strong>Task Name</strong>: Create the ‘rabin’ user.</li><li><strong>Purpose</strong>: Creates a new user named rabin on each server if it doesn’t already exist.</li><li><strong>Details</strong>:</li><li><strong>name</strong>: rabin: Specifies the username.</li><li><strong>append</strong>: yes: Allows adding the user to additional groups later if needed.</li><li><strong>state</strong>: present: Ensures the user is created and exists.</li><li><strong>create_home</strong>: yes: Creates a home directory for the user at /home/rabin.</li><li><strong>shell</strong>: /bin/bash: Assigns the Bash shell as the default shell for the rabin user.</li></ul><p><strong>Allow ‘rabin’ to Have Passwordless Sudo:</strong></p><ul><li><strong>Task Name</strong>: Allow ‘rabin’ to have passwordless sudo.</li><li><strong>Purpose</strong>: Modifies the /etc/sudoers file to allow the rabin user to run any command as sudo without entering a password.</li></ul><p><strong>Details</strong>:</p><ul><li><strong>lineinfile</strong>: A module used to insert or update a line in a file.</li><li><strong>dest</strong>: /etc/sudoers: Specifies the file to modify (the sudoers file).</li><li><strong>line</strong>: ‘rabin ALL=(ALL) NOPASSWD: ALL’: Adds a line to give the rabin user full sudo privileges without needing a password.</li><li><strong>validate</strong>: ‘visudo -cf %s’: Validates the file after editing using visudo to ensure there are no syntax errors.</li></ul><p><strong>Ensure the .ssh Directory Exists for the Rabin User:</strong></p><ul><li><strong>Task Name</strong>: Ensure the .ssh directory exists for the rabin user.</li><li><strong>Purpose</strong>: Ensures that the .ssh directory is created in the home directory of the rabin user if it doesn’t already exist.</li></ul><p><strong>Details</strong>:</p><ul><li><strong>path</strong>: /home/rabin/.ssh: Specifies the path to the .ssh directory.</li><li><strong>state</strong>: directory: Ensures that the path is a directory.</li><li><strong>mode</strong>: ‘0700’: Sets permissions to 700 (only the owner can read, write, and execute).</li><li><strong>owner</strong>: rabin: Ensures that the rabin user owns the directory.</li><li><strong>group</strong>: rabin: Ensures the group ownership is set to rabin.</li></ul><p><strong>Copy the Public Key from Ansible Server to the Rabin User’s authorized_keys:</strong></p><ul><li><strong>Task Name</strong>: Copy the public key from Ansible server to the rabin user’s authorized_keys.</li><li><strong>Purpose</strong>: Copies the public SSH key from the Ansible server to the authorized_keys file of the rabin user. This allows passwordless SSH login for the rabin user.</li></ul><p><strong>Details</strong>:</p><ul><li><strong>authorized_key</strong>: A module to manage SSH authorized keys.</li><li><strong>user</strong>: rabin: Specifies the user whose authorized_keys file should be updated.</li><li><strong>key</strong>: “{{ lookup(‘file’, ‘/home/ubuntu/.ssh/id_rsa.pub’) }}”: Reads the public key from the Ansible server’s file /home/ubuntu/.ssh/id_rsa.pub and adds it to the authorized_keys file of rabin.</li></ul><p><strong>Ensure Correct Permissions on the authorized_keys File:</strong></p><ul><li><strong>Task Name</strong>: Ensure correct permissions on the authorized_keys file.</li><li><strong>Purpose</strong>: Ensures the authorized_keys file for the rabin user has the correct permissions, as incorrect permissions can lead to SSH key authentication failure.</li></ul><p><strong>Details</strong>:</p><ul><li><strong>path</strong>: /home/rabin/.ssh/authorized_keys: Specifies the path to the authorized_keys file.</li><li><strong>mode</strong>: ‘0600’: Sets permissions to 600 (only the owner can read and write).</li><li><strong>owner</strong>: rabin: Ensures that the rabin user owns the file.</li><li><strong>group</strong>: rabin: Ensures the group ownership is set to rabin.</li></ul><p><strong>Verify the Existence of the SSH Public Key</strong>: Ensure the public key exists on the Ansible server.</p><p>Run the following command on your Ansible server (the server from where you’re running the playbook):</p><blockquote>cat ~/.ssh/id_rsa.pub</blockquote><p>If the file doesn’t exist, generate an SSH key pair using:</p><blockquote>ssh-keygen -t rsa -b 4096 -f ~/.ssh/id_rsa</blockquote><p>Press Enter for default paths and no passphrase (unless you prefer a passphrase).</p><p>Run the playbook</p><blockquote>ansible-playbook -i ~/kube-cluster/hosts ~/kube-cluster/initial.yml</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BfYShg0uczJjZnmP" /></figure><p>Verify the New User: After the playbook is successfully applied, verify that the new rabin user is created and that you can SSH into the servers using the new user:</p><blockquote>ssh rabin@master-public-ip<br>ssh rabin@worker1-public-ip<br>ssh rabin@worker2-public-ip</blockquote><p>This playbook creates a non-root user (rabin), gives them passwordless sudo privileges, ensures SSH access by adding a public key to their authorized_keys, and properly sets up permissions for the .ssh directory and files.</p><h3>Installing Kubernetetes’ Dependencies</h3><p>In this section you’ll use Ubuntu’s package manager to install the operating-system-level packages necessary for Kubernetes. These packages include:</p><ul><li><strong>Docker</strong>: A container runtime responsible for running your containers. Kubernetes is actively developing support for other runtimes as well like rkt.</li><li><strong>kubeadm</strong>: A command-line tool designed to install and configure the various components of a Kubernetes cluster in a standardized manner.</li><li><strong>kubelet</strong>: A system service or program that operates on all nodes and manages node-level functions.</li><li><strong>kubectl</strong>: A command-line tool used to issue commands to the cluster via its API Server.</li></ul><p><strong>Create a file named ~/kube-cluster/kubedependencies.yml in your workspace:</strong></p><p>vi /kube-cluster/kubedependencies.yml</p><p>Add the following line of code.</p><pre>- hosts: all<br> become: yes<br> tasks:<br> — name: Ensure apt-transport-https, ca-certificates, and curl are installed<br> apt:<br> name:<br> — apt-transport-https<br> — ca-certificates<br> — curl<br> — gpg<br> state: present<br> update_cache: yes</pre><pre> — name: Ensure /etc/apt/keyrings directory exists<br> file:<br> path: /etc/apt/keyrings<br> state: directory<br> mode: ‘0755’</pre><pre> — name: Download Kubernetes GPG key and save it to /etc/apt/keyrings/kubernetes-apt-keyring.gpg<br> ansible.builtin.shell: |<br> curl -fsSL https://pkgs.k8s.io/core:/stable:/v1.31/deb/Release.key | gpg — dearmor -o /etc/apt/keyrings/kubernetes-apt-keyring.gpg<br> args:<br> creates: /etc/apt/keyrings/kubernetes-apt-keyring.gpg # To prevent running this task every time</pre><pre> — name: Add Kubernetes APT repository<br> ansible.builtin.shell: |<br> echo ‘deb [signed-by=/etc/apt/keyrings/kubernetes-apt-keyring.gpg] https://pkgs.k8s.io/core:/stable:/v1.31/deb/ /’ | tee /etc/apt/sources.list.d/kubernetes.list<br> args:<br> creates: /etc/apt/sources.list.d/kubernetes.list # To prevent running this task every time</pre><pre> — name: Update APT cache<br> apt:<br> update_cache: yes</pre><pre> — name: Install kubelet<br> apt:<br> name: kubelet<br> state: present</pre><pre> — name: Install kubeadm<br> apt:<br> name: kubeadm<br> state: present</pre><pre> — name: Install kubectl (only on master)<br> apt:<br> name: kubectl<br> state: present<br> when: “‘master’ in inventory_hostname”</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_OmvK4B5a1vbvW6o" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pesbEKZvWetrYcwU" /></figure><p>All the dependencies required for running kubernetes cluster are installed using the above playbook.</p><h3>Setting Up the Master Node</h3><p>Create an Ansible playbook named master.yml on your ec2.</p><blockquote>vi ~/kube-cluster/master.yml</blockquote><p>Add the following play to the file to initialize the cluster and install Flannel:</p><pre>- hosts: master<br> become: yes<br> tasks:<br> — name: Initialize the Kubernetes cluster<br> shell: kubeadm init — pod-network-cidr=10.244.0.0/16 &gt;&gt; cluster_initialized.txt<br> args:<br> chdir: $HOME<br> creates: cluster_initialized.txt</pre><pre> — name: Create .kube directory for kubeconfig<br> file:<br> path: /home/rabin/.kube<br> state: directory<br> mode: ‘0755’<br> owner: rabin<br> group: rabin</pre><pre> — name: Copy admin.conf to user’s kube config<br> copy:<br> src: /etc/kubernetes/admin.conf<br> dest: /home/rabin/.kube/config<br> remote_src: yes<br> owner: rabin<br> group: rabin<br> mode: ‘0644’</pre><pre> — name: Ensure kubeconfig is exported in environment<br> shell: export KUBECONFIG=/home/rabin/.kube/config<br> environment:<br> KUBECONFIG: /home/rabin/.kube/config</pre><pre> — name: Wait for Kubernetes API server to be ready<br> shell: kubectl get nodes<br> register: result<br> until: result.rc == 0<br> retries: 10<br> delay: 15<br> environment:<br> KUBECONFIG: /home/rabin/.kube/config</pre><pre> — name: Install Pod network (Flannel)<br> shell: kubectl apply -f https://raw.githubusercontent.com/flannel-io/flannel/master/Documentation/kube-flannel.yml — validate=false &gt;&gt; pod_network_setup.txt<br> args:<br> chdir: $HOME<br> creates: pod_network_setup.txt<br> environment:<br> KUBECONFIG: /home/rabin/.kube/config</pre><pre> — name: Get the token for joining the worker nodes<br> shell: kubeadm token create — print-join-command<br> register: kubernetes_join_command</pre><pre> — name: Display the join command<br> debug:<br> msg: “{{ kubernetes_join_command.stdout }}”</pre><pre> — name: Copy join command to local file<br> become: yes<br> local_action:<br> module: copy<br> content: “{{ kubernetes_join_command.stdout_lines[0] }}”<br> dest: /tmp/kubernetes_join_command<br> mode: ‘0777’</pre><p>Apply the Playbook.</p><p>ansible-playbook -i hosts master.yml</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*s2u6VyQ4IlH_I8aE" /></figure><h3>Setting Up the Worker Node:</h3><p>Navigate back to your workspace and create a playbook named workers.yml:</p><blockquote>vi ~/kube-cluster/workers.yml</blockquote><p>Add the following text to the file to add the workers to the cluster:</p><pre>- hosts: workers<br> become: yes<br> gather_facts: yes</pre><pre> tasks:<br> — name: Copy join command from Ansible host to the worker nodes<br> become: yes<br> copy:<br> src: /tmp/kubernetes_join_command<br> dest: /tmp/kubernetes_join_command<br> mode: ‘0777’</pre><pre> — name: Join the Worker nodes to the cluster<br> become: yes<br> command: sh /tmp/kubernetes_join_command<br> register: joined_or_not</pre><p>Apply the playbook:</p><p>ansible-playbook -i hosts workers.yml</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eKwfNGcZvtthfCoB" /></figure><p>Verifying the Cluster</p><blockquote>ssh rabin@Master_IP</blockquote><blockquote>Kubectl get nodes</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/0*K2cBA0FxTs2Z7LY6" /></figure><p>If all your nodes show “Ready,” they are part of the cluster and ready to work. If some nodes show “NotReady,” it means they might still be setting up. Wait 5 to 10 minutes and check again by running kubectl get nodes. If any nodes are still “NotReady,” you may need to go back and try the previous steps again. Once your cluster is ready, you can move on to running an example Nginx application.</p><h3>Running An Application on the Cluster</h3><p>You’re now ready to deploy any containerized application to your cluster. To keep it simple, let’s use Nginx and deploy it with Deployments and Services to show how an application can be launched on the cluster.</p><p>within the master node, execute the following command to create a deployment named nginx:</p><blockquote>kubectl create deployment nginx — image=nginx</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/0*hylo5T4DarsXFNs9" /></figure><p>Execute the following command to create a service called nginx, which will make the application accessible to the public.</p><blockquote>kubectl expose deployment nginx — type=LoadBalancer — name=nginx-lb — port=80 — target-port=80</blockquote><p>To test that everything is working</p><p><a href="http://worker_1_ip:nginx_port">http://worker_1_ip:nginx_port</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FvcLBcsDcNZgGlp_" /></figure><h3>Conclusion:</h3><p>You have successfully set up a Kubernetes cluster using Kubeadm on AWS! This configuration provides you with a robust platform for deploying and managing containerized applications</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4f076e2c10c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Test Failure Injection Simulation (FIS) for ECS Stop Tasks with AWS Resilience Hub]]></title>
            <link>https://medium.com/@rabinbhandari44/how-to-test-failure-injection-simulation-fis-for-ecs-stop-tasks-with-aws-resilience-hub-91ee580a195d?source=rss-61e80e7fd9fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/91ee580a195d</guid>
            <dc:creator><![CDATA[Rabin bhandari]]></dc:creator>
            <pubDate>Fri, 06 Sep 2024 08:31:43 GMT</pubDate>
            <atom:updated>2024-09-06T08:31:43.710Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In today’s dynamic cloud environments, ensuring the resilience and reliability of your applications is paramount. AWS Resilience Hub, coupled with Failure Injection Simulation (FIS), provides a robust framework for testing the resilience of your systems. This blog will guide you through the process of testing an ECS stop task using AWS Resilience Hub and FIS, enabling you to understand how your applications behave under failure conditions.</p><h3>Prerequisites</h3><p>Before we dive into the steps, make sure you have the following:</p><p>An active AWS account with the necessary permissions.</p><p>AWS CLI installed and configured.</p><p>An ECS cluster with running tasks.</p><h3>Step 1: Create an IAM Role for FIS</h3><p>FIS requires an IAM role to execute actions on your behalf:</p><p>Open the IAM console.</p><p>Create a new role with the necessary permissions for ECS (e.g., AmazonECS_FullAccess and AWSFISFullAccess).</p><h3>Step 2: Create ECS Cluster</h3><p>Open the Amazon ECS console.</p><p>Click on Clusters and then Create Cluster.</p><p>Choose the appropriate cluster template and follow the wizard to create your cluster.</p><p>Deploy Tasks to the ECS Cluster</p><p>Open the Amazon ECS console.</p><p>Click on Task Definitions and then Create a new Task Definition.</p><p>Define your task and service, then deploy them to your cluster.</p><p>I already have ECS cluster running:</p><p><strong>Cluster Name </strong>: valmiki-backend-prod</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UuUwEFINtFpsPejd" /></figure><p><strong>Service name </strong>: valmiki-backend-prod</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*F0RuxmCYZpKZ0wkt" /></figure><p>Currently, Two Task are running in Cluster</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*68la9kGJPkLuT_ea" /></figure><h3>Step 3: Create a FIS Experiment Template</h3><p>Open the AWS Resilience Hub console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_ONDWX0YOET377S_" /></figure><p>Navigate to FIS Experiment templates and click on Create experiment template.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/0*pFlNA8ioMVdrZeb3" /></figure><p>Configure the following details:</p><p><strong>Name</strong>: Enter a name for your experiment.</p><p><strong>Description</strong>: Enter a description.</p><p><strong>Role</strong>: Select the IAM role created earlier.</p><p><strong>Actions:</strong> Add an action for stopping ECS tasks:</p><p><strong>Action type</strong>: aws:ecs:stopTask</p><p><strong>Parameters</strong>: Specify the cluster and task ARNs.</p><h3>Step 4: Define the Stop Task Action</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/0*jvnPsVNK5ybSX788" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*farwq5g6BU4YGx3y" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/0*JNZsf7fgFKotqATV" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/0*wzR4oFMQ6EH5mA3z" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/0*0IrymtckZwvpbw1A" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/0*gktWiqYmvk5_OMFq" /></figure><p>Now experiment template is created and now you can start the experiment</p><h3>Step 6 : Start Experiment</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KtZdvsUbVWrQziZO" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*b5fk4V-sXg4Mn6AX" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mY9CX2njy3f2pJtJ" /></figure><h3>Step 7: Review and Analyze Results</h3><p>After the experiment completes, review the results in the AWS Resilience Hub:</p><p>Analyze the impact on your ECS service.</p><p>Assess the resilience of your application under failure conditions.</p><h3>Conclusion:</h3><p>Testing failure scenarios is crucial to understanding how your applications will behave under stress. AWS Resilience Hub and FIS provide powerful tools to simulate failures and improve the resilience of your services. By following these steps, you can confidently test ECS stop tasks and ensure your applications are robust and reliable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91ee580a195d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Launch an EC2 Instance Using Ansible]]></title>
            <link>https://medium.com/@rabinbhandari44/how-to-launch-an-ec2-instance-using-ansible-3cc83896468a?source=rss-61e80e7fd9fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/3cc83896468a</guid>
            <dc:creator><![CDATA[Rabin bhandari]]></dc:creator>
            <pubDate>Thu, 29 Aug 2024 10:26:24 GMT</pubDate>
            <atom:updated>2024-08-29T10:26:24.257Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Introduction:</strong></h4><p>Ansible is a powerful automation tool that allows you to automate cloud operations, including provisioning and managing EC2 instances on AWS. In this blog, we will walk through the steps required to launch an EC2 instance using Ansible.</p><h4><strong>Prerequisites</strong></h4><p>Before you start, make sure you have the following:</p><ul><li>An AWS account.</li><li>Ansible installed on your local machine.</li><li>AWS credentials configured on your machine (aws_access_key and aws_secret_key).</li><li>Python’s boto3 and botocore libraries installed (Ansible requires these to interact with AWS).</li></ul><h4><strong>Step1: Install Ansible</strong></h4><blockquote>sudo apt update<br>sudo apt install software-properties-common<br>sudo add-apt-repository — yes — update ppa:ansible/ansible<br>sudo apt install ansible<br>ansible — version</blockquote><h4><strong>Step2: Create a IAM user:</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AFvNGpG3qFKVITnD" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*q7AwXxnTDFG8SrIL" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2yeQER2gas_VCI9l" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7xCy8pMXRmFfYVt9" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qbS_Zjt_q9T7r1p1" /></figure><p>Download the CSV&gt;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*R8_O-OUYVMamaa7c" /></figure><h4><strong>Step3: Export AK and SK</strong></h4><p>In the control machine in EC2 export AWS_ACCESS_KEY and AWS_SECRET_KEY</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/0*_RaXOz8sJg3AIyHM" /></figure><p>Also I will put AK and SK to the .bashrc file because when I exit the shell the variables will be gone and I need to export it again.</p><p>vi .bashrc</p><p>In the last line add your Access key and secret key</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/0*0ohs1ZI-W2Hlzk0o" /></figure><p>source .bashrc</p><h4><strong>Step4: Create a task for key pair</strong></h4><blockquote>mkdir aws<br>cd aws</blockquote><p>open the file test-aws.yml</p><p>vi test-aws.yml</p><p><strong>Add following line of code.</strong></p><p>hosts: localhost<br> gather_facts: False<br> tasks: <br> — name: Create key pair<br> ec2_key:<br> name: sample<br> region: us-east-1</p><p>save and exit.</p><p><strong>Install necessary python dependency.</strong></p><p>sudo apt update<br> sudo apt install python3-pip -y<br>sudo apt install python3-boto3 python3-botocore</p><p><strong>Run Playbook</strong>.</p><p>ansible-playbook -i client-key.pem test-aws.yml</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*j9z7PP3CM1OTbPKM" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mT0isIpuOXSb_cde" /></figure><p>Ansible playbook was applied successfully but it did not return the private key. To return the key you need to add a register parameter.</p><p>- hosts: localhost<br> gather_facts: False<br> tasks: <br> — name: Create key pair<br> ec2_key:<br> name: sample<br> region: us-east-1<br> register: keyout</p><p>— name: print key<br> debug:<br> var: keyout</p><p>Ansible-playbook -i client-key.pem test-aws.yml</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PTGSiv-Dr0oPRQ-G" /></figure><p>The key already exists, first you need to delete the key and then apply ansible-playbook again.</p><p>Goto aws console and delete Sample key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yXQPhafSR171PjdR" /></figure><p>Apply ansible-playbook once again.</p><p>ansible-playbook -i client-key.pem test-aws.yml</p><p>Now the keypair is created successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_PZmrKDzcrXxGwfd" /></figure><p>We can create the task in the playbook and save the content by putting the condition there or we can just copy the text and create the file.</p><p>- hosts: localhost<br> gather_facts: False<br> tasks: <br> — name: Create key pair<br> ec2_key:<br> name: sample<br> region: us-east-1<br> register: keyout</p><p>— name: print key<br> debug:<br> var: keyout</p><p>— name: save key<br> copy:<br> content: “{{keyout.key.private_key}}”<br> dest: ./sample.pem<br> when: keyout.changed</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Avr9NPZbwbgPD22o" /></figure><p>Now the key name sample.pem is created and saved in the destination</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/0*LStJ70KcW76u0iQ-" /></figure><h4><strong>Step 5: Launch EC2 instance.</strong></h4><p>Step1. Install amazon.aws</p><p>ansible-galaxy collection install amazon.aws</p><p>Write a task to lunch the ec2 instance</p><p>- hosts: localhost<br> gather_facts: False<br> tasks: <br> — name: Create key pair<br> ec2_key:<br> name: sample<br> region: us-east-1<br> register: keyout</p><p>— name: print key<br> debug:<br> var: keyout</p><p>— name: save key<br> copy:<br> content: “{{keyout.key.private_key}}”<br> dest: ./sample.pem<br> when: keyout.changed</p><p>— name: start an instance with a public IP address<br> amazon.aws.ec2_instance:<br> name: “public-compute-instance”<br> key_name: “sample”<br> #vpc_subnet_id: subnet-5ca1ab1e<br> instance_type: t2.micro<br> security_group: default<br> #network:<br> #assign_public_ip: true<br> image_id: ami-0df2a11dd1fe1f8e3<br> exact_count: 1<br> region: us-east-1<br> tags:<br> Environment: Testing</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TexYUiUL1SBSlloU" /></figure><p>Once the playbook has run successfully, you can verify that the EC2 instance has been launched by visiting the AWS Management Console. Navigate to the EC2 dashboard, and you should see your new instance listed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4QmG3GPDzuq8foc_" /></figure><p><strong>Conclusion</strong></p><p>Launching an EC2 instance using Ansible is a straightforward process that allows for repeatable and scalable infrastructure management. By leveraging Ansible’s automation capabilities, you can efficiently manage your cloud resources and integrate them into your CI/CD pipeline or other automated workflows</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3cc83896468a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to setup kops for k8’s Setup in AWS.]]></title>
            <link>https://medium.com/@rabinbhandari44/how-to-setup-kops-for-k8s-setup-in-aws-c9df1eb2d275?source=rss-61e80e7fd9fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9df1eb2d275</guid>
            <dc:creator><![CDATA[Rabin bhandari]]></dc:creator>
            <pubDate>Fri, 19 Jul 2024 11:13:41 GMT</pubDate>
            <atom:updated>2024-07-19T11:13:41.858Z</atom:updated>
            <content:encoded><![CDATA[<h3>Prerequisites:</h3><ul><li>AWS account</li><li>Create VPC &amp; Deploy t2.micro Instance for management</li><li>Create AWS S3 Bucket</li><li>Domain Name</li><li>Create AWS Route53 Zone</li><li>Create Ec2 Instance and Access key &amp; secret key of the user</li><li>Generate SSH-Keys</li><li>Download the kOps binary to the management server and execute the permission</li><li>Download the kubectl binary to the management server and execute the permission</li><li>Deploy Kubernetes server with kOps</li></ul><h3>Step 1: Launch EC2 instance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4IvBr-4tOe3YhV_-" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/0*OWtrAP7n3Ss688yq" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/0*jtg-XZM_tASlglHM" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*W2tqXa9Uu8XDhT7v" /></figure><h3>Step 2: Create a S3 Bucket.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/0*YSoiCKdvmMOiPSAc" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*omqxAuDIP6oHoVdM" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nj5IEOX6wB3hA9nB" /></figure><h3>Step 3: Create an IAM user.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4ion0ccFruolNK-6" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rpfBDPxGhkX33UZl" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kA2cTjE4VKcxViI4" /></figure><p>Go to security credentials and generate Access Key and Secret Key</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HU5YcfJjqOifpso1" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FbJo8XXnxq1fWhTB" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Dw9iRfPf9pw5UpiR" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ORIqAEGPI493_5FT" /></figure><p>Download the Access Key</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*G_d6mNoO1sKY5iAN" /></figure><h3>Step 4 : Create a Hosted Zone</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/0*GqSADZ4iU7T3n93b" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*G-YKfpSwsdT1t4Lr" /></figure><h3>Step 5 : Setup EC2 Instance</h3><h3>Login to ec2 instance</h3><p>ssh -i “rabin-server.pem” ubuntu@ec2–54–242–114–95.compute-1.amazonaws.com</p><h3>Generate RSA key pair</h3><p>ssh key-gen</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/0*u9uOGQhO64xnDGCL" /></figure><h3>Install AWS CLI</h3><p>sudo apt update &amp;&amp; sudo apt install awscli</p><p>Configure AWS CLI</p><p>aws configure</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/0*52Pmb1Q-b5Pi3Ynp" /></figure><h3>Install and setup kubectl</h3><p>curl -LO “https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl&quot;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/0*n8BBrxMBg5rXlK3a" /></figure><p>chmod +x ./kubectl<br> sudo mv kubectl /usr/local/bin</p><h3>Install kops</h3><p>curl -LO <a href="https://github.com/kubernetes/kops/releases/download/$(curl">https://github.com/kubernetes/kops/releases/download/$(curl</a> -s <a href="https://api.github.com/repos/kubernetes/kops/releases/latest">https://api.github.com/repos/kubernetes/kops/releases/latest</a> | grep tag_name | cut -d ‘“‘ -f 4)/kops-linux-amd64</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/0*NTEk4hDMn0e3-XmU" /></figure><p>chmod +x kops-linux-amd64<br>sudo mv kops-linux-amd64 /usr/local/bin/kops</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/0*GszjsMdT1Llwyn5a" /></figure><h3>Create Kubernetes Cluster</h3><p>kops create cluster — name=bhandarirabin.com.np \</p><p>— state=s3://rabin-k8-state \</p><p>— zones=us-east-1a \</p><p>— node-count=2 \</p><p>— node-size=t3.small \</p><p>— master-size=t3.medium \</p><p>— dns-zone=bhandarirabin.com.np \</p><p>— node-volume-size=12 \</p><p>— master-volume-size=20 \</p><p>— yes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GPgHmwXLVMbUjEL1" /></figure><p><strong>NOTE</strong>: After issuing this command wait for like 15 minutes and after that we can verify our nodes.</p><p>We can see the provisioned servers on AWS console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lP5VgAAFDSrC7x4F" /></figure><p>Fig: Instances Created by kops</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4vnst_IIwSlh3W7N" /></figure><p>Fig Auto Scaling Group Created by Kops</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KVFJB7aU-yWj6AQs" /></figure><p>Fig Route 53 Hosted Zones</p><p>Delete the cluster. It will delete the entire cluster and its dependencies created on AWS.</p><p>kops delete cluster — name bhandarirabin.com.np — state s3://rabin-k8-state — yes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TpNwVzNCLwGq4PyD" /></figure><h3>Conclusion:</h3><p>After configuring the above steps on the management server, you can proceed to set up your applications. Setting up a Kubernetes cluster with kOps is a bit more complex than using kubeadm and requires substantial knowledge of AWS, but it is considered a reliable method for deploying production-grade clusters.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9df1eb2d275" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use AWS SSM in hybrid environment]]></title>
            <link>https://medium.com/@rabinbhandari44/how-to-use-aws-ssm-hybrid-environment-ac60381109a2?source=rss-61e80e7fd9fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac60381109a2</guid>
            <dc:creator><![CDATA[Rabin bhandari]]></dc:creator>
            <pubDate>Mon, 18 Dec 2023 06:12:45 GMT</pubDate>
            <atom:updated>2023-12-28T11:22:19.239Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Scope</strong></p><p>Today, I will be writing on how you can manage your EC2 instance, on-prem Hybrid environment using AWS Systems Manager</p><p><strong>Prerequisite:</strong></p><ul><li>AWS ACCOUNT</li><li>IAM Role</li><li>Onprem Server</li><li>SSM Agent</li></ul><p>You can set up and configure System Manager for overseeing on-premises servers, IoT devices, edge devices, and virtual machines. In the System Manager console, EC2 instances are identified with the prefix “i-,” while hybrid managed nodes are distinguished with the prefix “mi-.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/0*g5xYmY2nZWfg5I7s" /></figure><p>Automating SSM Hybrid Activation Creation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/0*l7v0QkqRQF64aUwA" /></figure><p><strong>Step1</strong>. Login to your AWS Console.</p><p><strong>Step </strong>2.Under the services tab, search for “Systems Manager”</p><p><strong>Step </strong>3. Click on “Hybrid Activations” and click “Create an Activation”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LzApHXi505fTLfcM" /></figure><p><strong>Step 4</strong>: On the Create Activation page, provide the following information:</p><p><strong>Activation Description</strong>: Enter the name for your activation.</p><p><strong>Instance Limit</strong>: Indicate the maximum number of servers to deploy the agent.</p><p><strong>IAM Role</strong>: Choose “Create a System Default Command” from the options.</p><p><strong>Activation Expiry Date</strong>: Set the preferred expiration date for the activation.</p><p>If you plan to add more servers after the expiry date, a new activation must be created.</p><p><strong>Default Instance Name</strong>: Specify the desired name for the servers, which will be displayed on the console.</p><p>Click “<strong>Create Activation</strong>” to initiate the activation process</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*JJFO6HVS-FeBzoM5" /></figure><p><strong>Step 5.</strong> Once you’ve created your activation, you will be redirected to the Hybrid Activations page and at the top, you should see your activation code and activation ID. Take note of these values as you will need them on the next section where you will install the SSM agent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KhIiwpiGX7O2T5av" /></figure><p><strong>Ubuntu Activation Code:</strong></p><blockquote>mkdir /tmp/ssm<br>curl <a href="https://s3.amazonaws.com/ec2-downloads-windows/SSMAgent/latest/debian_amd64/amazon-ssm-agent.deb">https://s3.amazonaws.com/ec2-downloads-windows/SSMAgent/latest/debian_amd64/amazon-ssm-agent.deb</a> -o /tmp/ssm/amazon-ssm-agent.deb<br>sudo dpkg -i /tmp/ssm/amazon-ssm-agent.deb<br>sudo service amazon-ssm-agent stop<br>sudo -E amazon-ssm-agent -register -code “activation-code” -id “activation-id” -region “region” <br>sudo service amazon-ssm-agent start</blockquote><p><strong>Monitoring Managed Instances</strong></p><p>You can now monitor your registered instances under the “Managed Instances” tab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/0*OfGZj6pLIy2yYD9r" /></figure><p>And!!! Everything is set!</p><p>Having effectively installed the SSM agent on our on-premises server, we can now effortlessly oversee it using SSM. This enables us to perform patches and automated tasks across all instances simultaneously, among other fantastic features!</p><p>Isn’t that fantastic?</p><p>AWS System Manager proves to be a potent tool, and the intriguing part is that it comes at no cost to us.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac60381109a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Config]]></title>
            <link>https://medium.com/@rabinbhandari44/aws-config-3f0d747c8550?source=rss-61e80e7fd9fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f0d747c8550</guid>
            <category><![CDATA[aws-config]]></category>
            <dc:creator><![CDATA[Rabin bhandari]]></dc:creator>
            <pubDate>Mon, 11 Dec 2023 08:28:01 GMT</pubDate>
            <atom:updated>2023-12-11T08:28:41.021Z</atom:updated>
            <content:encoded><![CDATA[<p>Setting up the Configuration Recorder</p><p>1. In the AWS Management Console search bar, enter <em>Config</em>, and click the <strong>Config</strong> result under <strong>Services</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/0*vnypOIAJLn_XW-0X" /></figure><p>2. Click on <strong>Get Started</strong> when presented with the AWS Config welcome page:</p><p>. 3. Enter the following commands into the <strong>Settings</strong> form:</p><ul><li><strong>Resource strategy</strong></li><li><strong>Record specific resource types</strong>: <em>Checked</em></li><li><strong>Resource type</strong>: AWS EC2 SecurityGroup</li><li><strong>IAM role for AWS Config</strong></li><li><strong>Choose a role from your account</strong>: <em>Selected</em></li><li><strong>Role name</strong>:<em> config-role-us-west-2</em></li><li><strong>Amazon S3 bucket</strong></li><li><strong>Choose a bucket from your account</strong>: <em>Selected</em></li><li><strong>Bucket name</strong>: Leave the default value (it will be something like config-bucket-123456789012, changing this will mean you won’t have access to the created bucket)</li><li><strong>Amazon SNS topic</strong></li><li><strong>Stream configuration changes and notifications to an Amazon SNS topic</strong>: <em>Unchecked</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2x8y6_Eg7oY8whbJ" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w80j9KuyRC-VaocH" /></figure><p>4. Once you have verified the values are correct, click <strong>Next</strong>.</p><p>5. In the <strong>Rules</strong> step, click <strong>Next</strong> at the bottom right of the page.</p><p>There are more managed rules available after you initialize the configuration recorder than there are available now, before it is initialized.</p><p>6. In the <strong>Review</strong> step, verify there are 0 <strong>Config rules </strong>and <strong>All resources (excluding global resources)</strong> appears:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NTsGUWDdStMdCttx" /></figure><p>7. Click <strong>Confirm </strong>to start the configuration recorder.</p><p><strong>Summary</strong></p><p>configured the configuration recorder to record all resource configurations in the us-west-2 region and created an S3 bucket to store AWS Config history files and snapshots.</p><h4>Working With AWS Config Managed Rules:</h4><p>1. Click <strong>Rules</strong> in the AWS Config navigation panel on the left(not the one under <strong>Aggregators</strong>).</p><p>2. On the right-hand side, click <strong>Add rule</strong>:</p><p>You are presented with a list of AWS managed rules. Take a moment to see the types of rules available in the list.</p><p>3. In the <strong>Find rules</strong> text box, enter <em>required-tags</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/0*9PJDl86xl6z0DQn_" /></figure><p>4. Select the <strong>required-tags</strong> rule, and click on <strong>Next</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7JyVrFe_2cay26uX" /></figure><p>The <strong>required-tags </strong>rule can check that resources have specific tags that you require. imagine you are building out a blue-green deployment environment. Blue-green deployments maintain two copies of the deployment environment, a blue environment, and a green environment. As part of governing your environments, you require all resources to have a Deployment tag that identifies if it is part of the blue environment or the green environment.</p><p>5. In the <strong>Configure rule </strong>form, keep the default values for <strong>Name</strong>,<strong> Description</strong>, and <strong>Scope of changes </strong>fields.</p><p>Notice that the <strong>Trigger type</strong> is set to <strong>When configuration changes</strong>. This means the rule will evaluate any time the configuration recorder records a new configuration. The <strong>Resources</strong> <strong>Scope of changes</strong> allows you to select a subset of all the resources being recorded by AWS Config.</p><p>6. Move on the <strong>Resources</strong> list and delete all the selected resources to clear the list.</p><p>7. To quickly clear all the pre-selected resource types, change the <strong>Resource category</strong> drop-down to <strong>AWS resources</strong> and then back to <strong>All resource categories</strong>.</p><p>8. In the <strong>Resource type</strong> box, enter <em>ec2</em> and select <strong>SecurityGroup</strong> from the drop-down menu:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/0*2U_Bvn4uTbijR6Rq" /></figure><p>9. In the <strong>Parameters </strong>section at the bottom of the form, enter:</p><ul><li><strong>tag1Key</strong>: <em>Deployment</em></li><li><strong>tag1Value</strong>: <em>Blue, Green</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/0*itqqpYr_39jblVPo" /></figure><p>The key is required, while the value(s) is optional. When the value is specified, the tag must have one of the specified values. Multiple values are separated by commas. If no value is specified, the rule only checks if the tag is set with no specific criteria for the tag value.</p><p>10. Click <strong>Next</strong> and then <strong>Save</strong> to create the rule and have AWS Config automatically start evaluating the rule on the resources.</p><p>It can take a minute for the evaluation to complete.</p><h4>Analyzing and Remedying a Noncompliant Resource</h4><p>1. On the AWS Config <strong>Rules</strong> page, observe that it found <strong>1 Noncompliant resource(s) </strong>after rule evaluation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pa0-UJv84Q9k03yR" /></figure><p><em>Note</em>: To refresh the <strong>Rules</strong> page, refresh the page using your web browser. The managed rule can take about a minute to finish evaluating.</p><p>2. Click on <strong>required-tags </strong>in the <strong>Name</strong> column.</p><p>This will open the rule details view for the <strong>required-tags</strong> rule. In the top section, you will see all of the settings you configured when adding the rule.</p><p>3. Scroll down to the <strong>Resources in scope </strong>section:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/0*4slCt310TKC1W-F2" /></figure><p>Here you will find a summary of all the resources evaluated against your rules. You will see it evaluated an <strong>EC2 Security Group </strong>and it is <strong>Noncompliant</strong> with your rules.</p><p>4. Click on the resource, and, on the right, click on <strong>Resource timeline</strong>:</p><p>You will see a panel listing <strong>Events</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*71C9NwhACDK3MZWa" /></figure><p><em>note</em>: You can periodically refresh your browser tab to refresh the timeline in case you don’t see any <strong>Events </strong>under the configuration item in the timeline.</p><p><em>Note</em>: Ensure the <strong>Event type</strong> drop-down is set to <strong>All event types</strong> to ensure all types of events are shown.</p><p>5. Go back to the resource page and expand the <strong>View Configuration Item (JSON)</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/0*GuWUjG7R3-TL9W_J" /></figure><p>This will open the full configuration. There are many details here that are not in the summary. For example, scroll down and see that the <strong>ipPermissions</strong> that specify the security group ingress and egress permissions are visible.</p><p>6. Scroll to the top and click <strong>Manage resource</strong>:</p><p>7. On the <strong>Tags</strong> tab, click the <strong>Manage tags</strong> button:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/0*I0q9FTOb1dZXewp4" /></figure><p>8. In the Manage Tags dialog, click <strong>Add new tag</strong> and enter the following values:</p><ul><li><strong>Key</strong>: <em>Deployment</em></li><li><strong>Value</strong>: <em>Green</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/0*oepuyLcm2WSHho5D" /></figure><p>This tag makes the security group compliant with the managed rule you enabled.</p><p>9. Click <strong>Save changes</strong> and return to the AWS Config browser tab.</p><p>10. Click <strong>Resource Timeline</strong>, and refresh your browser every minute until you see a new configuration item in the timeline.</p><p><em>Note:</em> It can take up to 10 minutes for the configuration change to be recorded</p><p>Notice the new item has a <strong>Change</strong> and an <strong>Event</strong>. The <strong>Configuration Details</strong> also include the <strong>Deployment:Green</strong> tag now:</p><p>Notice the two latest events:</p><ul><li>A <strong>Configuration change</strong> event, showing that the deployment tag was added to the security group</li><li>A <strong>Rule compliance</strong> event, showing that all resources are now compliant with this rule</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/0*Ka2pVaPQOHu096Qp" /></figure><p>11. Return to the <strong>Rules</strong> page by clicking <strong>Rules</strong> in the left-hand navigation panel.</p><p>The <strong>Compliance </strong>column value reads <strong>Compliant</strong>, verifying the rule is in compliance after the security group configuration change:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/0*y6ndEevRMWAv9Syc" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f0d747c8550" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Standard Operating Procedure (SOP)]]></title>
            <link>https://medium.com/@rabinbhandari44/aws-standard-operating-procedure-sop-78668af8151d?source=rss-61e80e7fd9fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/78668af8151d</guid>
            <dc:creator><![CDATA[Rabin bhandari]]></dc:creator>
            <pubDate>Thu, 07 Sep 2023 03:33:24 GMT</pubDate>
            <atom:updated>2023-12-28T10:32:52.055Z</atom:updated>
            <content:encoded><![CDATA[<h4>Objective:</h4><p>The purpose of this Standard Operating Procedure (SOP) document is to establish a standardized and secure approach to DevOps operations based on AWS best practices. By following these guidelines is to ensure compliance with industry regulations, enhance security measures, and maintain a high level of efficiency and scalability. The implementation of these best practices will improve the reliability and resilience of our systems, minimize downtime, and enable rapid scaling of applications and infrastructure. Additionally, promoting collaboration and clear documentation will facilitate seamless cross-functional teamwork and knowledge sharing among development, operations, and security teams.</p><h3>Account Creation Process:</h3><ul><li>Determine the need for a new AWS account based on customer requirements.</li><li>Initiates the account creation process on behalf of the customer.</li><li>Accesses the AWS Partner Central portal or AWS Control Tower console.</li><li>Navigates to the account creation section or dashboard.</li><li>Select the option to create a new AWS account for the customer.</li><li>Enter the customer’s information, such as company name, contact details, and billing information.</li><li>verify the customer’s eligibility and agreement to the terms and conditions.</li><li>selects the desired AWS services and features to be enabled for the customer account.</li><li>Configure the Service Control Policies (SCPs) to apply fine-grained permissions and access controls for the customer’s account.</li><li>Specify the desired restrictions and access controls within the SCPs to align with the customer’s requirements and compliance needs.</li><li>Review the account creation and SCP configuration settings.</li><li>Clicks on the “Create Account” to initiate the account creation process.</li><li>AWS provisions the new AWS account and applies the configured SCPs based on the partner’s settings.</li><li>AWS sends a confirmation email to the customer’s provided email address.</li><li>Customer receives the confirmation email and is notified that the AWS account has been created on their behalf by the AWS Partner.</li><li>Customers follow the instructions in the email to verify their account and set their password.</li><li>Customer accesses the AWS Management Console using the provided credentials.</li><li>Customers log in to the AWS Management Console using their email address and newly set password.</li><li>AWS authenticates the customer’s credentials and grants access to the customer’s AWS account.</li><li>Customers can now manage and utilize the AWS services and features enabled by the AWS Partner.</li><li>Customers operate within the access controls and restrictions enforced by the configured SCPs, ensuring compliance with the partner’s guidelines and policies.</li></ul><p><strong><em>NOTE</em></strong><em>: Ensure that the account is provisioned using standardized naming conventions and appropriate account settings. Document all relevant information about the new account, including the purpose, responsible personnel, and any other specific requirements.</em></p><h3>Root Account Usage:</h3><ul><li>It is recommended to avoid using the root account for regular workload activities. Instead, create and use separate AWS Identity and Access Management (IAM) users with appropriate permissions.</li><li>The root account should only be used for initial account setup and emergency access purposes.</li></ul><h3>Multi-Factor Authentication (MFA):</h3><ul><li>During the onboarding process, users are guided through the process of setting up their MFA device and associating it with their AWS account.</li><li>Enable Multi-Factor Authentication (MFA) for all AWS accounts, including the root account.</li><li>Each user is required to associate an MFA device with their AWS account. This device is typically a hardware token or a virtual MFA app on a smartphone, for the time being we are using the device Virtual MFA app on the smartphone.</li><li>MFA should be enforced for all users accessing AWS resources, including the AWS Management Console, AWS CLI (Command Line Interface), and AWS API operations.</li><li>Once MFA is enabled, users are prompted to enter their MFA-generated code after successfully entering their username and password.</li><li>Document the MFA device or service used for each account and store the relevant information securely.</li><li>Monitor MFA usage through AWS CloudTrail logs.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*G7dfYCtCSpZA-0Ze" /></figure><h3>Contact Information:</h3><ul><li>Set the contact information for each AWS account to a corporate email address or phone number.</li><li>Ensure that the contact information is accurate and up to date.</li><li>Periodically review and update the contact information as required.</li></ul><h3>CloudTrail Logging:</h3><ul><li>Enable CloudTrail logs in all regions for each AWS account.</li><li>Configure CloudTrail to send logs to a dedicated Amazon S3 bucket.</li><li>Implement appropriate access controls to protect the CloudTrail logs from accidental deletion or unauthorized access.</li><li>Regularly review and monitor CloudTrail logs for any suspicious activities or security incidents.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IT02n-ZOlW6Mop3Q" /></figure><h3>Documentation and Communication:</h3><ul><li>Maintain a centralized record or database of all created AWS accounts, including relevant details such as account names, responsible personnel, and creation dates.</li><li>Communicate the account details and any specific instructions to the appropriate stakeholders.</li><li>Ensure that all relevant teams, such as operations, security, and support, are aware of the new account and its associated requirements.</li></ul><h3>Review and Audit:</h3><ul><li>Conduct periodic reviews and audits of AWS accounts to ensure compliance with security best practices.</li><li>Evaluate the usage of root accounts, MFA settings, contact information, and CloudTrail logging for each account.</li><li>Document and address any identified issues or deviations from the established best practices.</li></ul><h3>Accessing Customer-Owned AWS Accounts</h3><ul><li>Access to the AWS Management Console should be limited to authorized personnel only.</li><li>Users must authenticate using their individual user accounts associated with AWS Identity and Access Management (IAM).</li><li>Multi-Factor Authentication (MFA) should be enabled for all users accessing the AWS Management Console.</li><li>Regularly review and manage user access permissions to ensure least privilege.</li></ul><h3>Programmatic Access</h3><ul><li>Programmatic access should be performed using AWS Command Line Interface (CLI)</li><li>Programmatic access requires the use of access keys associated with IAM users or IAM roles.</li><li>Access keys should be securely stored and never shared among users.</li><li>Rotate access keys periodically and consider using AWS Secrets Manager or AWS Systems Manager Parameter Store for secure storage.</li><li>Apply the principle of least privilege when assigning IAM policies to IAM users or roles.</li></ul><h3>Temporary Credentials (IAM Roles)</h3><ul><li>Utilize temporary credentials, such as IAM roles, whenever possible instead of long-term access keys.</li><li>Define and manage IAM roles that grant specific permissions required for individual tasks or functions.</li><li>Assign IAM roles to users or applications based on the principle of least privilege.</li><li>Regularly review and update IAM roles to ensure they align with current requirements.</li><li>Avoid sharing IAM role credentials and limit the scope of permissions granted to minimize potential risks.</li></ul><h3>IAM Privilege Management</h3><ul><li>IAM principals should be granted only the minimum privileges necessary to perform their assigned tasks.</li><li>The use of wildcards in Action and Resource elements should be avoided as much as possible to limit the scope of permissions. For example, Suppose we have an AWS IAM policy that grants permissions to perform actions on S3 buckets, and we use wildcards to specify the resource:</li></ul><blockquote>{</blockquote><blockquote>“Version”: “2012–10–17”,</blockquote><blockquote>“Statement”: [</blockquote><blockquote>{</blockquote><blockquote>“Effect”: “Allow”,</blockquote><blockquote>“Action”: “s3:*”,</blockquote><blockquote>“Resource”: “*”</blockquote><blockquote>}</blockquote><blockquote>]</blockquote><blockquote>}</blockquote><p>In this example, the use of wildcards for both actions and resources allows any action to be performed on any S3 bucket in the AWS environment. This policy is overly permissive and could lead to potential security issues:</p><p><strong>Over-Privilege</strong>: This policy grants all S3 actions on all buckets. If you only intended to allow read access to specific buckets for certain users, you’ve given them much more power than needed.</p><p><strong>Escalation of Privilege</strong>s: An attacker who compromises an IAM user or role with this policy could easily manipulate, delete, or exfiltrate data from any S3 bucket, even those not intended to be accessed.</p><p>To avoid these issues, we should follow the principle of least privilege, which means granting only the necessary permissions for specific actions and resources:</p><blockquote>{</blockquote><blockquote>“Version”: “2012–10–17”,</blockquote><blockquote>“Statement”: [</blockquote><blockquote>{</blockquote><blockquote>“Effect”: “Allow”,</blockquote><blockquote>“Action”: “s3:GetObject”,</blockquote><blockquote>“Resource”: “arn:aws:s3:::example-bucket/*”</blockquote><blockquote>}</blockquote><blockquote>]</blockquote><blockquote>}</blockquote><p>In this improved policy, only the GetObject action is allowed on a specific S3 bucket. This policy is more secure as it limits the scope of actions and resources, reducing the potential attack surface.</p><ul><li>Regular reviews and audits of IAM policies and permissions should be conducted to ensure compliance with the principle of least privilege.</li></ul><h3>Access by AWS Partner Individuals</h3><ul><li>Every AWS Partner individual accessing an AWS account must use dedicated credentials.</li><li>Dedicated IAM users or roles should be created specifically for AWS Partner individuals, with appropriate permissions based on their roles and responsibilities.</li><li>Partner access should be closely monitored and revoked promptly when no longer required.</li></ul><h3>Identity Federation and AWS Managed Active Directory</h3><ul><li>Whenever applicable, the customer’s existing enterprise user identities and their credentials should be leveraged for accessing AWS services.</li><li>Identity Federation should be implemented, allowing users to authenticate against their existing identity provider (IdP) and receive temporary AWS credentials.</li><li>Migrating to AWS Managed Active Directory (AD) can provide seamless integration with existing on-premises directories and simplify identity management.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78668af8151d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Guidance to develop customer workload health KPIs]]></title>
            <link>https://medium.com/@rabinbhandari44/guidance-to-develop-customer-workload-health-kpis-425d02892cf?source=rss-61e80e7fd9fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/425d02892cf</guid>
            <dc:creator><![CDATA[Rabin bhandari]]></dc:creator>
            <pubDate>Tue, 29 Aug 2023 10:04:00 GMT</pubDate>
            <atom:updated>2023-08-29T10:04:00.281Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. AWS CloudWatch</h3><p>AWS CloudWatch is a monitoring and observability service provided by Amazon Web Services (AWS). It allows you to collect and track metrics, collect and monitor log files, set alarms, create dashboards, and automatically react to changes in your AWS resources.</p><h3>2. Getting Started</h3><h3>2.1 Creating an Amazon Account</h3><p>To get started with Amazon CloudWatch, you will need an AWS account. If you don’t have an AWS account, you can sign up at <a href="https://aws.amazon.com/">https://aws.amazon.com/.</a></p><h3>2.2 Installing and Configuring the AWS Command Line Interface (CLI)</h3><p>The AWS CLI is a unified tool to manage your AWS services. To install and configure the AWS CLI, follow the instructions provided in the official AWS documentation at <a href="https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html.">https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html.</a></p><p><strong>3. Using CloudWatch</strong></p><h3>3.1 CloudWatch Metrics</h3><p>CloudWatch Metrics enables you to monitor AWS resources and custom metrics in near real-time.</p><h3>3.2 CloudWatch Logs</h3><p>CloudWatch Logs allows you to monitor, store, and access log files from your applications and AWS resources. Refer to the official AWS CloudWatch Logs documentation at <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/WhatIsCloudWatchLogs.html">https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/WhatIsCloudWatchLogs.html</a> for information on configuring, searching, and analyzing logs.</p><p><strong>Send Log Files to AWS CloudWatch</strong></p><p>To allow an EC2 instance to communicate with CloudWatch, you first need to create an IAM Role. You only need to do this once, so you can skip this step after it’s been created</p><ul><li>Open the IAM console. From the menu, select Roles and then click the Create role button.</li><li>Under Choose the service that will use this role, select EC2 and click the Next: Permissions button:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/0*AazZtOQ5R5IyG-Pn" /></figure><ul><li>Search for the CloudWatchAgentServerPolicy policy, check the checkbox and click Next: Tags:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/0*49X6GlGSQoU-uw-Y" /></figure><ul><li>Add tags if required . Click Next: Review.</li><li>Enter a Role name (e.g. CloudWatchAgentServerRole). Then click Create role.</li></ul><p><strong>Attach IAM Role</strong></p><p>To attach the IAM Role to the EC2 instance, you can either do it through the AWS console or via the AWS Command Line Interface (CLI):</p><p>Go to the EC2 Dashboard, select Instances from the menu and check the checkbox next to the EC2 instance you want to stream the logs from. To attach the IAM Role, click the Actions dropdown and select Instance Settings &gt; Attach/Replace IAM Role:</p><p>Search for and select the IAM role created above (e.g. CloudWatchAgentServerRole), then click Apply to attach the IAM role:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/0*-CsAl62iMrHnf9vz" /></figure><p><strong>Install CloudWatch Agent:</strong></p><p>wget <a href="https://s3.amazonaws.com/amazoncloudwatch-agent/ubuntu/amd64/latest/amazon-cloudwatch-agent.deb">https://s3.amazonaws.com/amazoncloudwatch-agent/ubuntu/amd64/latest/amazon-cloudwatch-agent.deb</a></p><p>Install the Agent with:</p><p>sudo dpkg -i -E ./amazon-cloudwatch-agent.deb</p><h3>Now it’s installed it needs to be configured before it can be started. There are two ways to do this, using the wizard which will ask you a series of questions and generate a config file for you, or you can manually add a config file. As we’re only interested in logging one file to CloudWatch and it’s the same on each EC2 instance, it’s easy to manually add a config file:</h3><p><strong>Manually create config.json:</strong></p><p>The Log Agent uses a config file located at /opt/aws/amazon-cloudwatch-agent/bin/config.json. Use your favorite editor (e.g. vim) to create and edit a file with the following content, e.g.</p><p>sudo vim /opt/aws/amazon-cloudwatch-agent/bin/config.json</p><p>{<br> “agent”: {<br> “run_as_user”: “root”<br> },<br> “logs”: {<br> “logs_collected”: {<br> “files”: {<br> “collect_list”: [<br> {<br> “file_path”: “/var/log/apache2/error.log”,<br> “log_group_name”: “apache-error-log”,<br> “log_stream_name”: “{instance_id}”<br> }<br> ]<br> }<br> }<br> }<br> }</p><h3>The most important part of the config file is file_path. This is the path to the log file on the server that you want to collect data from. /var/log/apache2/error.log is the default error log for Apache on Ubuntu. The log_group_name and log_stream_name options are just used for naming the Log Group and Log Streams respectively in CloudWatch. I’d recommend keeping {instance_id} for the log_stream_name as this helps identify which EC2 instance sent the log data</h3><p><strong>Wizard</strong></p><p>To start the wizard run:</p><p>$ sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-config-wizard</p><p><strong>Start the Agent:</strong></p><p>Run the following command to run the agent. The CloudWatch agent is integrated with systemd so it will start automatically after a reboot:</p><p>$ sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a fetch-config -m ec2 -c file:/opt/aws/amazon-cloudwatch-agent/bin/config.json -s</p><p>You’ll be asked a series of questions. The Log Agent can be used to collect system-level metrics, so you will be asked about them. But you can ignore those questions as they’re not related to collecting logs. If you do use the wizard, you can always take the config file that’s generated and then manually add that (following the step above) to any additional instances<strong>.</strong></p><p><strong>View Logs</strong></p><p>Once the log file you are watching has data written to it, you’ll be able to find it in CloudWatch. Go to the CloudWatch Overview and select Logs from the menu. You should see the label for the Log Group you used in the config (e.g. apache-error-log).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/0*GNBfwlY5cpCX_lGD" /></figure><p>Click on the log group name to see the log streams. Each log stream uses the EC2 instance ID, so you know which EC2 instance logged the data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/0*9Ci5oLQHDdp_0Fxu" /></figure><p>To search the logs, click the Search Log Group button. In the filter text box, enter a search term to search all your log files in one go:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/0*bPzwcQAaXT4BAqT-" /></figure><h3>3.3 CloudWatch Alarms</h3><p>CloudWatch Alarms enables you to monitor metrics over time and take automated actions based on predefined thresholds.</p><p><strong>Setting Up a CloudWatch Alarm</strong></p><p>Creating a CloudWatch Alarm is a precise process that requires maintaining a set of rules to ensure that the proper measures are taken when the right conditions are met. The process includes 10 individual steps and below is a step-by-step guide with the appropriate precautions:</p><p><strong>Ensure the right permissions</strong></p><p>Ensure you have the proper CloudWatch permissions to create and manage</p><p>Alarms. In general, Access control and writing permission policies are attached to IAM identities, AWS provides a table with API operations with the respectively required permissions.</p><p><strong>Initiate the process</strong></p><p>To start the process, you will have to first open the CloudWatch Console and use the navigation page to expand “Alarms”, then press on “All Alarms” &gt;“Create Alarm”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xDw3mAifN8aYXEK7" /></figure><p><strong>Condition phase</strong></p><p>The first step in creating an Alarm is specifying the metric and conditions. When pressing the “Select Metric” button on the user interface below, the user will have to specify a single CloudWatch metric or add an algebraic expression built around that value metric. Usually, the action that will come next would be associated with a threshold value assigned to a specific metric over a number of time periods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-pU1W759q_pjMeNN" /></figure><p><strong>Choosing the metric</strong></p><p>Select the metric to monitor with the alarm. The metric options include the free provided insights into resources like Amazon EC2 instances, Amazon EBS volumes, and Amazon RDS DB instances. Detailed monitoring is also supported if enabled, in addition to personal application metrics as those can be added for search, graphing, and alarms.</p><p>In the example below, we are monitoring CPU utilization across all EC2 instances:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*C43ed1a6Smtm6lNL" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WzDvWy2txEy5Tm61" /></figure><p><strong>Statistics and time periods</strong></p><p>After choosing the proper metric, you can now choose the statistics which represent aggregations over a time frame pre-determined by the user. In this step, it’s important to wisely pick the Period of time as the values collected will span the specified timeframe. CloudWatch supports a list of statistics documented by AWS here.</p><p>As for the conditional options, the user will have the option to define a value or band as a threshold with a specific mathematical condition (greater, lower, lower\equal, greater\equal).</p><p>In the example below, we are setting the alarm threshold to 10% of the average CPU utilization over 5 minutes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/0*MROfkC3hrQ9a4dbz" /></figure><p><strong>Additional Configurations</strong></p><p>In the “Additional Configuration” section, the user can define how many data points need to breach the threshold in order for the alarm to be triggered:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/0*eEcMEY-yPlW96nrf" /></figure><p><strong>Missing data treatment</strong></p><p>In the “Additional Configuration” section, define how Cloudwatch should treat missing data. In the example below, we are “treating missing data as missing”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/0*Aeb2G0as8MKDKiJK" /></figure><p><strong>Configure actions</strong></p><p>After deliberately defining the conditions, next comes choosing the actions that will be triggered given said conditions. The user will have multiple actionable options such as: sending a notification to an Amazon SNS topic, performing an Amazon EC2 action or an Amazon EC2 Auto Scaling action, or creating an OpsItem or incident in Systems Manager.</p><p>In the example below, we are choosing an SNS notification, with an existing SNS topic:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/0*LhuF6Uf0wJV76hGW" /></figure><p>Note that when creating an Amazon SNS with CloudWatch the publication of alarm notifications will cover both the standard topic or FIFO topic.</p><p><strong>Name and description</strong></p><p>Next, enter a name for the new alarm. Users can briefly describe the alarm — this is optional, but is recommended if you create many similar alarms:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/0*HfE_PZ4P7PvAVrpr" /></figure><p><strong>Summary</strong></p><p>Finally, the user can review the alarm preview which summarizes the alarm metric, conditions, and action:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/0*er1ecBbHoA6RJHee" /></figure><p>After thoroughly assessing the summary; if the alarm has been configured correctly, the user simply clicks “Create Alarm”.</p><h3>3.4 CloudWatch Dashboards</h3><p>CloudWatch Dashboards allows you to create customized dashboards to visualize and monitor your resources and applications.</p><h3>3.5 CloudWatch Events</h3><p>CloudWatch Events helps you respond to state changes in your AWS resources by delivering notifications.</p><p>Amazon CloudWatch Events delivers a near real-time stream of system events that describe changes in Amazon Web Services (AWS) resources. Using simple rules that you can quickly set up, you can match events and route them to one or more target functions or streams. CloudWatch Events becomes aware of operational changes as they occur. CloudWatch Events responds to these operational changes and takes corrective action as necessary, by sending messages to respond to the environment, activating functions, making changes, and capturing state information.</p><p>You can also use CloudWatch Events to schedule automated actions that self-trigger at certain times using cron or rate expressions.</p><p><strong>Example: Using Lambda &amp; CloudWatch Events to start and stop Ec2 Instances:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*IInbhWn80AqoxEiV" /></figure><p>Log in to the AWS Console under an account with the necessary permissions. I am using one with admin privileges but not my root account.</p><p>Navigate to the IAM service and create a policy that we will attach to the Lamba service allowing it to do certain actions with certain resources (not a full access policy)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/0*lY4n_l62OWmY044d" /></figure><p>Enter in the below code in the JSON tab removing the existing default code. Then click next</p><p>{<br> “Version”: “2012–10–17”,<br> “Statement”: [<br> {<br> “Effect”: “Allow”,<br> “Action”: [<br> “logs:CreateLogGroup”,<br> “logs:CreateLogStream”,<br> “logs:PutLogEvents”<br> ],<br> “Resource”: “arn:aws:logs:*:*:*”<br> },<br> {<br> “Effect”: “Allow”,<br> “Action”: [<br> “ec2:Start*”,<br> “ec2:Stop*”<br> ],<br> “Resource”: “*”<br> }<br> ]<br>}</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/0*8Hb0kGEg_YjU2Eeb" /></figure><p>Next, we will attach this policy to a role that will be attached to the Lambda service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/0*wdKBkAg5xlSUHEVw" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/0*EoQQCA53-taNZlcb" /></figure><p>Click Next.</p><p>Then Search for StartandStopInstancePolicy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/0*wh8blQO3HO1rbZNK" /></figure><p>Click Next, then Next again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/0*jR1_v5i2C8HLFJIo" /></figure><p>Then click Create Role.</p><p>create our Ec2 Instances so that we can insert the instance id into our lambda code before creating our Lambda functions. Navigate to the Ec2 service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/0*8CLTHwt27kpPk2G9" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/0*2uC-9UEyo_gj9DjQ" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/0*c59T_vbCs1nTyJOR" /></figure><p>Click Next Configure Instance Details.</p><p>We are going to create two ec2 instances and we will create a new IAM role before we leave the screen to give ec2 full access for simplicity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/0*T_wYBzbkVGPWZWeA" /></figure><p>On the next screen, click Create Role. Click AWS Service and Ec2 for the service. Then search for Ec2FullAccess on the next screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/0*CahQ2YXwAstheL5c" /></figure><p>Then click next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/0*vF6e7uXn8_picVd2" /></figure><p>Then Click create role.</p><p>Prior to launching ensure that you create a new pair and download the keypair before launching the instances.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/0*Ddnj07a-QBnQ6Avc" /></figure><p>Next, locate your Ec2 instance ids that you will copy and paste into your python code on each of the startec2.py and stopeec2.py files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/0*7Da2pyv8UVbzpJSC" /></figure><p>Copy and paste the entire line of the file that you replace and paste it in the other .py file for simplicity.</p><p>Now we will create a Lambda Function that will invoke when we want to stop our instances to either stop or start. We will create two separate functions, one stopping and one starting the instances.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/0*SnqijURO0HfuBCBa" /></figure><p>Create the startinstance function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/0*mf9AfqTuTeX7xLAQ" /></figure><p>Start python code:</p><p># Starts the EC2 instances<br> <br>import boto3<br>region = ‘us-east-1’<br>instances = [‘i-12345’, ‘i-2345’]<br>ec2 = boto3.client(‘ec2’, region_name=region)</p><p>def lambda_handler(event, context):<br> ec2.start_instances(InstanceIds=instances)<br> print(‘started your instances: ‘ + str(instances))</p><p>Repeat the same stop but for stop instance using the stopec2.py code for your lambda function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/0*5ZTITW59Gs1c3jIJ" /></figure><p>Stop python code:</p><p># Stops the EC2 instances</p><p>import boto3<br>region = ‘us-east-1’<br>instances = [‘i-12345’, ‘i-2345’]<br>ec2 = boto3.client(‘ec2’, region_name=region)</p><p>def lambda_handler(event, context):<br> ec2.stop_instances(InstanceIds=instances)<br> print(‘stopped your instances: ‘ + str(instances))</p><p>Now that we see we have both functions you can test the lambda function to see whether it works before you continue. You would have to run the stop instance function since we have already launched and seen that our instances are in the run state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/0*oHxDOezMdj6KI67Y" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/0*PSt_NEUekk0TTagI" /></figure><p>Next, navigate to the CloudWatch service and go to events. Here we will create an event cron expression and add a custom rule to start our instances at a certain time. We will then do another one to stop it 10 minutes later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/0*FUpHltwAgaRe7s-V" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/0*7zph77KGAmoZQcsY" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/0*VKZyRMLmBQhzLCKK" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/0*zRPXVqS-vCifHJMy" /></figure><p>Let’s check the final step to see if both of our instances have been stopped.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/0*7i5GE6Ye9qmKFA6F" /></figure><p><strong>AWS CloudTrail</strong></p><p>CloudTrail is a service provided by AWS that enables you to monitor, log, and retain account activity-related events for your AWS infrastructure. It provides detailed event history, including the actions taken by users, services, or even external entities in your AWS account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MGL0xwCDGMZJm8-1" /></figure><h3>2. Setup</h3><h3>2.1 Prerequisites</h3><p>Before setting up CloudTrail, ensure that you have the following prerequisites in place:</p><p>An AWS account with appropriate permissions to create and manage CloudTrail.</p><p>An S3 bucket where the CloudTrail logs will be stored.</p><p>IAM roles with appropriate permissions to enable CloudTrail and deliver logs to the S3 bucket.</p><h3>2.2 Enable CloudTrail</h3><p>To enable CloudTrail, follow these steps:</p><ul><li>Sign in to the AWS Management Console.</li><li>Navigate to the CloudTrail service.</li><li>Click on “Create Trail.”</li><li>Provide a trail name and choose the desired settings, such as logging options, storage location, and encryption.</li><li>Configure CloudTrail to track the desired AWS services, such as AWS Lambda, Amazon S3, or AWS IAM.</li><li>Enable CloudTrail Insights if needed.</li><li>Configure event selectors to specify the events you want to capture.</li><li>Set up CloudTrail management and data event settings.</li><li>Specify the S3 bucket where the CloudTrail logs will be stored.</li><li>Configure advanced options, if necessary.</li><li>Review the settings and click on “Create” to enable CloudTrail.</li></ul><h3>2.3 Verify CloudTrail Setup</h3><p>After enabling CloudTrail, it’s essential to verify that it’s correctly configured and operational. Follow these steps to verify:</p><ul><li>Go to the CloudTrail console.</li><li>Select the appropriate trail.</li><li>Click on the “Event history” tab to review the recorded events.</li><li>Ensure that events are being captured and stored in the designated S3 bucket.</li></ul><h3>3. Configuration</h3><p>This section covers advanced configuration options for CloudTrail.</p><h3>3.1 Multi-Region Configuration</h3><p>CloudTrail can be configured to capture events from multiple AWS regions. Follow these steps to configure multi-region settings:</p><ul><li>Go to the CloudTrail console.</li><li>Select the trail you want to configure.</li><li>Click on the “Edit” button.</li><li>Enable the “Apply trail to all regions” option.</li><li>Review the settings and click on “Save” to apply the changes.</li></ul><h3>3.2 CloudWatch Logs Integration</h3><p>CloudTrail logs can be sent to CloudWatch Logs for real-time monitoring and analysis. To integrate CloudTrail with CloudWatch Logs, perform the following steps:</p><ul><li>Go to the CloudTrail console.</li><li>Select the desired trail.</li><li>Click on the “Edit” button.</li><li>Enable the “Send to CloudWatch Logs” option.</li><li>Select an existing CloudWatch Logs group or create a new one.</li><li>Review the settings and click on “Save” to apply the changes.</li></ul><h3>4. Monitoring and Management</h3><h3>4.1 Viewing CloudTrail Events</h3><p>CloudTrail provides several ways to view and analyze recorded events:</p><p>Event history in the CloudTrail console: Access the CloudTrail console and navigate to the “Event history” tab to view recorded events.</p><p>CloudWatch Logs: If CloudTrail is integrated with CloudWatch Logs, use the CloudWatch Logs console to analyze logs in real-time.</p><p>EventBridge (formerly CloudTrail Insights): EventBridge can be used to analyze and route CloudTrail events to other AWS services or external systems for further processing.</p><h3>4.2 CloudTrail Insights</h3><p>CloudTrail Insights provides advanced event analysis capabilities, including anomaly detection and threat intelligence. To enable CloudTrail Insights, follow these steps:</p><ul><li>Go to the CloudTrail console.</li><li>Select the desired trail.</li><li>Click on the “Insights” tab.</li><li>Enable CloudTrail Insights and choose the appropriate insights category.</li><li>Configure the sensitivity level for anomaly detection.</li><li>Review the settings and click on “Save” to apply the changes.</li></ul><h3>4.3 Managing CloudTrail Trails</h3><p>To manage CloudTrail trails effectively, consider the following:</p><ul><li>Enable log file validation: Enable log file validation to ensure the integrity and authenticity of CloudTrail log files.</li><li>Regularly review and analyze logs: Continuously monitor and review CloudTrail logs for any unusual activities or security incidents.</li><li>Set up alerts: Configure CloudWatch Alarms or use AWS EventBridge to trigger notifications or automate actions based on specific events.</li><li>Manage log retention: Define an appropriate log retention period based on compliance and operational requirements.</li><li>Regularly update CloudTrail settings: Keep track of changes in your AWS infrastructure and adjust CloudTrail settings accordingly.</li></ul><h3>5. Troubleshooting</h3><p>This section provides guidance for troubleshooting common issues related to CloudTrail.</p><ul><li>Ensure that CloudTrail is enabled and configured correctly.</li><li>Verify IAM permissions for the IAM role associated with CloudTrail.</li><li>Check if the S3 bucket for CloudTrail logs has the necessary permissions.</li><li>Review CloudTrail error logs in CloudWatch Logs for any reported issues.</li><li>Check the CloudTrail documentation and AWS Support resources for specific error messages or known issues.</li></ul><h3>6. Best Practices</h3><p>Follow these best practices to optimize the use of CloudTrail:</p><ul><li>Enable CloudTrail for all AWS accounts within your organization.</li><li>Use CloudTrail to monitor and detect unauthorized access attempts or unusual activities.</li><li>Regularly review CloudTrail logs for security and compliance purposes.</li><li>Enable log file validation to ensure log file integrity.</li><li>Apply the principle of least privilege when configuring IAM roles for CloudTrail.</li><li>Regularly update and patch your AWS resources to mitigate security vulnerabilities.</li></ul><p><strong>Use Case</strong>: AWS Centralise CloudTrail Logs of Multiple Accounts, Multiple Regions | Governance &amp; Compliance</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/0*S18eDefEhrFeDRGu" /></figure><ul><li>When you have multiple AWS accounts, from a security perspective, its good to have all the logs directed to a central account.</li><li>In the central account, create a bucket to hold the logs.</li><li>Ensure a bucket policy is in place to provide access to all other accounts the ability to add objects to the central S3 bucket</li><li>This is the procedure of using Central CloudTrail S3 Bucket for Multiple AWS Accounts</li></ul><p><strong>Step 1)</strong> Let’s assume that your central account is called the Centralised Account for logs.</p><p>First create a bucket that will hold all of the CloudTrail log files.</p><p>Click on AWS Services -&gt; select -&gt; S3</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/0*VWaPEO4CHXWZ2sYi" /></figure><p><strong>Step 2</strong>) Go to the bucket and add a bucket policy</p><p>Open Your Bucket -&gt; Click on Permissions -&gt; Edit Bucket Policy -&gt; Copy and paste the below code and update BucketName and Account ID.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*1YZjv4pth1YSHcuF" /></figure><p>{<br> “Version”: “2012–10–17”,<br> “Statement”: [<br> {<br> “Sid”: “AWSCloudTrailAclCheck20150319”,<br> “Effect”: “Allow”,<br> “Principal”: {<br> “Service”: “cloudtrail.amazonaws.com”<br> },<br> “Action”: “s3:GetBucketAcl”,<br> “Resource”: “arn:aws:s3:::BucketName”<br> },<br> {<br> “Sid”: “AWSCloudTrailWrite20150319”,<br> “Effect”: “Allow”,<br> “Principal”: {<br> “Service”: “cloudtrail.amazonaws.com”<br> },<br> “Action”: “s3:PutObject”,<br> “Resource”: [<br> “arn:aws:s3:::BucketName/DemoAccount1/AWSLogs/FirstAccountId/*”,<br> “arn:aws:s3:::BucketName/DemoAccount2/AWSLogs/SecondAccountId/*”<br> ],<br> “Condition”: {<br> “StringEquals”: {<br> “s3:x-amz-acl”: “bucket-owner-full-control”<br> }<br> }<br> }<br> ]<br>}</p><p>About Bucket Policy:</p><p>1. Allowing CloudTrail to have the permission to get the bucket ACL.</p><p>2. Add the account ID to have the permission to add objects to the centralized bucket.</p><p>3. You have to create these folders DemoAccount2 and AWSLogs in your bucket because we have provided access to particular folders only.</p><p><strong>Step 3) </strong>Now log into the other First/Second Account.</p><p>Modify the Cloudtrail log storage location by:</p><p>Select Use existing S3 bucket</p><p>Select Trail log bucket name</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/0*So0PXiGXup0yOQR3" /></figure><p>Now go to the Centralised security bucket, you will see the log files of the other account</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/0*Ksuc7JVpof4lifRz" /></figure><p><strong>AWS X-Ray</strong></p><h3>Introduction</h3><p>AWS X-Ray is a service that collects data about requests that your application serves, and provides tools that you can use to view, filter, and gain insights into that data to identify issues and opportunities for optimization. For any traced request to your application, you can see detailed information not only about the request and response, but also about calls that your application makes to downstream AWS resources, microservices, databases, and web APIs.</p><h3>Prerequisites</h3><p>To get started with AWS X-Ray, ensure you have the following prerequisites:</p><p>An AWS account with appropriate permissions to enable and use X-Ray.</p><p>An application deployed on AWS or on supported platforms.</p><p>Basic knowledge of distributed systems and application tracing concepts.</p><h3>Concepts:</h3><p><strong>Service graph:</strong></p><p>Service graph or map is a visual representation for your application. Each resource is shown as a node in a graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wWacOSmfYOPYjZpT" /></figure><p><strong>Segment</strong></p><p>Is a representation of a logical compute resource in the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PSaWnb5cvg5bL_fv" /></figure><p><strong>Subsegment</strong></p><p>A further breakdown of the data with more granular timing information and details about the call.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uQ-DxI2EK8hMuqif" /></figure><p><strong>Traces</strong></p><p>Log in to the AWS Management Console:</p><p>Go to the AWS Management Console (https://aws.amazon.com/console/) and log in with your AWS account.</p><p>Navigate to AWS X-Ray:</p><p>Once logged in, search for “X-Ray” in the AWS services search bar, or you can find it under the “Management &amp; Governance” section.</p><p>Select a Service:</p><p>In the X-Ray console, you’ll see a list of services and applications that are currently generating traces. Select the service or application for which you want to view traces.</p><p>View Traces:</p><p>Each trace id represents a path that a particular request uses to go through an application</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*J4tvIr7kK0ifOWgc" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fcvrWrOh0qGY6Nm4" /></figure><h3>Setup</h3><p>AWS X-ray can trace different types of requests:</p><ul><li>API Gateway requests</li><li>http(s) calls from the application</li><li>AWS SDK calls</li><li>DB queries</li><li>Custom segments/subsegments</li></ul><h3>AWS X-Ray wrappers</h3><p>AWS X-Ray uses wrappers to instrument the calls and supports multiple languages: Go, Java, Node.js, Python, Ruby, .NET.</p><h3>AWS X-Ray daemon</h3><p>AWS X-Ray Daemon is required to get raw segment data and send it to AWS X-Ray API.</p><h3>API Gateway</h3><p>AWS X-Ray tracing for API GW could be enabled with CloudFormation; however, it only supports new API Gateways and cannot be added to an existing one. If you have an existing API GW with CFN template, adding TracingEnabled would cause a failure.</p><p>However, AWS Console and AWS CLI could be used for it with no issues.</p><p>aws apigateway update-stage — rest-api-id ${REST_API_ID} — stage-name ${STAGE} — patch-operations op=replace,path=/tracingEnabled,value=true</p><p>Make sure a role you’re using has the following permissions</p><p>Statement:<br> — Action:<br> — ‘iam:CreateServiceLinkedRole’<br> Resource: !Sub ‘arn:aws:iam::${AWS::AccountId}:role/aws-service-role/*’ <br> Effect: Allow</p><h3>http(s) calls from the application</h3><p>AWS X-Ray could be used to trace any outcoming HTTP(s) calls. It uses a wrapper that gets a data from the call request/response and adds a tracing header with a Parent ID to the call.</p><p>To start tracing it, your application needs two main parts:</p><ul><li>permissions</li><li>aws x-ray sdk</li></ul><p>ManagedPolicyArns:</p><p>- “arn:aws:iam::aws:policy/AWSXrayWriteOnlyAccess”</p><p>e.g. NodeJS</p><p>const AWSXRay = require(‘aws-xray-sdk’);<br> AWSXRay.captureHTTPsGlobal(require(‘http’)); AWSXRay.captureHTTPsGlobal(require(‘https’));</p><p>And that’s it! Place those 3 lines of code in your handler.js and all your nested classes would be traced for outgoing http(s) calls: rest, soap etc.</p><p>If you’re using restful microservices than adding just HTTP(s) calls capture would give you quite a good picture of what your distributed system is doing and how requests get propagated. Yes, by adding 3 lines of code and the permission.</p><h3>AWS SDK calls</h3><p>To trace AWS SDK calls with X-Ray just use x-ray wrapper and the same permission as above.</p><p>ManagedPolicyArns:</p><p>- “arn:aws:iam::aws:policy/AWSXrayWriteOnlyAccess”</p><p>And a wrapper</p><p>const AWS = AWSXRay.captureAWS(require(‘aws-sdk’));</p><p>That’s all that is needed for a NodeJS application to trace AWS SDK calls with AWS X-Ray.</p><h3>DB queries</h3><p>To capture Postgres or MySQL queries use the same policy</p><p>ManagedPolicyArns:</p><p>- “arn:aws:iam::aws:policy/AWSXrayWriteOnlyAccess”</p><p>and a corresponding wrapper to create a connection</p><p>const AWSXRay = require(‘aws-xray-sdk’);<br>const pg = AWSXRay.capturePostgres(require(‘pg’));<br>…<br>const AWSXRay = require(‘aws-xray-sdk’);<br>const mysql = AWSXRay.captureMySQL(require(‘mysql’));</p><h3>Custom subsegment.</h3><p>You can create your own segments and subsegments to wrap some pieces of code and get a visual representation of it on a service map. This could be useful for some transformation or sorting within an application to keep an eye on performance an errors.</p><p>AWSXRay.captureAsyncFunc(‘send’, function(subsegment) {<br> sendRequest(host, function() {<br> console.log(‘rendering!’);<br> res.render(‘index’);<br> subsegment.close();<br> });<br> });</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=425d02892cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>