<?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 Kaushikkp on Medium]]></title>
        <description><![CDATA[Stories by Kaushikkp on Medium]]></description>
        <link>https://medium.com/@kaushikkp03?source=rss-edde9899a6cd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*R6xUPsduEk7ClN2D</url>
            <title>Stories by Kaushikkp on Medium</title>
            <link>https://medium.com/@kaushikkp03?source=rss-edde9899a6cd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 17:39:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kaushikkp03/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[Streamlining System Management: Automating Nginx and Crontab Backups Across Multiple Servers with…]]></title>
            <link>https://medium.com/@kaushikkp03/streamlining-system-management-automating-nginx-and-crontab-backups-across-multiple-servers-with-0a52a1496671?source=rss-edde9899a6cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a52a1496671</guid>
            <category><![CDATA[server-backup]]></category>
            <category><![CDATA[ansible-backup]]></category>
            <category><![CDATA[nginx-backup]]></category>
            <category><![CDATA[ansible]]></category>
            <category><![CDATA[ansible-vault]]></category>
            <dc:creator><![CDATA[Kaushikkp]]></dc:creator>
            <pubDate>Wed, 03 Apr 2024 15:24:26 GMT</pubDate>
            <atom:updated>2024-04-03T15:27:59.287Z</atom:updated>
            <content:encoded><![CDATA[<h3>Streamlining System Management: Automating Nginx and Crontab Backups Across Multiple Servers with Ansible and Ansible-Vault</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wM53Vdwb68FX-rq05xuQGA.jpeg" /></figure><blockquote><strong>What is Ansible ?</strong></blockquote><p>Ansible is a powerful open-source automation tool that simplifies IT orchestration, configuration management, and application deployment. Developed by Red Hat, Ansible enables users to automate repetitive tasks, streamline complex workflows, and manage infrastructure efficiently.</p><p>Ansible is a powerful open-source automation tool that simplifies IT orchestration, configuration management, and application deployment. Developed by Red Hat, Ansible enables users to automate repetitive tasks, streamline complex workflows, and manage infrastructure efficiently.</p><p>With Ansible, tasks are defined in YAML files, known as playbooks, which describe the desired state of the system. These playbooks can be used to automate various tasks such as software installation, backup , configuration management, provisioning of servers, and deployment of applications.</p><blockquote><strong>Introduction :-</strong></blockquote><p>In this comprehensive guide, we delve into the essential practice of automating backups for critical components like Nginx configurations and crontab entries across multiple servers. Leveraging the robust capabilities of Ansible, a leading open-source automation tool, we’ll walk you through the seamless process of orchestrating backups effortlessly.</p><p>But that’s not all. We’ll take a step further by demonstrating how to safeguard sensitive information, such as root user passwords, using Ansible Vault. By encrypting this crucial data, we ensure the utmost security while maintaining the integrity of our automation workflows.</p><ol><li><strong>Adding the id_rsa.pub Key of the Parent Server: </strong>Before we can remotely manage the child servers from the parent server using Ansible, we must establish secure SSH connections between them. To do this, we’ll add the id_rsa.pub key of the parent server to each child server&#39;s authorized_keys file. This allows the parent server to authenticate with the child servers securely without needing to enter a password each time.</li><li><strong>Updating the Ansible Inventory File (</strong><strong>/etc/ansible/hosts):</strong> Once the SSH connections are established, we need to update the Ansible inventory file (/etc/ansible/hosts) on the parent server. In this file, we define the IP addresses or hostnames of the child servers under appropriate groups. Additionally, we provide the ansible_become_pass parameter for each server, which Ansible Vault will use to access sensitive information securely from the vault file.</li></ol><pre>[web_servers]<br>DevServer ansible_host=192.168.1.101 ansible_become_pass=&quot;{{ DevServer_password }}&quot;<br>QaServer2 ansible_host=192.168.1.102 ansible_become_pass=&quot;{{ QaServer2_password }}&quot;<br>ProdServer3 ansible_host=192.168.1.103 ansible_become_pass=&quot;{{ ProdServer3_password }}&quot;</pre><p>3. <strong><em>Ansible Vault Configuration:</em></strong> Ansible-Vault provides a secure way to encrypt sensitive information such as passwords, API keys, or in our case, any authentication details required for the backup process. Create an Ansible-Vault encrypted file to store the necessary credentials securely.</p><pre>ansible-vault create vault.yml</pre><p>i) It will ask for password for vault.yml file</p><p>This will open an editor where you can enter the password for each server. The file will be encrypted and saved when you exit the editor.</p><p>ii) Add the server-specific variables and their values (passwords) in the vault file.</p><pre>DevServer_password: &quot;password1&quot;<br>QaServer2_password: &quot;password2&quot;<br>ProdServer3_password: &quot;password3&quot;</pre><p>Save and exit the vault file.</p><p>4. In playbook(b<em>ackupfiles.yml</em>) to use the vault password.</p><pre>---<br><br>- name: Backup and Retrieve Nginx Configuration Files<br>  vars_files: vault.yml<br>  hosts: webservers<br>  gather_facts: true<br>  tasks:</pre><p>5. Complete ansible script</p><pre>---<br>- name: Backup and Retrieve Nginx Configuration Files<br>  vars_files: vault.yml<br>  hosts: webservers<br>  gather_facts: true<br>  tasks:<br>    - name: Clean local devops_backup folder<br>      ansible.builtin.file:<br>        path: &quot;/home/admin/devops_backup/{{ inventory_hostname }}&quot;<br>        state: absent<br>      delegate_to: localhost<br><br>    - name: Create folder with hostname and date on control node<br>      ansible.builtin.file:<br>        path: &quot;/home/admin/devops_backup/{{ inventory_hostname }}_{{ ansible_date_time.date }}&quot;<br>        state: directory<br>      delegate_to: localhost<br><br>    - name: Get crontab contents<br>      ansible.builtin.shell:<br>        cmd: &quot;crontab -l&quot;<br>      register: crontab_contents<br>      delegate_to: &quot;{{ inventory_hostname }}&quot;<br>      ignore_errors: yes<br><br>    - name: Save crontab backup<br>      ansible.builtin.copy:<br>        content: &quot;{{ crontab_contents.stdout }}&quot;<br>        dest: &quot;/home/admin/devops_backup/{{ inventory_hostname }}_{{ ansible_date_time.date }}/crontab_backup&quot;<br>      delegate_to: localhost<br>      failed_when: crontab_contents is failed<br><br>    - name: Backup Nginx configuration files<br>      become: true<br>      ansible.builtin.copy:<br>        src: &quot;/etc/nginx/sites-enabled/&quot;<br>        dest: &quot;/home/admin/devops_backup/{{ inventory_hostname }}_{{ ansible_date_time.date }}/nginx_config_backup/&quot;<br>        remote_src: yes<br>        backup: yes<br>      ignore_errors: yes<br><br>    - name: Create tar archive of the backup<br>      become: true<br>      ansible.builtin.archive:<br>        path: &quot;/home/admin/devops_backup/{{ inventory_hostname }}_{{ ansible_date_time.date }}/nginx_config_backup/&quot;<br>        dest: &quot;/home/admin/devops_backup/{{ inventory_hostname }}_{{ ansible_date_time.date }}/nginx_config_backup.tar.gz&quot;<br>        format: gz<br>      ignore_errors: yes<br><br>    - name: Fetch tar files from other servers<br>      ansible.builtin.fetch:<br>        src: &quot;/home/admin/devops_backup/{{ inventory_hostname }}_{{ ansible_date_time.date }}/nginx_config_backup.tar.gz&quot;<br>        dest: &quot;/home/admin/devops_backup/{{ inventory_hostname }}_{{ ansible_date_time.date }}/&quot;<br>        flat: yes<br>        remote_src: yes<br>        ignore_errors: true<br><br>    - name: Clean backup folders on child servers<br>      become: true<br>      ansible.builtin.file:<br>        path: &quot;/home/admin/devops_backup/&quot;<br>        state: absent<br>#      become: true<br>      ignore_errors: yes</pre><p>RUN SCRIPT USING BELOW COMMAND:-</p><pre>ansible-playbook -i /etc/ansible/hosts backupfiles.yml --ask-vault-pass</pre><p>Vault Integration (vars_files: vault.yml): The playbook integrates with Ansible Vault by specifying a vault file (vault.yml). Ansible Vault is used to securely store sensitive information such as passwords or API keys. This ensures that sensitive data is encrypted and not exposed in plain text within the playbook.</p><p>Target Hosts (hosts: webservers): The playbook targets a group of hosts defined in the Ansible inventory file under the webservers group. These hosts represent the web servers where Nginx is installed and need to be backed up.</p><p>Gathering Facts (gather_facts: true): Ansible gathers facts about the target hosts before executing tasks. Facts include details such as operating system, IP address, and hardware information. This information can be used in subsequent tasks.</p><p><strong>Task 1: </strong>Cleaning Local Backup Folder:</p><p>This task deletes the local backup folder (/home/admin/devops_backup/{{ inventory_hostname }}) on the control node (localhost) to ensure a clean backup environment.</p><p><strong>Task 2:</strong> Creating Folder with Hostname and Date:</p><p>This task creates a new folder on the control node to store the backups. The folder name includes the hostname of the target server ({{ inventory_hostname }}) and the current date ({{ ansible_date_time.date }}). This ensures that backups are organized and easily identifiable.</p><p><strong>Task 3:</strong> Getting Crontab Contents:</p><p>This task retrieves the crontab contents from the target server using the crontab -l command and stores them in the crontab_contents variable.</p><p><strong>Task 4: </strong>Saving Crontab Backup:</p><p>This task saves the crontab contents into a file within the backup folder created earlier. The file name includes the hostname and current date.</p><p><strong>Task 5:</strong> Backing Up Nginx Configuration Files:</p><p>This task copies Nginx configuration files from /etc/nginx/sites-enabled/ on the target server to the backup folder. The backup: yes option ensures that existing files are backed up before being overwritten.</p><p><strong>Tasks 6–7:</strong> Creating Tar Archives of Backups:</p><p>These tasks create compressed tar archives (.tar.gz) of the Nginx configuration backups and any additional backups (e.g., start script backups) for each target server.</p><p><strong>Task 8:</strong> Fetching Tar Files from Other Servers:</p><p>This task fetches the tar files containing the backups from each target server to the local backup directory on the control node. The ignore_errors: true option allows the task to continue even if fetching fails for some servers.</p><p><strong>Task 9:</strong> Cleaning Backup Folders on Child Servers:</p><p>This task cleans up the backup folders on the child servers after the backup process is complete. The state: absent option ensures that the folders are removed.</p><blockquote><strong><em>Conclusion :-</em></strong></blockquote><p>In today’s fast-paced IT landscape, automation is essential for staying competitive. With Ansible, organizations can enhance agility and build resilient infrastructure to meet modern digital demands. Automating backups, including Nginx configuration files and crontab entries, is crucial for system reliability and data integrity. Through Ansible automation and Vault, we’ve shown how to efficiently streamline this process while ensuring security.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a52a1496671" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Install TIG stack using docker-compose (Telegraf, Influx and Grafana) on Ubuntu and…]]></title>
            <link>https://medium.com/@kaushikkp03/how-to-install-tig-stack-telegraf-influx-and-grafana-on-ubuntu-and-container-and-system-c7d6c5dd77d6?source=rss-edde9899a6cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7d6c5dd77d6</guid>
            <category><![CDATA[telegraf]]></category>
            <category><![CDATA[grafana]]></category>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[influxdb]]></category>
            <dc:creator><![CDATA[Kaushikkp]]></dc:creator>
            <pubDate>Sun, 26 Nov 2023 13:11:28 GMT</pubDate>
            <atom:updated>2023-11-26T14:04:24.257Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Install TIG stack using docker-compose (Telegraf, Influx and Grafana) on Ubuntu and Monitoring Docker Container with Telegraf, Influxdb, and Grafana</h3><p><strong>Introduction:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*34vKjlgoHRP6ZxZ6XkN11g.png" /></figure><p>This tutorial series will guide you through the process of setting up a TIG stack using Docker-compose. Moreover, it will demonstrate how to automate the configuration for an almost seamless and hands-free setup. Throughout the tutorials, you’ll learn how to effectively monitor Dockerized containers, gaining insights into resource usage such as memory and CPU metrics.</p><p><strong>What is a TIG stack?</strong></p><ol><li>Telegraf — Data Collection</li><li>InfluxDB — Data Storage</li><li>Grafana — Data Visualiztion</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*Ro5WL8-P9nXGRhFqe2HzPw.png" /><figcaption>Fig 1: Architecture Diagram for Container and System Monitoring with Docker, Telegraf, Influxdb and Grafana</figcaption></figure><ul><li><strong>InfluxDB </strong>serves as the Time Series Database. It is an open-source database designed for rapid, high-availability storage, and retrieval of time series data. Developed in Go, InfluxDB proves particularly valuable for operations monitoring, application metrics, and real-time analytics.</li><li><strong>Telegraf</strong> functions as the agent responsible for collecting and reporting metrics and data. As a plugin-driven server agent within the TIG Stack, Telegraf excels at collecting and reporting metrics. It integrates with various sources, including containers and systems it operates on, fetching metrics from third-party APIs, and listening for metrics through StatsD and Kafka consumer services. Additionally, Telegraf supports output plugins to send metrics to different data stores, services, and message queues, including but not limited to InfluxDB, Graphite, OpenTSDB, Datadog, Librato, Kafka, MQTT, NSQ, and more.</li><li><strong>Grafana </strong>an open-source metric analytics and visualization suite, is commonly used for visualizing time series data related to infrastructure and application analytics. However, it finds application in diverse domains such as industrial sensors, home automation, weather monitoring, and process control. This tool offers visually appealing dashboards and metric analytics, empowering users to manage and create customized dashboards for applications or monitor infrastructure performance.</li></ul><p><strong>Docker Compose: Initial setup</strong></p><p>In the root of the TIG directory , we currently working in create a file called docker-compose.yaml</p><pre>Mkdir TIG<br>Nano /TIG/docker-compose.yml</pre><pre>version: &#39;3.6&#39; <br>services:</pre><blockquote><strong>version: “3.6”</strong><br>This line specifies the version of the Docker Compose file format being used.<br><strong>services:</strong><br>This line indicates the start of the services section, where we willl define the individual services that make up our TIG stack.</blockquote><p>We will go through the services one by one and in detail to help explain some Docker Compose concepts.</p><p>We will initially setup them as below:</p><p><strong>Telegraf</strong></p><pre>telegraf:<br>    image: telegraf<br>    container_name: telegraf<br>    restart: always<br>    volumes:<br>    - ./telegraf.conf:/etc/telegraf/telegraf.conf:ro<br>    - /var/run/docker.sock:/var/run/docker.sock<br>    depends_on:<br>      - influxdb<br>    links:<br>      - influxdb<br>    ports:<br>    - &#39;8125:8125&#39;</pre><p>Certainly! This configuration appears to be a Docker Compose snippet for setting up a Telegraf container. Here’s a breakdown of each line:</p><blockquote><strong>telegraf:</strong> Specifies the service name as “telegraf.”</blockquote><blockquote><strong>image: telegraf</strong></blockquote><blockquote>Specifies the Docker image to use, in this case, “telegraf.”</blockquote><blockquote><strong>container_name: telegraf</strong></blockquote><blockquote>Sets the name of the container to “telegraf.”</blockquote><blockquote><strong>restart: always</strong></blockquote><blockquote>Configures the container to always restart automatically.</blockquote><blockquote><strong>volumes:</strong></blockquote><blockquote>Specifies volume mappings for the container.</blockquote><blockquote>/telegraf.conf:/etc/telegraf/telegraf.conf:ro</blockquote><blockquote>Mounts the local file “./telegraf.conf” into the container at “/etc/telegraf/telegraf.conf” in read-only mode.</blockquote><blockquote>/var/run/docker.sock:/var/run/docker.sock</blockquote><blockquote>Binds the Docker socket from the host to the container, allowing Telegraf to collect Docker metrics.</blockquote><blockquote><strong>depends_on:</strong></blockquote><blockquote>Indicates that this container depends on another service, in this case, “influxdb.”</blockquote><blockquote><strong>links:</strong></blockquote><blockquote>Establishes a link to the “influxdb” service.</blockquote><blockquote><strong>ports:</strong></blockquote><blockquote>Maps ports between the host and the container.</blockquote><blockquote>8125:8125 Maps port 8125 on the host to port 8125 in the container, allowing access to the Telegraf metrics collector.</blockquote><blockquote>This configuration sets up a Telegraf container with specific settings, dependencies, and configurations for data collection and communication with an InfluxDB service.</blockquote><p><strong>InfluxDB</strong></p><pre>influxdb:<br>    image: influxdb:1.8-alpine<br>    container_name: influxdb<br>    restart: always<br>    environment:<br>      - INFLUXDB_DB=influx<br>      - INFLUXDB_ADMIN_USER=admin<br>      - INFLUXDB_ADMIN_PASSWORD=admin<br>    ports:<br>      - &#39;8086:8086&#39;<br>    volumes:<br>      - influxdb_data:/var/lib/influxdb</pre><p>Certainly! This is a Docker Compose configuration for setting up an InfluxDB container. Here’s a breakdown of each line:</p><blockquote><strong>influxdb:</strong></blockquote><blockquote>Specifies the service name as “influxdb.”</blockquote><blockquote><strong>image: influxdb:1.8-alpine</strong></blockquote><blockquote>Specifies the Docker image to use, in this case, InfluxDB version 1.8 with the Alpine Linux base image.</blockquote><blockquote><strong>container_name: influxdb</strong></blockquote><blockquote>Sets the name of the container to “influxdb.”</blockquote><blockquote><strong>restart: always</strong></blockquote><blockquote>Configures the container to always restart automatically.</blockquote><blockquote><strong>environment: </strong>Sets environment variables for the InfluxDB container.</blockquote><blockquote><strong>INFLUXDB_DB=influx</strong></blockquote><blockquote>Defines the name of the InfluxDB database as “influx.”</blockquote><blockquote><strong>INFLUXDB_ADMIN_USER=admin</strong></blockquote><blockquote>Specifies the admin username as “admin.”</blockquote><blockquote><strong>INFLUXDB_ADMIN_PASSWORD=admin</strong></blockquote><blockquote>Sets the admin password as “admin.”</blockquote><blockquote><strong>ports:</strong></blockquote><blockquote>Maps ports between the host and the container.</blockquote><blockquote>8086:8086 Maps port 8086 on the host to port 8086 in the container. Port 8086 is the default port for InfluxDB’s HTTP API.</blockquote><blockquote><strong>volumes:</strong></blockquote><blockquote>Specifies volume mappings for the container.</blockquote><blockquote><strong>influxdb_data:/var/lib/influxdb</strong></blockquote><blockquote>Creates a named volume named “influxdb_data” and mounts it to the “/var/lib/influxdb” directory in the container. This is where InfluxDB stores its data.</blockquote><p><strong>Grafana</strong></p><pre>  grafana:<br>    image: grafana/grafana<br>    container_name: grafana-server<br>    restart: always<br>    depends_on:<br>      - influxdb<br>    environment:<br>      - GF_SECURITY_ADMIN_USER=admin<br>      - GF_SECURITY_ADMIN_PASSWORD=admin<br>      - GF_INSTALL_PLUGINS=<br>    links:<br>      - influxdb<br>    ports:<br>      - &#39;3000:3000&#39;<br>    volumes:<br>      - grafana_data:/var/lib/grafana</pre><p>Certainly! This Docker Compose snippet is for setting up a Grafana service. Let’s break down each line:</p><blockquote><strong>grafana: </strong>Specifies the service name as “grafana.”</blockquote><blockquote><strong>image: grafana/grafana</strong></blockquote><blockquote>Specifies the Docker image to use, in this case, “grafana/grafana.”</blockquote><blockquote><strong>container_name: grafana-server</strong></blockquote><blockquote>Sets the name of the container to “grafana-server.”</blockquote><blockquote><strong>restart: always</strong></blockquote><blockquote>Configures the container to always restart automatically.</blockquote><blockquote><strong>depends_on:</strong></blockquote><blockquote>Indicates that this container depends on another service, in this case, “influxdb.” This ensures that the InfluxDB service is started before Grafana.</blockquote><blockquote><strong>environment:</strong> Sets environment variables for the Grafana container.</blockquote><blockquote><strong>GF_SECURITY_ADMIN_USER=admin</strong> Sets the Grafana admin user to “admin.”</blockquote><blockquote><strong>GF_SECURITY_ADMIN_PASSWORD=admin</strong> Sets the password for the Grafana admin user to “admin.”</blockquote><blockquote><strong>GF_INSTALL_PLUGINS= </strong>Specifies an empty value for the variable responsible for installing Grafana plugins during startup.</blockquote><blockquote><strong>links:</strong> Establishes a link to the “influxdb” service.</blockquote><blockquote><strong>ports: </strong>Maps ports between the host and the container.</blockquote><blockquote><strong>3000:3000</strong> Maps port 3000 on the host to port 3000 in the container, allowing access to the Grafana web interface.</blockquote><blockquote><strong>volumes:</strong> Specifies volume mappings for the container.</blockquote><blockquote><strong>grafana_data:/var/lib/grafana </strong>Creates a Docker volume named “grafana_data” and mounts it into the container at “/var/lib/grafana.” This is used to persist Grafana’s data, ensuring that data is retained even if the container is stopped or removed.</blockquote><p><strong>Docker Compose file</strong></p><pre>version: &#39;3.6&#39;<br>services:<br>  telegraf:<br>    image: telegraf<br>    container_name: telegraf<br>    restart: always<br>    volumes:<br>    - ./telegraf.conf:/etc/telegraf/telegraf.conf:ro<br>    - /var/run/docker.sock:/var/run/docker.sock<br>    depends_on:<br>      - influxdb<br>    links:<br>      - influxdb<br>    ports:<br>    - &#39;8125:8125&#39;<br><br>  influxdb:<br>    image: influxdb:1.8-alpine<br>    container_name: influxdb<br>    restart: always<br>    environment:<br>      - INFLUXDB_DB=influx<br>      - INFLUXDB_ADMIN_USER=admin<br>      - INFLUXDB_ADMIN_PASSWORD=admin<br>    ports:<br>      - &#39;8086:8086&#39;<br>    volumes:<br>      - influxdb_data:/var/lib/influxdb<br><br>  grafana:<br>    image: grafana/grafana<br>    container_name: grafana-server<br>    restart: always<br>    depends_on:<br>      - influxdb<br>    environment:<br>      - GF_SECURITY_ADMIN_USER=admin<br>      - GF_SECURITY_ADMIN_PASSWORD=admin<br>      - GF_INSTALL_PLUGINS=<br>    links:<br>      - influxdb<br>    ports:<br>      - &#39;3000:3000&#39;<br>    volumes:<br>      - grafana_data:/var/lib/grafana<br><br>volumes:<br>  grafana_data: {}<br>  influxdb_data: {}</pre><p>Telegraf.config file</p><pre>[global_tags]<br><br>[agent]<br>  interval =           &quot;60s&quot;<br>  round_interval = true<br>  metric_batch_size = 1000<br>  metric_buffer_limit = 10000<br>  collection_jitter = &quot;0s&quot;<br>  flush_interval = &quot;10s&quot;<br>  flush_jitter = &quot;0s&quot;<br>  precision = &quot;&quot;<br>  hostname = &quot;127.0.0.1&quot;<br>  omit_hostname = false<br><br>[[outputs.influxdb]]<br>  urls = [&quot;http://influxdb:8086&quot;]<br>  database = &quot;influx&quot;<br>  timeout = &quot;5s&quot;<br>  username = &quot;telegraf&quot;<br>  password = &quot;metricsmetricsmetricsmetrics&quot;<br><br><br>[[inputs.cpu]]<br>  percpu = true<br>  totalcpu = true<br>  collect_cpu_time = false<br>  report_active = false<br><br><br>[[inputs.disk]]<br>  ignore_fs = [&quot;autofs&quot;, &quot;binfmt_misc&quot;, &quot;cgroup&quot;, &quot;configfs&quot;, &quot;debugfs&quot;, &quot;devfs&quot;, &quot;devtmpfs&quot;, &quot;devpts&quot;, &quot;fusectl&quot;, &quot;fuse.lxcfs&quot;, &quot;hugetlbfs&quot;, &quot;lxcfs&quot;, &quot;mqueue&quot;, &quot;none&quot;, &quot;nsfs&quot;, &quot;overlay&quot;, &quot;pstore&quot;, &quot;shm&quot;, &quot;sysfs&quot;, &quot;systemd-1&quot;, &quot;tracefs&quot;, &quot;tmpfs&quot;]<br><br><br>[[inputs.diskio]]<br><br>[[inputs.kernel]]<br><br>[[inputs.mem]]<br><br>[[inputs.processes]]<br><br>[[inputs.swap]]<br><br>[[inputs.system]]<br><br><br><br># Read metrics about docker containers<br>[[inputs.docker]]<br> <br>  endpoint = &quot;unix:///var/run/docker.sock&quot;<br><br>  <br>  gather_services = false<br><br>  container_names = []<br><br>  ## Set the source tag for the metrics to the container ID hostname, eg first 12 chars<br>  source_tag = false<br><br>  ## Containers to include and exclude. Collect all if empty. Globs accepted.<br>  container_name_include = []<br>  container_name_exclude = []<br>  ## example: container_state_include = [&quot;created&quot;, &quot;restarting&quot;, &quot;running&quot;, &quot;removing&quot;, &quot;paused&quot;, &quot;exited&quot;, &quot;dead&quot;]<br>  ## example: container_state_exclude = [&quot;created&quot;, &quot;restarting&quot;, &quot;running&quot;, &quot;removing&quot;, &quot;paused&quot;, &quot;exited&quot;, &quot;dead&quot;]<br>  container_state_include = [&quot;created&quot;, &quot;restarting&quot;, &quot;running&quot;, &quot;removing&quot;, &quot;paused&quot;, &quot;exited&quot;, &quot;dead&quot;]<br>#  container_state_exclude = [&quot;created&quot;, &quot;restarting&quot;, &quot;running&quot;, &quot;removing&quot;, &quot;paused&quot;, &quot;exited&quot;, &quot;dead&quot;]<br>  timeout = &quot;5s&quot;<br><br>  perdevice = true<br><br>  total = false<br><br>  docker_label_include = []<br>  docker_label_exclude = []<br><br>  ## Which environment variables should we use as a tag<br>  tag_env = [&quot;JAVA_HOME&quot;, &quot;HEAP_SIZE&quot;]</pre><p><strong>Running the stack</strong><br>After creating all this, you can run the following in the same directory where your Docker Compose file is located at.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IDvbW6fLPbTOaaMewBSVxA.png" /></figure><p>You will be able to access Grafana on &lt;your-machines-ip&gt;:3000 , with the default credentials:</p><pre>Username: admin<br>Password: admin</pre><p>Once logged in it should look similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v6oSza_8OzJmG_RS4_B6-w.png" /></figure><h3>Add the Data source</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1BeFpDslLfFmQXvvlw_-3Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SnWv14s170fLuoookkzZ7A.png" /><figcaption>Add the database name, user, password which we have added in docker-compose file</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ERCLVSzTDxuyevxR2Q9ESQ.png" /></figure><blockquote><em>NOTE:</em> If you receive same error then do flowing step on server</blockquote><pre>cd /var/run<br>sudo chmod 666 docker.sock</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V72EHvwFfDYUHnViNCajTw.png" /></figure><h3>Create New Dashboard from Scratch</h3><p>On the Grafana home page, click on New dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hBmxVceJJp1zI-Ev1_igNQ.png" /></figure><p><strong>Query:</strong> To get total number of container</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bxT7xw43oWL0Fb-RPkbNJA.png" /></figure><p><strong>Query: </strong>Total Container Running</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EXaLcQtfdji1bSWUABbIzA.png" /></figure><p><strong>Query: </strong>Total Images</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BUTOL-nmw85pWXZeYD2lnA.png" /></figure><p><strong>Query: </strong>Total Stopped Container</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m59V4DBgyCoV-KJ51TgoRw.png" /></figure><p><strong>Query: </strong>Name of Container Running</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AZkr8cUoUNlvcnjhRCa7Dg.png" /></figure><p><strong>Query: </strong>Stop Container Name</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yl-AMO-DEgmKOuyJ7o_pmQ.png" /></figure><p><strong>Query: </strong>Container Up time</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jy1tAi4Z71GxexQckCmgrw.png" /></figure><p><strong>Query: </strong>Memory Usage</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CfToWjYchJh2OyuM6ohfMg.png" /></figure><p>Finally the dashboard look like this!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*miKIzgqEsyIHCpHLrPLwzg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u1auvbfYfVJB75elxQd0WQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7d6c5dd77d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automated ci/cd pipeline for your java project and deployed to Aws cloud with ASG and ALB]]></title>
            <link>https://medium.com/@kaushikkp03/automated-ci-cd-pipeline-for-your-java-project-and-deployed-to-aws-cloud-with-asg-and-alb-26827392863a?source=rss-edde9899a6cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/26827392863a</guid>
            <dc:creator><![CDATA[Kaushikkp]]></dc:creator>
            <pubDate>Sun, 23 Apr 2023 09:40:35 GMT</pubDate>
            <atom:updated>2023-04-24T08:07:47.783Z</atom:updated>
            <content:encoded><![CDATA[<h3>Automated ci/cd pipeline for java project and deployed to Aws cloud with ASG and ALB</h3><p>Automated ci/cd pipeline for your java project using Jenkins, docker, and aws. With this pipeline, your project will be automatically built, tested, and deployed to your aws ec2 instance every time you push code to your GitHub repository</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*YjFLHxad1ZUQBqAUI7d7eQ.png" /></figure><p>Deploying a project on AWS Cloud involves several steps in its workflow, starting from designing and developing the application to testing, deployment, and maintenance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4wWfsTbvazwEQAYVK49eTA.png" /></figure><p><strong>Prerequisite:</strong></p><p>GitHub and Docker Hub account</p><p>AWS account and knowledge of EC2 Instances</p><p>Knowledge of Jenkins, Docker, and Maven, Aws cloud computing</p><h3>Create a AWS VPC.</h3><ol><li>Create a VPC with an IPv4 CIDR of 10.10.0.0/16</li><li>Create three public subnets with 10.10.1.0/24 &amp; 10.10.2.0/24 &amp; 10.10.3.0/24</li><li>Create an Application Load Balancer to distribute traffic to the autoscaling group.</li><li>Create web server security group that allows inbound traffic from HTTP from your Application Load Balancer.</li></ol><h3>Step 1: Create a VPC with an IPv4 of CIDR 10.10.0.0/16</h3><ol><li>Login to the AWS console making sure that the Region is set to us-east-1, navigate to the VPC dashboard and click on create VPC.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*k5rFHugg_B67FV15hfNf_Q.png" /></figure><p>2. Under VPC settings, give your VPC a name and enter the IPv4 CIDR then</p><p>click on create VPC</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*9B50y5fRTrd-RuzvlARmMA.png" /></figure><h3>Step 2: Create three public subnets with the IPv4 CIDR blocks: 10.10.1.0/24, 10.10.2.0/24 and 10.10.3.0/24 respectively</h3><p>Within the VPC console, on the left click on subnets, you will see many subnets in your account including those of the default VPC. We will create our own new subnets for the new VPC.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z8mNjkkoH1p9KgN0qyrvAw.png" /></figure><ol><li>Click on create subnet, under VPC ID, select our subnet, you will see the name we gave it (DEMO-VPC)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gNXhHP-82hH3Z5x_fhTVIQ.png" /></figure><p>2. To create our first subnet, give it a name, select an Availability Zone (AZ) and enter the IPv4 CIDR block for each subnet. We will create our the subnets with the following information:</p><blockquote>Subnet Name: sb-public-A | AZ: US East (Ohio) / us-east-2a | IPv4 CIDR: 10.10.1.0/24</blockquote><blockquote>Subnet Name: sb-public-B | AZ: US East (Ohio) us-east-2b | IPv4 CIDR:10.10.2.0/24</blockquote><blockquote>Subnet Name: sb-public-C | AZ: US East (Ohio) us-east-2c | IPv4 CIDR: 10.10.3.0/24</blockquote><p>3. Enter the information for your first subnet then click on ‘Add new subnet’ for each subsequent subnet. Once you have entered the information for all threes subnets, click ‘Create subnet’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*DAOwADxmJoQRSFV22vZATw.png" /></figure><h3>Step 3: Attach an Internet Gateway to the custom VPC</h3><ol><li>Under the VPC → Internet gateways, click ‘Create internet gateway’</li><li>Give the internet gateway a name and click on ‘Create internet gateway’</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*H43V-ALLlgXWkCvYEh7VhQ.png" /></figure><p>3. Attach the internet gateway to the VPC</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jk4KrbKs6-giUyumP7Y1Iw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*aSsjUoamrt0oZ9SWLM48uA.png" /></figure><h3>Step 4: Make our subnets public! Configure a route table and routes to our internet gateway</h3><ol><li>Under VPC → Route tables, click ‘Create route table’. Give the route table the name ‘DEMO-pub-rt’. For VPC, select our VPC from the dropdown list.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*-9blCk__H2w-GciCeHtS8Q.png" /></figure><p>Great! We now have a route table. We now need to explicitly associate our subnets with this route table. To do so, we’ll need to edit the subnet associations.</p><p>2. Click on the ‘Subnet associations’ tab, then click ‘Edit subnet associations’, select the three subnets and then save associations</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*gHzsys89_qOwP-Zli5gemA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SHC86LPSa08FQ_v4Sd2c1g.png" /></figure><p>Now we need to create a route to the Internet gateway.</p><p>3. Click on the Routes tab, edit routes then add route. We need to add a route to the internet. Where the destination is 0.0.0.0/0 and the target is the Internet gateway.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7zonkv6zksQ13rafez-STA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D5y5cYvHnEe5LhTrw498-g.png" /></figure><p>4. Add the route, set the target as the internet gateway then click ‘Save changes’.</p><p>Excellent! This means that any IPv4 traffic that is not destined to the VPC CIDR range 10.10.0.0/16 will be sent to the Internet gateway.</p><h3>Step 5: Automatically assign any resources launched into our public subnets with IPv4 addresses</h3><ol><li>Under VPC → Subnets select each subnet (one by one), click on ‘edit subnet settings’. Under ‘Auto-assign IP settings’, check the box for ‘Enable auto-assign public IPv4 address’ then click save.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JZSDeOXjgQGn5ZQIsJ3CNA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*3Vz32ZwyxJofWLzWEMeIGQ.png" /></figure><h3>Step 6: Create a Security Group</h3><ol><li>Navigate to the EC2 console → Security Groups</li><li>Create a Security Group; for name and description, write ‘SG-DEMO-vpc-1’</li><li>For the security group inbound rules. Allow SSH from ‘Anywhere’ (this is not best practice, however, for the purpose of connecting to the instance via EC2 Instance Connect. In your case, make sure its allow SSH traffic from only your IP address) and allow HTTP traffic from ‘Anywhere’ (0.0.0.0/0)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3fZOixbWWst7FNkpYaUnjw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Danrt1w5nu62K80wm8Mzew.png" /></figure><h3><strong>Create a EC2 instance on which our website is Going to be Deploy.</strong></h3><ol><li>Select the region on which our instance is going to be create in this case I have create a vpc in Ohio region so make sure to select the specific region.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*Nq5oFnqvtxZ2QzVxKIziNw.png" /></figure><p>2. Give the Server name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*ZSTrnd_ClvoFtBrAHRz-5w.png" /></figure><p>3. This step we have to select the OS for our server, so I have select the ubuntu 20.04 AMI</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c_JmxHoV_9_kizbJocTZdA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c_If6QQmHU1IxR3aATAImw.png" /></figure><p>4. Create a new key pair select .pem to connect instance using ssh connection and click on create key pair</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*4LbhTXuZpHcqbHRdBKHppA.png" /></figure><p>5. In Network Setting click on edit button and select the vpc which we have create in above configuration and also select the security groups which we have create</p><p>Select existing security group &gt; your created SG-group</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*XL2nOsI3YNyIr3rj-z4H1Q.png" /></figure><p>6. Finally, after all setup click on launch instance button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E09umFwzQkIZfisU_yLvFg.png" /></figure><h3>Automated CI/CD pipeline for Java Project</h3><p>we will be creating an automated CI/CD pipeline for your Java project using Jenkins, Docker, and AWS. With this pipeline, your project will be automatically built, tested, and deployed to your AWS EC2 instance every time you push code to your GitHub repository.</p><p><strong>Prerequisite:</strong></p><p>· GitHub and Docker Hub account</p><p>· AWS account and knowledge of EC2 Instances</p><p>· Knowledge of Jenkins, Docker, and Maven</p><h3>Step 1: Setup Jenkins Server</h3><p>First set up the Jenkins server to create a pipeline. Launch an EC2 instance and install Java and Jenkins into it. You need to install Maven and Docker as well. Maven to build the Java project and Docker to build the docker image in Jenkins. SSH into your instance and install maven and Docker using the below commands. For Jenkins, I am using an Ubuntu instance.</p><pre># Install Maven in Jenkins<br>sudo apt-get install maven -y<br>## Update packages<br>sudo apt-get update<br>## Install Docker<br>sudo apt-get install docker.io -y<br>## Add Jenkins user to Docker group<br>sudo usermod -a -G docker jenkins</pre><h3>1.1. Install Plugins</h3><p>Install plugins to integrate Jenkins with GitHub, Maven, and EC2. Go to Manage Jenkins, and select Manage plugins. Under available plugins search for the below plugins and Install without restart</p><ol><li>Git</li><li>Pipeline maven integration</li><li>Pipeline stage view</li><li>SSH Agent</li><li>SonarQube</li></ol><h3>1.2. Configure Java and Maven in Jenkins</h3><p>Go to Manage Jenkins, select Global tool configuration, and scroll down to add JDK and Maven path that we exported in the above steps as shown below. Uncheck the Install automatically checkbox, Give Name and Path and click Save.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*rvURCNaaI7y-vgUsc1PNEA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*uJYa2suIlP9YgIWn3wBDvw.png" /></figure><h3>Step 2: Add DockerHub credential in Jenkins</h3><p>To build and push the Docker image to DockerHub, we need to add docker credentials in Jenkins. Go to your DockerHub account and select the dropdown near username and click Account settings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*ow97q_NucyEhJ34jqJKifA.png" /></figure><p>Click Security in the left panel and click New Access Token. Give a description and click Generate. Copy the token and close. Keep this token as we will be adding this to the Jenkins credential in the next steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*LGfzSoMi7fqJRr7Mn1064A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*fBMfFAGcHWCzCB8pYno7JQ.png" /></figure><p>Go to the Jenkins dashboard -&gt; Manage Jenkins -&gt; Manage credentials. Click System -&gt; Global credentials and then click Add credentials. Select the kind as Username and Password and enter your DockerHub username and enter the token in Password that we have generated in dockerHub. Give the ID and description of your choice but remember this ID as we will be using it in Jenkinsfile and click Create.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*Mv2WGHnsNoCGtDPZzIF8IQ.png" /></figure><h3>2.1. Create a Repository in DockerHub</h3><p>Go to the DockerHub registry, select Repositories and click Create repository. Give a name to the repository and select visibility as Public and click Create.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*ElPNHor3JoSq8AcAt63xzw.png" /></figure><h3>Step 3: Setup Docker in EC2 Instance</h3><p>Launch an EC2 instance and install docker into it. Open port 22 to SSH into the instance and open port 8007 as I will be exposing my Java application to port 8081. After successful deployment, you will be able to access the application in the browser using DNS of Application Load balancer</p><p>I have launched the Ubuntu 20.04 instance and setup Docker using the below commands:</p><pre># Update packages<br>sudo yum update<br># Install Docker<br>sudo yum install docker<br># Add ec2-user to Docer group<br>sudo usermod -a -G docker ec2-user<br># Enable docker service at AMI boot time<br>sudo systemctl enable docker.service<br># Start the Docker service<br>sudo systemctl start docker.service</pre><h3>3.1. Add EC2 credentials in Jenkins</h3><p>Go to Jenkins Dashboard -&gt; Manage Jenkins -&gt; Manage Credentials. Click on Global and Add Credentials and select SSH Username with the private key under Kind. Enter the ID and Description of your choice. Make note of this ID as we will be using it in Jenkinsfile. Enter the username of the EC2 instance that you have launched. For the Amazon Linux instance, the username is ec2-user. Select Enter directly and click Add and copy-paste the private key that you have created while launching an instance and click Create.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*JmDdQZnUMwAluGIpNfADoA.png" /></figure><h3>Step 4: Write Jenkinsfile and Dockerfile</h3><p>Write Jenkinsfile with all the below steps to fetch, build, test and deploy Java application. Remember to add the below Jenkinsfile in the root directory of your project in GitHub.</p><pre>pipeline {<br>  agent any<br><br>  environment {<br>    DOCKERHUB_CREDENTIALS = credentials(&#39;dockerHUb&#39;)<br>    REMOTE_SERVER = &#39;18.117.71.25&#39;<br>    REMOTE_USER = &#39;ubuntu&#39;            <br>  }<br><br>  // Fetch code from GitHub<br><br>  stages {<br>    stage(&#39;project clone&#39;) {<br>      steps {<br>        git branch: &#39;master&#39;, url: &#39;https://gitlab.com/kaushik1391/java-todo-list-d.git&#39;<br><br>      }<br>    }<br><br>   // Build Java application<br><br>    stage(&#39;Maven Build&#39;) {<br>      steps {<br>        sh &#39;mvn clean install&#39;<br>      }<br><br>     // Post building archive Java application<br><br>      post {<br>        success {<br>          archiveArtifacts artifacts: &#39;**/target/*.jar&#39;<br>        }<br>      }<br>    }<br><br>  // Test Java application<br><br>    stage(&#39;Maven Test&#39;) {<br>      steps {<br>        sh &#39;mvn test&#39;<br>      }<br>    }<br><br>    stage(&quot;sonarblock&quot;){<br>            steps{<br>                withSonarQubeEnv(credentialsId: &#39;1030b002-0530-414b-8585-168d81582fd5&#39;, installationName:&#39;sonarserver1&#39;) {<br>                // sh &quot;${scannerHome}/bin/sonar-scanner&quot;<br>                sh &#39;mvn clean package sonar:sonar&#39;<br>                }<br>            }<br>        }<br><br>   // Build docker image in Jenkins<br><br>    stage(&#39;Build Docker Image&#39;) {<br><br>      steps {<br>        sh &#39;docker rmi javachecklist:v1 || true&#39;<br>        sh &#39;docker build -t javachecklist:v1 .&#39;<br>        sh &#39;docker tag javachecklist:v1 kaushik1391/checklist:v1.1&#39;<br>      }<br>    }<br><br>   // Login to DockerHub before pushing docker Image<br><br>    stage(&#39;Login to DockerHub&#39;) {<br>      steps {<br>        sh &#39;echo $DOCKERHUB_CREDENTIALS_PSW | docker login -u    $DOCKERHUB_CREDENTIALS_USR --password-stdin&#39;<br>      }<br>    }<br><br>   // Push image to DockerHub registry<br><br>    stage(&#39;Push Image to dockerHUb&#39;) {<br>      steps {<br>        sh &#39;docker push kaushik1391/checklist:v1.1&#39;<br>      }<br>      post {<br>        always {<br>          sh &#39;docker logout&#39;<br>        }<br>      }<br><br>    }<br><br>   // Pull docker image from DockerHub and run in EC2 instance <br><br>    stage(&#39;Deploy Docker image to AWS instance&#39;) {<br>      steps {<br>        script {<br>          sshagent(credentials: [&#39;aws-javaserver&#39;]) {<br>          sh &quot;ssh -o StrictHostKeyChecking=no ${REMOTE_USER}@${REMOTE_SERVER} &#39;docker stop javachecklist || true &amp;&amp; docker rm javachecklist || true&#39;&quot;<br>          sh &quot;ssh -o StrictHostKeyChecking=no ${REMOTE_USER}@${REMOTE_SERVER} &#39;docker rmi kaushik1391/checklist:v1.1 || true&#39;&quot;<br>          sh &quot;ssh -o StrictHostKeyChecking=no ${REMOTE_USER}@${REMOTE_SERVER} &#39;docker pull kaushik1391/checklist:v1.1&#39;&quot;<br>          sh &quot;ssh -o StrictHostKeyChecking=no ${REMOTE_USER}@${REMOTE_SERVER} &#39;docker run --name javachecklist -d -p 8081:8081 kaushik1391/checklist:v1.1&#39;&quot;<br>          }<br>        }<br>      }<br>    }<br>  }<br>}</pre><p>Docker File</p><pre>FROM adoptopenjdk/openjdk11<br>FROM maven:3.6.3-jdk-11<br>WORKDIR /home/training/kaushik/todo-spring-back<br>COPY . .<br>RUN mvn clean install<br>RUN ls /home/training/kaushik/todo-spring-back/target/<br><br>CMD [ &quot;java&quot;,&quot;-jar&quot;,&quot;/home/training/kaushik/todo-spring-back/target/todo-spring-back-0.0.1-SNAPSHOT.jar&quot; ]</pre><h3>Step 5: Create a Jenkins pipeline</h3><p>Go to Jenkins Dashboard click New Item -&gt; Give a name to the pipeline -&gt; Select Pipeline -&gt; Click Ok</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*nBZMj4jdVXa2TXqfgvB5NA.png" /></figure><p>The Jenkins pipeline run successfully and the docker image got deployed to the EC2 instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*XxII_EV_ENELa7cCCJUhKA.png" /></figure><p>Sonar Scan the project and deployed to EC2 instance</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*iZuKfkl5HVJhgUAsTp1zjg.png" /></figure><h3>Step 6: After successfully deployed on EC2 connect using SSH</h3><p>After connect write a shell script and set that shell script on Crontab, because when ever the new instance get launch by auto scaling the crontab will run the script and the website will be up in new instance (start.sh)</p><p>nano start.sh</p><pre>#!bin/bash<br>docker start javachecklist</pre><p>Set this shell script in crontab</p><pre>@reboot sh /home/ubuntu/start.sh &gt;/dev/null 2&gt;&gt;/home/ubuntu/some.log</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*8RebjNf7Jk9HZtJgruPprQ.png" /></figure><h3>Create a Aws infrastructure</h3><h4>Step 1: Create a AMI of our EC2 instance</h4><p>Select the instance on which we have deployed for website.and click on &gt; Action &gt; Image and template &gt; create image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*n3YuPaNU27rl7_HkR8D8Hg.png" /></figure><h4>Step 2: After create an AMI wait for few minutes to became status active.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*O8TzkLqURJDNoXaqmgFi3Q.png" /></figure><h4>Step 3: Create a Launch Template for Auto Scaling Group</h4><p>Now we have to create a Launch template of our AMI. This Launch template will be use in our Auto scaling group</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*IvO-34jNhUgnJ63Ag2Gs5w.png" /></figure><h4>Step 4:Select the AMI which we have create</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*FMxKbJq-n7GsqZoam0vGeA.png" /></figure><h4>Step 5: Choose the instance type and key pair</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*vjghtrosbhZwoiU1nFxCtw.png" /></figure><h4>Step 6: Select the Subnet which we have create in Vpc and select the security group we have create in early steps.</h4><p>After doing this step click on Launch template.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*azOWC1DIIZ5KhA-0JL-CHg.png" /></figure><h3>Create Auto Scaling Group and Application Load Balancer</h3><h4>Step 1: Create an Auto-Scaling Group (ASG)</h4><p>1. Name the ASG ‘java-service-ASG’</p><p>2. For Launch template, select our launch template from the dropdown list (template-java-service)</p><p>3. For version, select Latest. (Launch templates can be modified and versioned, this is very useful). Click Next</p><p>4. Under Network &gt; VPC, select our VPC (DEMO-VPC)</p><p>5. Select all three Availability Zones and subnets:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*TFHfIGtboubpVM5D_EY2ZQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*QAUSM07DgUnLKva3Y6eKKw.png" /></figure><h4>Step 2: To attach a load balancer click on ‘Attach to a new load balancer’ and select Application Load Balancer and After that select internet-facing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*nmZugCxRBXl1Krf9R7wiOQ.png" /></figure><h4>Step 3: Select the port and click on create a target group there will auto generate target group</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*ts9gotyTV8IMkebAXEpQMA.png" /></figure><h4>Step 4: Under Health check types, check the box for ELB in addition to the EC2 health checks the click next. Under group size. Specify the size of the Auto scaling group. Set the desired capacity to 1, the minimum capacity to 1 and the maximum capacity to 8</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*dbKodlhMNLrExj8O78JFFw.png" /></figure><h4>Step 5: Select the target tracking scaling policy and Average CPU utilization with target value 40 and click on Next.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*rNUBiVbPZTgSfgEVr9q5kg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N5IgmHXqk3k9wpKzcKKmTw.png" /></figure><blockquote>We can Accsess the website using this DNS:- ALB-java-1303581534.us-east-2.elb.amazonaws.com</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q2axcP9P1TlQHBxdL-meVw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26827392863a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>