<?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 Shubham Soni on Medium]]></title>
        <description><![CDATA[Stories by Shubham Soni on Medium]]></description>
        <link>https://medium.com/@surajsoni3332?source=rss-5923bdda6c4a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*l0zFW4ay6yvZm1Qe8xhkjA.jpeg</url>
            <title>Stories by Shubham Soni on Medium</title>
            <link>https://medium.com/@surajsoni3332?source=rss-5923bdda6c4a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 03:39:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@surajsoni3332/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[Setting Up ELK Stack on Kubernetes: A Step-by-Step Guide]]></title>
            <link>https://surajsoni3332.medium.com/setting-up-elk-stack-on-kubernetes-a-step-by-step-guide-227690eb57f4?source=rss-5923bdda6c4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/227690eb57f4</guid>
            <dc:creator><![CDATA[Shubham Soni]]></dc:creator>
            <pubDate>Thu, 16 May 2024 11:08:59 GMT</pubDate>
            <atom:updated>2024-05-16T11:08:59.976Z</atom:updated>
            <content:encoded><![CDATA[<p>In the world of modern DevOps, the ELK stack (Elasticsearch, Logstash, and Kibana) has become an essential tool for log management and analysis. Combining the power of ELK with the scalability of Kubernetes (k8s) can significantly enhance your logging capabilities. This guide will walk you through the process of setting up an ELK stack on a Kubernetes cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LXIDmftDCGGPY4WvMjRJrw.jpeg" /></figure><h3>Table of Contents</h3><ol><li>Introduction</li><li>Prerequisites</li><li>Setting Up Elasticsearch</li><li>Setting Up Kibana</li><li>Deploying Filebeat</li><li>Deploying Logstash</li><li>Configuring and Launching Kibana</li></ol><h3>1. Introduction</h3><p>In today’s world of microservices and distributed systems, effective logging and monitoring are crucial for maintaining the health and performance of your applications. The ELK stack — comprising Elasticsearch, Logstash, and Kibana — along with Filebeat, provides a powerful solution for aggregating and analyzing log data. In this blog, we will walk through the steps to set up the ELK stack with Filebeat on a Kubernetes cluster.</p><h3>2. Prerequisites</h3><p>Before we begin, ensure you have the following:</p><ul><li>A running Kubernetes cluster (Minikube, EKS, GKE, etc.).</li><li>kubectl command-line tool configured to interact with your cluster.</li><li>Lens software to connect and see all the information related to the cluster.</li></ul><h3>Install Operator</h3><p>Things to consider before you start:</p><p>Install <a href="https://kubernetes.io/docs/concepts/extend-kubernetes/api-extension/custom-resources/">custom resource definitions</a> and Install the operator with its RBAC rules:</p><pre>kubectl create -f https://download.elastic.co/downloads/eck/2.2.0/crds.yaml<br>kubectl apply -f https://download.elastic.co/downloads/eck/2.2.0/operator.yaml</pre><h3>{MAKE SURE ALL YOUR RESOURCES ARE OF THE SAME VERSION THAT IS ELASTICSEARCH, KIBANA, LOGSTASH &amp; FILEBEAT. }</h3><h3>3: Setting Up Elasticsearch</h3><p>First, we’ll deploy Elasticsearch, which will store our log data. For this I am using a YAML file in which I have mention all the details for the Elasticsearch called “elasticsearch.yaml” as below.</p><pre>apiVersion: elasticsearch.k8s.elastic.co/v1<br>kind: Elasticsearch<br>metadata:<br>  name: quickstart<br>spec:<br>  version: 8.13.4<br>  nodeSets:<br>  - name: default<br>    count: 1<br>    config:<br>      node.store.allow_mmap: false</pre><p>After creating the script file we have to apply this YAML file by applying the below command on Lens or Terminal</p><pre>kubectl apply -f elasticsearch.yaml</pre><p>To monitor cluster health and creation progress apply this command:</p><pre>kubectl get elasticsearch</pre><p>Request Elasticsearch access</p><p>A ClusterIP Service is automatically created for your cluster:</p><pre>kubectl get service quickstart-es-http</pre><p>3.1: Get the credentials.</p><p>A default user named elastic is automatically created with the password stored in a Kubernetes secret:</p><pre>PASSWORD=$(kubectl get secret quickstart-es-elastic-user -o go-template=&#39;{{.data.elastic | base64decode}}&#39;)</pre><p>3.2: Request the Elasticsearch endpoint.</p><p>From inside the Kubernetes cluster:</p><pre>curl -u &quot;elastic:$PASSWORD&quot; -k &quot;https://quickstart-es-http:9200&quot;</pre><p>From your local workstation, use the following command in a separate terminal:</p><pre>kubectl port-forward service/quickstart-es-http 9200</pre><p>Then request localhost:</p><pre>curl -u &quot;elastic:$PASSWORD&quot; -k &quot;https://localhost:9200&quot;</pre><p>Or Open https://localhost:9200 in your browser. Your browser will show a warning because the self-signed certificate configured by default is not verified by a known certificate authority and not trusted by your browser. You can temporarily acknowledge the warning for the purposes of this quick start but it is highly recommended that you <a href="https://www.elastic.co/guide/en/cloud-on-k8s/current/k8s-tls-certificates.html#k8s-setting-up-your-own-certificate">configure valid certificates</a> for any production deployments.</p><p>Login as the elastic user and password is stored in lens (Your Cluster) -&gt; Config -&gt; Secrets -&gt; (keys = elastic).</p><h3>4: Setting Up Kibana</h3><p>Kibana provides a web interface to visualize logs stored in Elasticsearch. For that create a Kibana instance and associate it with your Elasticsearch cluster and for that create a YAML file “kibana.yaml” as mentioned below</p><pre>apiVersion: kibana.k8s.elastic.co/v1<br>kind: Kibana<br>metadata:<br>  name: quickstart<br>spec:<br>  version: 8.13.4<br>  count: 1<br>  elasticsearchRef:<br>    name: quickstart<br>  # http:<br>  #   tls:<br>  #     selfSignedCertificate:<br>  #       disabled: true</pre><p>After creating the script file we have to apply this YAML file by applying the below command on Lens terminal:</p><pre>kubectl apply -f kibana.yaml</pre><p>4.1: Monitor Kibana health and creation progress.</p><p>Similar to Elasticsearch, you can retrieve details about Kibana instances:</p><pre>kubectl get kibana</pre><p>4.2: To access Kibana.</p><p>A ClusterIP Service is automatically created for Kibana:</p><pre>kubectl get service quickstart-kb-http</pre><p>Use kubectl port-forward to access Kibana from your local workstation:</p><pre>kubectl port-forward service/quickstart-kb-http 5601</pre><p>Open https://localhost:5601 in your browser. Your browser will show a warning because the self-signed certificate configured by default is not verified by a known certificate authority and not trusted by your browser. You can temporarily acknowledge the warning for the purposes of this quick start but it is highly recommended that you <a href="https://www.elastic.co/guide/en/cloud-on-k8s/current/k8s-tls-certificates.html#k8s-setting-up-your-own-certificate">configure valid certificates</a> for any production deployments.</p><p>Login as the elastic user. The password can be obtained with the following command:</p><pre>kubectl get secret quickstart-es-elastic-user -o=jsonpath=&#39;{.data.elastic}&#39; | base64 --decode; echo</pre><h3>5: Deploying Filebeat</h3><p>Filebeat is a lightweight shipper for forwarding and centralizing log data. Apply the following specification to deploy Filebeat and collect the logs of all containers running in the Kubernetes cluster.</p><p>For that create a filebeat instance and for that create a YAML file “filebeat.yaml” as mentioned below:</p><pre>apiVersion: beat.k8s.elastic.co/v1beta1<br>kind: Beat<br>metadata:<br>  name: quickstart<br>spec:<br>  type: filebeat<br>  version: 8.13.4<br>  # elasticsearchRef:<br>  #   name: quickstart<br>  # kibanaRef:<br>  #   name: kibana<br>  config:<br>    filebeat.inputs:<br>    - type: container<br>      paths:<br>      - /var/log/containers/*.log<br>      processors:<br>        - add_kubernetes_metadata:<br>            host: ${NODE_NAME}<br>            matchers:<br>            - logs_path:<br>                logs_path: &quot;/var/log/containers/&quot;<br>        - drop_event.when:<br>            or:<br>            - equals:<br>                kubernetes.namespace: &quot;kube-system&quot;<br>            - equals:<br>                kubernetes.namespace: &quot;kube-public&quot;  <br>            - equals:<br>                kubernetes.namespace: &quot;quickstart&quot;<br>            - equals:<br>                kubernetes.namespace: &quot;kube-node-lease&quot;<br>            - equals:<br>                kubernetes.namespace: &quot;elastic-system&quot;<br>    output.logstash:<br>      hosts: [&quot;logstash.logging.svc:5044&quot;]<br>  daemonSet:<br>    podTemplate:<br>      spec:<br>        serviceAccountName: filebeat<br>        automountServiceAccountToken: true<br>        terminationGracePeriodSeconds: 30<br>        tolerations:<br>        - key: dedicated<br>          operator: Exists<br>          effect: NoSchedule       <br>        dnsPolicy: ClusterFirstWithHostNet<br>        hostNetwork: true # Allows to provide richer host metadata<br>        containers:<br>        - name: filebeat<br>          securityContext:<br>            runAsUser: 0<br>            # If using Red Hat OpenShift uncomment this:<br>            #privileged: true<br>          volumeMounts:<br>          - name: varlogcontainers<br>            mountPath: /var/log/containers<br>          - name: varlogpods<br>            mountPath: /var/log/pods<br>          - name: varlibdockercontainers<br>            mountPath: /var/lib/docker/containers<br>          env:<br>            - name: NODE_NAME<br>              valueFrom:<br>                fieldRef:<br>                  fieldPath: spec.nodeName<br>          resources:<br>            limits:<br>              cpu: 500m<br>              memory: 2000Mi<br>            requests:<br>              cpu: 100m<br>              memory: 200Mi<br>        volumes:<br>        - name: varlogcontainers<br>          hostPath:<br>            path: /var/log/containers<br>        - name: varlogpods<br>          hostPath:<br>            path: /var/log/pods<br>        - name: varlibdockercontainers<br>          hostPath:<br>            path: /var/lib/docker/containers<br> <br>---<br> <br>apiVersion: rbac.authorization.k8s.io/v1<br>kind: ClusterRole<br>metadata:<br>  name: filebeat<br>rules:<br>- apiGroups: [&quot;&quot;] # &quot;&quot; indicates the core API group<br>  resources:<br>  - namespaces<br>  - pods<br>  - nodes<br>  verbs:<br>  - get<br>  - watch<br>  - list<br> <br>---<br> <br>apiVersion: rbac.authorization.k8s.io/v1<br>kind: ClusterRoleBinding<br>metadata:<br>  name: filebeat<br>subjects:<br>- kind: ServiceAccount<br>  name: filebeat<br>  namespace: elk-test<br>roleRef:<br>  kind: ClusterRole<br>  name: filebeat<br>  apiGroup: rbac.authorization.k8s.io<br> <br>---<br> <br>apiVersion: v1<br>kind: ServiceAccount<br>metadata:<br>  name: filebeat</pre><p>After creating the script file we have to apply this YAML file by applying the below command on Lens terminal:</p><pre>kubectl apply -f filebeat.yaml</pre><p>5.1: Monitor Beats.</p><p>Retrieve details about the Filebeat.</p><pre>kubectl get beat</pre><p>5.2: Access logs of the filebeat Pods.</p><pre>kubectl logs -f quickstart-beat-filebeat-plr8h</pre><p>5.3: Access logs ingested by Filebeat.</p><p>You have two options:</p><ul><li>Follow the Elasticsearch deployment <a href="https://www.elastic.co/guide/en/cloud-on-k8s/current/k8s-deploy-elasticsearch.html">guide</a> and run:</li></ul><pre>curl -u &quot;elastic:$PASSWORD&quot; -k &quot;https://localhost:9200/filebeat-*/_search&quot;</pre><ul><li>Follow the Kibana deployment <a href="https://www.elastic.co/guide/en/cloud-on-k8s/current/k8s-deploy-kibana.html">guide</a>, log in and go to <strong>Kibana</strong> &gt; <strong>Discover</strong>.</li></ul><h3>6: Deploying Logstash</h3><p>Add the following specification to create a minimal Logstash deployment that will listen to a Beats agent or Elastic Agent configured to send to Logstash on port 5044, create the service and write the output to an Elasticsearch cluster named quickstart, created in the <a href="https://www.elastic.co/guide/en/cloud-on-k8s/current/k8s-quickstart.html">Elasticsearch quickstart</a>.</p><p>For that create a logstash instance and for that create a YAML file “logstash.yaml” as mentioned below:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: logstash<br>  labels:<br>    app.kubernetes.io/name: elasticsearch-logstash<br>    app.kubernetes.io/component: logstash<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app.kubernetes.io/name: elasticsearch-logstash<br>      app.kubernetes.io/component: logstash<br>  template:<br>    metadata:<br>      labels:<br>        app.kubernetes.io/name: elasticsearch-logstash<br>        app.kubernetes.io/component: logstash<br>    spec:<br>      containers:<br>        - name: logstash<br>          image: docker.elastic.co/logstash/logstash:8.13.4<br>          ports:<br>            - name: &quot;tcp-beats&quot;<br>              containerPort: 5044<br>          env:<br>            - name: ES_HOSTS<br>              value: &quot;https://quickstart-es-http.elk-test.svc:9200&quot;<br>            - name: ES_USER<br>              value: &quot;elastic&quot;<br>            - name: ES_PASSWORD<br>              valueFrom:<br>                secretKeyRef:<br>                  name: quickstart-es-elastic-user<br>                  key: elastic<br>          volumeMounts:<br>            - name: config-volume<br>              mountPath: /usr/share/logstash/config<br>            - name: pipeline-volume<br>              mountPath: /usr/share/logstash/pipeline<br>            # - name: ca-certs<br>            #   mountPath: /etc/logstash/certificates<br>            #   readOnly: true<br>      volumes:<br>        - name: config-volume<br>          configMap:<br>            name: logstash-config<br>        - name: pipeline-volume<br>          configMap:<br>            name: logstash-pipeline<br>        # - name: ca-certs<br>        #   secret:<br>        #     secretName: elasticsearch-es-http-certs-public<br> <br>---<br> <br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: logstash<br>  labels:<br>    app.kubernetes.io/name: elasticsearch-logstash<br>    app.kubernetes.io/component: logstash<br>spec:<br>  ports:<br>    - name: &quot;tcp-beats&quot;<br>      port: 5044<br>      targetPort: 5044<br>  selector:<br>    app.kubernetes.io/name: elasticsearch-logstash<br>    app.kubernetes.io/component: logstash</pre><p>The config maps defined in the following YAML file are given as volume in the logstash deployment yaml file named as “logstash-config.yaml” as mentioned below:</p><pre>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  name: quickstart<br>  labels:<br>    app.kubernetes.io/name: elasticsearch-logstash<br>    app.kubernetes.io/component: logstash<br>data:<br>  logstash.yml: |<br>    http.host: 0.0.0.0<br>    pipeline.ecs_compatibility: disabled<br>  pipelines.yml: |<br>    - pipeline.id: logstash<br>      path.config: &quot;/usr/share/logstash/pipeline/logstash.conf&quot;<br> <br>  log4j2.properties: |<br>    logger.logstashpipeline.name = logstash.inputs.beats<br>    logger.logstashpipeline.level = error<br> <br>---<br> <br>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  name: logstash-pipeline<br>  labels:<br>    app.kubernetes.io/name: elasticsearch-logstash<br>    app.kubernetes.io/component: logstash<br>data:<br>  logstash.conf: |<br>    input {<br>      beats {<br>        port =&gt; 5044<br>      }<br>    }<br>    filter {<br>      json {<br>        source =&gt; &quot;message&quot;<br>      }<br>      prune {<br>        whitelist_names =&gt; [ &quot;msg&quot; ]<br>      }<br>      mutate {<br>        rename =&gt; { &quot;msg&quot; =&gt; &quot;message&quot; }<br>      }<br>    }<br>    output {<br>      if [message]  =~ &quot;admission&quot; {<br>        elasticsearch {<br>          index =&gt; &quot;logstashadmission-%{+YYYY.MM.dd}&quot;<br>          hosts =&gt; [ &quot;${ES_HOSTS}&quot; ]<br>          user =&gt; &quot;${ES_USER}&quot;<br>          password =&gt; &quot;${ES_PASSWORD}&quot;<br>          cacert =&gt; &#39;/etc/logstash/certificates/ca.crt&#39;<br>        }<br>      }<br>    }</pre><p>After creating the script file we have to apply this YAML file by applying the below command on Lens terminal:</p><pre>kubectl apply -f logstash.yaml<br>kubectl apply -f logstash-config.yaml</pre><p>6.1: Check the status of Logstash</p><pre>kubectl get logstash</pre><h3>7: Accessing and Visualizing Logs in Kibana</h3><p>Once Filebeat is running and shipping logs, you can access Kibana to visualize the logs.</p><ol><li>Navigate to the Discover tab in Kibana.</li><li>Select the Filebeat index pattern (you may need to create this pattern if it’s your first time).</li><li>Explore your logs!</li></ol><h3>Conclusion</h3><p>Setting up the ELK stack with Filebeat on a Kubernetes cluster can greatly enhance your ability to monitor and troubleshoot your applications. With Elasticsearch storing your logs, Filebeat shipping them, and Kibana providing visualization, you have a powerful toolset at your disposal.</p><p>Thank you for reading….❤️❤️ I hope you learn something new.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=227690eb57f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deployment of Django app using Jenkins CI/CD Pipeline.]]></title>
            <link>https://surajsoni3332.medium.com/deployment-of-django-app-using-jenkins-ci-cd-pipeline-2ddf54971f03?source=rss-5923bdda6c4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ddf54971f03</guid>
            <dc:creator><![CDATA[Shubham Soni]]></dc:creator>
            <pubDate>Tue, 28 Nov 2023 10:35:24 GMT</pubDate>
            <atom:updated>2023-11-28T10:50:37.891Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>A new day, a new topic. Let’s learn along!😉</strong></p><p>In this story post, we will explore a DevOps project that involves deploying a Django notes app on an EC2 instance using Jenkins declarative CI/CD pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/0*SA3lcxDIDkwwcfux.jpeg" /><figcaption>Flow of CI/CD.</figcaption></figure><p>We will leverage Docker containers and Docker Hub for containerization and image management. The project focuses on automating the deployment process, ensuring seamless integration and delivery of the application.</p><h3>Prerequisites:</h3><p>Before diving into the project, let’s ensure that we have the necessary prerequisites.</p><p>1. First of all, go to the AWS portal, and create a new instance. As,</p><p>· Name: Jenkins-server</p><p>· AMI: ubuntu.</p><p>· Instance type: t2.micro (free tier).</p><p>· Key pair login: Create &gt; docker.pem.</p><p>· Allow HTTP (Anywhere).</p><p>· Allow HTTPS (Anywhere).</p><p>(Download the .pem file.)</p><p>Click on Launch Instance, then connect to the EC2 instance and install following packages:</p><pre>#update all the pre-installed packages<br>$ sudo apt-get update</pre><p>2. <a href="https://docs.docker.com/engine/install/">Docker installation</a> ,</p><p>3. Openjdk-17-jre</p><pre>sudo apt install openjdk-17-jre</pre><p>4. <a href="https://www.jenkins.io/doc/book/installing/">Jenkins installation</a></p><p>5. Docker compose-</p><pre>sudo apt-get install docker-compose`</pre><p>Make sure you have this Installed on your system.</p><p>Additionally, we need to add users to the Docker group to grant them appropriate permissions. Run the following commands to add users to the Docker group:</p><pre>sudo usermod -aG docker $USER<br>sudo usermod -aG docker jenkins<br>sudo reboot</pre><p>Remember to reboot the system after making these changes.</p><p>To verify whether these packages are installed on your server or not, you may use:</p><pre>java --version <br><br>jenkins --version<br><br>docker --version<br><br>docker-compose --version</pre><ul><li>Now, we will allow “Inbound Rule” ports 8080 and 8000 for this machine from a security group. We can find the security group in the ec2 instance description.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P9fwCoIfL2jdLwJ2o8U95A.png" /><figcaption>Edit the Security groups here.</figcaption></figure><ul><li>Now, Copy the &lt; Public Ip:8080 &gt; of the machine and paste it to the browser to access the Jenkins portal.</li><li>We need an Administrator Password to unlock this. Run the following command</li><li>cat /var/lib/jenkins/secrets/initialAdminPassord`</li><li>Now Click on, “Install Suggested Plugins”</li><li>Now, Jenkins will ask us to create the First Admin User.</li><li>You can get Jenkin’s homepage.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d8Kn6B7tva4POdRMP_e5zQ.png" /><figcaption>Jenkins Dashboard.</figcaption></figure><ul><li>Now, we will create a CI/CD pipeline.</li><li>From the Jenkins Dashboard, Click on “New Item”.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9fI49tauybtswqChuA63NA.png" /><figcaption>create a new job.</figcaption></figure><ul><li>Now, Add the name as</li></ul><p>Name: notes-app-cicd</p><p>Project: Pipeline</p><p>Click “Ok”.</p><p>Now we have to configure pipeline as follows</p><p>Dashboards &gt; notes-app-cicd &gt; configuration &gt; general</p><p>Check✅Github project:</p><p><a href="https://github.com/ShubhamSoni-1/Notes-app.git">GitHub - ShubhamSoni-1/Notes-app</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EN7aLN1rudjf17HrVMfdOg.png" /><figcaption>paste the github url here.</figcaption></figure><p>Check ✅GitHub hook trigger for GIT SCM polling</p><p>Put this basic Declarative pipeline code in the script dialogue box.</p><p>Just to try, add a simple pipeline:</p><pre>pipeline {<br>    agent any<br><br>    stages {<br>        stage(&#39;Clone Code&#39;) {<br>            steps {<br>                echo &#39;Cloning the code&#39;<br>            }<br>        }<br>        stage(&#39;Build&#39;) {<br>            steps {<br>                echo &#39;This is Build Stage&#39;<br>            }<br>        }<br>        stage(&#39;Push to Docker hub&#39;) {<br>            steps {<br>                echo &#39;This is Test stage&#39;<br>            }<br>        }<br>        stage(&#39;Deployment&#39;) {<br>            steps {<br>                echo &#39;Deploying container&#39;<br>            }<br>        }<br>    }<br>}</pre><p>This code represents a Jenkins declarative pipeline, which is a popular way to define continuous integration and continuous deployment (CI/CD) workflows. Let’s go through each section and understand its purpose:</p><ol><li><strong>agent any</strong>: This line specifies that the pipeline can run on any available agent or executor in the Jenkins environment.</li><li><strong>stages</strong>: This block defines the different stages of the pipeline. Each stage represents a logical step in the CI/CD process.</li><li>a. <strong>stage(&#39;Clone Code&#39;)</strong>: This stage is responsible for cloning the source code repository. In this case, the pipeline simply echoes the message &quot;Cloning the code.&quot; In a real scenario, this stage would typically include commands to clone the repository using a version control system like Git.</li><li>b. <strong>stage(&#39;Build&#39;)</strong>: This stage is responsible for building the application or project. Here, the pipeline echoes the message &quot;This is the Build Stage.&quot; In a real scenario, this stage would typically include commands to compile the code, run tests, and generate build artifacts.</li><li>c. <strong>stage(&#39;Push to Docker hub&#39;)</strong>: This stage is responsible for pushing the built artifacts to a Docker registry (such as Docker Hub). The pipeline echoes the message &quot;This is the Test stage.&quot; In a real scenario, this stage would typically include commands to package the application into a Docker container and push it to the desired registry.</li><li>d. <strong>stage(&#39;Deployment&#39;)</strong>: This stage is responsible for deploying the application or container to the target environment. The pipeline echoes the message &quot;Deploying container.&quot; In a real scenario, this stage would typically include commands to deploy the Docker container or perform any necessary configuration and setup for the application to run.</li></ol><p>Each stage can have more complex logic and multiple steps, such as running shell commands, executing scripts, or invoking external tools.</p><p>By defining the pipeline stages and their associated steps, Jenkins can automate the entire CI/CD process, providing a consistent and reproducible workflow for building, testing, and deploying software applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Doad61whvTOCAo262vn8GA.png" /><figcaption>adding a simple pipeline script.</figcaption></figure><ul><li>Now Click on Save button and start the build on pipeline page.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ehmAAQVm_S0O7cbI40BkDg.png" /><figcaption>Building the pipeline.</figcaption></figure><ul><li>After getting success, you can see stages are green boxes with execution time.</li></ul><h3>Developing the Notes App Code: To develop the Django notes app code, follow these steps:</h3><ol><li>Clone the code: In the pipeline script, add the following code to clone the code from your repository:</li></ol><pre>git url: &quot;https://github.com/ShubhamSoni-1/Notes-app.git&quot;, branch: &quot;main&quot;</pre><p>2. Build the code: Add the following code to build the application and create docker image with tag</p><pre>sh &quot;docker build . -t notes-app&quot;</pre><p>3. Push to Docker Hub: Add the code to push the Docker image to Docker Hub:</p><p>For docker login in pipeline you have to create docker credentials and use them as environment variable</p><p>Create Credentials in Dashboard &gt; Manage jenkins &gt; Credentials &gt; System &gt; Global credentials.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k4qYnG33omZAL3Cq1rH9vw.png" /><figcaption>Here enter the credentials of DockerHub</figcaption></figure><pre>withCredentials([usernamePassword(credentialsId:&quot;dockerhub-login&quot;,passwordVariable:&quot;dockerhubpass&quot;,usernameVariable:&quot;dockerhubuser&quot; )]){<br>    sh &quot;docker tag notes-app ${env.dockerhubuser}/notes-app:latest&quot;<br>    sh &quot;docker login -u ${env.dockerhubuser} -p ${env.dockerhubpass}&quot; <br>    sh &quot;docker push ${env.dockerhubuser}/notes-app:latest&quot;<br>}</pre><ol><li><strong>withCredentials</strong>: This is a Jenkins pipeline step provided by the &quot;Credentials Binding Plugin.&quot; It allows you to securely retrieve and use credentials within the block. In this case, we are retrieving the Docker Hub credentials using the usernamePassword method.</li><li><strong>usernamePassword(credentialsId: &quot;dockerhub-login&quot;, passwordVariable: &quot;dockerhubpass&quot;, usernameVariable: &quot;dockerhubuser&quot;)</strong>: This line retrieves the username and password from the Jenkins credentials store. The credentialsId parameter specifies the unique identifier of the stored Docker Hub credentials. The usernameVariable and passwordVariable parameters define the environment variables where the username and password will be stored, respectively. The environment variables are prefixed with env. in Jenkins, which is why you see env.dockerhubuser and env.dockerhubpass later in the code.</li><li><strong>sh &quot;docker tag notes-app ${env.dockerhubuser}/notes-app:latest&quot;</strong>: This line creates a new Docker image tag with the Docker Hub username as a prefix. The notes-app is the original local image name, and we&#39;re tagging it with the new name ${env.dockerhubuser}/notes-app:latest. This is necessary to ensure that the image can be pushed to the Docker Hub registry with the correct repository name.</li><li><strong>sh &quot;docker login -u ${env.dockerhubuser} -p ${env.dockerhubpass}&quot;</strong>: This line runs the docker login command to authenticate with Docker Hub using the username and password retrieved from the Jenkins credentials store. The -u flag specifies the Docker Hub username, and the -p flag specifies the password.</li><li><strong>sh &quot;docker push ${env.dockerhubuser}/notes-app:latest&quot;</strong>: This line pushes the tagged Docker image to the Docker Hub registry using the docker push command. After authentication, the image is pushed to the repository specified by ${env.dockerhubuser}/notes-app:latest.</li></ol><p>4. Deployment: Finally, deploy the code on the EC2 instance using the following code:</p><pre><br>sh &quot;docker-compose down &amp;&amp; docker-compose up -d&quot;</pre><p>Here is the full Declarative pipeline code for django-notes-app deployment on ec2 using docker container.</p><pre>pipeline {<br>    agent any<br><br>    stages {<br>        stage(&#39;Clone Code&#39;) {<br>            steps {<br>                echo &#39;Cloning the code&#39;<br>                git url: &quot;https://github.com/ShubhamSoni-1/Notes-app.git&quot;, branch: &quot;main&quot;<br>            }<br>        }<br>        stage(&#39;Build&#39;) {<br>            steps {<br>                echo &#39;This is Build Stage&#39;<br>                sh &quot;docker build . -t notes-app&quot;<br>            }<br>        }<br>        stage(&#39;Push to Docker hub&#39;) {<br>            steps {<br>                echo &#39;Pushing image to dockerhub&#39;<br>                withCredentials([usernamePassword(credentialsId:&quot;dockerhub-login&quot;,passwordVariable:&quot;dockerhubpass&quot;,usernameVariable:&quot;dockerhubuser&quot; )]){<br>                sh &quot;docker tag notes-app ${env.dockerhubuser}/notes-app:latest&quot;<br>                sh &quot;docker login -u ${env.dockerhubuser} -p ${env.dockerhubpass}&quot; <br>                sh &quot;docker push ${env.dockerhubuser}/notes-app:latest&quot;<br>                }<br>                <br>            }<br>        }<br>        stage(&#39;Deployment&#39;) {<br>            steps {<br>                echo &#39;Deploying container&#39;<br>                sh &quot;docker-compose down &amp;&amp; docker-compose up -d&quot;<br>            }<br>        }<br>    }<br>}</pre><p>Whenever the developer commits their code in GitHub, after every commit, it should reflect in the live web app.</p><p>· For that, we will use “github webhook”.</p><p>· Every time, a developer made a commit, a trigger will run automatically, which will rebuild the image and run a container on your behalf as a part of automation that will run the pipeline automatically.</p><ul><li>go to on your github repository &gt; setttings &gt; Webhook &gt; Payload URL &gt; put your jenkins public ip address &gt; “add webhook”.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O4WmKELu_PFs3ENJMwbaSg.png" /><figcaption>add webhook in the github repo. of the code.</figcaption></figure><ul><li>Do some changes in the code and push to GitHub, this will automatically run a pipeline, and the new code will be Live.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UvkzqHYxkzgmwuR9yKwKCQ.png" /></figure><ul><li>Now Here is our app is live and working fine.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dpn-pxnUT6u39I6_N53N6w.png" /><figcaption>Application is live.</figcaption></figure><p>Thank you for reading….❤️❤️ I hope you learn something new.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ddf54971f03" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TO-DO APPLICATION IN 3 WAYS.]]></title>
            <link>https://surajsoni3332.medium.com/to-do-application-in-3-ways-83e50178946f?source=rss-5923bdda6c4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/83e50178946f</guid>
            <dc:creator><![CDATA[Shubham Soni]]></dc:creator>
            <pubDate>Mon, 27 Nov 2023 16:19:49 GMT</pubDate>
            <atom:updated>2023-11-27T16:21:36.626Z</atom:updated>
            <content:encoded><![CDATA[<p>Deploying a To-Do App with Jenkins: A Step-by-Step Guide &amp; Accelerate Your Web Application Deployment with a Jenkins Pipeline Triggered by GitHub Webhook Integration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*S0Q5d7o-Y85j7QW1-6J5gQ.png" /></figure><h3>Introduction:</h3><p>The project aims to automate the building, testing, and deployment process of a web application using Jenkins and GitHub. The Jenkins pipeline will be triggered automatically by GitHub webhook integration when changes are made to the code repository. The pipeline will include stages such as building, testing, and deploying the application.</p><h3>Task 1</h3><h3>Step 1:</h3><p>Go to EC2 console and Create an EC2 instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OkunxIaJaIF1-k5LmI5dgA.png" /></figure><p>Check whether EC2 instance is running and copy the IPv4 address of the instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oPpKBRduHAZgR8nbM3o0lA.png" /></figure><p>Connect to the EC2 instance using Puttygen and Putty with the help of IPv4 and Keys generated at the time of instance launch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yKFgQ9-6D5QQqjWWQWKiZA.png" /><figcaption>load the public key and generate a private key.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bs1NXNjciBVH2FkwTjDh-Q.png" /><figcaption>Paste the ipv4 and private key.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cHmpR9Hl8sA3aQBRXM-pYg.png" /><figcaption>When the machine starts properly.</figcaption></figure><h3>Step 2: Install jenkins on AWS EC2 Ubuntu instance.</h3><p>1: <strong>Install Java</strong></p><p>Jenkins requires the Java Runtime Environment (JRE).</p><p>To install OpenJDK 11, run:</p><pre>$ java<br>$ sudo apt install openjdk-11-jdk-headless -y</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OWCb2kjeVnv10NXNzz0UEQ.png" /></figure><p>2: <strong>Add Jenkins Repository</strong></p><p>1. Start by importing the GPG key. The GPG key verifies package integrity but there is no output.$</p><pre>$ sudo wget -O /usr/share/keyrings/jenkins-keyring.asc \<br>  https://pkg.jenkins.io/debian-stable/jenkins.io-2023.key</pre><p>2. Add the Jenkins software repository to the source list and provide the authentication key:</p><pre>$ echo deb [signed-by=/usr/share/keyrings/jenkins-keyring.asc] \<br>  https://pkg.jenkins.io/debian-stable binary/ | sudo tee \<br>  /etc/apt/sources.list.d/jenkins.list &gt; /dev/null</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_nbhWpzhol8j5no5z3tdtw.png" /></figure><p>3: <strong>Install Jenkins</strong></p><p>1. Update the system repository</p><pre>$ sudo apt-get update</pre><p>2. Install Jenkins by running:</p><pre>$ sudo apt-get install jenkins</pre><p>To check if Jenkins is installed and running, run the following command:</p><pre>$ sudo systemctl enable jenkins<br>$ sudo systemctl status jenkins</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VdzB5hqwwvMaj8zUsUK7Gw.png" /><figcaption>Here the status of Jenkins is Active (Running).</figcaption></figure><p>4: <strong>Generate SSH Keys (Public and Private):</strong></p><p>Generate the SSH keys for integrating your Jenkins project with your git repository. Use ssh-keygen command to create public and private key.</p><pre>$ ssh-keygen<br>$ cd .ssh<br>$ ls</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vi7VdtbKTXo62sTAlOAO1g.png" /><figcaption>Generating public and private keys.</figcaption></figure><h3>Step 3:</h3><p>1: <strong>Go to Security Groups and Edit inbound rules:</strong></p><p>For Jenkins we used port 8080 and to deploy our application we use port 8000.</p><p>To add port 8080 to an instance, you need to allow traffic on port 8080 in the instance’s security group and configure the instance’s firewall to allow traffic on port 8080 and same with the port 8000.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZJ3CIUMyvhJj6Cm4vM0-PQ.png" /><figcaption>Edit and Save the Security Group.</figcaption></figure><p>2: <strong>To verify Jenkins server is running :</strong></p><p>Browse &lt; instance-public-IP:8080 &gt; it will open the Jenkins dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eeQbs0GSe9vq1tkocmrwxg.png" /></figure><p>3. We need an Administrator Password to unlock this. Go to terminal and use below command for password.</p><pre>cat /var/lib/jenkins/secrets/initialAdminPassword</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lRGzIniJMK4zcAcrW74kTA.png" /><figcaption>Here we find the password for Jenkins.</figcaption></figure><p>Paste the above password in Administrator Password and click on Continue</p><p>4. <strong>Select Install suggested plugins:</strong></p><p>This will install all the suggested plugins in the Jenkins server automatically or you can select plugins to install.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*0d9yzbd-YMjokW-L5RVAgg.png" /><figcaption>Automatically install plugins in our Jenkins.</figcaption></figure><p>5. <strong>Plugins start installing automatically:</strong></p><p>When we select the above option all the plugins start installing automatically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EUaYaW6r0bjxBQZT7sktaA.png" /><figcaption>Installing Plugins may consume some time.</figcaption></figure><p>5. <strong>Create first admin user:</strong></p><p>Now fill this page to create a user and click on Save and Continue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YhStVhg6LaE4ufQImb8unw.png" /><figcaption>Fill the blanks with your identities and save.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c2lM1EWUY-7vx3UwJ8LVAw.png" /><figcaption>Here we got our Jenkin server’s configuration.</figcaption></figure><p>6.<strong> Jenkins setup is completed and Jenkins is ready to use.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L5_ztmf-4Mzja3rTjercvw.png" /><figcaption>Getting Started with Jenkins.</figcaption></figure><p>7. <strong>Jenkins Dashboard:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2x1C4Qr6F--GJwwCD8ZL6A.png" /><figcaption>Jenkins Dashboard</figcaption></figure><h3>Step 4: Create a freestyle project</h3><ol><li>In the Jenkins dashboard, Click on the ‘New Item’ button on the left sidebar then give your project a name and select “Freestyle project” as the project type.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hoyegqSv4EQAGgQeU4FJ1g.png" /></figure><p>2. <strong>Configure the Job:</strong></p><p>Click on Configure, Add a description and paste the github URL of the project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5TwsgSaIkQrMMlDyi5e_rA.png" /><figcaption>Add description and project url.</figcaption></figure><p>3. In source code management, Write your GitHub repository URL</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9qBZweju4PAsBHvcc-jfrQ.png" /><figcaption>Paste the project URL in SCM.</figcaption></figure><p>4. <strong>Add the SSH Keys in the Github:</strong></p><p>Here to integrate both github and Jenkins so that the Jenkins can access the code from github, we have to provide the public keys to github so that it can authorize the access of jenkins.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1jPUsYMicxksamrthOq40w.png" /><figcaption>paste the keys here.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tjjq5FdLB9AS7_GoHgfbvg.png" /></figure><p>5. <strong>Add credentials for Jenkins:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2SPCkH_SGPLQw8UJ-DczoQ.png" /><figcaption>Select the correct option.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JE6gnM1NkjNS65Dw1IjAEg.png" /><figcaption>Paste the Private key here.</figcaption></figure><p>Select the credentials we have made above and clock on Apply and Save.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FU4k4v2jPE6gUUpN74zRbw.png" /><figcaption>select the credentials.</figcaption></figure><p>6. <strong>Build Now:</strong></p><p>After filling in all the required options our job is now ready to build.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_S_T9pupxq4EUZs8jFDpcA.png" /><figcaption>click on build now.</figcaption></figure><p>You can check the status of the build also by simply clicking on the Status.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eWn-dC0pxbkr-H6PK0NTnA.png" /><figcaption>Status of the Job.</figcaption></figure><p>7. <strong>Result of the Job:</strong></p><p>To check the result of the job simply click on the Console Output and check whether the job is Successful or Fail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lPeq1eTPU3MXiy-Uz3cqIw.png" /><figcaption>Output of the job is successful.</figcaption></figure><p>8. <strong>Install some Dependencies:</strong></p><p>To run the application using github, jenkins and localhost we need some dependencies to run the application. For this we have to install some dependencies like:</p><pre>$ sudo apt install nodejs<br>$ sudo apt install npm<br>$ sudo npm install<br>$ node app.js</pre><p>Here our first requirement is nodejs as the app is made on nodejs so we have to install nodejs in our system, then we have to install npm which is a node package manager and then npm install means that it will install all the packages in package.json file which are required to run the app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3rOwCi8r5-8f9xvIKO7VDg.png" /></figure><p>OR you can execute these commands in the Jenkins Job also. To execute commands in the Jenkins Job, go to the job then go to Build Steps and select Execute Shell as we have to execute shell commands here and write the commands there and SAVE the Job.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xNUBhPaq207ocEb1nHi7vA.png" /><figcaption>Write the commands here.</figcaption></figure><p>9. <strong>Build the Project:</strong></p><p>Click on Build Now and build the job and check the output of the Job.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mpZQtBKDDgJ1p32iM31LTQ.png" /></figure><p>10. <strong>To Verify the Application:</strong></p><p>Go to Chrome and search the &lt;Public-IP:8000&gt; and check whether the app is running or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wuyv8vKESD89nAv9OrfHLA.png" /></figure><h3>Task 2</h3><h3>Step 5: Deployment using Docker</h3><ol><li><strong>Install Docker on EC2 instance:</strong></li></ol><p>Install docker using the below command</p><pre>sudo apt-get install docker.io</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xxb6_HLP6mSIRf47QTp2hQ.png" /><figcaption>Docker installation.</figcaption></figure><p>2. <strong>Create a Dockerfile:</strong></p><p>To automate things we need a Dockerfile, to create a Docker Image and Container. So we are going to create a Dockerfile here and save it.</p><pre>$ vim Dockerfile</pre><pre># Type these steps in the Dockerfile<br><br>FROM node:12.2.0-alpine<br><br>WORKDIR app<br><br>COPY . .<br><br>RUN npm install<br><br>EXPOSE 8000<br><br>CMD [&quot;node&quot;,&quot;app.js&quot;]</pre><p>Add your user to the docker group:</p><pre>sudo usermod -a -G docker $USER</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LyvTTGfEgV5FMYNh0sFXvQ.png" /></figure><p>This command adds your current user to the docker group, which grants permission to access the Docker socket.</p><p>3. <strong>Create a Docker Image and Docker Container:</strong></p><p>By using this Dockerfile we are now going to create a Docker image and Docker Container to run our Application.</p><p>To create a Docker image run below command</p><pre>$ docker build -t to-do-img:v1 .</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E4JBYUy9pK9EgjvkDZV8og.png" /></figure><p>After creating a Docker image now we are going to create a Docker container from this image, for this run the below command:</p><pre>$ docker run -d --name to-do-cont -p 8000:8000 to-do-img:v1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UszRX7qS0MbhNITF3U-hQA.png" /></figure><p>OR you can also do this (Docker image and Docker Container) with the help of Jenkins for the automation. For this go to Build Steps and enter the same code in Execute Shell.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8pAxgSUgvbpv48r84dSXmA.png" /><figcaption>To create a Docker image and Docker Container.</figcaption></figure><p>After Configuring the Job, click on Apply and Save.</p><p>4. <strong>Add the Jenkins user to the docker group:</strong></p><pre>sudo usermod -a -G docker jenkins</pre><p>This command adds the Jenkins user to the docker group, which grants permission to access the Docker socket.</p><p>After creating a User, restart the Jenkins server by:</p><pre>$ sudo systemctl restart jenkins</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xk_46he1y84LeaK7StBUWg.png" /></figure><p>5. <strong>Build Job:</strong></p><p>Click on Build Now and check the output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SMOf_CJEO3kNI07BHX0ahg.png" /><figcaption>Build is Successful.</figcaption></figure><p>Also verify with the help of Console Output to check the output of the Job.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xlg5josWclt3ASFmFN8nbg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T8TWW-cKdLnP1zKwbZo5rQ.png" /><figcaption>Output</figcaption></figure><p>6. <strong>Browse public IP address with port no.8000:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wuyv8vKESD89nAv9OrfHLA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rVHX_f6b4_yIn9sK5kZAxA.png" /></figure><h3>Task 3:</h3><p>The Jenkins pipeline will be triggered automatically by GitHub webhook integration when changes are made to the code repository.</p><h3>Step 1: Configuring GitHub</h3><p>1.Go to your GitHub account settings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UUoGQSeGody8uTLw3UwInA.png" /></figure><p>And verify, that there is a SSH and GPG Key must be there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tjjq5FdLB9AS7_GoHgfbvg.png" /></figure><h3>Step 2: For GitHub-Webhook</h3><p>1.Go to your GitHub repository and click on Settings.</p><p>Click on Webhooks and then click on Add Webhook.</p><p>In the ‘Payload URL’ field, paste your Jenkins environment URL. At the end of this URL add /github-webhook/. In the ‘Content type’ select: ‘application/json’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2RSNo0e-OBhk8FpIBBNe3g.png" /></figure><p>Click on Add Webhook.</p><p>Webhook is Added.</p><h3>Step 3: For Installing GitHub Integration plugin in Jenkins</h3><ol><li>Open your jenkins dashboard.</li><li>Click on the Manage Jenkins button on your Jenkins dashboard.</li><li>Click on Manage Plugins.</li><li>Install GitHub Integration plugin.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BPv5IxLc07MT1RordrmcPg.png" /><figcaption>install Plugins.</figcaption></figure><h3>Step 4: Configuring Jenkins</h3><p>1.In build Triggers, select ‘Github hook trigger for GITScm polling’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aI4zIWIsFk9bKtr3TI12lw.png" /></figure><p>2. Do some changes in the code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4g4_bWpGb1CBeAncC95pXw.png" /><figcaption>Old Code.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o-Q4y0Kpe5XgUhIyIsalAA.png" /><figcaption>Updated Code.</figcaption></figure><p>3. Making changes to the file’s content trigger the pipeline and this will automatically build a pipeline.</p><p>4. Browse public IP address with port no.8000</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wuyv8vKESD89nAv9OrfHLA.png" /></figure><p>You can also visit my Github repository for the complete Code:</p><p><a href="https://github.com/ShubhamSoni-1/To-Do-App.git">GitHub - ShubhamSoni-1/To-Do-App: In this project we have a node to-do app which we are going to deploy on AWS EC2 using Docker, Dockerfile, Jenkins and Webhook....</a></p><h3>I hope you enjoyed the Reading…❤️❤️</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83e50178946f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Create local users using script.]]></title>
            <link>https://surajsoni3332.medium.com/how-to-create-local-users-using-script-0f30c90d850e?source=rss-5923bdda6c4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/0f30c90d850e</guid>
            <dc:creator><![CDATA[Shubham Soni]]></dc:creator>
            <pubDate>Tue, 21 Nov 2023 16:04:16 GMT</pubDate>
            <atom:updated>2023-11-21T16:04:16.233Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*RbfFxF0su_I6viRvt7L6Ig.png" /></figure><p>When we have to create an account for a user in our Linux server then we can run the script and provide the user name, so that it will create a user, its password and tell the hostname of the system.</p><p><strong>REQUIREMENT:</strong></p><p>The script should be executed with root user else exit with some status 1 and error message.</p><p>Script will take 1st argument as user and the rest will be treated as comment.</p><p>Auto-generated password for the user.</p><p>Upon successful execution of the script, display the following:</p><p>Username: &lt;user-name&gt;</p><p>Password: &lt;auto-generated-password&gt;</p><p>Host: &lt;host-name&gt;</p><p><strong>STEPS:</strong></p><p>Check if the script is being executed with superuser privileges.</p><p>If the user does not provide at least one argument, then give them help.</p><p>The first parameter is the user name.</p><p>The rest of the parameters are for the comments.</p><p>Generate a password.</p><p>Create the user with the password.</p><p>Check to see if the useradd command succeeded.</p><p>Set the password.</p><p>Check to see if the passwd command succeeded.</p><p>Force password change on the first login.</p><p>Display the username, password and host where the user is created.</p><p><strong>SCRIPT:</strong></p><p>Go to the specific folder where you want to create the script and then create a new file called “user_creation.sh” using vim editor.</p><pre>$cd /home/Yuvraj/projects/<br>$vim user_creation.sh</pre><p>step 1:</p><p>After creating a new file, we start with writing the shebang line of the script, then we comment and inform about the version of the script and date of creation of the file.</p><pre>#!/bin/bash<br># Version- 1<br># Date of creation of script –</pre><p>Step 2. Check if the script is being executed with superuser privileges.</p><pre>#Script should be executed with sudo/root access<br>if [[ &quot;${UID}&quot; -ne 0 ]]<br>then<br>echo &quot;Please run the script with sudo or root user&quot;<br>exit 1<br>fi</pre><p>Here we are confirming whether the script is executed with sudo or root user. For this we are using UID, as we know the UID of the root user is ZERO so we are using that to confirm, if it is not equal to zero then echo “Please run the script with sudo or root user” and exit the script at the same step.</p><p>But if it is executed by sudo or root user then execute the next step.</p><p>Step 3. If the user does not provide at least one argument, then give them help.</p><pre>#User should provide at least one argument as username else guide the admin<br>If [[ &quot;${#}&quot; -lt 1 ]]<br>then<br>echo &quot;Usage: ${0} USER_NAME [COMMENT]…&quot;<br>echo &quot;Create a user with name USER_NAME and comments field of COMMENT &quot;<br>exit 1<br>fi</pre><p>In this step, we are using the if-condition to check whether the admin is providing any argument with the execution of the script or not.</p><p>${#} means the length of the argument, if it is less than 1, then echo “Usage: ${0} USER_NAME [COMMENT]…” to help the admin how to give the argument while running the script.</p><p>After that echo “Create a user with name USER_NAME and comments field of COMMENT ”</p><p>If the condition is true then exit the script at the same step and end the if condition with fi.</p><p>Step 4. The first parameter is the user name.</p><pre>#Store the 1st argument as the user name<br>USER_NAME=&quot;${1}&quot;<br>echo $USER_NAME</pre><p>here in this step, we are storing the 1st argument provided by the admin to a variable called USER_NAME and to verify it we can echo the USER_NAME.</p><p>Step 5. The rest of the parameters are for the comments.</p><pre>#In case of more than one argument, store it as account comments<br>shift<br>COMMENT=&quot;${@}&quot;<br>echo $COMMENT</pre><p>In this step, if there is more than one argument provided by the admin then we are storing all the input to the other variable called COMMENT. For this, we are using “shift” so that the first output is stored in the USER_NAME and all other data is stored in the COMMENT variable.</p><p>To verify we can check using the echo command.</p><p>Step 6. Generate a password.</p><pre>#create a password<br>PASSWORD=$(date +%s%N)<br>echo PASSWORD</pre><p>In this step, we are generating a password for this we can use either $RANDOM or the above syntax.</p><p>Random is not used because it always prints a random number from 0 to 32757, it may be 2 digit, 3 digit, 4 digit or 5 digit, that’s why we are not using that.</p><p>$(date +%s%N) means we are printing the date in a different way as nano-sec type so that the output is a long and fixed number of letters in the password.</p><p>We can store this output in the PASSWORD variable so that we can use it in the script later.</p><p>Step 7. Create the user with the password.</p><pre>#Create the user<br>useradd -c &quot;$COMMENT&quot; -m $USER_NAME</pre><p>This means we are creating a user named USER_NAME and comment as COMMENT. Here -m means we are also creating the home directory for the user.</p><p>Step 8. Check to see if the useradd command succeeded.</p><pre># Check if the user is successfully created or not<br>if [[ $? -ne 0 ]]<br>then<br>echo &quot;The Account could not be created&quot;<br>exit 1<br>fi</pre><p>here we are using if-condition, $? is used to check whether the last step is successful (0) or not. If not successful then echo “The Account could not be created” and exit the script and write fi to end the if-condition.</p><p>Step 9. Set the password.</p><pre>#Set the password for the user<br>echo -e &quot;$PASSWORD\n$PASSWORD&quot; |passwd &quot;$USER_NAME&quot;</pre><p>here we are creating a password for the user.</p><p>Step 10. Check to see if the passwd command succeeded.</p><pre>#Check if the password is successfully created or not<br>if [[ $? -ne 0 ]]<br>then<br>echo &quot;Password could not be set&quot;<br>exit 1<br>fi</pre><p>Step 11. Force password change on the first login.</p><pre>#Force password change on its first login<br>passwd -e $USER_NAME</pre><p>in this step, we are using passwd with -e means the user must have changed the password on their 1st login.</p><p>Step 12. Display the username, password and host where the user is created.</p><pre># Display the username, password and host where the user is created.<br>echo<br>echo &quot;Username: $USER_NAME&quot;<br>echo<br>echo &quot;Password: $PASSWORD&quot;<br>echo<br>echo &quot;Hostname: $(hostname)&quot;</pre><p>Here, the scripting is completed and to save the file and exit the editor press ESC and the write</p><p><strong>:wq</strong></p><p>the script.</p><p>There are the following ways to execute a script, which are as below:</p><p>1. use chmod +x user_creation.sh to provide the execute permission of the file to all and then execute the script using user_creation.sh</p><p>2. Direct execute using bash user_creation.sh</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WOWerIQQlaV67UDYvZtMoA.png" /></figure><p>You can also visit my Github repository for the complete script:</p><p><a href="https://github.com/ShubhamSoni-1/Create-local-users-using-shell-script.git">GitHub - ShubhamSoni-1/Create-local-users-using-shell-script: When we have to create an account for a user in our Linux server then we can run the script and provide the user name, so that it will create a user, its password and tell hostname of the system.</a></p><p>Hope you like my work and got something new. Thank You!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0f30c90d850e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ARCHIVE LARGE FILES USING SHELL SCRIPT]]></title>
            <link>https://surajsoni3332.medium.com/archive-large-files-using-shell-script-d852d81e82e4?source=rss-5923bdda6c4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d852d81e82e4</guid>
            <dc:creator><![CDATA[Shubham Soni]]></dc:creator>
            <pubDate>Tue, 21 Nov 2023 15:24:17 GMT</pubDate>
            <atom:updated>2023-11-21T15:50:47.001Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4HES98840fRqJicfy8b9Hg.png" /></figure><p>It is a kind of real-life project to show how we create a script in real life.</p><p>In this project, we are filtering files that are greater than 20MB in a specific path or folder, then we have to zip those files and move the zip file to a new folder named “archive” in the same path or folder in which these files are present.</p><p><strong>PROJECT REQUIREMENT</strong></p><p>In the given directory, if you find files more than a given size (20mb) or files older than given days (10 days),</p><p>Compress those files and move them in an “<strong>archive</strong>” folder.</p><p><strong>PURPOSE OF THE SCRIPT</strong></p><p>In real life, we have a server running on a limited disk space (1tb, 2tb,…) and we have an application running on that server. So the application produces logs (1gb, 2gb 5gb, 10gb,…) on a regular basis in a particular directory then the disk space become full and it is running out of space. So we can archive the older files or large files to a specific folder so that the disk space becomes free and if we need those files we can access them as well.</p><p><strong>STEPS OF SCRIPT:</strong></p><p>Provide the path of the directory.</p><p>Check if the directory is present or not.</p><p>Create “<strong>archive</strong>” folder if not already present.</p><p>Find all the files with size more than 20mb.</p><p>Compress all files.</p><p>Move the compressed files in the “<strong>archive</strong>” folder.</p><p>Make a cron job to run the script every day at a given time.</p><p><strong>SCRIPT:</strong></p><p>Go to the specific folder where you want to create the script and then create a new file called “archive_files.sh” using vim editor.</p><pre>$cd /home/Yuvraj/projects/<br>$vim archive_files.sh</pre><p>step 1:</p><p>After creating a new file, we start with writing the shebang line of the script, then we comment and inform about the version of script and date of creation of file.</p><pre>#!/bin/bash<br># Version- 1<br># Date of creation of script –</pre><p>Step 2: to create variables in the script</p><pre>#variables<br>LOC=/home/yuvraj/project_data   #Path of files you want to filter<br>DAYS=10<br>DEPTH=1<br>RUN=0</pre><p>Here LOC means the path of the directory where all the files are present on which we have to perform the operation.</p><p>DAYS mean the number of days after which the file is moved to the archive folder.</p><p>DEPTH means how deep the script works on the folder. Here 1 means the script only works on the files present in the given directory, not in the sub-directories.</p><p>Step 3: to check whether the given Path(LOC) is present or not</p><pre>#Check if the directory is present or not<br>if [ ! -d $LOC ]<br>then<br>echo &quot;directory does not exist- $LOC&quot;<br>exit 1<br>fi</pre><p>in the above step we are checking whether the data directory is present or not on which we have to perform the operation.</p><p>For this, we are using if condition.</p><p>if [ ! -d $LOC] means if the directory in variable LOC is not present,</p><p>then echo “directory does not exist-” and “write the given path of the directory” and then exit the script</p><p>fi is used to tell the if condition ends here.</p><p>Step 4: Create ‘archive’ folder if not present</p><pre>#create an &#39;archive&#39; folder if not present<br>if [ ! -d $LOC/archive]<br>then<br>mkdir $LOC/archive<br>fi</pre><p>in this step we are checking whether the archive folder is present or not, if it is not present then create a directory called ‘archive’ in the same directory(LOC) where our data is present.</p><p>Step 5: how to find the files larger than 20mb in the directory</p><pre>#Find the list of files larger than 20mb<br>for i in `find $LOC -maxdepth $DEPTH -type f -size +20M`<br>do<br>if [ $RUN -eq 0 ]<br>then<br>echo &quot; $date archiving $i è $LOC/archive&quot;<br>gzip $i || exit 1<br>mv $i.gz $LOC/archive || exit 1<br>fi<br>done</pre><p>here we are using for-loop, we are storing the files that are greater than size 20mb only in the given directory at LOC with the help of find command in i.</p><p>after that, we use the if-condition that for all the values present in i,</p><p>gzip all the files one by one and if it is unable to do that then exit the script at the same time.</p><p>After it is done gzip of file, in the next step we move all the files stored in $i, and add “.gz” in its name, to the “archive” folder one by one and if it is unable to do that then exit the script at the same time using “exit 1”.</p><p>To end the ‘if-condition’ using “fi” and ‘for-loop’ using “done”.</p><p>NOTE: to filter out the files based on time</p><pre>for i in `find $LOC -maxdepth $DEPTH -type -mtime +10`</pre><p>Here, the scripting is completed and to save the file and exit the editor press ESC and the write</p><p><strong>:wq</strong></p><p>the script.</p><p>There are the following ways to execute a script, which are as below:</p><p>1. use chmod +x archive_files.sh to provide the execute permission of the file to all and then execute the script using archive_files.sh</p><p>2. Direct execute using bash archive_files.sh</p><p>To verify whether our script is running perfectly or not we can go to the PATH and see whether the archive folder is present or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oQEj4gaYuEUY8ye5J0_Lzw.png" /></figure><p>Step 6: To Automate our script we can use the cron job for this:</p><pre>$crontab -e</pre><pre>00 12 * * * /home/Yuvraj/projects/archive_files.sh</pre><p>This means our script is running every day at 12’o clock in the noon.</p><p>To verify whether our cron job is created or not, use “crontab -l”.</p><p>You can also visit my Github repository for the complete script:</p><p><a href="https://github.com/ShubhamSoni-1/Archive-Larger-files.git">GitHub - ShubhamSoni-1/Archive-Larger-files: In this project, we are filtering files that are greater than 20MB in a specific path or folder, then we have to zip those files and move the zip file to a new folder named &quot;archive&quot; in the same path or folder in which these files are present.</a></p><p>Hope you like my work and got something new. Thank You!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d852d81e82e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CREATE A SCRIPT TO MONITOR THE RAM]]></title>
            <link>https://surajsoni3332.medium.com/create-a-script-to-monitor-the-ram-62cbf235dd9d?source=rss-5923bdda6c4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/62cbf235dd9d</guid>
            <dc:creator><![CDATA[Shubham Soni]]></dc:creator>
            <pubDate>Tue, 21 Nov 2023 14:54:28 GMT</pubDate>
            <atom:updated>2023-11-21T16:05:01.491Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lYivkJ02aLCvbqQz" /><figcaption>Photo by <a href="https://unsplash.com/@samsungmemory?utm_source=medium&amp;utm_medium=referral">Samsung Memory</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>First of all, create a script file named ram_monitoring.sh</p><p>sh means it is a script file and to write our script we are using the vim editor.</p><pre>$vim ram_monitoring.sh</pre><p>and press i to work in insert mode in the editor.</p><p>Write the shebang line means we have to tell which shell we are currently using to run our script and provide a complete path.</p><pre>#!/bin/bash</pre><p>After the shebang line, we have to write a script to monitor the RAM available in our system.</p><p>As we know we can use the ‘<strong>free</strong>’ command to see the RAM status of our system (physical memory &amp; swap memory), we can use options with the free command like -h, -m, -t,…</p><p>So here we use “<strong>free -mt</strong>” which means we are calling the information regarding RAM with the options -m and -t.</p><p><strong>-m</strong> is for showing the memory specs in MiB</p><p><strong>-t</strong> is for showing the total, used and free memory of the system.</p><p><strong>free -mt</strong></p><p>After that, we only require the total aspects of memory from the output, so we can use the ‘grep’ command to filter out the desired output.</p><p><strong>free -mt | grep “Total”</strong></p><p>the above command means to run free -mt and when it completely executes then fire grep “Total” query on the output and it will give the final output as total specs of the memory.</p><p>After this, we get the output as shown below:</p><p>As we only require the leftover memory of the system, not the total memory or used memory, we can filter out the output to the desired output using the “awk” command</p><p><strong>free -mt | grep “Total” | awk ‘{print $4}’</strong></p><p>awk is used for pattern processing in the Linux O.S. Here we use awk to process the output and filter out the output that is on number 4.</p><p>The output is as follows:</p><p>4748</p><p>Now we can store this output in a variable called “FREE_SPACE” as shown below:</p><pre>FREE_SPACE=$(free -mt | grep &quot;Total&quot; | awk &#39;{print $4}&#39;)</pre><p>Now we can fix a threshold value so that if the total free memory is less than the threshold value it will create a warning.</p><p>Create a variable called TH and set a value to it as shown below:</p><pre>TH=1024</pre><p>Here we set the threshold value to 1024 mb (set according to your system).</p><p>Now to create a warning we will use the if-else condition here as shown below:</p><pre>if [[ $FREE_SPACE -lt $TH]]<br>then<br>echo &quot;WARNING!!!! RAM is running low&quot;<br>else<br>echo &quot;RAM space is sufficient- $FREE-SPACE MiB &quot;<br>fi</pre><p>Here we compare the free space of the system and threshold value so that if the value of FREE_SPACE becomes less than TH then it will echo a warning to the terminal, if the FREE_SPACE is equal to or more than the TH value then it will echo RAM space is sufficient and will print the current available status of the RAM. Then we will end the if-else condition by writing “fi” at the end of the condition.</p><p>Here, the scripting is completed and to save the file and exit the editor press ESC and the write</p><p><strong>:wq</strong></p><p>As we have created the script above, now we have to execute or run the script.</p><p>There are the following ways to execute a script, which are as below:</p><p>1. use chmod +x ram_monitoring.sh to provide the execute permission of the file to all and then execute the script using ram_monitoring.sh</p><p>2. Direct execute using bash ram_monitoring.sh</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*97pllszfqMZzgX-Zw3Bdqg.png" /></figure><p>Also, you can visit my Github Repository for the complete script:</p><p><a href="https://github.com/ShubhamSoni-1/Ram-Monitoring.git">GitHub - ShubhamSoni-1/Ram-Monitoring: In this project, we are writing a shell script to monitor the free memory in the system and use &quot;if-condition&quot; so that if the memory is greater than the threshold value, it will give a WARNING!!!! to the user.</a></p><h3><strong><em>THANK YOU</em></strong></h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62cbf235dd9d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CALCULATOR USING SHELL SCRIPT]]></title>
            <link>https://surajsoni3332.medium.com/calculator-using-shell-script-1e3584395f22?source=rss-5923bdda6c4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e3584395f22</guid>
            <dc:creator><![CDATA[Shubham Soni]]></dc:creator>
            <pubDate>Tue, 21 Nov 2023 14:10:52 GMT</pubDate>
            <atom:updated>2023-11-21T16:05:52.783Z</atom:updated>
            <content:encoded><![CDATA[<h3>TO CREATE A CALCULATOR</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*uIcDW-2IdyxPnrOzHQf2KA.png" /></figure><p>First of all, create a new script file named newCal.sh.</p><p>sh means it is a script file and to write our script we are using the vim editor</p><pre>$vim newCal.sh</pre><p>and press i to work in insert mode in the editor.</p><p>Write the shebang line means we have to tell which shell we are currently using to run our script and provide a complete path.</p><pre>#!/bin/bash</pre><p>As we are creating a calculator we need some input, for that we are using “read -p” to take input from the user and storing the input in a variable called “fir”</p><pre>read -p &quot;Enter the first number- &quot; fir</pre><p>To perform any Arithmetic Operation we require another input, and for that, we require another input from the user. For that, we again use read -p and store the input in another variable called “sec”.</p><pre>read -p &quot;Enter the second number- &quot; sec</pre><p>Now we have to provide some options to the user so that the user can choose any option to perform any operation like ADD, SUB, MUL, or DIV.</p><p>To do this we are using the ‘echo’ command so that the options will be visible on the terminal and the user can select any of them like:</p><pre>echo &quot;Provide an Option to perform any task&quot;<br>echo &quot;a for addition&quot;<br>echo &quot;b for subtraction&quot;<br>echo &quot;c for multiplication&quot;<br>echo &quot;d for division&quot;</pre><p>Now in the next step, the user chooses one of the given options like a, b, c or d and writes on the terminal, we use a variable called “choice” and the given option is stored in the variable.</p><pre>read choice</pre><p>In the next step, we create some cases so that the operation is performed depending on the user’s requirement</p><p>For that, we will take the fir and sec variables as input and the choice of user to perform any operation. Here we use cases</p><pre>case $choice in</pre><p>If the user chooses the option ‘a’ then the script performs addition for the user and we can write it as</p><pre>a) sum=$(($fir+$sec))<br>echo &quot;Addition of $fir and $sec is $sum&quot; ;;</pre><p>the above code means we are creating a variable called ‘sum’ in which we are storing the values of the addition of fir and sec input, then we echo a line on the terminal as “Addition of input1 and input2 is ‘Result stored in sum’ ”.</p><p>then we add “;;” which means our option a is ended here.</p><p>Same with the Subtraction, Multiplication and Division</p><pre>b) sub=$(($fir-$sec))<br>echo &quot;Subtraction of $fir and $sec is $sub&quot; ;;<br>c) mul=$(($fir*$sec))<br>echo &quot;Multiplication of $fir and $sec is $mul&quot; ;;<br>d) div=$(($fir/$sec))<br>echo &quot;Division of $fir and $sec is $div&quot; ;;<br>*) echo &quot;Please enter a valid option&quot; ;;</pre><p>If the user does not provide any of the given options and enter any other key then, we use *</p><p>* Means all the keys other than a, b, c, and d will give an output as “Please enter a valid option” on the terminal.</p><p>In the last we have to close the case, for that, we use esac in our script.</p><pre>esac</pre><p>Here, the scripting is completed and to save the file and exit the editor press ESC and the write</p><p><strong>:wq</strong></p><p>As we have created the script above, now we have to execute or run the script.</p><p>There are the following ways to execute a script, which are as below:</p><p>1. use chmod +x newCal.sh to provide the execute permission of the file to all and then execute the script using ./newCal.sh</p><p>2. Direct execute using bash newCal.sh</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FZC06Ry5n1lYTiSiibH4VA.png" /><figcaption>OUTPUT-PICTURE</figcaption></figure><p>You can also check my GitHub-repo for the complete script:</p><p><a href="https://github.com/ShubhamSoni-1/Calculator-Using-Shell-script.git">GitHub - ShubhamSoni-1/Calculator-Using-Shell-script: In this project, we are creating a Simple Calculator using Shell-Script by taking input from the user and ask user which operation the user want to perform.</a></p><p><strong><em>Thank You….</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e3584395f22" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to install Postfix on Ubuntu]]></title>
            <link>https://surajsoni3332.medium.com/how-to-install-postfix-on-ubuntu-1ff654b6bb26?source=rss-5923bdda6c4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ff654b6bb26</guid>
            <dc:creator><![CDATA[Shubham Soni]]></dc:creator>
            <pubDate>Sun, 19 Nov 2023 17:16:18 GMT</pubDate>
            <atom:updated>2023-11-19T17:16:18.263Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to install Postfix in Ubuntu</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qqtqNIZIaf3NWw-s6LLaSg.png" /></figure><p>To install Postfix on Ubuntu, you can use the following steps. Postfix is a popular mail server that can be used to send and receive emails on a Linux system.</p><p>Update Package List:</p><p>Before installing any new software, it’s a good idea to update the package list to ensure you get the latest versions of packages.</p><pre>$sudo apt update</pre><p>1.) Install the packages:</p><pre>$sudo apt-get install postfix -y<br>$sudo apt-get install mailx -y</pre><p>To send and receive mail you need to install some packages.</p><p>2.) Postfix configurations:</p><p>To configure the postfix go to the location</p><pre>$cd /etc/postfix</pre><p>Now, we have to work on the main.cf file. So for that, create a backup for the file so that the main data is secure in the backup file</p><pre>cp main.cf main.cf_bkp</pre><p>open the file in any editor and edit file</p><pre>vim main.cf</pre><p>{ADD THE FOLLOWING LINES}</p><pre>relayhost = [smtp.gmail.com]:587<br>myhostname = &lt;your hostname/SURAJ-LAPTOP&gt;</pre><p>587 is the port for secure TLS</p><p>To check your hostname use “hostname -f”</p><pre>#Location of sasl_passwd we saved<br>smtp_sasl_password_maps = hash:/etc/postfix/sasl/sasl_passwd<br>#Enables SASL authentication for postfix<br>smtp_sasl_auth_enable = yes<br>smtp_tls_security_level = encrypt<br>#Disallow methods that allow anonymous authentication<br>smtp_sasl_security_options = noanonymous</pre><p>3.) now create a file at /etc/postfix/sasl/ named sasl_passwd</p><pre>cd /etc/postfix/sasl/<br>vim sasl_passwd</pre><p>Add the below line and change the “email.gmail” to your Gmail.</p><pre>[smtp.gmail.com]:587 email@gmail.com:&lt;password&gt;</pre><p>Go to mail which is used here and go to security and ENABLE 2-STEP VERIFICATION</p><p>Now go to app passwords in security =&gt; Click on select app =&gt; Choose other</p><p>Write “smtp” and click on generate</p><p>It will show a window in which a password is written. Copy the password and paste it in the above file “sasl_passwd” at &lt;password&gt;.</p><p>4.) Convert the sasl_passwd file into db file</p><pre>postmap /etc/postfix/sasl/sasl_passwd</pre><p>a new file sasl_passwd.db is created here</p><p>as it contain sensitive info so we only allow user to read and write permissions on this file</p><pre>chmod 600 /etc/postfix/sasl/*</pre><p>5.) start the postfix service</p><pre># To start the postfix service<br>systemctl start/enable postfix<br># To stop the postfix service<br>systemctl stop/disable postfix<br># To re-start the postfix service<br>systemctl restart postfix</pre><p>6.) How to send an email</p><pre>echo &quot;Test Mail&quot; | mail -s &quot;Postfix TEST&quot; email@gmail.com</pre><p>7.) If you encounter any kind of error then go to main.cf file and comment on the line</p><pre># smtp_tls_security_level = may</pre><p>After editing the file do</p><pre>systemctl restart postfix.service</pre><p>8.) to attach any file with the mail</p><p>Create a file testfile</p><pre>vim testfile</pre><pre>#write something in the file to verify<br>&quot;Suraj soni attach a file with the mail&quot;</pre><p>Save the file</p><pre>echo &quot;Test Mail&quot; | mail -s &quot;Postfix TEST&quot; -a &lt;filename/testfile&gt; email@gmail.com</pre><p>After all steps are completed, and to verify whether the Postfix service is working or not you can check Gmail and there you will see a mail regarding the same.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ff654b6bb26" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Configuring Docker Container by Ansible]]></title>
            <link>https://surajsoni3332.medium.com/configuring-docker-container-by-ansible-2d0c45e63ccb?source=rss-5923bdda6c4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d0c45e63ccb</guid>
            <dc:creator><![CDATA[Shubham Soni]]></dc:creator>
            <pubDate>Fri, 09 Jun 2023 07:43:28 GMT</pubDate>
            <atom:updated>2023-06-09T07:43:28.279Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/690/0*JQaELlEpf07GMijJ.png" /></figure><p>In this article we will see how to enable ssh in the container so that we can configure the container by the help of ansible.</p><h3>Pre-Requisite</h3><ul><li>Docker</li><li>Docker SDK</li><li>Python3</li></ul><p>Follow the belows steps to make a customized image</p><ol><li>Pull Centos image using command</li></ol><pre>$docker pull centos:latest</pre><p>2. Launch a container using this image</p><pre>$docker run -dit --name os1 centos:latest</pre><p>3. Login to the container os1</p><pre>$docker attach os1</pre><p>4. Install sshd in this container</p><pre>$yum install openssh-server -y</pre><p>5. Install passwd command</p><pre>$yum install passwd -y</pre><p>5. Set the root passwd</p><pre>$passwd root</pre><p>6. Make ssh service enable permanent, add the path<em> /usr/sbin/sshd</em> to <em>/root/.bashrc</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/0*5pP6BKd99yZZESLI.png" /></figure><p>7. Exit from the container and commit this image with a different name and tag</p><pre>$docker commit os1 centos_ssh:v1</pre><p>Lets create a ansible playbook which launch the container and add thier ip in the inventory for further configuration.</p><pre>- name: start a docker container<br>  docker_container:<br>    name: “os1”<br>    image: centos_ssh:v1<br>    state: started<br>    ports:<br>      — “81:22”<br>      — “8080:80”<br>    interactive: yes<br>    tty: yes<br>    restart: yes<br>  register: x<br>- debug:<br>   msg: this is the IP of docker {{     x.ansible_facts.docker_container.NetworkSettings.IPAddress }}- blockinfile:<br>  path: /etc/ansible/myhosts.txt<br>  block: |<br>        [docker]<br>         {{ x.ansible_facts.docker_container.NetworkSettings.IPAddress }} ansible_ssh_user=root ansible_ssh_pass=redhat</pre><p>Now a container has been lauched with port 22 and 80 exposed, Lets check does this container is able to do ssh or or not for this i’m creating a playbook which will install and enable httpd service in the contianer.</p><pre>- hosts: docker       #here docker contains the ip of contianer<br>  tasks:<br>   — name: install httpd<br>     package:<br>        name: httpd<br>        state: present<br>   — copy:<br>      src: /root/index.html<br>      dest: /var/www/html/index.html <br>   — command: /usr/sbin/httpd         #to start service</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*76TvziZ14F1IPCzT.png" /></figure><p>Playbook runs successfully, now we can use this inventory for further configuration.</p><p>If you have any suggestion and query commen below</p><p>Thanku You!!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d0c45e63ccb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating EC2 based ECS cluster with Terraform]]></title>
            <link>https://surajsoni3332.medium.com/creating-ec2-based-ecs-cluster-with-terraform-70e1052180ca?source=rss-5923bdda6c4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/70e1052180ca</guid>
            <dc:creator><![CDATA[Shubham Soni]]></dc:creator>
            <pubDate>Fri, 09 Jun 2023 07:32:56 GMT</pubDate>
            <atom:updated>2023-06-09T07:32:56.603Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/774/0*BDtbVCMrFJ43h2dq.png" /></figure><p>In this article, we will see how to set up a secure EC2 based ECS cluster with the help of IaaC (Terraform).</p><h3>Terraform</h3><p>Terraform is an open-source infrastructure as a code software tool that helps to deploy infrastructure easily using declarative language(HCL). It allows to write each part of infrastructure once, provides features of rollbacks as well as versioning. By placing the state file remotely multiple team members can work on the same project.</p><h3>Amazon ECS</h3><p>As you are already familiar with some orchestration tools like ( K8s, DockerSwarm), AWS also come with their own similar service (Elastic Container Service) with some more advantages. In this, AWS uses multiple services that are integrated like EC2,cloudwatch,autoscaling_groups and uses the docker as a containerized tool.</p><p>Below Diagram shows the high-level architecture of our cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2J8FKYMgLjT3-eIn.png" /></figure><p>Here we have to set up the VPC according to the needs, autoscaling group always ensures that desired number of instances is always up. ECS service maintains the container inside these instances which contains the application.</p><p>The services which are to be provisioned in infrastructure</p><ol><li>VPC which contains (subnets,internet_gateway,nat_gateway,route_tables)</li><li>Security_groups (filter out the traffic)</li><li>Launch configuration (contains metadata of an instance to be launched)</li><li>Autoscaling group (make desired instances up)</li><li>Application Load Balancer (helps to distribute the traffic)</li><li>Roles ( permissions to be given for interaction with another service)</li><li>ECS cluster</li><li>ECS task_definitions</li><li>ECS service</li></ol><p>Let’s start building one by one with the help of terraform</p><h3>Provider</h3><p>Before moving ahead lets set the providers, if aws cli is already configured with credentials then simply provide the profile and region name.</p><pre>provider &quot;aws&quot; {<br>    profile = &quot;profile name&quot;<br>    region = var.region<br>  <br>}</pre><h3>VPC</h3><p>Amazon Virtual Private Cloud (VPC) gives you complete control over your virtual networking environment including resource placement, connectivity, and security.</p><pre>resource &quot;aws_vpc&quot; &quot;this&quot; {<br>    cidr_block = var.vpccidr<br>    instance_tenancy = var.tenancy                            ~This will create a VPC in your account.<br>    tags = {<br>      &quot;Name&quot; = &quot;Ecs-Vpc&quot;<br>    }<br>  <br>}<br><br>resource &quot;aws_subnet&quot; &quot;private&quot; {<br>    count = length(var.azs)<br>    availability_zone = element(var.azs,count.index)<br>    vpc_id = aws_vpc.this.id                                  ~ creates desired number of private subnet within a given range of CIDR.<br>    cidr_block = element(var.prvcidr,count.index)<br>tags = {<br>    &quot;Name&quot; = &quot;private-${count.index+1}&quot;<br>}<br>  <br>}<br>resource &quot;aws_subnet&quot; &quot;public&quot; {<br>    count = length(var.azs)<br>    availability_zone = element(var.azs,count.index)<br>    vpc_id = aws_vpc.this.id                                  ~ create the desired number of public subnets within a given range of CIDR.<br>    cidr_block = element(var.pubcidr,count.index)<br>    map_public_ip_on_launch = true<br>  <br>tags = {<br>  &quot;Name&quot; = &quot;public-${count.index+1}&quot;<br>}<br>}<br><br><br>resource &quot;aws_internet_gateway&quot; &quot;gw&quot; {<br>    depends_on = [                                            <br>      aws_vpc.this<br>    ]<br>    vpc_id = aws_vpc.this.id<br><br>tags = {<br>      &quot;Name&quot; = &quot;Ecs-gw&quot;<br>    }<br>}<br><br>resource &quot;aws_route_table&quot; &quot;public&quot; {<br>    depends_on = [<br>      aws_internet_gateway.gw<br>    ]<br>    vpc_id = aws_vpc.this.id<br>    route {<br>    cidr_block = &quot;0.0.0.0/0&quot;<br>    gateway_id = aws_internet_gateway.gw.id<br>}<br>    <br>    tags = {<br>      &quot;Name&quot; = &quot;pub-routes&quot;<br>    }   <br>}<br><br><br>resource &quot;aws_route_table&quot; &quot;private&quot; {<br>    vpc_id = aws_vpc.this.id<br>    tags = {<br>      &quot;Name&quot; = &quot;private&quot;<br>    }<br>}<br><br>resource &quot;aws_route_table_association&quot; &quot;public&quot; {<br>  count = length(aws_subnet.public.*.id)<br>  subnet_id = element(aws_subnet.public.*.id, count.index)<br>  route_table_id = aws_route_table.public.id<br>}<br>resource &quot;aws_route_table_association&quot; &quot;private&quot; {<br>  count = length(aws_subnet.private.*.id)<br>  subnet_id = element(aws_subnet.private.*.id, count.index)<br>  route_table_id = aws_route_table.private.id<br>  <br>}<br><br><br>resource &quot;aws_eip&quot; &quot;ecs_eip&quot; {<br>  vpc = true<br>}<br>resource &quot;aws_nat_gateway&quot; &quot;ecs_nat&quot; {<br>    depends_on = [<br>      aws_subnet.private<br>    ]<br>  allocation_id = aws_eip.ecs_eip.id<br>  subnet_id = aws_subnet.public.0.id<br><br>}<br><br>resource &quot;aws_route&quot; &quot;nat_route&quot; {<br>  route_table_id = aws_route_table.private.id<br>  nat_gateway_id = aws_nat_gateway.ecs_nat.id<br>  destination_cidr_block = &quot;0.0.0.0/0&quot;<br>}</pre><p><em>~This will create a VPC in your account.</em></p><p><em>~ creates desired number of private subnet within a given range of CIDR.</em></p><p><em>~ create the desired number of public subnets within a given range of CIDR.</em></p><p><em>~ create internet gateway</em></p><p><em>~ create a public route that helps public subnet have local as well as internet connectivity.</em></p><p><em>~create a private route that restricts internet connectivity, hence all private subnets are associated with it, below this rules of routes defined.</em></p><p><em>~ create an elastic IP for the nat gateway</em></p><p><em>~ create nat gateway (allows instance generated data to go to the internet but restricts the outside data. Helps private instances to securely communicate with ECS service.)</em></p><p><em>~ create routes for nat gateway</em></p><h3>Security Groups</h3><p>Security groups act as firewall which helps to filter out the traffic according to the rules. So, here we create sg for our instances as well as for our Load Balancer so that we can control the flow of traffic.</p><pre>resource &quot;aws_security_group&quot; &quot;ecs_ec2_sg&quot; {<br>  name        = &quot;ecs_ec2_sg&quot;<br>  description = &quot;Allow TLS inbound traffic&quot;<br>  vpc_id      = aws_vpc.this.id<br><br>  ingress {<br>    <br>      description      = &quot;TLS from VPC&quot;<br>      from_port        = 0<br>      to_port          = 0<br>      protocol         = &quot;-1&quot;<br>      security_groups  = [aws_security_group.ecs_alb_sg.id]<br>        <br>  }<br><br>    ingress {<br>    <br>      description      = &quot;TLS from VPC&quot;<br>      from_port        = 22<br>      to_port          = 22<br>      protocol         = &quot;tcp&quot;<br>      cidr_blocks      = [&quot;0.0.0.0/0&quot;]<br>        <br>  }<br>  <br><br>  egress {<br>    <br>      from_port        = 0<br>      to_port          = 0<br>      protocol         = &quot;-1&quot;<br>      cidr_blocks      = [&quot;0.0.0.0/0&quot;]<br><br>    <br>    }<br>  <br><br><br>}<br>resource &quot;aws_security_group&quot; &quot;ecs_alb_sg&quot; {<br>  name        = &quot;ecs_alb_sg&quot;<br>  description = &quot;Allow TLS inbound traffic&quot;<br>  vpc_id      = aws_vpc.this.id<br><br>  ingress {<br>    <br>      description      = &quot;TLS from VPC&quot;<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><br>  <br><br>  egress {<br>    <br>      from_port        = 0<br>      to_port          = 0<br>      protocol         = &quot;-1&quot;<br>      cidr_blocks      = [&quot;0.0.0.0/0&quot;]<br><br>    <br>    }<br>  <br><br><br>}</pre><p><em>~ingress rule of instance allows the load balancer to hit on any port of the instances because each time container got diff port. So we can’t decide which ports the new container holds</em></p><p><em>~open port 22 for all for ssh, but the best practice is that give a fixed IP of your bastion host.</em></p><p><em>~ all traffic generated by the instance can go out.</em></p><p><em>~ ingress rule of load balancer will allow all the traffic on the internet can hit on port 80 of the load balancer.</em></p><p><em>~ all traffic from load balancer can go out</em></p><h3>Launch Configuration</h3><p>A launch configuration is <strong>an instance configuration template that an Auto Scaling group uses to launch EC2 instances</strong>. Include the ID of the Amazon Machine Image (AMI), the instance type, a key pair, one or more security groups, and a block device mapping.</p><p>Here we use the latest ECS optimized AMI which has inbuilt features of ECS, we just have to modify the config file according to our needs. The file userdata.sh contains the config file.</p><pre>resource &quot;aws_launch_configuration&quot; &quot;ecs_launch_config&quot; {<br>    image_id             = var.ecs_ami<br>    iam_instance_profile = aws_iam_instance_profile.ecs_role.name<br>    security_groups      = [aws_security_group.ecs_ec2_sg.id]<br>    user_data            = templatefile(&quot;userdata.sh&quot;,<br>    {<br>      clustername = var.clusterName<br>      region      = var.region<br>    })<br>    instance_type        = &quot;t2.micro&quot;<br>    key_name             = var.key_name<br>}</pre><p><em>~here we have to mention the detail of instances like ami, instance_type,key_pair,user_data, roles. So, it will be easy to launch instances directly from launch_configuration.</em></p><h3>Autoscaling Group</h3><p>An <em>Auto Scaling group</em> contains a collection of Amazon EC2 instances that are treated as a logical grouping for the purposes of automatic scaling and management. An Auto Scaling group also enables you to use Amazon EC2 Auto Scaling features such as health check replacements and scaling policies. Both maintaining the number of instances in an Auto Scaling group and automatic scaling are the core functionality of the Amazon EC2 Auto Scaling service. Asg needs launch_configuration or launch template to launch instances.</p><pre>resource &quot;aws_autoscaling_group&quot; &quot;ecs_sg&quot; {<br><br>    name                      = &quot;asg&quot;<br>    vpc_zone_identifier       = aws_subnet.private.*.id<br>    launch_configuration      = aws_launch_configuration.ecs_launch_config.name<br><br>    desired_capacity          = var.desired_capacity_asg<br>    min_size                  = var.min_size_asg<br>    max_size                  = var.max_size_asg<br>    health_check_grace_period = 150<br>    health_check_type         = &quot;EC2&quot;<br>    <br>}</pre><p><em>~here it is compulsory to pass the vpc_zone and launch_Config, to know more about the attributes used here refer to official </em><a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/autoscaling_group"><em>docs</em></a><em>.</em></p><h3>Load Balancer</h3><p>Elastic Load Balancing automatically distributes your incoming traffic across multiple targets, such as EC2 instances, containers, and IP addresses, in one or more Availability Zones. It monitors the health of its registered targets, and routes traffic only to the healthy targets. Elastic Load Balancing scales your load balancer as your incoming traffic changes over time. It can automatically scale to the vast majority of workloads.</p><pre>resource &quot;aws_lb_target_group&quot; &quot;autoscaleTG&quot; {<br>  name     = &quot;AutoscaleTG&quot;<br>  port     = 80<br>  protocol = &quot;HTTP&quot;<br>  vpc_id   = aws_vpc.this.id<br>}<br><br>## application load balancer<br>resource &quot;aws_lb&quot; &quot;ecs_lb&quot; {<br>  name               = &quot;ecslb&quot;<br>  internal           = false<br>  load_balancer_type = &quot;application&quot;<br>  security_groups    = [aws_security_group.ecs_alb_sg.id]<br>  subnets            = aws_subnet.public.*.id<br>  enable_deletion_protection = false<br><br>}<br>## listener for load balancer<br>resource &quot;aws_lb_listener&quot; &quot;front_end&quot; {<br>  load_balancer_arn = aws_lb.ecs_lb.arn<br>  port              = &quot;80&quot;<br>  protocol          = &quot;HTTP&quot;<br>  <br><br>  default_action {<br>    type             = &quot;forward&quot;<br>    target_group_arn = aws_lb_target_group.autoscaleTG.arn<br>  }<br>}<br>resource &quot;aws_lb_listener_rule&quot; &quot;test&quot; {<br>  listener_arn = aws_lb_listener.front_end.arn<br>  priority     = 100<br><br>  action {<br>    type             = &quot;forward&quot;<br>    target_group_arn = aws_lb_target_group.autoscaleTG.arn<br>  }<br><br>  condition {<br>    path_pattern {<br>      values = [&quot;/home/*&quot;]<br>    }<br>  }<br>}<br><br><br>output &quot;alb_dnsname&quot; {<br>  value = aws_lb.ecs_lb.dns_name<br>}</pre><p><em>~it will create a target group that holds the target where the load is to be distributed, and this will be attached to the ECS service</em></p><p>~<em>then it creates the load balancer with essential attributes such as type, security_group_id, subnets(public)</em></p><p>~ <em>also create frontend rule for load balancer where it listens to the traffic.</em></p><p>~ s<em>hows the dns_name as output</em></p><h3>IAM Roles</h3><p>An IAM <em>role</em> is an IAM identity that you can create in your account that has specific permissions. An IAM role is similar to an IAM user, in that it is an AWS identity with permission policies that determine what the identity can and cannot do in AWS. However, instead of being uniquely associated with one person, a role is intended to be assumable by anyone who needs it. Also, a role does not have standard long-term credentials such as a password or access keys associated with it. Instead, when you assume a role, it provides you with temporary security credentials for your role session.</p><pre>data &quot;aws_iam_policy_document&quot; &quot;ecs_task-assume-role-policy&quot; {<br>  statement {<br>    actions = [&quot;sts:AssumeRole&quot;]<br><br>    principals {<br>      type        = &quot;Service&quot;<br>      identifiers = [&quot;ecs-tasks.amazonaws.com&quot;]<br>    }<br>  }<br>}<br><br><br>resource &quot;aws_iam_role&quot; &quot;ecsTaskExecution_role&quot; {<br>  name               = &quot;ecsTaskExecution_role&quot;<br>  assume_role_policy = data.aws_iam_policy_document.ecs_task-assume-role-policy.json<br>}<br>resource &quot;aws_iam_role_policy&quot; &quot;ecsTaskExecution_policy&quot; {<br>  name = &quot;ecsTaskExecPolicy&quot;<br>  role = aws_iam_role.ecsTaskExecution_role.id<br>  policy = file(&quot;policies/ecsTaskExecutionPolicy.json&quot;)<br>}<br><br><br><br><br><br>#ecs role for Ec2 instance<br><br>data &quot;aws_iam_policy_document&quot; &quot;instance-assume-role-policy&quot; {<br>  statement {<br>    actions = [&quot;sts:AssumeRole&quot;]<br><br>    principals {<br>      type        = &quot;Service&quot;<br>      identifiers = [&quot;ec2.amazonaws.com&quot;]<br>    }<br>  }<br>}<br><br>resource &quot;aws_iam_role&quot; &quot;ecsinstance_role&quot; {<br>  name               = &quot;ecsinstance_role&quot;<br>  assume_role_policy = data.aws_iam_policy_document.instance-assume-role-policy.json<br>}<br>resource &quot;aws_iam_role_policy&quot; &quot;ecspolicy&quot; {<br>  name = &quot;ecspolicy&quot;<br>  role = aws_iam_role.ecsinstance_role.id<br>  policy = file(&quot;policies/ecsInstancePolicy.json&quot;)<br>}<br>  resource &quot;aws_iam_instance_profile&quot; &quot;ecs_role&quot; {<br>  name = &quot;ecs_role&quot;<br>  role = aws_iam_role.ecsinstance_role.name<br>}</pre><p><em>~ it will create a role for the ec2 instance and ECS-task so that they can communicate to the ECS service.</em></p><h3>ECS cluster</h3><p>An Amazon ECS cluster is a logical grouping of tasks or services. Tasks and services are run on infrastructure that is registered to a cluster. Here we first create an empty cluster and then add the computing, task definition and service. For the computing we have to pass the cluster name in the ecs.config file in the computing units here in ec2-instances, then it will automatically connects with the cluster if it has permission to do so.</p><pre>resource &quot;aws_ecs_cluster&quot; &quot;ecs_cluster&quot; {<br>  <br>  name = &quot;${var.clusterName}&quot;<br><br>  setting {<br>    name  = &quot;containerInsights&quot;<br>    value = &quot;enabled&quot;<br>  }<br>}</pre><p><em>~an empty cluster will create with container insights</em></p><h3>Task Definition</h3><p>A task definition is required to run Docker containers in Amazon ECS. The following are some of the parameters you can specify in a task definition:</p><ul><li>The Docker image to use with each container in your task</li><li>How much CPU and memory to use with each task or each container within a task</li><li>The launch type to use, which determines the infrastructure on which your tasks are hosted</li><li>The Docker networking mode to use for the containers in your task</li><li>The logging configuration to use for your tasks</li><li>Whether the task should continue to run if the container finishes or fails</li><li>The command the container should run when it is started</li><li>Any data volumes that should be used with the containers in the task</li><li>The IAM role that your tasks should use</li></ul><pre>resource &quot;aws_ecs_task_definition&quot; &quot;service&quot; {<br>  family = &quot;vimal13&quot;<br>  network_mode = &quot;bridge&quot;<br>  requires_compatibilities = [&quot;EC2&quot;]<br>  task_role_arn = aws_iam_role.ecsTaskExecution_role.arn<br>  execution_role_arn = aws_iam_role.ecsTaskExecution_role.arn<br>  container_definitions = jsonencode([<br>    {<br>      name      = &quot;first&quot;<br>      image     = &quot;vimal13/apache-webserver-php&quot;<br>      cpu       = 200<br>      memory    = 200<br>      essential = true<br>      portMappings = [<br>        {<br>          containerPort = 80<br>          hostPort      = 0<br>        }<br>      ]<br>    },<br>    <br>  ])<br>}</pre><p><em>~ here I am passing my own customized image which helps to detect that load is successfully distributed among the containers.</em></p><p><em>We can pass more attributes their like volume, scripts, and many more, refer </em><a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/ecs_task_definition"><em>docs </em></a><em>for more info.</em></p><h3>ECS Service</h3><p>An Amazon ECS service allows to run and maintain a specified number of instances of a task definition simultaneously in an Amazon ECS cluster. If any of your tasks should fail or stop for any reason, the Amazon ECS service scheduler launches another instance of your task definition to replace it in order to maintain the desired number of tasks in the service.</p><p>In addition to maintaining the desired number of tasks in your service, run our service behind the load balancer. The load balancer distributes traffic across the tasks that are associated with the service.</p><pre>resource &quot;aws_ecs_service&quot; &quot;worker&quot; {<br>  name            = &quot;worker&quot;<br>  cluster         = aws_ecs_cluster.ecs_cluster.id<br>  task_definition = aws_ecs_task_definition.service.arn<br>  desired_count   = var.count_container<br>  iam_role          = var.service_arn<br>  load_balancer {<br>      target_group_arn = aws_lb_target_group.autoscaleTG.arn<br>      container_name = &quot;first&quot;<br>      container_port = 80<br>  }<br>}</pre><p>~ task_definition arn can be found inside your iam console</p><p>~ pass the target arn here so that the containers are registered in the target group of the load balancer.</p><blockquote><em>IMP** Don not pass the target group arn in the auto scalling group otherwise your traffic will not be pass to the containers.</em></blockquote><h3>Deploying the code</h3><p>Before deploying firstly we have to install all the plugins of terraform and create a working directory where all data related to the infrastructure to be saved in the form of key pair. This working direct can be anywhere ( for ex. in S3), but here we initializing this in local. These all can be done by a single command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/0*IuNBbIpqabPbEn62.png" /></figure><p>Before applying any changes its good practice creates a plan which gives a rough idea of what is going to be implemented.</p><pre>$terraform plan</pre><p>If everything seems ok then apply all changes by the command</p><pre>$terraform apply</pre><p>For deletion of the infrastrtucture use command</p><pre>$terraform destroy</pre><blockquote><em>If we want to make any changes to the configuration of the instances we can do the same by launching a bastion host in the public subnet.</em></blockquote><p>Hope you like my work and got something new. Thank You!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70e1052180ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>