<?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 Majdnull on Medium]]></title>
        <description><![CDATA[Stories by Majdnull on Medium]]></description>
        <link>https://medium.com/@majdnull?source=rss-3842da3c44b8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*LTjo5v53ogXBuiZVzzK_oQ@2x.jpeg</url>
            <title>Stories by Majdnull on Medium</title>
            <link>https://medium.com/@majdnull?source=rss-3842da3c44b8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 11:15:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@majdnull/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[DevSecOps Project Using IAC : Part 11 (Kubernetes Operations and Security)]]></title>
            <link>https://medium.com/@majdnull/devsecops-project-using-iac-part-11-kubernetes-operations-and-security-e1816d9f965d?source=rss-3842da3c44b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1816d9f965d</guid>
            <dc:creator><![CDATA[Majdnull]]></dc:creator>
            <pubDate>Sat, 13 Apr 2024 12:03:17 GMT</pubDate>
            <atom:updated>2024-04-13T12:03:17.093Z</atom:updated>
            <content:encoded><![CDATA[<h3>DevSecOps Project Using IAC : Part 11 (Kubernetes Operations and Security)</h3><blockquote>LinkedIn : <a href="http://www.linkedin.com/in/majd-zahran-4314b1235">Majd Zahran</a> , <strong>Please Don’t Hesitate to Contact Me</strong></blockquote><h4>Part 11 (Kubernetes Operations and Security)</h4><p><a href="https://medium.com/@majdnull/devsecops-project-using-iac-overview-project-notes-febf35517839"><strong><em>From the start — Introduction</em></strong></a></p><p><a href="https://medium.com/@majdnull/devsecops-project-using-iac-part-10-implement-the-security-stages-on-the-cd-pipeline-f0188423444e"><strong><em>Previous Part — part 10</em></strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yzB5u1UfjORAEJvCz4xrVg.png" /></figure><h4><em>Pod-Pod Communication — Need for mTLS</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*jaiCKRGMw_NHf6ydAeu__A.png" /></figure><blockquote><em>suppose we have kubernetes node that have a 2 pod , and we need to communicate these pods with each other , the communication between this 2 pods is in plane text ( HTTP ) , so if there an attacker in same network he can see all data that sent between these 2 pods , so we need to implement a TLS , to make the communication over HTTPS ⇒ so how we can do that ??</em></blockquote><p>By using<strong><em> </em></strong><strong><em>Service Meshes </em></strong>like<strong><em> </em></strong><strong><em>Istio</em></strong></p><p><strong><em>ISTIO</em></strong> ⇒ <em>is a service mesh , when u install Istio within kubernetes and when u enable it for a specific namespace when you deploy a pod</em> .</p><ul><li>Istio Sidecar Proxy will also be deployed within the same pod running as a container ⇒ this Istio Sidecar container takes care of the TLS handshake</li></ul><blockquote>now if these pods want to communicate with each other so now the web server like nginx container from pod one will send the data to the Istio Sidecar proxy . Here the Sidecar proxy will encrypt the data using its keys , and it will be transmitted to the next pod over HTTPS ⇒ and the second pod the Istio Sidecar proxy will decrypt the data and give the decrypted data to the web server.</blockquote><p><strong><em>A service mesh is a dedicated infrastructure layer for handling service-to-service communication. It provides a way to manage, secure, and monitor communication between microservices in a containerized application. Service meshes often use sidecar proxies (such as Envoy) to intercept and manage communication between services .</em></strong></p><h3><em>ISTIO</em></h3><p><strong><em>Istio</em></strong> ⇒ is an open framework for <em>connecting</em> , <em>securing</em> , <em>managing and monitoring microservices</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*8ajTuMvtAgpYMQmc9DrzkA.png" /></figure><blockquote>Service Meshes helps in handling communication between services without the need to change code within each micro-service</blockquote><p>as we can see the Istio Mesh divided to 2 phases:</p><ul><li><strong><em>Data Plane &amp;&amp; control plane </em></strong>⇒ The Data Plane is composed of set intelligent proxies called envoy , which are deployed as Sidecar along your application within same pod . This Sidecar Proxies , they collect and report telemetry on all mesh traffic.</li></ul><p>Envoy is high-performance proxy , which is developed in c++ to mediate all inbound and outbound traffic but all services within the service mesh</p><blockquote><em>Whereas the control plane manages and configures the proxies to route the traffic &amp;&amp; it have 3 components ⇒ Pilot , Citadel , Galley</em></blockquote><ul><li>Pilot ⇒ is core component used for traffic management</li><li>Citadel ⇒ is used for service-to-service authentication using mutual TLS .</li><li>Galley ⇒ is used for data configuration , Galley is responsible for interpreting the YAML file in kubernetes and transforming them into a format that the Istio understand .</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/929/1*b2ANSNx99YBGV6GWrRPBjA.png" /></figure><p>look to this :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*byYJLqkmjT_Dw8vazEZ9fg.png" /></figure><p>Because it’s a demo project we will not deploy and applied it to our application</p><h4><em>Promoting App to Prod and Visualize using Kiali</em></h4><blockquote><em>Now we need to deploy our application to production ⇒</em></blockquote><ul><li>So first we will add this stage to the pipeline for deployment purposes</li></ul><pre>K8S_Deployment_PROD:<br>  stage: K8S_Deployment_PROD<br>  script:<br>    - sed -i &#39;s#replace#${imageName}#g&#39; k8s_PROD-deployment_service.yaml<br>    - kubectl apply --namespace=prod -f k8s_PROD-deployment_service.yaml<br>    - bash k8s-PROD-deployment-rollout-status.sh</pre><p>Now we need to type the <strong><em>k8s_PROD-deployment_service.yaml</em></strong></p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  labels:<br>    app: devsecops<br>  name: devsecops<br>spec:<br>  replicas: 3<br>  selector:<br>    matchLabels:<br>      app: devsecops<br>  strategy: {}<br>  template:<br>    metadata:<br>      labels:<br>        app: devsecops<br>    spec:<br>      serviceAccountName: default<br>      volumes:<br>      - name: vol<br>        emptyDir: {}<br>      containers:<br>      - image: replace<br>        name: devsecops-container<br>        volumeMounts:<br>          - mountPath: /tmp<br>            name: vol<br>        securityContext:<br>          capabilities:<br>            drop:<br>             - NET_RAW<br>          runAsUser: 100<br>          runAsNonRoot: true<br>          readOnlyRootFilesystem: true<br>          allowPrivilegeEscalation: false<br>        resources:<br>         requests:<br>          memory: &quot;256Mi&quot;<br>          cpu: &quot;200m&quot;<br>         limits:<br>          memory: &quot;512Mi&quot;<br>          cpu: &quot;500m&quot;<br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  labels:<br>    app: devsecops<br>  name: devsecops-svc<br>spec:<br>  ports:<br>  - port: 8080<br>    protocol: TCP<br>    targetPort: 8080<br>  selector:<br>    app: devsecops<br>  type: ClusterIP</pre><blockquote>as you can see the type deployment , and we set the replica set with value 3 , and as you can see we add a security context ⇒ <em>here we drop NET-RAW</em> , why ?? ⇒ <em>we did that to prevent a network attack on our cluster like ( DNS Spoofing )</em></blockquote><p>Now we need to type the <strong><em>k8s-PROD-deployment-rollout-status.sh</em></strong></p><pre>#!/bin/bash<br>sleep 60s<br><br>if [[ $(kubectl -n prod rollout status deploy ${deploymentName} --timeout 5s) != *&quot;successfully rolled out&quot;* ]]; <br>then     <br> echo &quot;Deployment ${deploymentName} Rollout has Failed&quot;<br>    kubectl -n prod rollout undo deploy ${deploymentName}<br>    exit 1;<br>else<br> echo &quot;Deployment ${deploymentName} Rollout is Success&quot;<br>fi</pre><p>The change here from the dev stage , is we set the node to production node just</p><blockquote>And now with Kiali we can change the service type from ClusterIP to NordPort and then see it’s dashboard in browser , and then see all traffic in gui and see the inbound and outbound traffics</blockquote><h4><em>Kubernetes Monitoring</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fWKf1PklhjKX4uwf_v_8ng.png" /></figure><blockquote><em>as we know on of the important thing is to monitoring your kubernetes resources like : pods , deployment , nodes , the application ⇒ so we want to see what the node availability and health , the missing and failed pods , the running instance …etc</em></blockquote><p>so we can use a open source tool to do this job like ⇒ Prometheus &amp;&amp; Grafana</p><h3><em>Prometheus &amp;&amp; Grafana</em></h3><p><strong><em>Prometheus</em></strong> ⇒ <em>is a open source metric-based monitoring and alerting system</em> , it has a powerful query lang called PromQL , with multidimensional data model suited for strong time series data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jVYNZszXikUYYe3NPb3UOg.png" /></figure><blockquote><em>we can use Prometheus as time series database to store matrices , and u can custom any alerting scenario</em></blockquote><blockquote><em>it’s a white box tool that based on your CPU , data consumption , number of requests , response time , it will work</em></blockquote><blockquote><em>So it’s fid the target using the service discovery + it pull the matrices from the application library and it can be exported it to any 3rd party application + and it stored the scraped data on the local storage + on talking to Data visualization </em><strong>Grafana</strong><em> </em>is the leading open source software for time series analytics<em> , </em>and it fetch the metrics via PromQL<em> , </em>it allow you to query , visualize and understand your metrics<em> .</em></blockquote><ul><li>The <strong><em>Grafana &amp;&amp;</em></strong> Prometheus ⇒ is from the istio system , u can see it from ⇒ <strong><em>kubectl -n istio-system get svc</em></strong></li></ul><blockquote><em>Now u will see it , so to see it on the browser u need to change these services from ClusterIP type to NodePort</em></blockquote><h3><em>Falco</em></h3><blockquote><em>is open source cloud-native runtime security project</em></blockquote><ul><li><strong><em>Falco detect unexpected application behavior and alerts on threats runtime</em></strong> .</li></ul><blockquote><em>it has complete container visibility through a single sensor that allow us to gain insight into application and container behavior .</em></blockquote><blockquote><em>Falco is based on rules and it detect and alert if this rules are met , like : a shell is run inside the container , the /etc/shadow file read from unexpected resource …etc</em></blockquote><ul><li>U can install it using the binary and configure with your kubernetes , or if u want the UI version u can use the <strong><em>Falcosidekick UI</em></strong></li></ul><blockquote><em>When u install the binary it will configure directly with your kubernetes and if u run a shell on any pod , if u see the Falco logs u will see the alert</em></blockquote><h4><em>Falco UI — HELM</em></h4><blockquote>Now in order to configure the binary Falco with the Falcosidekick UI , we need to install helm first</blockquote><p><strong><em>HELM chart</em></strong> ⇒ <em>are packages ( like rpms ) , it’s contain pre-configured kubernetes resources such as : ConfigMaps , Deployments , Services.</em></p><p><strong><em>Helm is the packages manager for kubernetes ( like yum ) that allows easily packages , configure , and deploy application onto kubernetes cluster .</em></strong></p><blockquote>To install it ⇒</blockquote><pre>curl https://baltocdn.com/helm/signing.asc | gpg --dearmor | sudo tee /usr/share/keyrings/helm.gpg &gt; /dev/null<br>sudo apt-get install apt-transport-https --yes<br>echo &quot;deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/helm.gpg] https://baltocdn.com/helm/stable/debian/ all main&quot; | sudo tee /etc/apt/sources.list.d/helm-stable-debian.list<br>sudo apt-get update<br>sudo apt-get install helm</pre><blockquote>Then to install Falcosidekick using HELM ⇒</blockquote><pre>kubectl create namespace falco<br>helm repo add falcosecurity https://falcosecurity.github.io/charts<br>helm install falco falcosecurity/falco \<br>--set falcosidekick.enabled=true \<br>--set falcosidekick.webui.enabled=true \<br>--set falcosidekick.config.slack.webhookurl=&quot;https://hooks.slack.com/services/XXXX&quot; \<br>-n falco</pre><p>U can verify that by run ⇒ <strong><em>kubectl -n falco get all</em></strong></p><p>Now we can verify that , there’s alot of things can be applied to kubernetes to secure it , but we will set on what we do for now .</p><p>Finally we come to the last part , thanks for being with me all this stories, i hope u enjoy with me and learn somethings .</p><h3>Summary</h3><p>In this part we see the security in kubernetes and who we can applied some security tool to our kubernetes and see how to deploy our application to kubernetes for prod and dev .</p><p>Now we will not have a next part for sorry :( , thanks for be with me along all these stories , and i hope see you in next projects.</p><p>For any thing, you can contact me in my LinkedIn : <a href="http://www.linkedin.com/in/majd-zahran-4314b1235">Majd Zahran</a></p><p><a href="https://medium.com/@majdnull/devsecops-project-using-iac-overview-project-notes-febf35517839">From Introduction</a>.</p><p><a href="https://medium.com/@majdnull/devsecops-project-using-iac-part-10-implement-the-security-stages-on-the-cd-pipeline-f0188423444e">Previous Story — Implement the security stages on the CD Pipeline</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1816d9f965d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DevSecOps Project Using IAC : Part 10(Implement the security stages on the CD Pipeline)]]></title>
            <link>https://medium.com/@majdnull/devsecops-project-using-iac-part-10-implement-the-security-stages-on-the-cd-pipeline-f0188423444e?source=rss-3842da3c44b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0188423444e</guid>
            <dc:creator><![CDATA[Majdnull]]></dc:creator>
            <pubDate>Fri, 12 Apr 2024 16:41:55 GMT</pubDate>
            <atom:updated>2024-04-13T12:06:41.189Z</atom:updated>
            <content:encoded><![CDATA[<h3>DevSecOps Project Using IAC : Part 10(Implement the security stages on the CD Pipeline)</h3><blockquote><em>LinkedIn : </em><a href="http://www.linkedin.com/in/majd-zahran-4314b1235"><em>Majd Zahran</em></a><em> , </em><strong><em>Please Don’t Hesitate to Contact Me</em></strong></blockquote><h3>Part 10: Implement the security stages on the CD Pipeline (Continuous Deployment/Delivery).</h3><p><a href="https://medium.com/@majdnull/devsecops-project-using-iac-overview-project-notes-febf35517839"><strong><em>From the start — Introduction</em></strong></a></p><p><a href="https://medium.com/@majdnull/devsecops-project-using-iac-part-9-implement-the-security-stages-on-the-ci-pipeline-2fa37b96ec9a"><strong><em>Previous Part — part 9</em></strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*9_Mj1bn3aV71UmEzcPcJ0A.png" /></figure><p>In this part we will Implement the security stages into our Continuous Deployment/Delivery (CD) pipeline.</p><h3><em>Trivy — docker image scanning</em></h3><p><strong><em>Trivy</em></strong> ⇒ <em>is a simple and comprehensive vulnerability scanner for </em>containers<em> and other artifacts</em> .</p><p>As we all know one of the core of any projects or application is the docker image , because every project contain multi microservices , the concept of DevOps methodology is to run every technology we have like to run the backend &amp; frontend and database each one in a docker image then let these docker images communication with each other.</p><p>So because of that in the real world you will see many cases , a base image like : java , python , these images can be found in docker hub so it’s like a standards images that another one created , and the another type is a customized images that you create , so because of that we need to scan every image before use it , we don’t know what inside every image , one vulnerable image will cost you alot trust me .</p><p>Here you can see the power of trivy , it will scan every image you have and if it vulnerable image or not , then when we will add it to our pipeline it will fail the project if it find a critical or high vuln on this image.</p><blockquote>To run it on any docker image ⇒ <strong><em>trivy image &lt;name of image &gt;</em></strong></blockquote><p>Now we need to added it to our pipeline , because on the the latest version of gitlab , there are some features changes and this effects to the trivy commands that should used so because of that i search and try alot to make it work like previous time but i fail , so for now we will use trivy and we will let it generate a reports for us but it can’t fail the pipeline if there are a vulnerabilities with our docker image or our dependences.</p><p>so we will work with trivy as a auto devops , what that mean ?? i will tell u, gitlab have a overpower feature called auto devops , this mean u can let your pipeline to use a templates instead of write a hole code to run your tool , for example: if we want to run our SAST tool , we saw previously we write a big chunk of command to run it , now instead of doing that we will can use the concept of templets , it’s a required command to run your tool in a templet it’s provided by gitlab and u can use it instead of write the command , for more info read this: <a href="https://medium.com/globant/optimize-pipeline-implementation-using-gitlab-ci-templates-6eef54046231">gitlab templets</a>.</p><p>You can find all the <a href="https://gitlab.com/gitlab-org/gitlab-foss/-/tree/master/lib/gitlab/ci/templates">gitlab templets here</a> , it’s have alot of templets u can use.</p><p>Now to use any templets that can be done easily by using <strong><em>include</em></strong> parameter</p><pre>include:<br>  - template: &lt;templet folder if it exist in folder&gt;/&lt;name of templet&gt;</pre><blockquote>U should but the include on top of your <strong><em>gitlab-ci.yml</em></strong> file.</blockquote><p>Now let’s take this advantage and use it in our pipeline , we need to include it and create a stage to provide the image that should be scanned.</p><pre>include:<br>  - template: Jobs/Container-Scanning.latest.gitlab-ci.yml<br><br>container_scanning:<br>  stage: CD-security-stages<br>  variables:<br>    CS_IMAGE: $image</pre><p>now we use the the Container-Scanning.latest templet for scanning our containers and it already scan our dependences , then we make the stage and provide it with the our image as variables.</p><p>Now our pipeline should be like this :</p><pre>stages:<br>  - build<br>  - test<br>  - CI-security-stages<br>  - CD-security-stages<br>  - deploy<br>  - dev_deploy<br><br>include:<br>  - template: Jobs/Container-Scanning.latest.gitlab-ci.yml<br><br>build_app:<br>  stage: build<br>  before_script:<br>    - apt-get update &amp;&amp; apt-get install maven -y<br>  script:<br>    - mvn clean package -DskipTests=true<br>  artifacts:<br>    paths:<br>      - target/*.jar<br><br>unit_tests:<br>  stage: test<br>  before_script:<br>    - apt-get update &amp;&amp; apt-get install maven -y<br>  script:<br>    - mvn test<br><br>sonarqube-check:<br>  stage: CI-security-stages<br>  image: <br>    name: sonarsource/sonar-scanner-cli:5.0<br>    entrypoint: [&quot;&quot;]<br>  variables:<br>    SONAR_USER_HOME: &quot;${CI_PROJECT_DIR}/.sonar&quot;  # Defines the location of the analysis task cache<br>    GIT_DEPTH: &quot;0&quot;  # Tells git to fetch all the branches of the project, required by the analysis task<br>  cache:<br>    key: &quot;${CI_JOB_NAME}&quot;<br>    paths:<br>      - .sonar/cache<br>  script: <br>    - sonar-scanner<br>  allow_failure: true<br>  only:<br>    - part8<br><br>owasp_dependency_check:<br>  image:<br>    name: owasp/dependency-check<br>    entrypoint: [ &quot;&quot; ]<br>  stage: CI-security-stages<br>  variables:<br>    DEPCHECK_NO_UPDATE: &quot;false&quot;<br>    DEPCHECK_OPTIONS: &quot;&quot;<br>    DEPCHECK_CVSS_SCORE_FAIL: &quot;5&quot;<br>    DEPCHECK_JUNIT_CVSS_FAIL: &quot;0&quot;<br>    DEPCHECK_EXPERIMENTALS: &quot;false&quot;<br>    DOTNET_DLL_ANALYZE: &quot;false&quot;<br>    DOTNET_VERSION: &quot;3.1&quot;<br>    PROJECT_ROOT: &quot;/&quot;<br>  cache:<br>    key: &quot;dependency-check:data&quot;<br>    paths:<br>      - ${CI_PROJECT_DIR}/dependency-check/data/<br>  script:<br>    # Installing .net if needed<br>    - |<br>      if [ &quot;$DOTNET_DLL_ANALYZE&quot; = &quot;true&quot; ]; then<br>        apk add wget curl bash unzip<br>        # Script coming from dotNET_Build job<br>        apk add autoconf build-base clang clang-dev cmake curl-dev gcc gettext-dev git icu-dev krb5-dev libtool linux-headers llvm make zlib-dev<br>        curl -O https://dotnet.microsoft.com/download/dotnet-core/scripts/v1/dotnet-install.sh<br>        chmod +x dotnet-install.sh<br>        bash dotnet-install.sh -Channel ${DOTNET_VERSION}<br>        export PATH=&quot;/root/.dotnet/:$PATH&quot;<br>      fi<br>    # Creating Dependency-Check report folder<br>    - mkdir ${CI_PROJECT_DIR}/report/<br>    # Env variables checking<br>    - if [ &quot;$DEPCHECK_NO_UPDATE&quot; = &quot;true&quot; ]; then export DEPCHECK_OPTIONS=&quot;-n $DEPCHECK_OPTIONS&quot;; fi<br>    - if [ &quot;$DEPCHECK_EXPERIMENTALS&quot; = &quot;true&quot; ]; then export DEPCHECK_OPTIONS=&quot;--enableExperimental $DEPCHECK_OPTIONS&quot;; fi<br>    # Lauchning analyze<br>    - /usr/share/dependency-check/bin/dependency-check.sh -f JUNIT -s ${CI_PROJECT_DIR}${PROJECT_ROOT} -o ${CI_PROJECT_DIR}/report/ --failOnCVSS ${DEPCHECK_CVSS_SCORE_FAIL} --junitFailOnCVSS ${DEPCHECK_JUNIT_CVSS_FAIL}<br>  artifacts:<br>    when: always<br>    reports:<br>      junit: &quot;${CI_PROJECT_DIR}/report/dependency-check-junit.xml&quot;<br><br>container_scanning:<br>  stage: CD-security-stages<br>  variables:<br>    CS_IMAGE: $image<br><br><br>build-docker:<br>  stage: deploy<br>  image: docker<br>  services:<br>    - docker:dind<br>  before_script:<br>    - echo $CI_REGISTRY_PASSWORD | docker login -u $CI_REGISTRY_USER $CI_REGISTRY --password-stdin<br>  script:<br>    - docker build -t $CI_REGISTRY/majdnull/voting-application .<br>    - docker push $CI_REGISTRY/majdnull/voting-application<br><br>install_kubectl:<br>  stage: dev_deploy<br>  image: <br>    name: alpine:3.7<br>  dependencies: []<br>  before_script:<br>    - wget https://storage.googleapis.com/kubernetes-release/release/$(wget -q -O - https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/linux/amd64/kubectl<br>    - chmod +x ./kubectl<br>    - mv ./kubectl /usr/bin/kubectl<br>  script:<br>    - export KUBECONFIG=$DEV_KUBE_CONFIG<br>    - kubectl version -o yaml<br>    - kubectl get nodes<br><br>deploy_nodejs_on_cluster:<br>  stage: dev_deploy<br>  before_script:<br>    - wget https://storage.googleapis.com/kubernetes-release/release/$(wget -q -O - https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/linux/amd64/kubectl<br>    - chmod +x ./kubectl<br>    - mv ./kubectl /usr/bin/kubectl<br>  script:<br>    - export KUBECONFIG=$DEV_KUBE_CONFIG<br>    - kubectl -n default create deploy node-app --image siddharth67/node-service:v1<br>    - kubectl -n default  expose deploy node-app --name node-service --port 5000<br>    - kubectl get all<br><br><br>k8s_deploy_dev:<br>  stage: dev_deploy<br>  before_script:<br>    - wget https://storage.googleapis.com/kubernetes-release/release/$(wget -q -O - https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/linux/amd64/kubectl<br>    - chmod +x ./kubectl<br>    - mv ./kubectl /usr/bin/kubectl<br>  script:<br>    - export KUBECONFIG=$DEV_KUBE_CONFIG<br>    - kubectl apply -f k8s_deployment_service.yaml</pre><p>When u run the pipeline u can see if it passed , u will have a 3 file in the artifacts , u can download it and see the results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e9AIQdVUi5twxb06_w2mSw.png" /></figure><p>Now let’s go the next stage on our CD-security-Stages .</p><h3>OPA Conftest</h3><p>When we come to docker and containers security a good starting point is to follow some Best Practices while writing proper file, so there are alot of Best Practices of writing a secure docker file or run a docker container , so how we can check of these practices ??</p><p><strong><em>OPA ( Open Policy Agent )</em></strong> ⇒ is an open source , general-purpose policy engine that unifies policy enforcement across the stack .</p><p><strong><em>Conftest</em></strong> ⇒ <em>is a utility to help you write test ( statically analyze ) against structured configuration data</em> .</p><p>Using Conftest u can write tests for :</p><ul><li>kubernetes Configuration</li><li>Terraform code</li><li>Dockerfile or any other config files</li></ul><blockquote><em>Conftest uses the </em><strong>Rego</strong><em> lang from open policy agent for writing the assertions .</em></blockquote><p>While I&#39;m searching about this step i find that gitlab included it on the SAST templet so we don’t need to do it 2 times , so we will skip it :) :) .</p><h3>SAST for our IAC</h3><p>I know the SAST should be on our CI-Security-Stages but i will included it in this story :) .</p><p>Now as we know one of the important part of our project was the creation of our infrastructure using code , but here where the critical things comes , suppose we create weak IAC what that mean ? that mean weak point in our system is the deepest level of the system , and this is the most critical thing might happen to any system , because of that we must ensure that we have a secure IAC process.</p><p>We can do that by check the SAST for our IAC , and this can be done using the <strong><em>SAST-IaC.gitlab-ci</em></strong> , Thanks for gitlab templets .</p><p>now as we did previously in SAST for our code we will do it for IAC, but now we will depend on the power of auto devops :</p><pre>include:<br>  - template: Jobs/SAST-IaC.latest.gitlab-ci.yml<br><br>kics-iac-sast:<br>  stage: CI-security-stages<br>  rules:<br>    - if: &#39;$CI_COMMIT_BRANCH == &quot;part8&quot;&#39;</pre><p>This template will triggers all the IAC files ( ansible, terraform , Aws , Azure …) , then it will run the <strong><em>kics</em></strong> scan to this file and generate a report for you that contain all the vulnibilty with our IAC file , the <strong><em>kics-iac-sast</em></strong> section is just to assign the IAC SAST to the <strong><em>CI-security-stages</em></strong> .</p><h3><em>Kubernetes Security Concepts</em></h3><p>A security context defines privilege and access control settings for a pod or container .</p><blockquote><em>So let’s assume we are dealing with a kubernetes developer , now the kubernetes developer pull alot docker images and for that so we need to make sure that the docker will not running as a root , so some of the kubernetes security context : </em><strong><em>runAsUser</em></strong><em> &amp;&amp; </em><strong><em>runAsNonRoot</em></strong></blockquote><ul><li>When we set <strong><em>runAsUser: 100</em></strong> you require that the containers will run with a UID 100</li><li>When we set <strong><em>runAsNonRoot</em></strong> you require that the containers will run with any UID other than 0</li><li><strong><em>readOnlyRootFilesystem</em></strong> ⇒ that will mounts the containers root filesystem as a <strong><em>read-only</em></strong> , so we can make use of empty directory volume to allow certain directories if required .</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*8btnjFQDlkBfmayz0vDMMA.png" /></figure><blockquote><em>This is just a simple security context , that can be used at the pod level and at a container level.</em></blockquote><h4>Kubescape</h4><p><strong><em>Kubescape</em></strong> ⇒ is an open-source Kubernetes security platform. It includes risk analysis, security compliance, and misconfiguration scanning. Targeted at the DevSecOps practitioner or platform engineer, it offers an easy-to-use CLI interface, flexible output formats, and automated scanning capabilities. It saves Kubernetes users and admins precious time, effort, and resources</p><blockquote>Kubescape scans clusters, YAML files, and Helm charts. It detects misconfigurations according to multiple frameworks (including <a href="https://www.armosec.io/blog/kubernetes-hardening-guidance-summary-by-armo/?utm_source=kubescape.io&amp;utm_medium=website">NSA-CISA</a>, <a href="https://www.microsoft.com/security/blog/2021/03/23/secure-containerized-environments-with-updated-threat-matrix-for-kubernetes/">MITRE ATT&amp;CK®</a> and the <a href="https://www.armosec.io/blog/cis-kubernetes-benchmark-framework-scanning-tools-comparison/?utm_source=kubescape.io&amp;utm_medium=website">CIS Benchmark</a>)</blockquote><p>Now let’s add it as a new job in our pipeline , it will place between the docker build and before the kubernetes deployment stage :</p><pre>kubespace:<br>  stage: CD-security-stages<br>  image: <br>    name: alpine<br>  script:<br>    - apk add curl gcompat<br>    - apk add bash<br>    - curl -s https://raw.githubusercontent.com/kubescape/kubescape/master/install.sh | bash <br>    - kubescape scan --compliance-threshold 80 .</pre><p>that will result on the cli like this :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IiaYEMwGSr1zBlLwEJ9Qjg.png" /></figure><h3>DAST (Dynamic Application Security Testing)</h3><p><strong><em>DAST</em></strong> ⇒ is type of security testing that looks for vuln by simulating external attacks on an application while the application is running .</p><blockquote>For DAST Tools we have some tools like ⇒ Burp Enterprise , OWSP ZAP Proxy</blockquote><p>For the DAST we will use Owsap zap proxy , is powerful tool to scan and attack your application while it running , runtime scanning.</p><p>we will integrate it as a docker image it will be after the deploy stage , so let’s type the pipeline stage</p><pre>Dast-security: <br>  stage: CD-security-stages<br>  image:<br>    name: softwaresecurityproject/zap-stable<br>  before_script:<br>    - mkdir -p /zap/wrk<br>  script:<br>    - pwd<br>    - ls<br>    - zap-full-scan.py -t &quot;https://www.yu.edu.jo/&quot; -m 1 -d -I -r testreport.html <br>    - cp /zap/wrk/testreport.html testreport.html<br>  artifacts:<br>    when: always<br>    paths:<br>      - testreport.html</pre><p>we will use the stable docker image for zap proxy , then we will run it on our application url , and generate a report to see it.</p><p>Now we have 2 type of security ⇒ <strong><em>CI-security-stages</em></strong> &amp;&amp; <strong><em>CD-security-stages</em></strong></p><pre>CI-security-stages:<br>   . secrete detection <br>   . SAST for IAC<br>   . SAST for our code <br>   . Dependency Check<br><br>----------------------------<br><br>CD-security-stages :<br>   . Container Scanning<br>   . Kubernetes Security<br>   . Dast security</pre><p>From there we are implement the security to our pipeline , i know in some spot we have a butter choices , but it just a project to let you learn how to create a project from infrastructure to the deploy stage with almost full automation ways , now we just need to make our front end and the database to store the counter when someone vote , so the next store will be the last story on our project.</p><p>Our pipeline now is look like this:</p><pre>stages:<br>  - build<br>  - test<br>  - CI-security-stages<br>  - CD-security-stages<br>  - deploy<br>  - dev_deploy<br><br>include:<br>  - template: Jobs/Container-Scanning.latest.gitlab-ci.yml<br>  - template: Jobs/SAST-IaC.latest.gitlab-ci.yml<br><br>build_app:<br>  stage: build<br>  before_script:<br>    - apt-get update &amp;&amp; apt-get install maven -y<br>  script:<br>    - mvn clean package -DskipTests=true<br>  artifacts:<br>    paths:<br>      - target/*.jar<br><br>unit_tests:<br>  stage: test<br>  before_script:<br>    - apt-get update &amp;&amp; apt-get install maven -y<br>  script:<br>    - mvn test<br><br>sonarqube-check:<br>  stage: CI-security-stages<br>  image: <br>    name: sonarsource/sonar-scanner-cli:5.0<br>    entrypoint: [&quot;&quot;]<br>  variables:<br>    SONAR_USER_HOME: &quot;${CI_PROJECT_DIR}/.sonar&quot;  # Defines the location of the analysis task cache<br>    GIT_DEPTH: &quot;0&quot;  # Tells git to fetch all the branches of the project, required by the analysis task<br>  cache:<br>    key: &quot;${CI_JOB_NAME}&quot;<br>    paths:<br>      - .sonar/cache<br>  script: <br>    - sonar-scanner<br>  allow_failure: true<br>  only:<br>    - part8<br><br>owasp_dependency_check:<br>  image:<br>    name: owasp/dependency-check<br>    entrypoint: [ &quot;&quot; ]<br>  stage: CI-security-stages<br>  variables:<br>    DEPCHECK_NO_UPDATE: &quot;false&quot;<br>    DEPCHECK_OPTIONS: &quot;&quot;<br>    DEPCHECK_CVSS_SCORE_FAIL: &quot;5&quot;<br>    DEPCHECK_JUNIT_CVSS_FAIL: &quot;0&quot;<br>    DEPCHECK_EXPERIMENTALS: &quot;false&quot;<br>    DOTNET_DLL_ANALYZE: &quot;false&quot;<br>    DOTNET_VERSION: &quot;3.1&quot;<br>    PROJECT_ROOT: &quot;/&quot;<br>  cache:<br>    key: &quot;dependency-check:data&quot;<br>    paths:<br>      - ${CI_PROJECT_DIR}/dependency-check/data/<br>  script:<br>    # Installing .net if needed<br>    - |<br>      if [ &quot;$DOTNET_DLL_ANALYZE&quot; = &quot;true&quot; ]; then<br>        apk add wget curl bash unzip<br>        # Script coming from dotNET_Build job<br>        apk add autoconf build-base clang clang-dev cmake curl-dev gcc gettext-dev git icu-dev krb5-dev libtool linux-headers llvm make zlib-dev<br>        curl -O https://dotnet.microsoft.com/download/dotnet-core/scripts/v1/dotnet-install.sh<br>        chmod +x dotnet-install.sh<br>        bash dotnet-install.sh -Channel ${DOTNET_VERSION}<br>        export PATH=&quot;/root/.dotnet/:$PATH&quot;<br>      fi<br>    # Creating Dependency-Check report folder<br>    - mkdir ${CI_PROJECT_DIR}/report/<br>    # Env variables checking<br>    - if [ &quot;$DEPCHECK_NO_UPDATE&quot; = &quot;true&quot; ]; then export DEPCHECK_OPTIONS=&quot;-n $DEPCHECK_OPTIONS&quot;; fi<br>    - if [ &quot;$DEPCHECK_EXPERIMENTALS&quot; = &quot;true&quot; ]; then export DEPCHECK_OPTIONS=&quot;--enableExperimental $DEPCHECK_OPTIONS&quot;; fi<br>    # Lauchning analyze<br>    - /usr/share/dependency-check/bin/dependency-check.sh -f JUNIT -s ${CI_PROJECT_DIR}${PROJECT_ROOT} -o ${CI_PROJECT_DIR}/report/ --failOnCVSS ${DEPCHECK_CVSS_SCORE_FAIL} --junitFailOnCVSS ${DEPCHECK_JUNIT_CVSS_FAIL}<br>  artifacts:<br>    when: always<br>    reports:<br>      junit: &quot;${CI_PROJECT_DIR}/report/dependency-check-junit.xml&quot;<br><br>container_scanning:<br>  stage: CD-security-stages<br>  variables:<br>    CS_IMAGE: $image<br><br>kics-iac-sast:<br>  stage: CI-security-stages<br>  rules:<br>    - if: &#39;$CI_COMMIT_BRANCH == &quot;part8&quot;&#39;<br><br>build-docker:<br>  stage: deploy<br>  image: docker<br>  services:<br>    - docker:dind<br>  before_script:<br>    - echo $CI_REGISTRY_PASSWORD | docker login -u $CI_REGISTRY_USER $CI_REGISTRY --password-stdin<br>  script:<br>    - docker build -t $image .<br>    - docker push $image<br><br>kubespace:<br>  stage: CD-security-stages<br>  image: <br>    name: alpine<br>  script:<br>    - apk add curl gcompat<br>    - apk add bash<br>    - curl -s https://raw.githubusercontent.com/kubescape/kubescape/master/install.sh | bash <br>    - kubescape scan --compliance-threshold 80 *.yaml <br><br><br>install_kubectl:<br>  stage: dev_deploy<br>  image: <br>    name: alpine:3.7<br>  dependencies: []<br>  before_script:<br>    - wget https://storage.googleapis.com/kubernetes-release/release/$(wget -q -O - https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/linux/amd64/kubectl<br>    - chmod +x ./kubectl<br>    - mv ./kubectl /usr/bin/kubectl<br>  script:<br>    - export KUBECONFIG=$DEV_KUBE_CONFIG<br>    - kubectl version -o yaml<br>    - kubectl get nodes<br><br>deploy_nodejs_on_cluster:<br>  stage: dev_deploy<br>  before_script:<br>    - wget https://storage.googleapis.com/kubernetes-release/release/$(wget -q -O - https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/linux/amd64/kubectl<br>    - chmod +x ./kubectl<br>    - mv ./kubectl /usr/bin/kubectl<br>  script:<br>    - export KUBECONFIG=$DEV_KUBE_CONFIG<br>    - kubectl -n default create deploy node-app --image siddharth67/node-service:v1<br>    - kubectl -n default  expose deploy node-app --name node-service --port 5000<br>    - kubectl get all<br><br>Dast-security: <br>  stage: CD-security-stages<br>  image:<br>    name: softwaresecurityproject/zap-stable<br>  before_script:<br>    - mkdir -p /zap/wrk<br>  script:<br>    - pwd<br>    - ls<br>    - zap-full-scan.py -t &quot;https://majd.master.com&quot; -m 1 -d -I -r testreport.html <br>    - cp /zap/wrk/testreport.html testreport.html<br>  artifacts:<br>    when: always<br>    paths:<br>      - testreport.html<br><br><br>k8s_deploy_dev:<br>  stage: dev_deploy<br>  before_script:<br>    - wget https://storage.googleapis.com/kubernetes-release/release/$(wget -q -O - https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/linux/amd64/kubectl<br>    - chmod +x ./kubectl<br>    - mv ./kubectl /usr/bin/kubectl<br>  script:<br>    - export KUBECONFIG=$DEV_KUBE_CONFIG<br>    - kubectl apply -f k8s_deployment_service.yaml<br><br></pre><h3>Summary</h3><p>In this part we discuss why the security is important and why we must append it into the SDLC and the DevOps pipeline, then we implemented the security into our CD Pipeline stages , by secure our container and kubernetes files , then we ensure that the application will scan when it is up and can be access on the web .</p><p>In next part we will deploy some security tool to our kubernetes and make sure that our kubernetes is secure , then we will deploy the application to production.</p><p><a href="https://medium.com/@majdnull/devsecops-project-using-iac-overview-project-notes-febf35517839">From Introduction</a>.</p><p><a href="https://medium.com/@majdnull/devsecops-project-using-iac-part-9-implement-the-security-stages-on-the-ci-pipeline-2fa37b96ec9a">Previous Story — Implement the security stages on the CI Pipeline</a></p><p><a href="https://medium.com/@majdnull/devsecops-project-using-iac-part-11-kubernetes-operations-and-security-e1816d9f965d">Next —Kubernetes Operations and Security</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0188423444e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DevSecOps Project Using IAC : Part 9(Implement the security stages on the CI Pipeline)]]></title>
            <link>https://medium.com/@majdnull/devsecops-project-using-iac-part-9-implement-the-security-stages-on-the-ci-pipeline-2fa37b96ec9a?source=rss-3842da3c44b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/2fa37b96ec9a</guid>
            <dc:creator><![CDATA[Majdnull]]></dc:creator>
            <pubDate>Sun, 07 Apr 2024 11:59:06 GMT</pubDate>
            <atom:updated>2025-05-14T17:16:29.551Z</atom:updated>
            <content:encoded><![CDATA[<h3>DevSecOps Project Using IAC : Part 9(Implement the security stages on the CI Pipeline)</h3><blockquote>LinkedIn : <a href="http://www.linkedin.com/in/majd-zahran-4314b1235">Majd Zahran</a> , <strong>Please Don’t Hesitate to Contact Me</strong></blockquote><h3>Part 9: Implement the security stages on the CI Pipeline (Continuous Integration).</h3><p><a href="https://medium.com/@majdnull/devsecops-project-using-iac-overview-project-notes-febf35517839"><strong><em>From the start — Introduction</em></strong></a></p><p><a href="https://medium.com/@majdnull/devsecops-project-using-iac-part-8-continuous-deployment-delivery-cd-container-orchestration-8914eac981d9"><strong><em>Previous Part — part 8</em></strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0TPx9yp11LtXnuxYDfYAhw.jpeg" /></figure><p>In this part we will Implement the security stages into our Continuous Integration(CI) pipeline.</p><p>Now as we know in the CI ( Continuous Integration ) , we have a 4 stages , first the plan stage and we will skip the security here , then we have the Code Stage , it’s <strong><em>stored</em></strong> our code using version control tools &amp;&amp; <strong><em>into</em></strong> Source code management tool ( Basically it’s where you manage your source code ) in our case it will be GitLab , then we have the build stage here we will implement the security while we build our application using Maven , then we have the test stage i will skip this stage , because it’s related for the test the application functionality and i don’t want to dive through this for now.</p><h3>Git Hooks and Talisman Introduction</h3><p>Backing to 2015 a person accidently published his AWS S3 key to Github , that let a bot to go and spin up several instance of Bitcoin Mining that cost 2400$ , to avoid that and avoid leak somethings due to accidently git commit.</p><p>Now to avoid that we have the <strong><em>pre-commit hooks</em></strong> this can be installed on the developer’s workstation to avoid leak somethings through any Git commit , the <strong><em>pre-commit hook</em></strong> work on pure Regix-based approach for filtering sensitive data . ( This step can be bypass by the developers )</p><p>when we come to the market we have a various tools which is help us with <strong><em>pre-commit</em></strong> &amp;&amp; <strong><em>pre-push</em></strong> hooks , one of this tools is <strong><em>Talisman</em></strong>.</p><p><strong><em>Talisman</em></strong>: is a open-source tool created by ThoughtWorks , which can be used to hook your repository to ensure that potential secrets or sensitive information dose not leave the developers workstation.</p><blockquote>It’s validate the outgoing changes that look sus , like : password , secrets , api key …etc , it can also be used as a repository history scanner , to detect secrets that have already been checked in.</blockquote><p>It’s have a 2 types of installations :</p><ol><li>Global Installation: <em>here talisman will not only check your existing Git repo , but also in any new repo that you “ init “ or you “ clone “.</em></li><li>Single Project Installation: <em>here u will implemented talisman in just a one repository.</em></li></ol><p>Now we will install it as a pre-push hook</p><p>First let’s install the talisman script :</p><pre>curl https://thoughtworks.github.io/talisman/install.sh &gt; ~/install-talisman.sh<br>chmod +x ~/install-talisman.sh</pre><p>Then navigate to your repo folder and run the script :</p><pre>cd my-git-project<br>~/install-talisman.sh</pre><p>now you should see output like this :</p><pre>Downloading talisman_linux_amd64 from https://github.com/thoughtworks/talisman/releases/download/v1.32.0/talisman_linux_amd64<br>Downloading checksums from https://github.com/thoughtworks/talisman/releases/download/v1.32.0/checksums<br>talisman_linux_amd64: OK<br><br>Talisman successfully installed to &#39;.git/hooks/pre-push&#39;.</pre><p>now if you navigate to the .git/hook folder you will see you have the pre-push file &amp;&amp; the bin folder have the talisman</p><p>now we as we talked previously we install it as a pre-push that mean before we push anything talisman will scan our files for any secrets we foregate to delete it , this is the power of talisman.</p><p>now we will create some file and write some temp secret to see if the talisman will catch it or not .</p><pre>echo &quot;awskey=dcmwkmwmowojcwojecoj&quot; &gt; file1.txt<br>echo &quot;password=jdunwncwndoc&quot; &gt; file2.txt</pre><p>now the scenario is if we try to push this to out gitlab repo before that talisman will scan our files and if catch anything it will stop the push process. so let’s try to push</p><pre>git init<br>git add .<br>git commit -m &quot;adding some secrets file&quot;<br>git push </pre><p>now after u type git push , u will see talisman will generate a report if any file have any secrets value and stop the push process .</p><p>after you trying to push , it will return with :</p><pre>majd@k8s-master:~/voting-application$ git push <br><br>Talisman Scan: 6 / 6 &lt;-----------------------------------------------------------------------------------&gt; 100.00%  <br><br>Talisman Report:<br>+-----------+--------------------------------+----------+<br>|   FILE    |             ERRORS             | SEVERITY |<br>+-----------+--------------------------------+----------+<br>| file1.txt | Potential secret pattern :     | low      |<br>|           | awskey=scnancojnojq            |          |<br>+-----------+--------------------------------+----------+<br>| file2.txt | Potential secret pattern :     | low      |<br>|           | password=retxvysvc             |          |<br>+-----------+--------------------------------+----------+<br><br><br><br>fileignoreconfig:<br>- filename: file1.txt<br>  checksum: d18e327102863f1c6785b0fad93c1ed5e4d0fb9d9f9812a31a9012ca6b271693<br>- filename: file2.txt<br>  checksum: 05765bb91d359025f35eaabf06ead1b757183fb602bde98394788c84c1598dec<br>version: &quot;&quot;<br><br>Talisman done in 26.315765ms<br><br>majd@k8s-master:~/voting-application$</pre><p>As you can see talisman catch the 2 file we created , and it reported it with the value of it , then it stop the push process , now with this we can make sure to not push any secrets into our repo.</p><h3>SonarQube — SAST</h3><p><strong><em>SAST</em></strong> ⇒ stand of a S<strong><em>tatic Application Security Testing</em></strong> used to secure software by reviewing the application code and identifying a potential code snippet that may have a bug.</p><p><strong><em>SonarQube</em></strong> ⇒ is a open source tool developed by sonarqube for continuous inspection of code quality to perform automatic review with static analysis of code .</p><blockquote>It help us to detect area in the code that may have a bug or it need a refactoring or simplification<em> , </em>SAST help to the bug early in the development cycle , which means lees cost to fix them.</blockquote><p>It’s a powerful tool , as we know the process of reviewing the source code is hard process and it’s need someone who have alot of experience with a different programming language, because of that sonarqube will make this process more easier , but to inform you it’s not detect all sus things , no but actually it can cover like 80% from the process.</p><p>now you can sonarqube using docker using this :</p><pre>docker run -d --name sonarqube -p 9000:9000 -p 9092:9092 sonarqube</pre><p>With this we can access the sonarqube UI , where we can see the scans results and review the configurations.</p><p>now after u run the sonarqube container u can access by navigate to : <a href="http://localhost:9000/">http://localhost:9000</a> .</p><p>now you will see the login page for sonarqube</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Q6SB2KJEk7_xxa7nYjDow.jpeg" /></figure><p>Now the username &amp;&amp; password should be “<strong><em>admin</em></strong>” , if not u need to get the admin token from the config file and login , after you login it request to change the password , let it <strong><em>admin:admin</em></strong></p><p>now you will access the sonarqube dashboard , and then you can scan your application using the sonarqube scanner , if it not installed by default when you install sonarqube , navigate to <a href="https://docs.sonarsource.com/sonarqube/latest/analyzing-source-code/scanners/sonarscanner/">sonarqube CLI</a> , and install it .</p><p>Now you can navigate to the dashboard and select to scan a existing project or integrated it with your repo url using the Personal token.</p><p>Now you know what is sonarqube and how it work let’s adding it to our pipeline so when any new commit come it will start scanning automatically .</p><p>First on the dashboard click on add a project , then select import from Devops platform , u should see screen like this :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CXrqQBCovl0UAJnJEE80OQ.png" /></figure><p>click on create a local project , then enter Project display name=numeric , select brunch name in my case will be brunch part8 , click on Use the global setting and create project , now u should see screen look like this :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nQvEQSc4PJHO2g7mgwMeLA.png" /></figure><p>click on with GitLab CI , then based on our application it’s based on java so first go with integration instructions , then our pipline should look like this:</p><pre>stages:<br>  - build<br>  - test<br>  - CI-security-stages<br>  - deploy<br>  - dev_deploy<br><br>build_app:<br>  stage: build<br>  before_script:<br>    - apt-get update &amp;&amp; apt-get install maven -y<br>  script:<br>    - mvn clean package -DskipTests=true<br>  artifacts:<br>    paths:<br>      - target/*.jar<br><br>unit_tests:<br>  stage: test<br>  before_script:<br>    - apt-get update &amp;&amp; apt-get install maven -y<br>  script:<br>    - mvn test<br><br>sonarqube-check:<br>  stage: CI-security-stages<br>  image: <br>    name: sonarsource/sonar-scanner-cli:5.0<br>    entrypoint: [&quot;&quot;]<br>  variables:<br>    SONAR_USER_HOME: &quot;${CI_PROJECT_DIR}/.sonar&quot;  # Defines the location of the analysis task cache<br>    GIT_DEPTH: &quot;0&quot;  # Tells git to fetch all the branches of the project, required by the analysis task<br>  cache:<br>    key: &quot;${CI_JOB_NAME}&quot;<br>    paths:<br>      - .sonar/cache<br>  script: <br>    - sonar-scanner<br>  allow_failure: false<br>  only:<br>    - part8 #Repository containing our code and files,to be fetched by SonarQube <br><br><br>build-docker:<br>  stage: deploy<br>  image: docker<br>  services:<br>    - docker:dind<br>  before_script:<br>    - echo $CI_REGISTRY_PASSWORD | docker login -u $CI_REGISTRY_USER $CI_REGISTRY --password-stdin<br>  script:<br>    - docker build -t $CI_REGISTRY/majdnull/voting-application .<br>    - docker push $CI_REGISTRY/majdnull/voting-application<br><br>install_kubectl:<br>  stage: dev_deploy<br>  image: <br>    name: alpine:3.7<br>  dependencies: []<br>  before_script:<br>    - wget https://storage.googleapis.com/kubernetes-release/release/$(wget -q -O - https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/linux/amd64/kubectl<br>    - chmod +x ./kubectl<br>    - mv ./kubectl /usr/bin/kubectl<br>  script:<br>    - export KUBECONFIG=$DEV_KUBE_CONFIG<br>    - kubectl version -o yaml<br>    - kubectl get nodes<br><br>deploy_nodejs_on_cluster:<br>  stage: dev_deploy<br>  before_script:<br>    - wget https://storage.googleapis.com/kubernetes-release/release/$(wget -q -O - https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/linux/amd64/kubectl<br>    - chmod +x ./kubectl<br>    - mv ./kubectl /usr/bin/kubectl<br>  script:<br>    - export KUBECONFIG=$DEV_KUBE_CONFIG<br>    - kubectl -n default create deploy node-app --image siddharth67/node-service:v1<br>    - kubectl -n default  expose deploy node-app --name node-service --port 5000<br>    - kubectl get all<br><br><br>k8s_deploy_dev:<br>  stage: dev_deploy<br>  before_script:<br>    - wget https://storage.googleapis.com/kubernetes-release/release/$(wget -q -O - https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/linux/amd64/kubectl<br>    - chmod +x ./kubectl<br>    - mv ./kubectl /usr/bin/kubectl<br>  script:<br>    - export KUBECONFIG=$DEV_KUBE_CONFIG<br>    - kubectl apply -f k8s_deployment_service.yaml</pre><p>Remember to add the sonarqube token &amp;&amp; the host url to the CI/CD Pipeline Variables</p><p>Now when you will run the pipeline , u can see sonarqube will scan your project and you can see the result on the sonarqube UI</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M1lnKW4iEfeS6HP0xcrnzQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EGWv2Xwc2x8_yCtRG3F5HA.png" /></figure><p>Now when every commit will happen the sonarqube will running automatically and scan your code , now we can verify that we will track all the code vulnerability .</p><p>Now we secure the code management tool , on it we secure every push to the gitlab using Talisman , then we secure our java code after we compile it using maven we will run a <strong><em>Static Application Security Testing </em></strong>to our java classes every time we make any new commit.</p><h3>Vulnerabilities Basics</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*gJG5J15qwlqAaQyn6dLGOg.png" /></figure><p>The <strong><em>Vulnerability</em></strong> is the bug that exist in the applications , then after the hacker take a advantage from this vuln is called <strong><em>Exploit</em></strong> , now the uses of multi exploit to make a attack called <strong><em>Threat</em></strong> , now the combination between it called <strong><em>Risk</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JpQVbn-PUaP4R1O_7A72YA.png" /></figure><p>Now as a security specialist , you need to scan your application to identify the security vuln in the applications code , then by referencing the security scoring standards like ( NVD , CVE ,CVSS , CWE ) , then after the security assessment you can found the security report , finally you can take this report and start to remediation process .</p><h3>Dependency Check</h3><blockquote>It always important to keep track to the version of dependences you have , and make sure to update it once we have a new version.</blockquote><p>As a security specialist and a person want his applications &amp; his SDLC secure you should focus on the Dependency Security Check.</p><p>So for this we will use a open source software from OWSP called <strong><em>dependences-check</em></strong> ⇒ <strong><em>it is a software composition analysis tool that identify project dependences on source code and check if there are known vuln associated with the code or not</em></strong> .</p><p>dependences-check gathers the information from the pom.xml &amp; packages ⇒ this info will be used to identify the CPE ( common platform enumeration ) of the dependences “ <em>CPE standardized name given to the software versions for universal identification</em>” ⇒ once the CPE is identified , it is stored in a index and compared to a list of CVE.</p><p>Let’s dive through the process of downloading it and integrate it with our pipeline</p><p>Now you have a 2 way to work with it , first one is to build a docker image customized to the owsap dependences-check and then let maven run the plugin from your pom.xml</p><p>Or u can use the official <strong><em>owsap/dependency-check</em></strong> docker image , then you will install the dependency-check script and run it , then use the <strong><em>junit</em></strong> plugin from your pom.xml to to generate the <strong><em>dependency-check report</em></strong></p><p>Now i will work with method 2 so let’s integrate this in our Gitlab pipeline:</p><pre>stages: <br>  - CI-security-stages<br><br>owasp_dependency_check:<br>  image:<br>    name: owasp/dependency-check<br>    entrypoint: [ &quot;&quot; ]<br>  stage: CI-security-stages<br>  variables:<br>    DEPCHECK_OPTIONS: &quot;&quot;<br>    DEPCHECK_CVSS_SCORE_FAIL: &quot;8&quot;<br>    DEPCHECK_EXPERIMENTALS: &quot;false&quot;<br>    DOTNET_DLL_ANALYZE: &quot;false&quot;<br>    DOTNET_VERSION: &quot;3.1&quot;<br>    PROJECT_ROOT: &quot;/&quot;<br>  cache:<br>    key: &quot;dependency-check:data&quot;<br>    paths:<br>      - ${CI_PROJECT_DIR}/dependency-check/data/<br>  script:<br>    # Installing .net if needed<br>    - |<br>      if [ &quot;$DOTNET_DLL_ANALYZE&quot; = &quot;true&quot; ]; then<br>        apk add wget curl bash unzip<br>        # Script coming from dotNET_Build job<br>        apk add autoconf build-base clang clang-dev cmake curl-dev gcc gettext-dev git icu-dev krb5-dev libtool linux-headers llvm make zlib-dev<br>        curl -O https://dotnet.microsoft.com/download/dotnet-core/scripts/v1/dotnet-install.sh<br>        chmod +x dotnet-install.sh<br>        bash dotnet-install.sh -Channel ${DOTNET_VERSION}<br>        export PATH=&quot;/root/.dotnet/:$PATH&quot;<br>      fi<br>    # Creating Dependency-Check report folder<br>    - mkdir ${CI_PROJECT_DIR}/report/<br>    # Env variables checking<br>    - if [ &quot;$DEPCHECK_NO_UPDATE&quot; = &quot;true&quot; ]; then export DEPCHECK_OPTIONS=&quot;-n $DEPCHECK_OPTIONS&quot;; fi<br>    - if [ &quot;$DEPCHECK_EXPERIMENTALS&quot; = &quot;true&quot; ]; then export DEPCHECK_OPTIONS=&quot;--enableExperimental $DEPCHECK_OPTIONS&quot;; fi<br>    # Lauchning analyze<br>    - /usr/share/dependency-check/bin/dependency-check.sh -f JUNIT -s ${CI_PROJECT_DIR}${PROJECT_ROOT} -o ${CI_PROJECT_DIR}/report/ --failOnCVSS ${DEPCHECK_CVSS_SCORE_FAIL} --junitFailOnCVSS ${DEPCHECK_JUNIT_CVSS_FAIL}<br>  artifacts:<br>    when: always<br>    reports:<br>      junit: &quot;${CI_PROJECT_DIR}/report/dependency-check-junit.xml&quot;</pre><p>Let’s break this , first as we talked we will use the <strong><em>owsap/dependency-check</em></strong> docker image , then we have some variables we need to identify , the important one is <strong><em>DEPCHECK_CVSS_SCORE_FAIL: “8”</em></strong> with this we inform the scanner if find any vulnerable dependence that have a CVE with score <strong><em>=&gt; 8</em></strong> which is high and critical it will fail the pipeline , the gitlab pipeline support using a cache , this allow us to save the cache from previous run to use directly instead of rerun the hole process , why we use it ? that’s come from that the <strong><em>owsap/dependency-check</em></strong> when run every time it’s update the NVD records so this process take like 10–15 min so instead of that we cached this on a file then when it come to run the stage again it will extract the cached data first and run the script , now on the script section we start with install dotnet , then creating dependency-check report folder to save the report on it , then we run the analyzer , and after this pipeline passed , u can see the scan report on the artifacts .</p><p>it will look like this report if you generated it by xml :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k0jlseXWAg12_uI9gQL5Jw.png" /></figure><p>Now our pipeline should look like this after this part :</p><pre>stages:<br>  - build<br>  - test<br>  - CI-security-stages<br>  - deploy<br>  - dev_deploy<br><br>build_app:<br>  stage: build<br>  before_script:<br>    - apt-get update &amp;&amp; apt-get install maven -y<br>  script:<br>    - mvn clean package -DskipTests=true<br>  artifacts:<br>    paths:<br>      - target/*.jar<br><br>unit_tests:<br>  stage: test<br>  before_script:<br>    - apt-get update &amp;&amp; apt-get install maven -y<br>  script:<br>    - mvn test<br><br>sonarqube-check:<br>  stage: CI-security-stages<br>  image: <br>    name: sonarsource/sonar-scanner-cli:5.0<br>    entrypoint: [&quot;&quot;]<br>  variables:<br>    SONAR_USER_HOME: &quot;${CI_PROJECT_DIR}/.sonar&quot;  <br>    GIT_DEPTH: &quot;0&quot;<br>  cache:<br>    key: &quot;${CI_JOB_NAME}&quot;<br>    paths:<br>      - .sonar/cache<br>  script: <br>    - sonar-scanner<br>  allow_failure: true<br>  only:<br>    - part-8<br><br>owasp_dependency_check:<br>  image:<br>    name: owasp/dependency-check<br>    entrypoint: [ &quot;&quot; ]<br>  stage: CI-security-stages<br>  variables:<br>    DEPCHECK_NO_UPDATE: &quot;false&quot;<br>    DEPCHECK_OPTIONS: &quot;&quot;<br>    DEPCHECK_CVSS_SCORE_FAIL: &quot;11&quot;<br>    DEPCHECK_JUNIT_CVSS_FAIL: &quot;0&quot;<br>    DEPCHECK_EXPERIMENTALS: &quot;false&quot;<br>    DOTNET_DLL_ANALYZE: &quot;false&quot;<br>    DOTNET_VERSION: &quot;3.1&quot;<br>    PROJECT_ROOT: &quot;/&quot;<br>  cache:<br>    key: &quot;dependency-check:data&quot;<br>    paths:<br>      - ${CI_PROJECT_DIR}/dependency-check/data/<br>  script:<br>    # Installing Dotnet if needed<br>    - |<br>      if [ &quot;$DOTNET_DLL_ANALYZE&quot; = &quot;true&quot; ]; then<br>        apk add wget curl bash unzip<br>        # Script coming from dotNET_Build job<br>        apk add autoconf build-base clang clang-dev cmake curl-dev gcc gettext-dev git icu-dev krb5-dev libtool linux-headers llvm make zlib-dev<br>        curl -O https://dotnet.microsoft.com/download/dotnet-core/scripts/v1/dotnet-install.sh<br>        chmod +x dotnet-install.sh<br>        bash dotnet-install.sh -Channel ${DOTNET_VERSION}<br>        export PATH=&quot;/root/.dotnet/:$PATH&quot;<br>      fi<br>    # Creating Dependency-Check report folder<br>    - mkdir ${CI_PROJECT_DIR}/report/<br>    # Env variables checking<br>    - if [ &quot;$DEPCHECK_NO_UPDATE&quot; = &quot;true&quot; ]; then export DEPCHECK_OPTIONS=&quot;-n $DEPCHECK_OPTIONS&quot;; fi<br>    - if [ &quot;$DEPCHECK_EXPERIMENTALS&quot; = &quot;true&quot; ]; then export DEPCHECK_OPTIONS=&quot;--enableExperimental $DEPCHECK_OPTIONS&quot;; fi<br>    # Lauchning analyze<br>    - /usr/share/dependency-check/bin/dependency-check.sh -f JUNIT -s ${CI_PROJECT_DIR}${PROJECT_ROOT} -o ${CI_PROJECT_DIR}/report/ --failOnCVSS ${DEPCHECK_CVSS_SCORE_FAIL} --junitFailOnCVSS ${DEPCHECK_JUNIT_CVSS_FAIL}<br>  artifacts:<br>    when: always<br>    reports:<br>      junit: &quot;${CI_PROJECT_DIR}/report/dependency-check-junit.xml&quot;<br><br>build-docker:<br>  stage: deploy<br>  image: docker<br>  services:<br>    - docker:dind<br>  before_script:<br>    - echo $CI_REGISTRY_PASSWORD | docker login -u $CI_REGISTRY_USER $CI_REGISTRY --password-stdin<br>  script:<br>    - docker build -t $CI_REGISTRY/majdnull/voting-application .<br>    - docker push $CI_REGISTRY/majdnull/voting-application<br><br>install_kubectl:<br>  stage: dev_deploy<br>  image: <br>    name: alpine:3.7<br>  dependencies: []<br>  before_script:<br>    - wget https://storage.googleapis.com/kubernetes-release/release/$(wget -q -O - https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/linux/amd64/kubectl<br>    - chmod +x ./kubectl<br>    - mv ./kubectl /usr/bin/kubectl<br>  script:<br>    - export KUBECONFIG=$DEV_KUBE_CONFIG<br>    - kubectl version -o yaml<br>    - kubectl get nodes<br><br>deploy_nodejs_on_cluster:<br>  stage: dev_deploy<br>  before_script:<br>    - wget https://storage.googleapis.com/kubernetes-release/release/$(wget -q -O - https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/linux/amd64/kubectl<br>    - chmod +x ./kubectl<br>    - mv ./kubectl /usr/bin/kubectl<br>  script:<br>    - export KUBECONFIG=$DEV_KUBE_CONFIG<br>    - kubectl -n default create deploy node-app --image siddharth67/node-service:v1<br>    - kubectl -n default  expose deploy node-app --name node-service --port 5000<br>    - kubectl get all<br><br><br>k8s_deploy_dev:<br>  stage: dev_deploy<br>  before_script:<br>    - wget https://storage.googleapis.com/kubernetes-release/release/$(wget -q -O - https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/linux/amd64/kubectl<br>    - chmod +x ./kubectl<br>    - mv ./kubectl /usr/bin/kubectl<br>  script:<br>    - export KUBECONFIG=$DEV_KUBE_CONFIG<br>    - kubectl apply -f k8s_deployment_service.yaml</pre><p>Now we implement the security stages into our CI Pipeline , in next part we will implement the security stages into our CD Pipeline.</p><h3>Summary</h3><p>In this part we discuss why the security is important and why we must append it into the SDLC and the DevOps pipeline, then we implemented the security into our CI Pipeline stages , by secure our source control using talisman , then we scan our source code to identify any vulnibilty that may exists and see the report on the sonarqube UI , then we understand the difference between some security concepts , from there we go to the next step which is scanning our dependences from any CVE .</p><p>In next part we will see a different tools that we will use to secure our CD Pipeline , we will implemented it into pipeline , to see how we can scan our docker images and how we can secure the docker , then how we can secure our kubernetes env .</p><p><a href="https://medium.com/@majdnull/devsecops-project-using-iac-overview-project-notes-febf35517839">From Introduction</a>.</p><p><a href="https://medium.com/@majdnull/devsecops-project-using-iac-part-8-continuous-deployment-delivery-cd-container-orchestration-8914eac981d9">Previous Story — Continuous Deployment/delivery (CD) &amp; Container Orchestration</a>.</p><p><a href="https://medium.com/@majdnull/devsecops-project-using-iac-part-10-implement-the-security-stages-on-the-cd-pipeline-f0188423444e">Next — Implement the security stages on the CD Pipeline</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2fa37b96ec9a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DevSecOps Project Using IAC : Part 8(Continuous Deployment/delivery (CD) & Container Orchestration…]]></title>
            <link>https://medium.com/@majdnull/devsecops-project-using-iac-part-8-continuous-deployment-delivery-cd-container-orchestration-8914eac981d9?source=rss-3842da3c44b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/8914eac981d9</guid>
            <dc:creator><![CDATA[Majdnull]]></dc:creator>
            <pubDate>Sun, 31 Mar 2024 19:00:33 GMT</pubDate>
            <atom:updated>2024-04-07T12:00:01.758Z</atom:updated>
            <content:encoded><![CDATA[<h3>DevSecOps Project Using IAC : Part 8(Continuous Deployment/delivery (CD) &amp; Container Orchestration )</h3><blockquote><em>LinkedIn : </em><a href="http://www.linkedin.com/in/majd-zahran-4314b1235"><em>Majd Zahran</em></a><em> , </em><strong><em>Please Don’t Hesitate to Contact Me</em></strong></blockquote><h3>Part 8: Continuous Deployment/delivery (CD) &amp; Container Orchestration.</h3><p><a href="https://medium.com/@majdnull/devsecops-project-using-iac-overview-project-notes-febf35517839"><strong><em>From the start — Introduction</em></strong></a></p><p><a href="https://medium.com/@majdnull/devsecops-project-using-iac-part-7-building-our-continuous-integration-ci-pipeline-using-b38f990e9644"><strong><em>Previous Part — part 7</em></strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hWsFauUM0j5La5hrK1HBUA.png" /></figure><p>In this part we will build our Continuous Deployment/delivery (CD) pipeline Using Gitlab Pipeline to deploy our application on the kubernetes .</p><p>You can find the code for this part here :</p><p><a href="https://gitlab.com/Majdnull/voting-application/-/tree/part8">https://gitlab.com/Majdnull/voting-application/-/tree/part8</a></p><h3>Continuous Deployment/delivery (CD)</h3><p>Now after we build our application and test it using our gitlab pipeline which is called Continuous Integration (CI ) , after that now we need to build our docker image and push it , then we can deploy it to our cluster.</p><p>as we did in the previous part we build and run our docker container manually in our local machine , now how we can turn this process to our gitlab CI/CD pipeline, to automate it and to see the power of the devops concept.</p><p>Now for the docker registry we will use <strong><em>Gitlab container registry</em></strong> , gitlab registry is like docker hub , it’s a place where gitlab provide you with a space ( registry) to save your docker image ( it’s really like docker hub ), so we will connect to it then build our docker image , then push it to it.</p><p>first let’s backing to our pipeline from the previous part:</p><pre>stages:<br>  - build<br>  - test<br><br>build_app:<br>  stage: build<br>  before_script:<br>    - apt-get update &amp;&amp; apt-get install maven -y<br>  script:<br>    - mvn clean package -DskipTests=true<br>  artifacts:<br>    paths:<br>      - target/*.jar<br><br>unit_tests:<br>  stage: test<br>  before_script:<br>    - apt-get update &amp;&amp; apt-get install maven -y<br>  script:<br>    - mvn test</pre><p>Now we need to add the the docker command to our pipeline , but first we need to config somethings.</p><p>First let’s go to our gitlab then on the <strong><em>Voting application repo</em></strong> ⇒ on the <strong><em>left side</em></strong> you can find under the <strong><em>Build</em></strong> ⇒ you can find <strong><em>Deploy</em></strong> under it u will find <strong><em>Container Registry</em></strong> , it should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ysb2wJ3PVP73ZYqxkBVumQ.png" /></figure><p>now let’s add the docker build and push procees to the pipeline</p><pre>build-docker:<br>  stage: deploy<br>  image: docker<br>  services:<br>    - docker:dind<br>  before_script:<br>    - echo $CI_REGISTRY_PASSWORD | docker login -u $CI_REGISTRY_USER $CI_REGISTRY --password-stdin<br>  script:<br>    - docker build -t $CI_REGISTRY/majdnull/voting-application .<br>    - docker push $CI_REGISTRY/majdnull/voting-application</pre><p>let’s break it :</p><p>First we will assign it to the deploy stage , but this time we will let gitlab runner to use the docker image , in default gitlab runner will use ruby docker image , if you want to use a custom image u can let gitlab runner to use it by use <strong><em>image</em></strong> parameter , so we use it and give it a docker as a value , that mean when the gitlab runner will come to this stage it will pull the docker image from docker hub and use it as a executable env.</p><p>Then there are a powerful concept in gitlab CI/CD called service , here we will use docker-in-docker ,what that mean ? first u can read about it here <a href="https://docs.gitlab.com/ee/ci/docker/using_docker_build.html">docker-in-docker</a> , is simple words docker-in-docker it’s want to run docker as a service , so we can used it to run our pipeline on it ,so to do that we can use the service parameter on it it will look like this docker:dind , that will use the docker as a service on the gitlab runner.</p><p>Next we made a before_script on it we will login on docker , here we will not for sure using our credentials as a plane , instead of that for sure we will use a variables , on gitlab go to the voting-application repo ⇒ on left side ⇒ in the bottom u will see the settings , click on it then select the CI/CD , now scroll down u will find variables expand it , then enter the variables you want:</p><ul><li><strong><em>$CI_REGISTRY</em></strong> ⇒ the value of this variable will be the registry you want to use ( if you are using container registry “ registry.gitlab.com “ ).</li><li><strong><em>$CI_REGISTRY_PASSWORD</em></strong> ⇒ the value of this variable will be your gitlab password.</li><li><strong><em>$CI_REGISTRY_USER</em></strong> ⇒ here the value will be the username.</li></ul><p>Now on the pipeline we first login on the before_script , the echo command is to instead of provide our password and logged , we can use password-stdin , to take the password from the the input command line</p><p>Finally we can build our image and push it to the registry, after you did that now we can run our pipeline and if all things go right , it’s should like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*POpjmOgkyINdNFLtRdVRvA.png" /></figure><p>Now after we added our docker image build process to our pipeline, it’s the time to go to the step 2 of the CD.</p><h3>Container Orchestration</h3><p><em>We know that all big </em>business<em> almost have alot of containers</em> , it’s not just 5,6 containers , no it’s <em>like a 5000 containers</em>, so how u will manage that ?? <em>how u will manage this 5000 containers</em> ?? how u will know if it configure right ?? or <em>how u will know that is communicate with each other right</em> ?? because we know if 1 containers not communicate right that will might to crash the application !</p><p>Another thing we know that like a amazon , it’s have like a normal traffic on the week , but it’s have like x4 || x5 load and traffic on the weekend , so how we will manage that , should we scaling up containers manual every weekend ?</p><p>We have our application packaged into a docker container , ok what next ? <em>how we can run it on production</em> ??? <em>what if your application relies on other container like database or massages application , how we can let it talk to each other</em> ??? what if the number of user increase and u want to scale your application ???</p><p><strong><em>Here we need to Orchestrate the connectivity between the container and automatically scale the application up and down based on the load .</em></strong></p><p><strong><em>The hole process of automatically deploying and managing container is known as a Container Orchestration.</em></strong></p><p>So how we can do that ? i think you know that, yes of course using Kubernetes.</p><p><strong><em>Kubernetes</em></strong>: is Container Orchestration technology used to orchestrate the deployment and management of hundreds maybe thousand of containers in a clustered environment .</p><blockquote><em>Kubernetes is a Container Orchestration technology</em></blockquote><h4><em>KUBERNETES ARCHITECTURE</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EFVRcDVySGtFj4YjKST19w.png" /></figure><ul><li><strong><em>Nodes</em></strong> ⇒ <em>is a machine , physical or virtual on which kubernetes is installed , the node is worker machine.</em></li><li><strong><em>Cluster</em></strong> ⇒ <em>is a set of nodes grouped together</em> . that’s mean if any node fail , your application will still accessible from the other nodes .</li><li><strong><em>Pods</em></strong><em> </em>⇒<em> First assume that the docker and kubernetes is running and we have the nodes and the docker images , as</em> we know with kubernetes our aim to deploy our application in the form of containers on a set of machine that are configured as a worker node in a cluster <em>However Kubernetes dose not deploy containers directly on worker nodes</em> ⇒ <em>the containers are encapsulated into a kubernetes objects known as a</em> ⇒ <strong><em>Pods</em></strong></li></ul><blockquote><strong><em>Pods</em></strong> ⇒ <em>is single instance of an application</em> , <em>Pods</em> <em>is the smallest object that you can create in kubernetes.</em></blockquote><p>To understand it in a butter way, let’s take a example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fMMPpCkXe8wWoQAseavYew.png" /></figure><p>Here we see the simplest of simplest cases , <em>where you have a single node kubernetes cluster</em> , <em>with a single instance of your application</em> , <em>running in a single docker container encapsulated in a pod</em> .</p><p>So what if the number of users accessing your application increases and you need to scale your application ??? <em>You need to add additional instance of your application to share the load</em> , right ?</p><blockquote>So how this can happen ?? is by adding a new instance in same pod ? No ⇒ <em>You can do that by create a new pod altogether with a new instance of the same application</em> ⇒ <em>so as we can see now we have a 2 instance running of our application in a 2 separate pod on same Kubernetes node</em> so we share the load by adding a new instance running in separate pod in same node.</blockquote><blockquote><em>So what if the user still increased and the current node has no sufficient capacity</em> ??<em> so we can always create a new node and deploy a new instance with a new pod in the cluster</em> ( <em>so we now have a new node added to the cluster to expand the cluster physical capacity</em> )</blockquote><p>You can deploy pods as many as you want form any node.</p><p><em>So pods usually have one-to-one relationship with containers running your application , to scale up you create a new pod and to scale down u delete a existing pods</em> . ( <em>You didn’t added additional containers to existing pod to scale your application</em> )</p><blockquote>We talked about the the pod have a one-to-one relationship with container , <em>but is that impossible to see 2 container running in same pods</em> ? the answer is no , <em>you might see in some scenario u need a helper container ( is a container related to your web application container is just used to help with some feature like , uploading file , input data … , and u want this container to run with your application in same pods ) so you can do that , then when u want scale this the pods will created with the helper container , and when the pods is deleted the helper container will deleted</em> .</blockquote><p>Now that we understand container orchestration and Kubernetes, it’s time to gain practical experience. Let’s get hands-on with Kubernetes.</p><h3>Deploy our Application to kubernetes</h3><p>Now we have the docker image on our gitlab registry , and we have all the previous proccess automated , now we will move to the next step:</p><h4>Kubectl with Our Gitlab Pipeline</h4><p>first before we work with kubernetes we need a tool to work with , in this case we will come to kubectl .</p><p><strong><em>Kubectl</em></strong>: kubectl tool is used to deploy and manage applications on kubernetes cluster . To get cluster information , to get the states of other nodes in a cluster and to manage many other thing.</p><p>It’s a huge tool you can get familiar with it <a href="https://www.bluematador.com/learn/kubectl-cheatsheet">from there</a></p><p>now we need to install it with our pipeline to manage the kubernetes and to deploy our application to it.</p><p>The stage of installing kubectl should look like this:</p><pre>install_kubectl:<br>  stage: kubectl_deploy<br>  image: <br>    name: alpine:3.7<br>  dependencies: []<br>  before_script:<br>    - wget https://storage.googleapis.com/kubernetes-release/release/$(wget -q -O - https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/linux/amd64/kubectl<br>    - chmod +x ./kubectl<br>    - mv ./kubectl /usr/bin/kubectl<br>  script:<br>    - export KUBECONFIG=$DEV_KUBE_CONFIG<br>    - kubectl version -o yaml<br>    - kubectl get nodes</pre><p>let’s break it : first we will assign it to a kubectl_deploy , then as we used previusly we will use a alpine docker image , we will let the dependencies empty , then before we run kubectl , it’s need to get the kubectl from kubernetes releases , then we change the permission to let it execute by chmod +x ./kubectl , then we moved it to bin directory , all these steps we need it before run kubectl .</p><p>Now on script section , we need to export the kubernetes config file ( it’s the configuration file for kubernetes , if you install it on your local machine it should be on the .kube file , to get it go to your cloud to the master node , navigate to .kube file , cat the config file this is the file we need to add it to our variables , so copy the content of the file and paste it to variable name DEV_KUBE_CONFIG , make sure to make it unprotracted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aYOnJkK18Kznjvl1EpW39g.png" /></figure><p>then we can run the kubectl command , to verify that we get the nodes deployed on our cluster.</p><p>Now we install kubectl , we need now to deploy our node.js application to the cluster , so our stage should look like this:</p><pre>deploy_nodejs_on_cluster:<br>  stage: deploy_node.js<br>  before_script:<br>    - wget https://storage.googleapis.com/kubernetes-release/release/$(wget -q -O - https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/linux/amd64/kubectl<br>    - chmod +x ./kubectl<br>    - mv ./kubectl /usr/bin/kubectl<br>  script:<br>    - export KUBECONFIG=$DEV_KUBE_CONFIG<br>    - kubectl -n default create deploy node-app --image siddharth67/node-service:v1<br>    - kubectl -n default  expose deploy node-app --name node-service --port 5000<br>    - kubectl get all</pre><p>On that we install kubectl another time in before_script section , then we will run kubectl command to deploy the node.js image on the default namespace , as previous i will not build it from scratch because the project doesn&#39;t focus on create a application itself , it to dive through devsecops methodology and see how this will work, so we will use the siddharth67 docker image , thank you siddharth67 , after we deploy it we will expose the node app service to run on port 5000 , i think you now doesn&#39;t understand what that , so let me teach you what is the service concept on kubernetes.</p><h4>Kubernetes Services</h4><p><strong><em>Kubernetes Services</em></strong> ⇒ used to enable communication between various components within and outside of the application.</p><blockquote><strong><em>Kubernetes services help us to connect applications together with our application or user</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2HjztHqYxVzQvIrJgVr8QQ.png" /></figure><p>Now imagen you have your backend microservices and your database and your frontend , now you deploy all these microservices in your cluster , how the backend will communicate with the database , and how the backend will communicate with your frontend ?? here where is services comes , services help you make a communication with your microservices to let the backend talk with the database and with your frontend . i think now you understand what the purpose of using services .</p><p>Now we have a 3 types of services :</p><ol><li>ClusterIP ⇒ <em>this service creates a Virtual IP inside the cluster to enable commination between different services.</em></li><li><strong><em>NodePort</em></strong> ⇒ <em>where the services makes an internal pod accessible on a port on the node</em> .</li><li><strong><em>Load Balancer</em></strong> ⇒<em> it’s a load balancer for our application in supported cloud provider , for example to share load across the different web servers.</em></li></ol><p>so now what we should select in our case ? now let’s discuses that we have a 3 microservices as an example : back-end , front-end , database .</p><p>so now we need to make the front-end public right and we need to expose it on port for example 8080 ,because this is what the user will see right , then we need to make connection between the ( <strong><em>back-end ⇒ front-end</em></strong> ) &amp; ( <strong><em>back-end ⇒ database</em></strong>) , that mean we need to just want to expose the front-end , so the service for front-end should be NodePort ( because as we talked previously NodePort service used to expose something to port and let it accusable from anywhere , that the purpose of NodePort Service ) , on the otherside should we make the back-end and the database NodePort too ?? for sure no , these microservice work behind the scene , so it will communicate with ClusterIP ( because ClusterIP used to communicates pods for internal access just ) , so now in our case we will make the back-end communicate with the front-end &amp; database with ClusterIP service , and the Front-end will expose using NodePort service.</p><p>Now i think you understand why we expose the node.js application with NodePort service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L8X3PS4QflnlBEZgDLoupA.png" /></figure><p>Now let’s continue to the last stage :</p><pre>k8s_deploy_dev:<br>  stage: dev_deploy<br>  before_script:<br>    - wget https://storage.googleapis.com/kubernetes-release/release/$(wget -q -O - https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/linux/amd64/kubectl<br>    - chmod +x ./kubectl<br>    - mv ./kubectl /usr/bin/kubectl<br>  script:<br>    - export KUBECONFIG=$DEV_KUBE_CONFIG<br>    - kubectl apply -f k8s_deployment_service.yaml</pre><p>Here we will deploy our numeric application to the cluster ( based on our compromised docker image which we created in first section of this part ) that by apply our kubernetes deployment file , kubernetes support using a yaml file so if you want deploy something , or make a service , or create pods or nodes ..etc , you need to create a deploy yaml file.</p><p>so our k8s_deployment_service.yaml file should look like this:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  labels:<br>    app: devsecops<br>  name: devsecops<br>spec:<br>  replicas: 2<br>  selector:<br>    matchLabels:<br>      app: devsecops<br>  strategy: {}<br>  template:<br>    metadata:<br>      labels:<br>        app: devsecops<br>    spec:<br>      volumes:<br>      - name: vol<br>        emptyDir: {}<br>      serviceAccountName: default<br>      containers:<br>      - image: *********/******/voting-application:latest<br>        name: devsecops-container<br>        volumeMounts:<br>        - mountPath: /tmp<br>          name: vol<br>        securityContext:<br>          runAsNonRoot: true<br>          runAsUser: 100<br>          readOnlyRootFilesystem: true<br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  labels:<br>    app: devsecops<br>  name: devsecops-svc<br>spec:<br>  ports:<br>  - port: 8080<br>    protocol: TCP<br>    targetPort: 8080<br>  selector:<br>    app: devsecops<br>  type: NodePort</pre><p>The syntax should be like this and if you look at the image we used it’s the image we created and deploy it our gitlab registry, here we make a 2 kind of kubernetes components , the first one is Deployment to deploy our numeric application to the cluster , one of the security best practice is to run the docker container as non root , and as uuid 100 or upper that.</p><p>And the other kind is service to create a service of our application and expose it on port 8080 as a NodePort.</p><p>I think you saw the replicas: 2 on specification section and think what is that ? so in simple word , we talked previously about on of most important purpose of deploying our application on kubernetes is to make it hurd to down , so you will deploy your docker container on pod right ? and to separate the load you will deploy it to like a 4 pods , so now what if the pod fail or down for some reason ( just to inform you the strongest pod be up for like 3 sec at most before it goes down :) ) , so for sure you will not deploy it manual every 3 sec , so here where the replicas come , it’s a parameter implement on the spec section on your deployment yaml file , the reason of that if your pod died , it will deploy another pod to replace it , so if we have a 3 pods and the pod number 3 died , if you refresh your node you will see it’s 3 same as what you deployed , so as we talked previous the replicas deploy the same pod if see the number of pods decrease , so on our deployment file we set the replicas: 2 , that mean if what happen when you come to your pods it will be 2 always , that because when any pod died the replicas will deploy another one to replace it and make your pods number as what you set.</p><p>Now after you create the deployment file , commit it to gitlab repo and , now save your pipeline and now let’s run it and see what will happen .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qlDrJ8_xwj_CCTRAtzrZvQ.png" /></figure><p>As you can see all stages passed and now if we check our master node it should have all deployments and pods and nodes… Etc , so lets check that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XL28SNC3xR4tbwl29bXSBw.png" /></figure><p>Congrats , you did it :)</p><p>now we have a 2 pods that related to the replicas value which we set it to 2 , and we have 2 service one for node.js application and as we talked it will be a ClusterIP and the other is related to our devsecops application and it assign to be a NodePort ,then we have a 2 deployments one for node.js and the other for our devsecops app , finally we have a 2 replicas sets that to ensure if any pods died it will be replace with another with a sec.</p><h3>Summary</h3><p>In this story we building our continuous deployment (CD) pipeline Using Gitlab Pipeline and we deploy our node.js and voting application to our cluster automatically and we verify that, then we describe some kubernetes components and how we can use it .</p><p>Now we have our virtual machine created by terraform and configure by Ansible , then we created our kubernetes cluster ,on last part we see the project use cases and run it on the local machine , and on this part we start build our CI Pipeline and we build our spring boot docker image and run it , then we build our CD pipeline to deploy our node.js &amp; voting app to the cluster, on the next part we will start implement the security into this to achieve the DevSecOps concept.</p><p><a href="https://medium.com/@majdnull/devsecops-project-using-iac-overview-project-notes-febf35517839">From Introduction</a>.</p><p><a href="https://medium.com/@majdnull/devsecops-project-using-iac-part-7-building-our-continuous-integration-ci-pipeline-using-b38f990e9644">Previous Story — Building our Continuous Integration (CI) pipeline Using Gitlab Pipeline &amp;&amp; Countrization</a></p><p><a href="https://medium.com/@majdnull/devsecops-project-using-iac-part-9-implement-the-security-stages-on-the-ci-pipeline-2fa37b96ec9a">Next —Implement the security stages on the CI Pipeline</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8914eac981d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DevSecOps Project Using IAC : Part 7 (Building our Continuous Integration (CI) pipeline Using…]]></title>
            <link>https://medium.com/@majdnull/devsecops-project-using-iac-part-7-building-our-continuous-integration-ci-pipeline-using-b38f990e9644?source=rss-3842da3c44b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/b38f990e9644</guid>
            <dc:creator><![CDATA[Majdnull]]></dc:creator>
            <pubDate>Wed, 27 Mar 2024 07:53:03 GMT</pubDate>
            <atom:updated>2024-04-01T04:20:23.679Z</atom:updated>
            <content:encoded><![CDATA[<h3>DevSecOps Project Using IAC : Part 7 (Building our Continuous Integration (CI) pipeline Using Gitlab Pipeline &amp;&amp; Countrization)</h3><blockquote><em>LinkedIn : </em><a href="http://www.linkedin.com/in/majd-zahran-4314b1235"><em>Majd Zahran</em></a><em> , </em><strong><em>Please Don’t Hesitate to Contact Me</em></strong></blockquote><h3>Part 7: Building our Continuous Integration (CI) pipeline Using Gitlab Pipeline.</h3><p><a href="https://medium.com/@majdnull/devsecops-project-using-iac-overview-project-notes-febf35517839"><strong><em>From the start — Introduction</em></strong></a></p><p><a href="https://medium.com/@majdnull/devsecops-project-using-iac-part-6-setting-up-a-persistent-volume-and-connecting-it-to-3fb7752f3f7c"><strong><em>Previous Part — part 6</em></strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KpZOSdvsgRNN3zA4pXtn7Q.png" /></figure><h4>In this part we will build our Continuous Integration (CI) pipeline Using Gitlab Pipeline .</h4><p>You can find the code for this part here :</p><p><a href="https://gitlab.com/Majdnull/voting-application/-/tree/part7">https://gitlab.com/Majdnull/voting-application/-/tree/part7</a></p><h3>Gitlab CI pipeline and Maven Build</h3><p>Now we need to build the package using maven package manager , but to not do that manually every time we will do it through the pipeline.</p><h4><strong><em>Gitlab Pipeline</em></strong></h4><p>Now first we need to enable the auto devops pipeline in the GitLab, on settings enable it , then to create our first GitLab pipeline we need to know somethings first :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zZarfKpRkCoBB7GRUgjpUg.png" /></figure><p>Gitlab offer alot of features like packages , secure , releases, monitor, deploy, Why we will use Gitlab as a CI/CD tool ? Gitlab will let you save your source code and make your pipeline on the same place so you don’t need to use a external thing like: jenkins, this will make your devops journey smoothly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0EOdFGFR3eMPR3Hc7M-Zlw.png" /></figure><p>So in simple word what is the CI/CD ⇒ install all the dependences and packing the app and test it manually , and rebuild it every time you will change any thing on the code that will cost alot on the money side or time side , so let’s imagine if you are a developer team and as we all know every developer have his task like , developer1 his task is to make the about page , developer2 his task is to make the Blog page ( this is just an example) , now when the developer1 want to change something it will change it and commit it , so then we should rebuild the app this will cost alot of time and money , but when we come to the DevOps concept and the power of CI/CD , with our pipeline we will automate all the steps we need to build the app , so that will save alot of time and money , and the power of the Gitlab pipeline here is , everytime any developer make a new commit gitlab will see that and rerun our pipeline, so that mean everytime any changes happen the hole process of build our app will replay , and the app with the new change will be ready automatically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fN_6nqba0NsqfliTIEfTCA.png" /></figure><p>This is the steps we will follow to create our Pipeline , on this part we will describe just the CI , from the git push to the build our app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VspdnA2aVYz0Ht2JpeEjAQ.png" /></figure><p>So the Pipeline on Gitlab called Gitlab pipeline , on every pipeline we have stages , on these stages we define what we want to do , this stages called jobs on GitLab.</p><p>How Gitlab fetch the pipeline and where we make it ? on gitlab we can make a pipeline using code , so we will define a yaml file and when this file commit to the gitlab repo , it will fetch it and run it as a pipeline , but this yaml file should called : <strong><em>.gitlab-ci.yml</em></strong></p><blockquote>This is just a Example of Gitlab Pipeline:</blockquote><pre>stages:          <br>  - build<br>  - test<br>  - deploy<br><br>build-job:       <br>  stage: build<br>  script:<br>    - echo &quot;Compiling the code...&quot;<br>    - echo &quot;Compile complete.&quot;<br><br>unit-test-job:   <br>  stage: test    <br>  script:<br>    - echo &quot;Running unit tests... This will take about 60 seconds.&quot;<br>    - sleep 60<br>    - echo &quot;Code coverage is 90%&quot;</pre><p><em>First we need to define a stages for jobs , we can ordering the stages: first build , second test, third deploy.</em></p><p>Then we have a our first stage ( first job ) which we name it build-job , on it we need first to assign it to what stage we want it to start run , we assign it to the build stage , that mean it will run as a first job , then to write the what we want the stage to do we need to define a script: , on it we can write what we want after this sign - .</p><p>Now let’s back to our pipeline crate a file on the project file called: .gitlab-ci.yml</p><pre>stages:<br>  - build<br><br>build-app:<br>  stage: build<br>  before_script:<br>    - apt-get update &amp;&amp; apt-get install maven -y<br>  script:<br>    - mvn clean package -DskipTests=true<br>  artifacts:<br>    paths:<br>      - target/*.jar</pre><p>We define a first stage called build , then we define the first job we assign it to build stage , then we create a parameter called before_script we use that when we need to run something before the main script ,here we will install maven because if u run the pipeline without the before_script the pipeline will failed because it can’t find maven command so we need to install it first, then we have the main script on it we will run maven to package the application , then we have the artifacts parameter on it we define the path where we want the result of the pipeline to save the file , so the package file will saved on target/app.jar if the pipeline passed.</p><blockquote>Now save it and commit it , when u commit it you will see the gitlab will fetch that a new pipeline commit so it will automatically run it and you can see it passed on , <strong><em>Build tap</em></strong> ⇒ <strong><em>Pipeline</em></strong> ⇒ <strong><em>Jobs</em></strong> :</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bt1SoWKENKdHbg_nwHuAyQ.png" /></figure><h4>Test application with maven</h4><p>Now as we created we have a test file on it we have the numeric application controls , so on it we have a 3 test: that to test the 3 endpoints, so now we need to test that by the pipeline to validation the status code of the endpoint.</p><p>Now let’s add it to our pipeline, to test it after any build:</p><pre>stages:<br>  - build<br>  - test<br><br>build_app:<br>  stage: build<br>  before_script:<br>    - apt-get update &amp;&amp; apt-get install maven -y<br>  script:<br>    - mvn clean package -DskipTests=true<br>  artifacts:<br>    paths:<br>      - target/*.jar<br><br>unit_tests:<br>  stage: test<br>  before_script:<br>    - apt-get update &amp;&amp; apt-get install maven -y<br>  script:<br>    - mvn test</pre><p>So as you can see we add another stage which is test stage , now let’s add the unit_tests on it as always we first download maven using before_script: ,then on script parameter we run the maven test , that will let maven to go through the the test file and test all endpoints.</p><h3>Countrization</h3><p>we all know what is virtual machine , <strong><em>Docker is the lightweight alternatives of virtual machine</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*hq0OmAL3soOkTF_rIzl-5Q.png" /></figure><p>There is alot of countrization tools, but i prefer docker.</p><blockquote>So what the case here ⇒ here <em>i will made my application and have a project file within the project file we will make a file called</em> <strong>Docker file</strong> , So with this <strong><em>Docker file</em></strong><em> we can make a</em> <strong><em>Docker image</em></strong> ( why we need to make a docker image ? this will <em>used to create docker container as many as u want from it</em> ) , so make the <strong><em>docker file ⇒ docker image</em></strong> , then anyone can create the <strong>docker container</strong> from it , <em>so with this docker image we can uploaded it to the docker hub</em> , which<em> is the git repo of docker images</em> (may be public or privet ) , <em>then from this repo , can anyone pull up this docker image and get the docker container and run the app.</em></blockquote><h4>Docker Basics</h4><p>Docker containers encapsulate everything an application needs to run ( and only those things), they allow applications to be shuttled easily between environments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*P8TAYIKsRIhs5ENH2nSpQA.png" /></figure><p>In order to have a docker containers , we need first a Docker File ( where we define everything required for the application to run ) , Then you build the docker file to git the docker image , And this docker image can be pushed to centralized repository like docker hub , or any third-party repository</p><p>Then if you want to run that image you can run this docker image to get the docker container.</p><p>In our case docker file should look like this :</p><pre>FROM openjdk:8-jdk-alpine<br>EXPOSE 9999<br>ARG JAR_FILE=target/*.jar<br>ADD ${JAR_FILE} app.jar<br>ENTRYPOINT [&quot;java&quot;,&quot;-jar&quot;,&quot;/app.jar&quot;]</pre><blockquote><em>Since we are building a Spring Boot-based application, we need a base image of </em><em>openjdk:8 , which used for building and running the spring boot application , we will also expose which port we want our application to listen on , and we are give the enterypoint as well, we are not define the user here , so it’s going to use the root as a end-user.</em></blockquote><p>Once we have the docker file , we can build our docker image by using this command :</p><pre> docker build -t &lt;docker-hub-username&gt;/&lt;docker image name (what you want)&gt;:&lt;tag(v1,v2...)&gt; .</pre><p>and we are type the dot notation because we are running this command in the same dir where we have the docker file ( so that mean u need to make the docker file on the same project directory)</p><p>After we build our docker image now we need to push it to our docker hub by using this command :</p><pre>docker push &lt;docker-hub-username&gt;/&lt;docker image name (what you want)&gt;:&lt;tag(v1,v2...)&gt;<br>................<br>For example : docker push majdhub/num-image:v7</pre><p>Now after we pushed the image to docker hub we can run it as a container :</p><pre>docker run -p 9999:9999 majdhub/num-image:v7</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WWCOo2sTiLdTKSKeMYTwKQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KH25cZGKUr3OrIXQBgtE3Q.png" /></figure><p>Now we successfully upload our image to docker hub , and we run the docker image to get the docker container.</p><p>In next part we will take a look to the <strong><em>Container Orchestration</em></strong> and deploy our docker containers to the kubernetes cluster which we made in part3.</p><h3>Summary</h3><p>In this story we building our continuous integration (CI) pipeline Using Gitlab Pipeline and describe why gitlab is a powerful devops platform , we see what is the CI and how we can start build our CI/CD Pipeline, then we see what is countrization.</p><p>Now we have our virtual machine created by terraform and configure by Ansible , then we created our kubernetes cluster ,on last part we see the project use cases and run it on the local machine , and on this part we start build our CI Pipeline and we build our spring boot docker image and run it , on the next part we will take a look to the Container Orchestration and deploy our docker containers to the kubernetes cluster.</p><p><a href="https://medium.com/@majdnull/devsecops-project-using-iac-overview-project-notes-febf35517839">From Introduction</a>.</p><p><a href="https://medium.com/@majdnull/devsecops-project-using-iac-part-6-setting-up-a-persistent-volume-and-connecting-it-to-3fb7752f3f7c">Previous Story — Project use cases &amp; Run the project on our local machine</a>.</p><p><a href="https://medium.com/@majdnull/devsecops-project-using-iac-part-8-continuous-deployment-delivery-cd-container-orchestration-8914eac981d9">Next —Continuous Deployment/delivery (CD) &amp; Container Orchestration</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b38f990e9644" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DevSecOps Project Using IAC : Part 6( Setting up a Persistent Volume and connecting it to…]]></title>
            <link>https://medium.com/@majdnull/devsecops-project-using-iac-part-6-setting-up-a-persistent-volume-and-connecting-it-to-3fb7752f3f7c?source=rss-3842da3c44b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/3fb7752f3f7c</guid>
            <dc:creator><![CDATA[Majdnull]]></dc:creator>
            <pubDate>Wed, 13 Mar 2024 11:44:52 GMT</pubDate>
            <atom:updated>2024-03-27T07:53:28.798Z</atom:updated>
            <content:encoded><![CDATA[<h3>DevSecOps Project Using IAC : Part 6 (Project use cases &amp; <em>Run the project on our local machine</em>)</h3><blockquote><em>LinkedIn: </em><a href="http://www.linkedin.com/in/majd-zahran-4314b1235"><em>Majd Zahran</em></a><em> , </em><strong><em>Please Don’t Hesitate to Contact Me</em></strong></blockquote><h4>Part 6: Project use cases &amp; Run the project on our local machine</h4><p>In this part we will see the project use cases and run the project on our local machine which is in my case windows.</p><p><a href="https://medium.com/@majdnull/devsecops-project-using-iac-overview-project-notes-febf35517839"><strong><em>From the start — Introduction</em></strong></a></p><p><a href="https://medium.com/@majdnull/devsecops-project-using-iac-part-5-create-our-cluster-on-kubernetes-6847c9110ede"><strong><em>Previous Part — part 5</em></strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3QEC1Quh9Zl8p88q_tFuaw.png" /></figure><blockquote>Now from this part , we will start focusses on doing things with our Kubernetes cluster. Rather than automating these steps , I love to do things manually , manual configuration gives us chance to understand more about what is happening behind the scene . If you wish to automate these steps, for sure you can do that .</blockquote><p>You can find the code for this part here:</p><p><a href="https://gitlab.com/Majdnull/voting-application/-/tree/part7">https://gitlab.com/Majdnull/voting-application/-/tree/part7</a></p><h3>Project Use Cases</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UEBq7cpixhkmQtxtwv9ebQ.png" /></figure><p>We will working with 2 very simple microservices :</p><ul><li>The first one is <strong><em>Node.js-based application</em></strong> , which is dockerized image , it’s run on port 5000 , and it has a single endpoint /plusone , whenever you give any number to this, it will simply increment it by one and return response back.</li><li>The other microservices is written in <strong><em>SpringBoot </em></strong>, which run on port 8080 , and it has a single endpoint /increment &amp; /compare &amp; / the root dir will just display a text like this “ <strong><em>Kubernetes DevSecOps</em></strong> “.</li></ul><blockquote>In this course we will be focusing on the <strong><em>SpringBoot application</em></strong> we will build it , test it, and we will create a docker image and deploy it on our kubernetes cluster</blockquote><p><strong><em>On the other hand we will be using simple docker image for Node.js to deploy it and to make the interactions between these 2 application.</em></strong></p><h3><em>Run the project on our local machine</em></h3><blockquote><strong><em>so now let’s clone the repo of this project ⇒ </em></strong><a href="https://gitlab.com/Majdnull/voting-application/-/tree/part7">https://gitlab.com/Majdnull/voting-application/-/tree/part7</a></blockquote><p>Now after you clone the project repo , navigate to the directory and let’s open the repo directory with any IDE you prefer, i will use visual studio code (VS Code ).</p><blockquote>Then we can see in the pom.xml that we have the project specifications , and if we go to the src/java/main we can see the source code and the api endpoints on numariccontrolar.java of our application so you can see we have a 3 endpoint.</blockquote><p>Now to run this on our local machine we need to run the node.js docker images , so we can get it from here ⇒ “ <em>siddharth67/node-service:v1</em>” , then ⇒ <strong><em>docker run -p 5000:5000 siddharth67/node-service:v1</em></strong> , so that will pull the image then run it . after run it the app should be pulled and the node.js should be running now.</p><blockquote>Kind note: u need to install docker-CLI as we talked in part1 , then you need to install docker desktop , if you work with windows like me.</blockquote><p>Now you should see there is a new image on your docker desktop , and if you navigate to the Container Tap , you should see there are a new container there and it’s running.</p><p>You can verify that by navigate to the browser and search for :</p><pre>localhost:5000/plusone/500</pre><p>That should print what ? yes, that’s right it should print a <strong><em>501</em></strong> , that what we are discussed on the Project Use Cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TEh-pUT59u8hTAsE9qamLw.png" /></figure><p>Now we need to build our SpringBoot image right ? let’s go</p><h3>Maven Basics</h3><blockquote><strong><em>Apache Maven</em></strong> is a software project management and comprehension tool. Based on the concept of a project object model (POM).</blockquote><p>Simply it’s <strong><em>Packages Manager</em></strong> , you know why that now .</p><p><strong><em>Maven can automate a Java based project by :</em></strong></p><ol><li>Download third-party dependencies which we define in the pom.xml file.</li><li>Test the code.</li><li>Compile written code into binary code.</li><li>Packaging compiled code into JAR , WAR (artefacts).</li><li>Deploy them to the application server or repository.</li></ol><p>There are a specific structure of the project file u should follow:</p><pre>-------------------------------------<br>item        -        default<br>-------------------------------------<br>source code          /src/main/java<br><br>resources            /src/main/resources<br><br>tests                /src/test<br><br>compiled byte code    /target<br><br>distributable JAR     /target/classes</pre><p>so as you can see we created our application on /src/main/java , and the resources on the /src/main/resources , so maven based on this structure it will work for compiling and packaging the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eV59vSv_JFTGsrbMZoyHKw.png" /></figure><p>Now Back to maven , maven have alot of phases as you can see , on our project we will just go through 2 phases the test phase and the packaging phase.</p><p>When u run maven it’s going to do a round of test based on the unit test which is find in the test file , in the packaging phase it’s going to do a packaging of the entire source code into a jar file.</p><p><strong><em>Now we need to build the package using maven package manager , but to not do that manually every time we will do it through the gitlab pipeline , so then every time we make a new commit , the gitlab will notice that and run the packaging step as a first phase on our pipeline , we will describe that on the next part .</em></strong></p><h3>Summary</h3><p>In this story we see the project use cases and describe why we have a 2 microservices and why we used the Node.js &amp; SpringBoot , then we run our project on local machine using docker.</p><p>Once we run our project on local machine and verify all thing fine , we describe the power of maven and how we can use it for packaging and manage the packages, in next part we will make our pipeline on gitlab and create our CI .</p><p><a href="https://medium.com/@majdnull/devsecops-project-using-iac-overview-project-notes-febf35517839">From Introduction</a>.</p><p><a href="https://medium.com/@majdnull/devsecops-project-using-iac-part-5-create-our-cluster-on-kubernetes-6847c9110ede">Previous Story — Create our cluster on Kubernetes</a>.</p><p><a href="https://medium.com/@majdnull/devsecops-project-using-iac-part-7-building-our-continuous-integration-ci-pipeline-using-b38f990e9644">Next — Building our Continuous Integration (CI) pipeline Using Gitlab Pipeline</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3fb7752f3f7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DevSecOps Project Using IAC : Part 5 ( Create our cluster on Kubernetes)]]></title>
            <link>https://medium.com/@majdnull/devsecops-project-using-iac-part-5-create-our-cluster-on-kubernetes-6847c9110ede?source=rss-3842da3c44b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/6847c9110ede</guid>
            <dc:creator><![CDATA[Majdnull]]></dc:creator>
            <pubDate>Fri, 08 Mar 2024 12:25:14 GMT</pubDate>
            <atom:updated>2024-03-26T13:09:15.038Z</atom:updated>
            <content:encoded><![CDATA[<h3>DevSecOps Project Using IAC : Part 5 ( Create our cluster on Kubernetes)</h3><blockquote><em>LinkedIn : </em><a href="http://www.linkedin.com/in/majd-zahran-4314b1235"><em>Majd Zahran</em></a><em> , </em><strong><em>Please Don’t Hesitate to Contact Me</em></strong></blockquote><h3>Part 5: Creating our cluster on Kubernetes</h3><h4>In this part we will configure the Droplets (VPS) nodes to a Kubernetes cluster using ansible.</h4><p><a href="https://medium.com/@majdnull/devsecops-project-using-iac-overview-project-notes-febf35517839">From the start — Introduction</a></p><p><a href="https://medium.com/@majdnull/devsecops-project-using-iac-part-4-configuring-servers-using-ansible-262e3d3bfc69">Follow from the previous part — Part4</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oGK87p-Ip4ttF64PsLhCaA.jpeg" /></figure><blockquote>To follow along with this part , you must now have 3 Droplets (VPSs) set up and configured with a base-level configuration , which we did in the<a href="https://medium.com/@majdnull/devsecops-project-using-iac-part-4-configuring-servers-using-ansible-262e3d3bfc69"> previous part</a> . now we will enhance that configurations to install the cluster on our Kubernetes.</blockquote><p>Code for this part here:</p><p><a href="https://gitlab.com/Majdnull/voting-iac/-/tree/part5">https://gitlab.com/Majdnull/voting-iac/-/tree/part5</a></p><h4>Ansible Roles</h4><p>We will build a 3 node on the cluster , one master and 2worker nodes.</p><p>All nodes require Docker to be installed so the Docker images will pulled from Docker Hub and can then run in Docker containers.</p><p>In order to manage these , we will using ansible roles to manage our configuration files. By using roles, we can overlay configurations based on the role of the server we are want to configure.</p><p>We will make four roles:</p><ul><li><strong><em>docker</em></strong></li><li><strong><em>k8s_base</em></strong></li><li><strong><em>k8s_master</em></strong></li><li><strong><em>k8s_node</em></strong></li></ul><p>Now this roles will assign to all nodes , but the difference here is we will assign the <strong><em>k8s_node</em></strong> to the worker nodes , <strong><em>k8s_master</em></strong> to the master node :</p><ul><li>master = <strong><em>docker</em></strong>, <strong><em>k8s_base</em></strong>, <strong><em>k8s_master</em></strong></li><li>node = <strong><em>docker</em></strong>, <strong><em>k8s_base</em></strong>, <strong><em>k8s_node</em></strong></li></ul><h3>Ansible Configuration</h3><p>Now moving to the next step We want to create our Kubernetes configurations in another folder called <strong><em>ansible/k8s</em></strong>. All our configuration will be added to this folder.</p><p>Create the <strong><em>ansible/k8s/ansible.cfg</em></strong>:</p><pre>[defaults]<br>inventory = ../inventory<br>private_key_file = C:\Users\Lenovo\.ssh\id_rsa<br>remote_user = majd</pre><p>Now create <strong><em>ansible/k8s/k8s.yml</em></strong> :</p><blockquote>Now on this we will tell ansible which roles each node should be configured with , as we plan previously we will set the <strong><em>docker</em></strong>, <strong><em>k8s_base</em></strong>, <strong><em>k8s_master</em></strong> to <strong><em>Master Node </em>&amp;</strong><strong><em>docker</em></strong>, <strong><em>k8s_base</em></strong>, <strong><em>k8s_node</em> to Worker Nodes.</strong></blockquote><pre>---<br><br>- hosts: k8s_master<br>  become: true<br>  roles:<br>    - docker<br>    - k8s_base<br>    - k8s_master<br><br>- hosts: k8s_node<br>  become: true<br>  roles:<br>    - docker<br>    - k8s_base<br>    - k8s_node</pre><p>Now as we did on the ansible before we make a 2 hosts one for master and the other for worker , become:true to assumes that all the configuration will be as a root user ( which is majd in our case (remember majd is enabled to use sudo)) , then we will assign the roles as we did previously.</p><blockquote>This configuration cannot be applied without the roles being defined. Ansible expects all roles to be defined in a <strong><em>roles</em></strong> subfolder.</blockquote><p>So now we need to make the roles folder , So create <strong><em>ansible/k8s/roles</em></strong> :</p><p>On it we will make a <strong><em>4 folders</em></strong> as following :</p><ul><li><strong>ansible/k8s/roles/docker</strong></li><li><strong><em>ansible/k8s/roles/k8s_base</em></strong></li><li><strong><em>ansible/k8s/roles/k8s_master</em></strong></li><li><strong><em>ansible/k8s/roles/k8s_node</em></strong></li></ul><p>Now let’s going to the <strong><em>docker</em></strong> folder :</p><p>The docker folder should be contain the following folder and on each folder we will make the main.yml file :</p><ul><li>ansible/k8s/roles/docker/task/main.yml : we will define the tasks of the roles folder.</li><li>ansible/k8s/roles/docker/vars/main.yml : we will define the sets of variables for the task here.</li><li>ansible/k8s/roles/docker/handler/main.yml : we will define the handlers for the playbook here.</li></ul><p>Now for <strong><em>ansible/k8s/roles/docker/task/main.yml</em></strong> :</p><p>Let’s go with that one by one :</p><pre>- name: Install Docker<br>  tags:<br>  - docker<br>  - k8s_base<br>  - k8s_master<br>  block:</pre><p>Now with that we want to install docker in the docker , k8s_base , k8s_master . we can see the demonstrates of use a block that contains further tasks ( makes sub-tasks ) , <strong><em>this means this block is configured if Ansible is asked to configure any of these groups. ( simply if any of this tags configure with ansible these block of tasks will configure )</em></strong></p><p>Now let’s dive into this block of sub-tasks :</p><pre>- name: Ubuntu | Configure Sysctl<br>    sysctl:<br>      name: &quot;net.ipv4.ip_forward&quot;<br>      value: &quot;1&quot;<br>      state: present</pre><p>Docker requires IPv4 forwarding to be enabled , so forward it here</p><pre>- name: Ubuntu | Install Prerequisites Packages<br>    package: name={{ item }} state=present force=yes<br>    loop: &quot;{{ docker_dependencies }}&quot;</pre><p>This installs the list of docker_dependencies that are defined in the ansible/k8s/roles/docker/vars/main.yml file ( we will create it later in this story )</p><pre>- name: Ubuntu | Add GPG Keys<br>    apt_key: <br>      url: &quot;{{ docker_url_apt_key }}&quot;<br><br>  - name: Ubuntu | Add Repo Source<br>    apt_repository: <br>      repo: &quot;{{ docker_repository }}&quot;<br>      update_cache: yes<br><br>  - name: Ubuntu | Install Specific Version of Docker Packages<br>    package: name={{ item }} state=present force=yes install_recommends=no<br>    loop: &quot;{{ docker_packages }}&quot;<br>    notify:<br>    - start docker</pre><p>These three tasks adds the docker repository and then installs docker itself , Note that a start_docker handler is notified of the updates. This will restart docker once the play has finished.</p><pre>- name: Enable CRI API<br>    lineinfile:<br>      path: /etc/containerd/config.toml<br>      regexp: &quot;disabled_plugins.*&quot;<br>      line: &quot;disabled_plugins = []&quot;<br>      state: present<br><br>  - name: Configure containerd - get default config<br>    shell: containerd config default | tee /etc/containerd/config.toml<br><br>  - name: Enable SystemdCgroup<br>    shell:  sed -i &#39;s/SystemdCgroup = false/SystemdCgroup = true/g&#39; /etc/containerd/config.toml  <br>    register: containerd</pre><p>First uses the Ansible <strong><em>apt_key</em></strong> module to add a GPG key for the Docker repository , this task uses <strong><em>lineinfile</em></strong> to modify the <strong><em>/etc/containerd/config.toml</em></strong> file , it ensures that the line containing <strong><em>disabled_plugins</em></strong> is set to an empty list (<strong><em>disabled_plugins = []</em></strong>) , The <strong><em>containerd</em></strong> service is then used to create the required default config . ( This step likely enables specific plugins or features within containerd )</p><p>Then runs the <strong><em>containerd config default</em></strong> command and saves the output to <strong><em>/etc/containerd/config.toml</em></strong>, it retrieves the default configuration for containerd and writes it to the specified file .</p><p>Then this task uses <strong><em>sed</em></strong> to replace <strong><em>SystemdCgroup = false</em></strong> with <strong><em>SystemdCgroup = true</em></strong> in the <strong><em>/etc/containerd/config.toml</em></strong> file , enabling <strong><em>SystemdCgroup</em></strong> ensures that containerd uses systemd cgroups for managing containers.</p><blockquote>When this config change is made the <strong><em>register: containerd</em></strong> command is used to trigger the handler to restart the <strong><em>containerd</em></strong> service.</blockquote><pre>- name: Restart containerd after config change<br>    service:<br>      name: containerd<br>      state: restarted<br>    when: containerd.changed<br><br>  - name: Ubuntu | Start and Enable Docker Service<br>    service:<br>      name: docker<br>      state: started<br>      enabled: yes</pre><p>Then we write this handler restarts <strong><em>containerd</em></strong>. The <strong><em>service</em></strong> module is used here instead of relying on a <strong><em>handler</em></strong> as we need to restart <strong><em>containerd</em></strong> before we start <em>docker</em></p><p>Finally we start a docker and enable it.</p><p>This is the hole code of this file ansible/k8s/roles/docker/task/main.yml :</p><pre>- name: Install Docker<br>  tags:<br>  - docker<br>  - k8s_base<br>  - k8s_master<br>  block:<br>  - name: Ubuntu | Configure Sysctl<br>    sysctl:<br>      name: &quot;net.ipv4.ip_forward&quot;<br>      value: &quot;1&quot;<br>      state: present<br><br>  - name: Ubuntu | Install Prerequisites Packages<br>    package: name={{ item }} state=present force=yes<br>    loop: &quot;{{ docker_dependencies }}&quot;<br><br>  - name: Ubuntu | Add GPG Keys<br>    apt_key: <br>      url: &quot;{{ docker_url_apt_key }}&quot;<br><br>  - name: Ubuntu | Add Repo Source<br>    apt_repository: <br>      repo: &quot;{{ docker_repository }}&quot;<br>      update_cache: yes<br><br>  - name: Ubuntu | Install Specific Version of Docker Packages<br>    package: name={{ item }} state=present force=yes install_recommends=no<br>    loop: &quot;{{ docker_packages }}&quot;<br>    notify: start docker<br><br>  - name: Enable CRI API<br>    lineinfile:<br>      path: /etc/containerd/config.toml<br>      regexp: &quot;disabled_plugins.*&quot;<br>      line: &quot;disabled_plugins = []&quot;<br>      state: present<br><br>  - name: Configure containerd - get default config<br>    shell: containerd config default | tee /etc/containerd/config.toml<br><br>  - name: Enable SystemdCgroup<br>    shell:  sed -i &#39;s/SystemdCgroup = false/SystemdCgroup = true/g&#39; /etc/containerd/config.toml  <br>    register: containerd<br><br>  - name: Restart containerd after config change<br>    service:<br>      name: containerd<br>      state: restarted<br>    when: containerd.changed<br><br>  - name: Ubuntu | Start and Enable Docker Service<br>    service:<br>      name: docker<br>      state: started<br>      enabled: yes</pre><p>Now we need to define the <strong><em>main.yml</em></strong> on the <strong><em>ansible/k8s/roles/docker/vars/</em></strong> :</p><pre>docker_dependencies:<br>- ca-certificates<br>- gnupg<br>- gnupg2<br>- gnupg-agent<br>- software-properties-common<br>- apt-transport-https<br>- curl<br>docker_packages:<br>- docker-ce<br>docker_url_apt_key: &quot;https://download.docker.com/linux/ubuntu/gpg&quot;<br>docker_repository: &quot;deb [arch=amd64] https://download.docker.com/linux/ubuntu focal stable&quot;</pre><p>So this is the decker dependencies we need to install.</p><p>Now moving to the ansible/k8s/roles/docker/handler/main.yml file :</p><pre>- name: start_docker<br>  service:<br>    name: docker<br>    state: started<br>    enabled: yes</pre><p>This handler to restart the docker after the configuration is applied.</p><p><strong><em>As Ansible is declarative</em></strong> , it is possible to run this now before extending it for Kubernetes . From the k8s folder:</p><pre>ansible-playbook k8s.yml --ask-pass --tags=docker</pre><p>The tag parameter ensure that ansible will run just those plays that tagged with <strong><em>docker</em></strong> . ( --ask-pass it’s for provide the ssh password, that because i face some issues with ssh key)</p><p>You should see output like this :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6U0Mt6dQ-NZcF7hN4Hd-vg.png" /></figure><h3>Now let’s moving to the <strong><em>k8s_base role</em></strong> :</h3><p>Now we will create the first part of the Kubernetes cluster. There are some applications that all nodes require.</p><p>On this folder ansible/k8s/roles/k8s_base , we will create 2 folder as we did on the docker folder:</p><ul><li>create the folder ansible/k8s/roles/k8s_base/vars/main.yml</li><li>And create this ansible/k8s/roles/k8s_base/task/main.yml</li></ul><p>Create <strong><em>ansible/k8s/roles/k8s_base/task/main.yml</em></strong>:</p><pre>- name: Set up base config for k8s master and node<br>  tags:<br>    - k8s_base<br>    - k8s_master<br>    - k8s_node<br>  block:<br>    - name: Disable SWAP K8S will not work with swap enabled (1/2)<br>      command: swapoff -a<br>      when: ansible_swaptotal_mb &gt; 0<br><br>    - name: Ubuntu | Remove SWAP from fstab K8S will not work with swap enabled (2/2)<br>      mount:<br>        name: &quot;{{ item }}&quot;<br>        fstype: swap<br>        state: absent<br>      with_items:<br>      - swap<br>      - none<br><br>    - name: Ubuntu | Add GPG Key<br>      apt_key:<br>        url: &quot;{{ k8s_url_apt_key }}&quot;<br>        state: present<br>      register: add_repository_key<br><br>    - name: Ubuntu | Add Kubernetes Repository<br>      apt_repository: <br>        repo: &quot;{{ k8s_repository }}&quot;<br>        update_cache: yes<br><br>    - name: Ubuntu | Install Dependencies<br>      package: name={{ item }} state=present force=yes install_recommends=no<br>      loop: &quot;{{ k8s_dependencies }}&quot;<br><br>    - name: Ubuntu | Install Kubernetes Packages<br>      package: name={{ item }} state=present force=yes install_recommends=no<br>      loop: &quot;{{ k8s_packages }}&quot;</pre><p>Like Docker, this is tagged to ensure it is run with tags of k8s_base, k8s_master and k8s_node.</p><p>Now as previous let’s break the sub-tasks :</p><pre>block:<br>    - name: Disable SWAP K8S will not work with swap enabled (1/2)<br>      command: swapoff -a<br>      when: ansible_swaptotal_mb &gt; 0<br><br>    - name: Ubuntu | Remove SWAP from fstab K8S will not work with swap enabled (2/2)<br>      mount:<br>        name: &quot;{{ item }}&quot;<br>        fstype: swap<br>        state: absent<br>      with_items:<br>      - swap<br>      - none</pre><p>Kubernetes will not work with memory swap space enabled. So these two tasks disable it and remove any that has been created. Noticing that Digital Ocean servers not have swap space enabled but this ensures this is the case.</p><blockquote>The first task is a <strong><em>command</em></strong>, which seems to break the idea of a declarative definition, however, when combined with a when statement, it makes this declarative.</blockquote><blockquote>The <strong><em>mount</em></strong> task is an example of setting multiple things at a time (<strong><em>with_items</em></strong>) and the <strong><em>state: absent</em></strong> line means “ make sure it is not there “ .</blockquote><pre>- name: Ubuntu | Remove SWAP from fstab K8S will not work with swap enabled (2/2)<br>      mount:<br>        name: &quot;{{ item }}&quot;<br>        fstype: swap<br>        state: absent<br>      with_items:<br>      - swap<br>      - none<br><br> - name: Ubuntu | Add GPG Key<br>      apt_key:<br>      url: &quot;{{ k8s_url_apt_key }}&quot;<br>      state: present<br>      register: add_repository_key<br><br> - name: Ubuntu | Add Kubernetes Repository<br>      apt_repository: <br>      repo: &quot;{{ k8s_repository }}&quot;<br>      update_cache: yes<br><br> - name: Ubuntu | Install Dependencies<br>      package: name={{ item }} state=present force=yes install_recommends=no<br>      loop: &quot;{{ k8s_dependencies }}&quot;<br><br> - name: Ubuntu | Install Kubernetes Packages<br>      package: name={{ item }} state=present force=yes install_recommends=no<br>      loop: &quot;{{ k8s_packages }}&quot;</pre><p>In the same way as we did with Docker, this loads in the repositories for <em>apt</em> to pick up Kubernetes. It then loads the list of dependencies and packages from the <strong><em>vars/main.yml</em></strong> .</p><p>Now create ansible/k8s/roles/k8s_base/vars/main.yml :</p><pre>k8s_dependencies: <br>  - kubernetes-cni<br>  - kubelet<br>  <br>k8s_packages:<br>  - kubeadm<br>k8s_url_apt_key: &quot;https://packages.cloud.google.com/apt/doc/apt-key.gpg&quot;<br>k8s_repository: &quot;deb https://mirrors.aliyun.com/kubernetes/apt/ kubernetes-xenial main&quot;</pre><p>This lists the information required to load the base level of packages for Kubernetes.</p><p>Now as what we did previously to the docker folder , we can run it now :</p><pre>ansible-playbook k8s.yml --ask-pass --tags=k8s_base</pre><p>Now you should see output like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RD3MwyNwh_GXnoUYSj8_Tg.png" /></figure><h3>Now we can going to k8s_master role</h3><blockquote>This role configures the master node. As we know there is a single master node on our project (<strong><em>Kubernetes allows multiple master nodes</em></strong>) and so this role is designed to only applied to a single node.</blockquote><p>The k8s_base configuration loads <strong><em>kubeadm</em></strong>, <strong><em>kubectl</em></strong> and <strong><em>kubelet</em></strong>, which allow the master to create and manage the cluster.</p><p>This role will contain :</p><p>Create ansible/k8s/roles/k8_master/task/main.yml :</p><pre>---<br>- name: Set up config for k8s master<br>  tags:<br>    - k8s_master<br>  block:<br>    - name: Ubuntu | Initialise the Kubernetes cluster using kubeadm<br>      become: true<br>      command: kubeadm init --pod-network-cidr=&quot;{{ k8s_pod_network }}&quot;<br>      args:<br>        creates: &quot;{{ k8s_admin_config }}&quot;<br><br>    - name: Ubuntu | Setup kubeconfig for &quot;{{ k8s_user }}&quot; user<br>      file:<br>        path: &quot;{{ k8s_user_home }}/.kube&quot;<br>        state: directory<br>        owner: &quot;{{ k8s_user }}&quot;<br>        group: &quot;{{ k8s_user }}&quot;<br>        mode: &quot;0750&quot;<br><br>    - name: Ubuntu | Copy &quot;{{ k8s_admin_config }}&quot;<br>      become: true<br>      copy:<br>        src: &quot;{{ k8s_admin_config }}&quot;<br>        dest: &quot;{{ k8s_user_home }}/.kube/config&quot;<br>        owner: &quot;{{ k8s_user }}&quot;<br>        group: &quot;{{ k8s_user }}&quot;<br>        mode: &quot;0600&quot;<br>        remote_src: yes<br><br>    - name: Ubuntu | Download &quot;{{ calico_operator_url }}&quot;<br>      get_url:<br>        url: &quot;{{ calico_operator_url }}&quot;<br>        dest: &quot;{{ k8s_user_home }}/{{ calico_operator_config }}&quot;<br>        owner: &quot;{{ k8s_user }}&quot;<br>        group: &quot;{{ k8s_user }}&quot;<br>        mode: &quot;0640&quot;<br><br>    - name: Ubuntu | Download &quot;{{ calico_net_url }}&quot;<br>      get_url:<br>        url: &quot;{{ calico_net_url }}&quot;<br>        dest: &quot;{{ k8s_user_home }}/{{ calico_net_config }}&quot;<br>        owner: &quot;{{ k8s_user }}&quot;<br>        group: &quot;{{ k8s_user }}&quot;<br>        mode: &quot;0640&quot;<br><br>    - name: Ubuntu | Install calico operator &quot;{{ calico_operator_config }}&quot;<br>      become: false<br>      command: kubectl create -f &quot;{{ k8s_user_home }}/{{ calico_operator_config }}&quot;<br><br>    - name: Ubuntu | Set CALICO_IPV4POOL_CIDR to &quot;{{ k8s_pod_network }}&quot;<br>      replace:<br>        path: &quot;{{ k8s_user_home }}/{{ calico_net_config }}&quot;<br>        regexp: &quot;192.168.0.0/16&quot;<br>        replace: &quot;{{ k8s_pod_network }}&quot;<br><br>    - name: Ubuntu | Install calico pod network &quot;{{ calico_net_config }}&quot;<br>      become: false<br>      command: kubectl apply -f &quot;{{ k8s_user_home }}/{{ calico_net_config }}&quot;<br><br>    - name: Ubuntu | wait for k8s API port to open<br>      wait_for:<br>        port: 6443<br><br>    - name: Ubuntu | Generate join command<br>      command: kubeadm token create --print-join-command<br>      register: join_command<br><br>    - name: Ubuntu | Copy join command to local file<br>      become: false<br>      local_action: copy content=&quot;{{ join_command.stdout_lines[0] }}&quot; dest=&quot;{{ k8s_token_file }}&quot;</pre><p><strong><em>As always let’s break it down to sub-tasks:</em></strong></p><pre>- name: Ubuntu | Initialise the Kubernetes cluster using kubeadm<br>      become: true<br>      command: kubeadm init --pod-network-cidr={{ k8s_pod_network }}<br>      args:<br>        creates: &quot;{{ k8s_admin_config }}&quot;</pre><p>This initialises the cluster and defines an internal pod network that is only accessible from within the cluster.</p><p>A pod is a Kubernetes abstraction of a container. Normally a pod only includes one container but it can contain more, such as sidecar containers that assist the main container.</p><p>Containers talk to each other across the cluster through the internal pod network. Kubernetes allocates each container/pod its own IP address within the pod network. Note that Kubernetes does not natively create the pod network (we will see that later).</p><pre>- name: Ubuntu | Setup kubeconfig for {{ k8s_user }} user<br>      file:<br>        path: &quot;{{ k8s_user_home }}/.kube&quot;<br>        state: directory<br>        owner: &quot;{{ k8s_user }}&quot;<br>        group: &quot;{{ k8s_user }}&quot;<br>        mode: &quot;0750&quot;<br><br>    - name: Ubuntu | Copy {{ k8s_admin_config }}<br>      become: true<br>      copy:<br>        src: &quot;{{ k8s_admin_config }}&quot;<br>        dest: &quot;{{ k8s_user_home }}/.kube/config&quot;<br>        owner: &quot;{{ k8s_user }}&quot;<br>        group: &quot;{{ k8s_user }}&quot;<br>        mode: &quot;0600&quot;<br>        remote_src: yes</pre><p>This section creates a .kube folder in the majd user’s home folder. This sets up the configuration such that the majd user can use kubectl .</p><p>As you can see there alot of variables like : { k8s_user_home } , so we will define a file called global vars file on it we will input all this variables.</p><pre>- name: Ubuntu | Download {{ calico_operator_url }}<br>      get_url:<br>        url: &quot;{{ calico_operator_url }}&quot;<br>        dest: &quot;{{ k8s_user_home }}/{{ calico_operator_config }}&quot;<br>        owner: &quot;{{ k8s_user }}&quot;<br>        group: &quot;{{ k8s_user }}&quot;<br>        mode: &quot;0640&quot;     <br><br>    - name: Ubuntu | Download {{ calico_net_url }}<br>      get_url:<br>        url: &quot;{{ calico_net_url }}&quot;<br>        dest: &quot;{{ k8s_user_home }}/{{ calico_net_config }}&quot;<br>        owner: &quot;{{ k8s_user }}&quot;<br>        group: &quot;{{ k8s_user }}&quot;<br>        mode: &quot;0640&quot;     <br><br>    - name: Ubuntu | Install calico operator {{ calico_operator_config }}<br>      become: false<br>      command: kubectl create -f &quot;{{ k8s_user_home }}/{{ calico_operator_config }}&quot;<br><br>    - name: Ubuntu | Set CALICO_IPV4POOL_CIDR to {{ k8s_pod_network }}<br>      replace:<br>        path: &quot;{{ k8s_user_home }}/{{ calico_net_config }}&quot;<br>        regexp: &quot;192.168.0.0/16&quot;<br>        replace: &quot;{{ k8s_pod_network }}&quot;<br><br>    - name: Ubuntu | Install calico pod network {{ calico_net_config }}<br>      become: false<br>      command: kubectl apply -f &quot;{{ k8s_user_home }}/{{ calico_net_config }}&quot;</pre><p>Here kubernetes requires a network overlay that allows the pods to communicate, routing the requests within and across nodes. There are several options for this overlay, including <strong><em>Flannel</em></strong> and <strong><em>Calico</em></strong>.</p><p>In this part of code you can see that Calico has been chosen. First the components are downloaded and then loaded into the cluster using kubectl .</p><pre>- name: Ubuntu | wait for k8s API port to open<br>      wait_for:<br>        port: 6443</pre><p>This to ensures that the Kubernetes management API has started and ready to accept instructions from kubectl before any further configuration takes place.</p><pre>- name: Ubuntu | Generate join command<br>      command: kubeadm token create --print-join-command<br>      register: join_command<br><br>    - name: Ubuntu | Copy join command to local file<br>      become: false<br>      local_action: copy content=&quot;{{ join_command.stdout_lines[0] }}&quot; dest=&quot;{{ k8s_token_file }}&quot;</pre><p>Once the Kubernetes API is up and running, kubeadm is used to obtain the join command instruction to join worker nodes into the cluster.</p><p>Then that will saved to a local file on the development machine for configuring the worker nodes.</p><p>Now we need to create the global variables as we said previously :</p><p>Create ansible/k8s/global_vars/all :</p><pre>k8s_pod_network: &quot;192.168.0.0/16&quot;<br>k8s_user: &quot;majd&quot;<br>k8s_user_home: &quot;/home/{{ k8s_user }}&quot;<br>k8s_token_file: &quot;join-k8s-command&quot;<br>k8s_admin_config: &quot;/etc/kubernetes/admin.conf&quot;<br>k8s_kubelet_config: &quot;/etc/kubernetes/kubelet.conf&quot;<br>calico_operator_url: &quot;https://raw.githubusercontent.com/projectcalico/calico/v3.26.1/manifests/tigera-operator.yaml&quot;<br>calico_operator_config: &quot;tigera-operator.yaml&quot;<br>calico_net_url: &quot;https://docs.projectcalico.org/manifests/calico.yaml&quot;<br>calico_net_config: &quot;calico.yaml&quot;</pre><p>That’s all variables we need .</p><p>Let’s now configure the master node:</p><pre>ansible-playbook k8s.yml --ask-pass --tags=k8s_master</pre><p>Then you should see this output :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Afmi2mXgphwpnakDBUowQ.png" /></figure><h3>k8s_node role</h3><p>This role will configures the worker nodes on our kubernetes. there are two worker nodes but you can have any number , that related to your setup on <a href="https://medium.com/@majdnull/devsecops-project-using-iac-part-3-automatic-creation-of-the-cloud-infrastructure-45b7c2002202">Part3</a>.</p><p>The k8s_base configuration loads kubelet, which is the main Kubernetes service for all nodes. These will be used in this configuration.</p><p>As we did previously , now we need the Task folder .</p><p>Create ansible/k8s/roles/k8s_node/task/main.yml :</p><pre>- name: Ubuntu | Copy {{ k8s_join_file }} to server location<br>  tags: k8s_node<br>  copy: <br>    src: &quot;{{ k8s_token_file }}&quot;<br>    dest: &quot;{{ k8s_user_home }}/{{ k8s_join_file }}.sh&quot;<br>    owner: &quot;{{ k8s_user }}&quot;<br>    group: &quot;{{ k8s_user }}&quot;<br>    mode: &quot;0750&quot;<br><br>- name: Ubuntu | Join the node to cluster unless file {{ k8s_kubelet_config }} exists<br>  tags: k8s_node<br>  become: true<br>  command: sh &quot;{{ k8s_user_home }}/{{ k8s_join_file }}.sh&quot;<br>  args:<br>    creates: &quot;{{ k8s_kubelet_config }}&quot;</pre><p>The node is much simpler than the master. With kubelet already installed it only requires the node to be given the details it needs to connect to the cluster. This is held in the join file created by the master_node configuration and copied to the development machine.</p><p>Now let’s run it :</p><pre>ansible-playbook k8s.yml --tags=k8s_node</pre><p>The output look like this :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_djiTJkRasn6coYb-o7vvw.png" /></figure><h3>Now Let’s Test our cluster</h3><p>It is possible to connect into your cluster from your development machine , but I decided to access my cluster from within the master node. By ssh into the master node :</p><pre>ssh -i C:\Users\Lenovo\.ssh\id_rsa majd@&lt;master ip address&gt;</pre><p>Once you are logged on, you can now enter:</p><pre>kubectl get nodes</pre><p>This will list all the nodes in our cluster. You should see an output like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*4LJb3rMVwKZuh_lxTbVvjg.png" /></figure><p>If this is what you see, congratulations man! You now have the tools to create a 3 node Kubernetes cluster using Terraform, Ansible and the Digital Ocean service provider.</p><h3>Summary</h3><p>In this Part we used Ansible to set up three nodes of a Kubernetes cluster. We used Ansible roles to define the different configurations required for the nodes.</p><p><a href="https://medium.com/@majdnull/devsecops-project-using-iac-overview-project-notes-febf35517839">Series Introduction</a></p><p><a href="https://medium.com/@majdnull/devsecops-project-using-iac-part-4-configuring-servers-using-ansible-262e3d3bfc69">Previous — Configuring servers using Ansible</a></p><p><a href="https://medium.com/@majdnull/devsecops-project-using-iac-part-6-setting-up-a-persistent-volume-and-connecting-it-to-3fb7752f3f7c">Next — Project use cases &amp; Run the project on our local machine</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6847c9110ede" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DevSecOps Project Using IAC : Part 4 (Configuring servers using Ansible )]]></title>
            <link>https://medium.com/@majdnull/devsecops-project-using-iac-part-4-configuring-servers-using-ansible-262e3d3bfc69?source=rss-3842da3c44b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/262e3d3bfc69</guid>
            <dc:creator><![CDATA[Majdnull]]></dc:creator>
            <pubDate>Sun, 03 Mar 2024 13:26:39 GMT</pubDate>
            <atom:updated>2024-03-08T12:28:01.051Z</atom:updated>
            <content:encoded><![CDATA[<h3>DevSecOps Project Using IAC : Part 4 (Configuring servers using Ansible )</h3><blockquote>LinkedIn : <a href="http://www.linkedin.com/in/majd-zahran-4314b1235">Majd Zahran</a> , <strong>Please Don’t Hesitate to Contact Me</strong></blockquote><h4><strong><em>Part4 — Configuring servers using Ansible</em></strong></h4><p><strong><em>This is part4 the articles that we created about a project to implement automated provisioning of cloud infrastructure in order to deploy a Spring Boot application to a Kubernetes cluster . In this part we will use Ansible to configure the Droplets (VPSs) we created previously using Terraform .</em></strong></p><p><a href="https://medium.com/@majdnull/devsecops-project-using-iac-overview-project-notes-febf35517839"><strong><em>From the start — — — Part1</em></strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*Yz66f0ps-ZW18Avk0mS6kQ.jpeg" /></figure><p>While we created our three VPS nodes in the <a href="https://medium.com/@majdnull/devsecops-project-using-iac-part-3-automatic-creation-of-the-cloud-infrastructure-45b7c2002202">previous part</a> , we will now set up a base configuration using Tool called Ansible.</p><p>You can find the code for this part here:</p><p><a href="https://gitlab.com/Majdnull/voting-iac/-/tree/part4">https://gitlab.com/Majdnull/voting-iac/-/tree/part4</a></p><h3>Ansible</h3><p>Similar to terraform , Ansible works from a set of <strong><em>declarative configuration</em></strong> files that tell you the state of each server you have . now create a file called ansible like what we did with terraform.</p><blockquote><strong><em>These declarative configuration called a Ansible playbook. think about it like a book that is used to run something , a playbook can have one or more plays within them ( that’s mean we can run a 2 play (configure) in the same playbook ). It executes these plays against each resources to configure it.</em></strong></blockquote><p>Each play can include one or more tasks . ansible uses a set of plugin modules with an extensive and useful set built in to the tool itself. Each module performs a task on the target host and can generally perform the action on a number of different environments or Operating Systems (OS) .</p><p>Some plays are specific to an OS ( like we want to install the command prompt to a windows OS ) and there are ways you <strong><em>can tell Ansible to carryout different play for different OSs</em></strong>. In this way, you can configure a set of different hosts using the same playbook. All the nodes we have created are Ubuntu nodes.</p><h4>Our Target Hosts</h4><p>The target hosts are defined in the <strong><em>ansible_inventory.tfpl</em></strong> file. If you remember we created it by terraform , we let terraform to print the IPs of the master node and the 2 worker node in this file , it’s looks like this :</p><pre>[k8s_master]<br>103.5.200.320<br><br>[k8s_node]<br>115.215.311.66<br>110.540.116.154</pre><p>The IP addresses displayed here are not real (fake IP ) , however, you can also utilize domain names (DNS) .</p><blockquote>The <strong><em>names between [ ] allow you to group target hosts</em></strong> , <em>allowing you to refer it to a number of hosts by their group name</em>. You can use groups to identify your hosts as particular types : (ex: db, web, app , prod , pre-prod etc.). A host can appear in one or more than one group , so u can set the node 1 to the prod &amp; pre-prod group .</blockquote><h4>Appling Ansible Playbooks</h4><p>For instance, you can tell Ansible to only configure the <strong><em>k8s_master</em></strong> hosts by using <strong><em>--limit=k8s_master</em></strong> on the command line . This will tell Ansible only to run the playbook against your one master node. If you used <strong><em>--limit=k8s_node</em></strong> it will configure both of the worker nodes (which are configured identically) , so u can let the playbook to run to one group or more than one .</p><h3>Configuring Servers using Ansible</h3><blockquote><strong>Whilst a single playbook can configure all your servers, it is sometimes useful to configure your servers in two steps</strong> :</blockquote><ol><li><strong><em>Bootstrapping the Servers with same configuration.</em></strong></li><li><strong><em>Configuring the Servers for your specific application.</em></strong></li></ol><p>In this story, we will bootstrap our servers to give them a common configuration on which we can build our Kubernetes cluster.</p><p>Just Remember, you can run your playbook against one or more of your target hosts. For me I will run the play to the k8s_master host first , then until I get it working right ,then I will apply it to all hosts on the group ( all hosts in the inventory ).</p><h3>Bootstrapping the Servers</h3><blockquote>All hosts need an initial configuration, such as updating the Operating Systems, adding a user etc. Rather than adding these plays to every playbook you create, <strong><em>it is easier to have it as a standalone playbook containing your standard set of plays</em></strong> , that will make the configuration of any server you create related to Ubuntu will be easy , because we have the ansible playbook just we need to run it.</blockquote><p>This configurations of an initial playbook is known as <strong><em>bootstrapping the servers </em></strong>and it can be done using Ansible once you have added the servers to the <strong><em>known_hosts</em></strong> file (see the <a href="https://medium.com/@majdnull/devsecops-project-using-iac-part-3-automatic-creation-of-the-cloud-infrastructure-45b7c2002202">previous Part</a>).</p><h4>Now let’s make our Bootstrap playbook</h4><p>Create a folder called ansible , add a subfolder called bootstrap. This is where we will create the configuration files for Ansible.</p><p>Create ansible/bootstrap/ansible.cfg :</p><pre>[defaults]<br>inventory = ../inventory<br>private_key_file = C:\Users\Lenovo\.ssh\id_rsa<br>remote_user = root</pre><p>That’s will tell ansible to use the inventory file from the path we saved it on , then to use the ssh key from the location on our local machine , then we need to define the user that the bootstrap should use , in our case it’s will be a root user , root is used as there are no other users on the servers.</p><p>A playbook is now needed to <strong><em>carry out the bootstrap</em></strong>. Ansible playbook files are written in the yaml format, so be careful of indentation errors.</p><p>So now we need to create the bootstrap playbook , create <strong><em>ansible/bootstrap/bootstrap.yml</em></strong></p><p><strong><em>Ok now first we need to start with :</em></strong></p><pre>---<br><br>- hosts: all<br>  become: yes<br>  pre_tasks:</pre><p>Ok now with this hosts: all , we tell ansible to apply this play to all hosts except where you might limit it on the command line as mentioned earlier , — — — this used in yaml file to allow you to define multiple files in one file.</p><p>The become: yes <strong><em>tells Ansible to execute the play as root</em></strong>. The command become allow you to define other users but the yes value indicates root and currently we have no other users on the server , so it’s fine.</p><p>Whilst these configuration files are <strong><em>declarative</em></strong>, you may need to define dependencies . The <strong><em>pre_tasks</em></strong> <strong><em>option tells Ansible that these configurations must be set before others.</em></strong></p><pre>- name: install updates (Ubuntu)<br>    tags: always<br>    apt:<br>      upgrade: dist<br>      update_cache: yes<br>    when: ansible_distribution == &quot;Ubuntu&quot;</pre><p>In this section, as we see within our play. As the play is within the <strong><em>pre_tasks</em></strong> option, this tasks (including this one) will get carried out before anything else .</p><p>Now we will start with our first task , we need to give it a name (install updates (Ubuntu)), which will be displayed on the console when the play is applied. This is followed by a tags. This parameter allow you to define which type of tasks you want Ansible to run. In our case we let it always, which mean <strong><em>always apply this task</em></strong>, <strong><em>regardless of any command line preference .</em></strong></p><p>Next line we have , apt parameter , is an Ansible module that will execute this task. Modules come with their own documentation, which you can find here:</p><p><a href="https://docs.ansible.com/ansible/latest/collections/ansible/builtin/apt_module.html">ansible.builtin.apt module - Manages apt-packages - Ansible Community Documentation</a></p><p>A module performs an action on the host to create a particular configurations . They each come with their own specific set of parameters and arguments. In our case we are asking it to <strong><em>update its cache</em></strong> of packages (update_cache: yes) and to <strong><em>upgrade the OS</em></strong> (upgrade: dist).</p><p>In last line we have a parameter called when it’s used to match the task with the OS version , <strong><em>that mean this task will only apply if the OS is Ubuntu , so if we have a node with Ubuntu and another with Debian , this parameter will be very useful</em></strong> . in our case all the node have the same OS version , the usage on this parameter just for show the discussed case.</p><p>Ok but how ansible will know the OS version before run this task ? ansible first extract all the information it needs about the host first . So when clause can target any of these fields, by this the ansible will know the OS version before it run the task.</p><pre>- name: install sudoers for Ubuntu servers<br>    tags: ubuntu<br>    apt:<br>      name:<br>        - sudo<br>      state: latest<br>    when: ansible_distribution == &quot;Ubuntu&quot;</pre><p>Now we have another task under the <strong><em>pre-tasks</em></strong> option , we give it a name install sudoers for Ubuntu servers, then we pass the tags parameter , but this time with value = Ubuntu , that mean it it excluded from the command line it will not run , then for apt , here u can see the power of ansible , <strong><em>as a declarative file, Ansible will only carryout this task if the latest version of sudoers has not been installed.</em></strong></p><blockquote>You need to remember this. Whilst it is tempting to think of tasks as an imperative set of instructions, they actually define what you want and not how to get there</blockquote><pre>- hosts: all<br>  become: true<br>  tasks:<br><br>  - name: create majd user<br>    tags: always<br>    user:<br>      name: majd<br>      groups: root<br>      shell: &quot;/bin/bash&quot;</pre><p>In this pieces of code we define a new play. Again it is applied to all hosts and is run as root.</p><p>But the difference here is that it’s not a pre-tasks , so it’s a regular task</p><p>Now we have a new task called create majd user , it will be running always , then we want adding the user majd to the OS and adds this user to the root group. It also sets the login shell to be /bin/bash .</p><p>Again, Ansible will only create this user if <em>they do not already exist</em>. This means you can run this playbook as many times as you like , this is the power of ansible ( if you remember we talked previously that ansible check shopping cart before checked out the checklist).</p><pre>- name: Set authorized key taken from file<br>    authorized_key:<br>      user: majd<br>      state: present<br>      key: &quot;{{ lookup(&#39;file&#39;, &#39;C:\Users\Lenovo\.ssh\id_rsa.pub&#39;) }}&quot;</pre><p>Now this task add your Voting Application ssh key to the <em>majd</em> user. This allow other ansible operations to be done under our user .</p><pre>- name: add sudoers file for majd<br>    tags: always<br>    copy:<br>      src: sudoer_majd<br>      dest: /etc/sudoers.d/majd<br>      owner: root<br>      group: root<br>      mode: 0440</pre><p>As we want to add more configuration using the majd user, we add the user to the sudoers file by copying over the permissions file (sudoer_majd). The Ansible copy module looks for the source files in a subfolder called files</p><p>Now we said that we need to copy the permissions file (sudoer_majd) , so now we need to create a folder called files , then create the sudoers permissions file <strong><em>ansible/bootstrapping/files/sudoer_majd</em></strong> :</p><pre>majd ALL=(ALL) NOPASSWD: ALL</pre><p>Now this give the majd user the same privileges as root using sudo. This is useful as it enables the rest of the ansible config to happen under this user, rather than under root. Later we will see that we will remove root from being able to login via ssh .</p><p>Now Back to the bootstrap.yml file, to the next pieces of code :</p><pre>- name: generate sshd_config file from template<br>    tags: ssh<br>    vars:<br>      ssh_users: majd<br>    template:<br>      src: &quot;sshd_config.j2&quot;<br>      dest: /etc/ssh/sshd_config<br>      owner: root<br>      group: root<br>      mode: 0644<br>    notify: restart_sshd</pre><p>In this task we will use the template module to create a file in the target’s filesystem based on a j2 template file. In this case the file provides a default sshd configuration that prevents password and root user login. The module looks for the file in the templates folder. It replaces user defined fields like {{ ssh_users }} with values from the vars section of the task definition.</p><p>Now Create the templet file templates/sshd_config.j2</p><pre># $OpenBSD: sshd_config,v 1.103 2018/04/09 20:41:22 tj Exp $<br><br># This is the sshd server system-wide configuration file.  See<br># sshd_config(5) for more information.<br><br># This sshd was compiled with PATH=/usr/bin:/bin:/usr/sbin:/sbin<br><br># The strategy used for options in the default sshd_config shipped with<br># OpenSSH is to specify options with their default value where<br># possible, but leave them commented.  Uncommented options override the<br># default value.<br><br>Include /etc/ssh/sshd_config.d/*.conf<br>AllowUsers {{ ssh_users }}<br><br>#Port 22<br>#AddressFamily any<br>#ListenAddress 0.0.0.0<br>#ListenAddress ::<br><br>#HostKey /etc/ssh/ssh_host_rsa_key<br>#HostKey /etc/ssh/ssh_host_ecdsa_key<br>#HostKey /etc/ssh/ssh_host_ed25519_key<br><br># Ciphers and keying<br>#RekeyLimit default none<br><br># Logging<br>#SyslogFacility AUTH<br>#LogLevel INFO<br><br># Authentication:<br><br>#LoginGraceTime 2m<br>#PermitRootLogin prohibit-password<br>PermitRootLogin yes<br>#StrictModes yes<br>#MaxAuthTries 6<br>#MaxSessions 10<br><br>#PubkeyAuthentication yes<br><br># Expect .ssh/authorized_keys2 to be disregarded by default in future.<br>#AuthorizedKeysFile .ssh/authorized_keys .ssh/authorized_keys2<br><br>#AuthorizedPrincipalsFile none<br><br>#AuthorizedKeysCommand none<br>#AuthorizedKeysCommandUser nobody<br><br># For this to work you will also need host keys in /etc/ssh/ssh_known_hosts<br>#HostbasedAuthentication no<br># Change to yes if you don&#39;t trust ~/.ssh/known_hosts for<br># HostbasedAuthentication<br>#IgnoreUserKnownHosts no<br># Don&#39;t read the user&#39;s ~/.rhosts and ~/.shosts files<br>#IgnoreRhosts yes<br><br># To disable tunneled clear text passwords, change to no here!<br>#PasswordAuthentication yes<br>#PermitEmptyPasswords no<br><br># Change to yes to enable challenge-response passwords (beware issues with<br># some PAM modules and threads)<br>ChallengeResponseAuthentication no<br><br># Kerberos options<br>#KerberosAuthentication no<br>#KerberosOrLocalPasswd yes<br>#KerberosTicketCleanup yes<br>#KerberosGetAFSToken no<br><br># GSSAPI options<br>#GSSAPIAuthentication no<br>#GSSAPICleanupCredentials yes<br>#GSSAPIStrictAcceptorCheck yes<br>#GSSAPIKeyExchange no<br><br># Set this to &#39;yes&#39; to enable PAM authentication, account processing,<br># and session processing. If this is enabled, PAM authentication will<br># be allowed through the ChallengeResponseAuthentication and<br># PasswordAuthentication.  Depending on your PAM configuration,<br># PAM authentication via ChallengeResponseAuthentication may bypass<br># the setting of &quot;PermitRootLogin without-password&quot;.<br># If you just want the PAM account and session checks to run without<br># PAM authentication, then enable this but set PasswordAuthentication<br># and ChallengeResponseAuthentication to &#39;no&#39;.<br>UsePAM yes<br><br>#AllowAgentForwarding yes<br>#AllowTcpForwarding yes<br>#GatewayPorts no<br>X11Forwarding yes<br>#X11DisplayOffset 10<br>#X11UseLocalhost yes<br>#PermitTTY yes<br>PrintMotd no<br>#PrintLastLog yes<br>#TCPKeepAlive yes<br>#PermitUserEnvironment no<br>#Compression delayed<br>#ClientAliveInterval 0<br>#ClientAliveCountMax 3<br>#UseDNS no<br>#PidFile /var/run/sshd.pid<br>#MaxStartups 10:30:100<br>#PermitTunnel no<br>#ChrootDirectory none<br>#VersionAddendum none<br><br># no default banner path<br>#Banner none<br><br># Allow client to pass locale environment variables<br>AcceptEnv LANG LC_*<br><br># override default of no subsystems<br>Subsystem sftp /usr/lib/openssh/sftp-server<br><br># Example of overriding settings on a per-user basis<br>#Match User anoncvs<br># X11Forwarding no<br># AllowTcpForwarding no<br># PermitTTY no<br># ForceCommand cvs server</pre><blockquote>In the last line of this task , we have :</blockquote><pre>notify: restart_sshd</pre><p>This line instructs Ansible to notify a handler (restart_sshd) that a change has been made and that Ansible needs to undertake an additional task. Multiple tasks can notify a handler to undertake that task.</p><blockquote><strong><em>Handlers are tasks that are run after all other plays have finished. They should be defined in your playbook as we have done here ( note that there are better ways to build your configuration files using roles , which we will describe it in the next Story)</em></strong></blockquote><pre> handlers:<br>  - name: restart_sshd<br>    service:<br>      name: sshd<br>      state: restarted</pre><p>In our case this handler restarts the sshd daemon whenever a change is made to its configuration , which mean this will be responsible for restart the sshd after we did anything (happening in this task).</p><blockquote>This is simple. Using the service module, we are requesting that the state of the sshd service is restarted. Ansible will now restart that service as a result of the notification it receives</blockquote><p>Now the hole bootstrap.yml file like this :</p><pre>---<br><br>- hosts: all<br>  become: yes<br>  pre_tasks:<br><br>  - name: install updates (Ubuntu)<br>    tags: always<br>    apt:<br>      upgrade: dist<br>      update_cache: yes<br>    when: ansible_distribution == &quot;Ubuntu&quot;<br><br>  - name: install sudoers for Ubuntu servers<br>    tags: ubuntu<br>    apt:<br>      name:<br>        - sudo<br>      state: latest<br>    when: ansible_distribution == &quot;Ubuntu&quot;<br><br>- hosts: all<br>  become: true<br>  tasks:<br><br>  - name: create majd user<br>    tags: always<br>    user:<br>      name: majd<br>      groups: root<br>      shell: &quot;/bin/bash&quot;<br><br>  - name: Set authorized key taken from file<br>    authorized_key:<br>      user: kates<br>      state: present<br>      key: &quot;{{ lookup(&#39;file&#39;, &#39;C:\Users\Lenovo\.ssh\id_rsa.pub&#39;) }}&quot;<br><br>  - name: add sudoers file for majd<br>    tags: always<br>    copy:<br>      src: sudoer_majd<br>      dest: /etc/sudoers.d/majd<br>      owner: root<br>      group: root<br>      mode: 0440<br><br>  - name: generate sshd_config file from template<br>    tags: ssh<br>    vars:<br>      ssh_users: majd<br>    template:<br>      src: &quot;sshd_config.j2&quot;<br>      dest: /etc/ssh/sshd_config<br>      owner: root<br>      group: root<br>      mode: 0644<br>    notify: restart_sshd<br><br>  handlers:<br>  - name: restart_sshd<br>    service:<br>      name: sshd<br>      state: restarted</pre><h4>Now let’s see the <strong><em>Directory Structure</em></strong></h4><pre>|-- terraform<br>|-- inventory<br>|-- ansible/<br>|   |-- bootstrapping/   <br>|       |-- files/<br>|           |-- sudoer_majd<br>|       |-- templates/<br>|           |-- sshd_config.j2<br>|       |-- ansible.cfg<br>|       |-- bootstrap.yml</pre><p>Now the inventory file created by terraform from the <a href="https://medium.com/@majdnull/devsecops-project-using-iac-part-3-automatic-creation-of-the-cloud-infrastructure-45b7c2002202">previous part</a> ( if you destroy all infrastructure that terraform created u need to reapply it to get the inventory file again )</p><h4>Apply the Ansible Playbook</h4><p>As Ansible has been given its configuration through the ansible.cfg file and we want to apply this bootstrap to all ours servers, all we need to navigate the bootstrapping folder (from the ansible/bootstrap folder) , then run the playbook :</p><pre>ansible-playbook bootstrap.yml</pre><p>This will now go through a series of steps :</p><p><strong><em>PLAY [all] **************************************************</em></strong></p><p>Shows you are applying this playbook to all resources :</p><p><strong><em>TASK [Gathering Facts] **************************************</em></strong></p><p>Shows it is gathering existing details of the servers so it can work out what to do.</p><p><strong><em>TASK [install updates (Ubuntu)] *****************************</em></strong></p><p>Shows it is installing updates to the OS. You may have noticed by now that these messages come from the task names in the playbook , as we talked previously we provide the name to let ansible print the name on the command line screen.</p><p><strong><em>TASK [install sudoers for Ubuntu servers] *******************</em></strong></p><p><strong><em>PLAY [all] **************************************************</em></strong></p><p>It shows this again as the first play was the pre-tasks it was running. This is the next play and it is applying to all servers :</p><p><strong><em>TASK [Gathering Facts] ****************************************</em></strong></p><p>Each play gathers facts about its target hosts as the targets may be different to the previous play.</p><p><strong><em>TASK [create majd user] **************************************</em></strong></p><p><strong><em>TASK [Set authorized key taken from file] *********************</em></strong></p><p><strong><em>TASK [add sudoers file for majd ] *****************************</em></strong></p><blockquote>After all tasks and plays are finished, it provides you with a recap of what it did:</blockquote><pre>PLAY RECAP ****************************************************<br>ip: ok=8 changed=5 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0<br>ip : ok=8 changed=5 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0<br>ip : ok=8 changed=5 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0</pre><blockquote>ok : says how many tasks were found and attempted</blockquote><blockquote>changed : says how many tasks caused a change</blockquote><blockquote>failed : says how many tasks could not be carried out as the host could not be reached or logged in to</blockquote><blockquote>skipped : says how many tasks were not executed because of their when clause</blockquote><blockquote>rescued : says how many rescue tasks were executed (tasks that are marked to be run when another task fails)</blockquote><blockquote>ignored : says how many tasks failed but the error was ignored due to a ignore_errors: true clause</blockquote><p>You now have three servers that are bootstrapped, ready for the next stage of configuration. <strong><em>This next stage will setup Kubernetes on our newly configured servers</em></strong></p><h3>Summary</h3><blockquote>In this story , we configured Ansible to provide a base layer of configuration on our servers. We used an Ansible bootstrap configuration which we can use with any of our servers</blockquote><p><a href="https://medium.com/@majdnull/devsecops-project-using-iac-overview-project-notes-febf35517839">Start from Introduction</a></p><p><a href="https://medium.com/@majdnull/devsecops-project-using-iac-part-3-automatic-creation-of-the-cloud-infrastructure-45b7c2002202">Previous — Automatic creation of the Cloud Infrastructure</a></p><p><a href="https://medium.com/@majdnull/devsecops-project-using-iac-part-5-create-our-cluster-on-kubernetes-6847c9110ede">Next — Create our cluster on Kubernetes</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=262e3d3bfc69" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DevSecOps Project Using IAC : Part 3(Automatic creation of the Cloud Infrastructure )]]></title>
            <link>https://medium.com/@majdnull/devsecops-project-using-iac-part-3-automatic-creation-of-the-cloud-infrastructure-45b7c2002202?source=rss-3842da3c44b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/45b7c2002202</guid>
            <dc:creator><![CDATA[Majdnull]]></dc:creator>
            <pubDate>Sat, 02 Mar 2024 14:47:34 GMT</pubDate>
            <atom:updated>2024-03-03T13:28:19.958Z</atom:updated>
            <content:encoded><![CDATA[<h3>DevSecOps Project Using IAC : Part 3(Automatic creation of the Cloud Infrastructure )</h3><blockquote><em>LinkedIn : </em><a href="http://www.linkedin.com/in/majd-zahran-4314b1235"><em>Majd Zahran</em></a><em> , </em><strong><em>Please Don’t Hesitate to Contact Me</em></strong></blockquote><h3>Part 3: Automatic creation of the cloud infrastructure using Terraform</h3><p><strong>This is part of a series of articles that creates a project to implement automated provisioning of cloud infrastructure in order to deploy a Spring Boot application to a Kubernetes cluster using CI/CD. In this part we provision the Virtual Private Cloud (VPC) and Virtual Private Servers (VPS) using the Terraform Infrastructure as Code (IaC) tool.</strong></p><p><a href="https://medium.com/@majdnull/devsecops-project-using-iac-overview-project-notes-febf35517839">Follow from the start — Introduction</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PdPq0h-69m7Fk390nTn58w.png" /></figure><p>In this article, we will create the Virtual Private Cloud (VPC) and Virtual Private Servers (VPCs) that will host our Kubernetes cluster. We will use HashiCorp’s Open Source Terraform application to set up these resources using Infrastructure as Code techniques.</p><p>Whilst HashiCorp&#39;s provide a cloud based version of Terraform, we will use the local CLI version on our development machine. This was installed during <a href="https://medium.com/@majdnull/devsecops-project-using-iac-part-2-setting-up-the-project-for-automated-provisioning-57b3b264589b">part 2 of the series.</a></p><p><strong><em>You can find the code for this part here:</em></strong><br><a href="https://gitlab.com/Majdnull/voting-iac/-/tree/part3">https://gitlab.com/Majdnull/voting-iac/-/tree/part3</a></p><h3>Infrastructure as Code</h3><p>Infrastructure as Code (IaC) is a concept that involves creating infrastructure using code, often in the cloud. This process is facilitated through a declarative definition, specifying what you want in a clear and concise manner.</p><h4>Imperative vs Declarative definitions</h4><p>There are a deference between imperative and declarative definitions , that important to understand the deference normally when you come to IAC :</p><ul><li><strong>Imperative definitions:</strong> This is when you write the <em>instructions you want the computer to follow</em>, such as for , if, and while statements.</li></ul><blockquote>You can think about it like this , if you want to make a cake you will write the recipe of the cake and then you will make it , <strong><em>so here we care about the recipe of the cake and what the instructions we should follow to make it (</em>Imperative)</strong></blockquote><ul><li><strong>Declarative definitions:</strong> This is where you specify the <em>results of what you want</em> and not how to get there , so here you just care about the result not how we got this result.</li></ul><blockquote>Back to our cake example with declarative , here you will take the cake recipe and go to a chef to make it , <strong><em>so here you just care about the cake not how to make it</em></strong></blockquote><blockquote><strong>When creating Infrastructure as Code (IaC), we need to think in terms of declarative definitions</strong></blockquote><h4>Setup vs Provisioning</h4><p>Now you understand what it means to create a declarative definition, now you need to understand the difference between the two steps required to get your cloud infrastructure up and running:</p><p>In the IAC ( Infrastructure As Code ) terms , it’s come with concept called <strong>Provisioning</strong> , provisioning mean to is the process whereby you configure the infrastructure you have set up by creating configurations, installing packages and setting up users etc.</p><blockquote>So almost all who work with IAC called the hole process a <strong>Provisioning , </strong>but I love to separate it to a 2 process<strong> , the first is Setup , second process</strong> <strong>Provisioning</strong></blockquote><ul><li><strong><em>Setup</em></strong> : This is the process whereby you create the virtual infrastructure you need, such as networks, VPC &amp; VPS and EBS ..etc.</li><li><strong><em>Provisioning</em></strong> : This is the process whereby you configure the infrastructure like : installing packages and setting up users etc.</li></ul><blockquote>Whilst IaC tools can do both setup and provisioning, each has been primarily designed with one of them in mind. In this project we will use :</blockquote><blockquote><strong><em>Terraform : for Setup process</em></strong></blockquote><blockquote><strong><em>Ansible : for provisioning process</em></strong></blockquote><h4>Managing State</h4><p>For managing state we have a 2 tool as we talked before terraform &amp; ansible</p><ul><li><strong><em>Managing state with Terraform:</em></strong> Consider it like a trip to the supermarket with a checklist and a shopping cart. We check the first item, place it in the cart, and repeat until every item is checked off. Our progress relies on the checklist; once it’s complete, our task is done. This scenario is analogous to Terraform, where it depends on Terraform scripts. Terraform doesn’t actively check the cloud for setup; it operates based on the scripts. Consequently, if something is set up or deployed outside of Terraform, it won’t notify you since it’s not aware of changes made independently.</li><li><strong><em>Managing state with Ansible: </em></strong>Back to the supermarket example , now we will depend on the cart and the<strong><em> </em></strong>shopping cart in parallel , so we will place a item and checked off it from the checklist , now with ansible in the next item we want to checked off , ansible will return to the cart and review all it’s item and then back to place the next item , so here ansible review the cloud every time he want to configure something new .</li></ul><h4>Setting up the VPC and VPS infrastructure</h4><p>We will now use Terraform to create our Virtual Private Cloud (VPC) and 3 Virtual Private Servers (VPSs) in that VPC.</p><h4>Digital Ocean API</h4><p>Whenever you want to create your cloud-based services using IaC, your tooling ( Terraform) will be using the API of your selected cloud provider to set up the resources you want. Like other cloud services, Digital Ocean has an API for this purpose, documented <a href="https://docs.digitalocean.com/reference/api/api-reference/">here</a> .</p><p>You gain access to this API once you have an account and provide the credit card . Access is controlled through your account API key . To create an API key, go here:</p><ol><li><a href="https://cloud.digitalocean.com/account/api/tokens">https://cloud.digitalocean.com/account/api/tokens</a></li><li>Now click create new token , then enter a name for it and copy it and save it in safe place , because u can’t see it again until recreate another one</li></ol><h4>How Terraform works</h4><p>Terraform takes your declarative definition of what you want and then interfaces to the Digital Ocean APIs to set it up.</p><blockquote>As we talked previously terraform depends on the checklist just , so if anything created by the digital ocean UI, terraform will not know , because we talked previously is managing state by using the checklist approach.</blockquote><blockquote>If an error occurs, Terraform will tell you that it is possible that the change was actually made and that it does not know. This means that its ‘actual state’ may be incorrect leading to more errors.</blockquote><p><strong><em>I rebuild this scripts like 7 time :( during the creation of this series of articles and found the easiest way is to delete everything and start again. The beauty of IaC is that this does not take long and very few commands.</em></strong></p><p><strong><em>Note : if things do go wrong, Terraform can end up creating more and more resources. If things go wrong, check your Digital Ocean account for duplicates as these will increase the fees you pay to Digital Ocean .</em></strong></p><h4>Providers</h4><p>So how Terraform can take into account so many different cloud services with so many different services ?</p><p>Terraform uses plugins called Providers. A Provider takes service specific definitions of what you want (the target state) and interfaces to the relevant service API to give you what you asked for.</p><p>When you define a provider in your terraform scripts and when you run terraform , it will install your cloud provider plugin to work with it .</p><p>in my case terraform will install the Digital Ocean plugin to work with it , you can see the <a href="https://registry.terraform.io/providers/digitalocean/digitalocean/latest/docs">official docs here</a>.</p><h4>Provisioners</h4><p>Terraform can do the Provisioning process by using a plugin that can do the configuration of your infrastructure once it is set up , but in our series we will using ansible.</p><h3>Terraform — folders and files</h3><p>When you run Terraform, it reads the configuration from all files in the current folder. there are a some extension we need to know first , This includes:</p><ul><li>*.tf ⇒ contain a definition of the infrastructure to setup.</li><li>*.tfvars ⇒ here we will define our variables as a key-value pairs as inputs , so here we will put our sensitive credential to use it as a variable on the other scripts.</li><li>*.tftpl ⇒ template files that can be used to create result files.</li><li>*.tfstate ⇒ the actual state of the infrastructure according to Terraform.</li><li>.terraform ⇒ a folder where Terraform holds its project set up.</li></ul><h4>Modules</h4><p>When creating infrastructure, it is useful to be able to reuse a particular setup. For example, when creating multiple copies of of a VPS .</p><p>Terraform uses the concepts of Modules. A Module is like a subroutine that performs the set up of a particular item of infrastructure. It is parameterized so you can pass it inputs, such as the VPS name. It also has the ability to return results of the Module creation and set up , so u can define a just one file for VPS and make as many as Module and pass to it what parameter u want by just using module.</p><h4>Kubernetes Cluster</h4><blockquote>Before we create the infrastructure, a quick description of Kubernetes : kubernetes a container orchestration, also known as K8s, is an open-source system for automating deployment, scaling, and management of containerized applications.</blockquote><p>With our project we will make a 3 kubernetes node:</p><ul><li>1 Master Node</li><li>2 Worker Node</li></ul><blockquote>The master node schedules your applications, which means it starts them, on the worker nodes using a selection algorithm</blockquote><h4>Configuring Terraform</h4><p>For this project, we will create files that will setup:</p><ul><li>1 Virtual Private Cloud ( VPC )</li><li>1 VPS Kubernetes master node ( Droplet )</li><li>2 VPS Kubernetes worker nodes ( Droplet )</li></ul><blockquote>A VPC is a Software Defined Network (SDN) that allows your cloud provider to create an isolated subnet for your servers. Droplet is the servers in the VPC , which means they have an interface connected to your private subnet and an interface connected to the Internet with a public IP address. Your cloud provider allocates all public and private IP addresses.</blockquote><blockquote>If the VPS has a public Internet connection, I refer to it as a public VPS. It it does not, I refer to it as a private VPS.</blockquote><blockquote>we will work with a <strong><em>master node with a 2 CPU node</em></strong> whereas the <strong><em>worker nodes can be 1 CPU nodes</em></strong>.</blockquote><p>We will add all Terraform configuration files to the voting-Iac/terraform project folder we created earlier. Use whatever editor you are most comfortable with , With me I love <strong><em>VS Code</em></strong></p><blockquote>We will start with the main.tf. Terraform files can be written in <strong><em>HashiCorp&#39;s Configuration Language (HCL)</em></strong> or JSON. In our case we will be using HCL.</blockquote><ul><li>Now let’s make the <strong><em>Directory Structure:</em></strong></li></ul><pre>|-- main.tf<br>|-- variables.tf<br>|-- ansible_inventory.tftpl  <br>|-- variables.tfvars<br>|-- .gitignore<br>|-- modules/<br>|   |-- vpc/   <br>|       |-- main.tf<br>|       |-- variables.tf<br>|       |-- outputs.tf<br>|   |-- public_vps/<br>|       |-- main.tf<br>|       |-- variables.tf<br>|       |-- outputs.tf</pre><h4>terraform/main.tf File</h4><p>I will give you the whole file first and then describe it in sections.</p><p>First we will create terraform/main.tf in the voting-IaC sub-project:</p><pre>terraform {<br>  required_providers {<br>    digitalocean = {<br>      source  = &quot;digitalocean/digitalocean&quot;<br>      version = &quot;~&gt; 2.0&quot;<br>    }<br>    template = {<br>      source  = &quot;hashicorp/template&quot;<br>      version = &quot;~&gt; 2.2&quot;<br>    }<br>    local = {<br>      source  = &quot;hashicorp/local&quot;<br>      version = &quot;~&gt; 2.1&quot;<br>    }<br>  }<br>}<br><br>provider &quot;digitalocean&quot; {<br>  token = var.do_token<br>}<br><br>data &quot;digitalocean_ssh_key&quot; &quot;terraform&quot; {<br>  name = &quot;terraform&quot;<br>}<br><br>module &quot;voting_vpc&quot; {<br>    source = &quot;./modules/vpc&quot;<br>    vpc_name = &quot;voting_vpc&quot;<br>    vpc_region = &quot;nyc3&quot;<br>    vpc_ip_range = &quot;10.0.0.0/16&quot;<br>}<br><br>output &quot;voting_vpc_output&quot; {<br>    description = &quot;voting_vpc&quot;<br>    value = module.voting_vpc.vpc_id<br>}<br><br>module &quot;voting_k8s_master&quot; {<br>    source = &quot;./modules/public_vps&quot;<br>    vps_name = &quot;k8s_master&quot;<br>    vps_size = &quot;s-2vcpu-4gb&quot;<br>    vpc_id = module.voting_vpc.vpc_id<br>}<br><br>output &quot;voting_k8s_master_output&quot; {<br>    description = &quot;voteing_k8s_master&quot;<br>    value = module.voting_k8s_master.v4_ips<br>}<br><br>module &quot;voting_k8s_node_1&quot;{<br>    source = &quot;./modules/public_vps&quot;<br>    vps_name = &quot;k8s_node_1&quot;<br>    vps_size = &quot;s-1vcpu-2gb&quot;<br>    vpc_id = module.voting_vpc.vpc_id <br>}<br><br>output &quot;voting_k8s_node_1_output&quot;{<br>    description = &quot;voting_k8s_node_1&quot;<br>    value = module.voting_k8s_node_1.v4_ips<br>} <br><br>module &quot;voting_k8s_node_2&quot;{<br>    source = &quot;./modules/public_vps&quot;<br>    vps_name = &quot;k8s_node_2&quot;<br>    vps_size = &quot;s-1vcpu-2gb&quot;<br>    vpc_id = module.voting_vpc.vpc_id <br>}<br><br>output &quot;voting_k8s_node_2_output&quot;{<br>    description = &quot;voting_k8s_node_2&quot;<br>    value = module.voting_k8s_node_2.v4_ips<br>}<br><br>resource &quot;local_file&quot; &quot;inventory&quot; {<br>  filename = &quot;../ansible/inventory&quot;<br>  content = templatefile(&quot;ansible_inventory.tftpl&quot;, {<br>    master_ip = module.voting_k8s_master.v4_ips.public<br>    node_ips = [<br>      module.voting_k8s_node_1.v4_ips.public,<br>      module.voting_k8s_node_2.v4_ips.public<br>    ]<br>  })<br>}</pre><p>This is the main configuration file that will create our VPC and our 3 VPC nodes.</p><pre>terraform {<br>  required_providers {<br>    digitalocean = {<br>      source  = &quot;digitalocean/digitalocean&quot;<br>      version = &quot;~&gt; 2.0&quot;<br>    }<br>    template = {<br>      source  = &quot;hashicorp/template&quot;<br>      version = &quot;~&gt; 2.2&quot;<br>    }<br>    local = {<br>      source  = &quot;hashicorp/local&quot;<br>      version = &quot;~&gt; 2.1&quot;<br>    }<br>  }<br>}<br><br>provider &quot;digitalocean&quot; {<br>  token = var.do_token<br>}<br><br>data &quot;digitalocean_ssh_key&quot; &quot;terraform&quot; {<br>  name = &quot;terraform&quot;<br>}</pre><p>This first section defines the version of Terraform required (≥ 1.5.5) and the providers to be used. In our case is just one:</p><ul><li>digitalocean/digitalocean: this is the REST API interface Provider that we will use to interface to digital ocean</li><li>hashicorp/templet: This specifies the hashicorp/template provider with version ~&gt; 2.2. The template provider is commonly used for local rendering and processing of templates. It allows you to use dynamic values and generate configuration files or other artifacts during Terraform execution.</li><li>hashicorp/local: is used for defining computed values within the Terraform configuration that can be used in other parts of the configuration. It allows you to create local variables and expressions</li></ul><blockquote>Then we define a variable called <strong><em>do_token</em></strong> &amp; <strong><em>ssh_key</em></strong> , so we pass the api token as a variable ( var.do_token) var. , used as a reference to the actual token that we will define it in the variable.tf, and we let terraform after it connect to our cloud using the api key it will search for the ssh_keywith a name terraform. ( you need to get the ssh key which we create it in <a href="https://medium.com/@majdnull/devsecops-project-using-iac-part-2-setting-up-the-project-for-automated-provisioning-57b3b264589b">part 2</a> and added it to the digital ocean .</blockquote><pre>module &quot;voting_vpc&quot; {<br>    source = &quot;./modules/vpc&quot;<br>    vpc_name = &quot;voting_vpc&quot;<br>    vpc_region = &quot;nyc3&quot;<br>    vpc_ip_range = &quot;10.0.0.0/16&quot;<br>}<br><br>output &quot;voting_vpc_output&quot; {<br>    description = &quot;voting_vpc&quot;<br>    value = module.voting_vpc.vpc_id<br>}</pre><p>Then we make our first module , so we make a module to make our VPC , then we need to pass some parameter like : source( on it we should enter the path of the VPC folder ) so that will be related to ./modules/vpc , vpc_name+ vpc_region+ vpc_ip_range, we need to enter the name of the vpc , the region where we want to create our vpc and the ip range of the vpc subnet .</p><p>From there now we need to take the VPC ID after we create it to assign it to the VPS , so we will make a output section to print the VPC ID .</p><pre>module &quot;voting_k8s_master&quot; {<br>    source = &quot;./modules/public_vps&quot;<br>    vps_name = &quot;k8s_master&quot;<br>    vps_size = &quot;s-2vcpu-4gb&quot;<br>    vpc_id = module.voting_vpc.vpc_id<br>}<br><br>output &quot;voting_k8s_master_output&quot; {<br>    description = &quot;voteing_k8s_master&quot;<br>    value = module.voting_k8s_master.v4_ips<br>}</pre><p>Now we have our VPC, we can setup our master node VPS within it. This time we are using the public VPS Module with public (i.e: Internet facing) networking: modules/public_vps</p><p>We are passing the name (k8s-master) and setting the digital ocean VPS size (s-2vcpu-4gb) . We are also passing the VPC that the VPS is to be setup in. To do this we use theid reference from the VPC description that we output earlier (module.voting_vpc.vpc_id).</p><blockquote><strong><em>Like we captured outputs from the VPC creation</em></strong>, we capture the <strong><em>IP address</em></strong> of the created VPS through the output of the Module.so we will capture the VPS IP</blockquote><pre>module &quot;voting_k8s_node_1&quot;{<br>    source = &quot;./modules/public_vps&quot;<br>    vps_name = &quot;k8s_node_1&quot;<br>    vps_size = &quot;s-1vcpu-2gb&quot;<br>    vpc_id = module.voting_vpc.vpc_id <br>}<br><br>output &quot;voting_k8s_node_1_output&quot;{<br>    description = &quot;voting_k8s_node_1&quot;<br>    value = module.voting_k8s_node_1.v4_ips<br>} <br><br>module &quot;voting_k8s_node_2&quot;{<br>    source = &quot;./modules/public_vps&quot;<br>    vps_name = &quot;k8s_node_2&quot;<br>    vps_size = &quot;s-1vcpu-2gb&quot;<br>    vpc_id = module.voting_vpc.vpc_id <br>}<br><br>output &quot;voting_k8s_node_2_output&quot;{<br>    description = &quot;voting_k8s_node_2&quot;<br>    value = module.voting_k8s_node_2.v4_ips<br>}</pre><p>In the same way as we created the master node, we now create 2 worker nodes. These use the same Module but you will notice we use a size (vps_size) of s-1cpu-2gb this time. This will save costs. You can create as many or as few nodes as you want, each with the size you need ( so here you will see the powerful of using module , we create a one and just we modify the size and some parameter and it will create what we want )</p><pre>resource &quot;local_file&quot; &quot;inventory&quot; {<br>  filename = &quot;../ansible/inventory&quot;<br>  content = templatefile(&quot;ansible_inventory.tftpl&quot;, {<br>    master_ip = module.voting_k8s_master.v4_ips.public<br>    node_ips = [<br>      module.voting_k8s_node_1.v4_ips.public,<br>      module.voting_k8s_node_2.v4_ips.public<br>    ]<br>  })<br>}</pre><p>Then we use the terraform ability for capture information into a file using a template , why we using this code to take the output of the VPC &amp; VPS ( the VPC id + the ip of the master &amp; worker node ) and print it in the <strong><em>ansible_inventory.tftpl</em></strong> to use it with <strong><em>Ansible</em></strong> in future.</p><h4>Modules</h4><p>Earlier we saw that our VPC and VPS resources were created by using Terraform Modules. We now need to define these Modules:</p><p>So create a folder: terraform/modules, on it we will create a 2 subfolder :`</p><ul><li>vpc : creates a VPC with a private subnet that will contain the VPS nodes that are created.</li><li>vps : crates our droplets resources ( on digital ocean the vps called Droplets ) with public and private connections.</li></ul><h4>terraform/modules/vpc</h4><p>Now under this folder , we will create a 3 files :</p><ul><li>main.tf : defines the configuration of the resource to be created in a way that the cloud required.</li><li>variables.tf : defines the inputs to the Module (like a method’s parameters)</li><li>output_vpc.tf: defines the outputs from the Module (like a method’s return values)</li></ul><p>Starting with the <strong><em>terraform/modules/vpc/main.tf</em></strong> :</p><pre>terraform {<br>  required_providers {<br>    digitalocean = {<br>      source = &quot;digitalocean/digitalocean&quot;<br>      version = &quot;~&gt; 2.0&quot;<br>    }<br>  }<br>}<br><br>resource &quot;digitalocean_vpc&quot; &quot;main_vpc&quot; {<br>  name       = var.vpc_name<br>  region     = var.vpc_region<br>  ip_range   = var.vpc_ip_range<br>}<br><br></pre><p>First we start with define the provider we will use with the module which is in our case digital ocean , then we define a new resource which is a vpc , with digital ocean the vpc resource can be defined using digitalocean_vpcthen we need to pass the name of the resource alongside main_vpc, now we need to pass the variables which we enter in the root main.tf , so what we do here is we pass the value of name, region , ip_range as a variables , ok then where we should enter the actual value ? yup that’s correct! If you go back to the main.tf file in the root directory, you’ll see that we’re passing these values in the module definitions within the root main.tf .</p><p>Now with the variables file : <strong><em>terraform/modules/vpc/variables.tf</em></strong></p><pre>variable &quot;vpc_name&quot; {<br>  description = &quot;Name of the VPC&quot;<br>}<br><br>variable &quot;vpc_region&quot; {<br>  description = &quot;Region for the VPC&quot;<br>}<br><br>variable &quot;vpc_ip_range&quot; {<br>  description = &quot;IP range for the VPC&quot;<br>}</pre><p>It’s very simple , here we define the variables we will use on the vpc main.tf</p><p>Going to the Output file : <strong><em>terraform/modules/vpc/output_vpc.tf</em></strong></p><pre>output &quot;vpc_id&quot; {<br>  description = &quot;Description of the created VPC&quot;<br>  value       = digitalocean_vpc.main_vpc.id<br>}</pre><p>as we talked previously , we need to print the vpc id after creation to be used and assign in each VPS .</p><h4>terraform/modules/public_vps</h4><p>Same thing we will create the same 3 file : ( main.tf , variables.tf , output_vps.tf</p><p>Starting with main file : <strong><em>terraform/modules/public_vps/main.tf</em></strong></p><pre>terraform {<br>  required_providers {<br>    digitalocean = {<br>      source = &quot;digitalocean/digitalocean&quot;<br>      version = &quot;~&gt; 2.0&quot;<br>    }<br>  }<br>}<br><br>resource &quot;digitalocean_droplet&quot; &quot;main_vps&quot; {<br>  vpc_uuid = var.vpc_id<br>  name = var.vps_name<br>  image    = &quot;ubuntu-20-04-x64&quot;<br>  size     = var.vps_size<br>}<br></pre><p>First we start with define the provider we will use with the module which is in our case digital ocean , then we define a new resource which is a vps , with digital ocean the vpc resource can be defined using digitalocean_droplet, then we need to pass the name of the resource alongside main_vps, now we need to pass some parameters : the vps_uuid which is be return from the output of the vpc , then name will be as a variable , the image will be same for all vps <strong><em>ubuntu-20–04-x64 , </em></strong>finally size will be as a variable , why because we we have a 3 vps and each one will have a different name and size , back to the root main.tf on each vps module we pass a different name and size .</p><p>Then we have the variables file : <strong><em>terraform/modules/public_vps/variables.tf</em></strong></p><pre>variable &quot;vpc_id&quot; {<br>  description = &quot;ID of the associated VPC&quot;<br>}<br><br>variable &quot;vps_name&quot; {<br>  description = &quot;name of the associated VPS&quot;<br>}<br><br>variable &quot;vps_size&quot; {<br>  description = &quot;size of the associated VPS&quot;<br>}<br><br></pre><p>we define a 3 variables which is the vpc id return from the vpc output , and the name &amp; size from the root main.tf</p><p>Finally the output file : <strong><em>terraform/modules/public_vps/output_vps.tf</em></strong></p><pre>output &quot;instance_id&quot; {<br>    description = &quot;ID of the created server&quot;<br>    value = digitalocean_droplet.main_vps.id<br>}<br><br>locals {<br>  v4_public_ip  = digitalocean_droplet.main_vps.ipv4_address<br>  v4_private_ip = digitalocean_droplet.main_vps.ipv4_address_private<br>}<br><br>output &quot;v4_ips&quot; {<br>  description = &quot;IP V4 addresses of VPS&quot;<br>  value = {<br>    public  = local.v4_public_ip,<br>    private = local.v4_private_ip<br>  }<br>}</pre><p>here we will first print the vps id for each vps , then we will print the public and private ipv4 of each vps</p><p>This sets values that can be used by Terraform elsewhere using a ‘path’ as follows:</p><p>module.&lt;name of instance&gt;.&lt;output name&gt;.&lt;field name&gt;</p><p>back to our root main.tf , ex : <strong><em>module.voting_k8s_node_1.v4_ips</em></strong></p><blockquote>Like Java methods, local variables can be created using the locals block. Variables are defined and referenced in the Go language format. This means that the JSON returned by a provider must be decoded using the built in jsondecode function</blockquote><p>We now have:</p><ul><li>The main.tf file that defines what we want (1 x VPC, 3 x VPS)</li><li>The vpc Module that creates a VPC</li><li>The public_vps Module that creates a VPS with internal and external IP addresses</li></ul><p>Now we need to define variables that allow us to pass values into the Terraform configuration that we may not want to commit to our repo.</p><h3>Variables</h3><p>When you create Terraform configurations, you may want to pass in variables, such as credentials. You do not want to commit these to your code repos.</p><p>Terraform allows you to define variables (with types and default values) and then to set these variables in a separate file</p><p>Now we have the root variables file : terraform/varaibles.tf</p><pre>variable &quot;do_token&quot; {<br>  description = &quot;API key used to login/verify for APIs used at digital ocean.&quot;<br>  default = &quot;default&quot;<br>}<br><br>variable &quot;ssh_key&quot; {<br>  description = &quot;The PUBLIC SSH key you want to use to access your VPSs.&quot;<br>  default = &quot;default&quot;<br>}<br><br></pre><p>we define the API key that will used to login/verify for APIs used at digital ocean , and the ssh_key that we enter it previously to digital ocean account .</p><p>now we can use the power of terraform to hide our api token and the ssh_key , using the *.tfvars</p><p>create it : terraform/variables.tfvars</p><pre>do_token = &quot; &lt; your api token here &quot;<br>ssh_key = &quot; &lt; your public ssh key here&quot;</pre><p>now when run terraform we will run it with this file to connect with digital ocean</p><p>Final thing we need to make sure to not commit this file and another sensitive file like : *.tfstate , log file ..etc.</p><p>so create the gitignore file : terraform/.gitignore</p><pre># Local .terraform directories<br>**/.terraform/*<br>.terraform.*.hcl<br><br># Local keys directories<br>**/keys/*<br><br># .tfstate files<br>*.tfstate<br>*.tfstate.*<br><br># Crash log files<br>crash.log<br>crash.*.log<br><br># Exclude all .tfvars files, which are likely to contain sensitive data, such as<br># password, private keys, and other secrets. These should not be part of version <br># control as they are data points which are potentially sensitive and subject <br># to change depending on the environment.<br>*.tfvars<br>*.tfvars.json<br><br># Ignore override files as they are usually used to override resources locally and so<br># are not checked in<br>override.tf<br>override.tf.json<br>*_override.tf<br>*_override.tf.json<br><br># Include override files you do wish to add to version control using negated pattern<br># !example_override.tf<br><br># Include tfplan files to ignore the plan output of command: terraform plan -out=tfplan<br># example: *tfplan*<br><br># Ignore CLI configuration files<br>.terraformrc<br>terraform.rc</pre><p>That a default file u can find it anywhere , and it commonly found on the terraform docs , this file responsible for ignore the commit for the files extensions , so when u commit the Terraform folder this files will not commit.</p><p><strong><em>There are additional file that are required.</em></strong></p><ul><li>terraform/ansible_inventory.tfpl</li></ul><pre>[k8s_master]<br>${master_ip}<br><br>[k8s_node]<br>%{ for addr in node_ips ~}<br>${addr}<br>%{ endfor ~}</pre><p>here where terraform will after it deploy all required vpc and vps , will print the IPs of the vps here on this file. to be used by ansible in future.</p><h3>Running Terraform</h3><p>Now after we created all the required files , we need to run terraform :</p><ol><li><strong><em>Step1 — Init</em></strong></li></ol><p>This step tells terraform to download the provider plugins it needs for the main configuration and any Modules. It also installs those Modules so they can be used.</p><p>You need to navigate to the terraform folder which holds all your created files .</p><pre>terraform init </pre><p>You should see a output like this :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*KFsAfKP5JCpTHssKjeD0sA.png" /></figure><p><strong><em>2 . Step2 — plan</em></strong></p><p>This step asks Terraform to show you what it is going to do, without doing anything. It is like a dry run. Not all information is available as some of it is only available once the resources have been created (eg: IP addresses) but you can see what it is planning on doing.</p><p>Now we will run the plan step and let terraform take the variables from the <strong><em>variables.tfvars</em></strong> file</p><pre>terraform plan -var-file=variables.tfvars</pre><p>You will see a output like this , if all things go right :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OuNey5cfL1UY_tQ5KwEjoA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*itbRQccbldKGlUe4opkFcw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*VQR1bc9Ii5MAbmRjv1cC9g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5j9wG6ax3iE2Edw4X9TILA.png" /></figure><p>The Important this you will see this :</p><blockquote><strong>Plan: 5 to add, 0 to change, 0 to destroy</strong></blockquote><p>Below this will be a series of outputs. Remember we put them in the main.tf file? When you place outputs at the upper most level, Terraform will print them out to the console. Most of it will be marked as (known after apply) as it needs to get them from digital ocean.</p><blockquote>Some resources (like our VPS) will be dependent on other resources (like our VPC). Terraform automatically detects these dependencies and creates the resources in the order needed.</blockquote><blockquote>There are situations where you can give Terraform dependencies but it is best not to do this as Terraform is declarative and not imperative</blockquote><p><strong><em>3. Step 3. apply</em></strong></p><p>The final step is to apply the configuration you have asked for.</p><p>Note that this may not do what the plan step said it would do, as Terraform always re plan before applying your configuration. This ensures any change made to the configuration will be picked up. For this reason, planning is optional but recommended.</p><ul><li>Apply your configuration (<strong>Note that this will start incurring costs with your cloud provider , Digital Ocean in our case ) , as we did in the plan step</strong></li></ul><pre>terraform apply -var-file=variables.tfvars</pre><blockquote>After typing this command, it will show you the latest plan. It will then ask you to confirm that you want it to create the infrastructure in accordance with this plan.</blockquote><blockquote>If you want to, type <em>yes</em> and press enter.</blockquote><p>You will see a output like this :</p><blockquote><strong><em>Apply complete! Resources: 3 added, 0 changed, 0 destroyed.</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/1*7ZUJ7LxGYJLxku4lkG5I3A.png" /></figure><p>The outputs in the main.tf file will then show the details of what was created. You can also check your Digital Ocean account and see the VPC with and 3 VPCs created.</p><p>You should also have a file in the ansible folder called inventory with the IP addresses of each of the VPS nodes in it.</p><p>You are now ready to configure the servers to install Kubernetes. Before you start the configuration, it is important that the new servers are added to your known_hosts file. The easiest way to do this and to prove your servers have been set up correctly is to ssh into each of them using:</p><pre>ssh -i ~/.ssh/qq_rsa root@&lt;ip address&gt;</pre><p>Answer <em>yes</em> when it asks to confirm the finger print of each. You should be able to log in without a password. If you have any problems, you can go to the Digital Ocean services page and reset the password.</p><p><strong><em>4 . Step4 — Destroy</em></strong></p><p>This step deletes all the resources created previously.</p><blockquote><strong>This is an unrecoverable step and all your configuration and <em>data will be lost.</em></strong></blockquote><p>To Delete all what terraform did , u can do that by :</p><pre>terraform destroy </pre><p>Like the apply step, it will tell you what it is going to delete and will ask you to enter <em>yes</em>. When you do, your infrastructure will be deleted.</p><p>You can then do step 3 to recreate the system again.</p><h3>Summary</h3><p>In this Story , we created a Scripts files that Terraform can use to create the infrastructure required for a Kubernetes, 3 node cluster : 1 master node , 2 worker node .</p><p>Using the Digital ocean Provider, Terraform called the Digital Ocean API to create the VPC and VPS nodes that we requested.</p><p>In the next article, we look at updating the OS on each node and then deploying a Kubernetes cluster on it using Ansible.</p><p><a href="https://medium.com/@majdnull/devsecops-project-using-iac-overview-project-notes-febf35517839">Series Introduction</a></p><p><a href="https://medium.com/@majdnull/devsecops-project-using-iac-part-2-setting-up-the-project-for-automated-provisioning-57b3b264589b">Previous — Project Setup</a></p><p><a href="https://medium.com/@majdnull/devsecops-project-using-iac-part-4-configuring-servers-using-ansible-262e3d3bfc69">Next — Configuring Servers using Ansible</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45b7c2002202" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DevSecOps Project Using IAC : Part 2 (Setting up the project for automated provisioning)]]></title>
            <link>https://medium.com/@majdnull/devsecops-project-using-iac-part-2-setting-up-the-project-for-automated-provisioning-57b3b264589b?source=rss-3842da3c44b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/57b3b264589b</guid>
            <dc:creator><![CDATA[Majdnull]]></dc:creator>
            <pubDate>Fri, 01 Mar 2024 12:35:33 GMT</pubDate>
            <atom:updated>2024-03-03T13:30:22.148Z</atom:updated>
            <content:encoded><![CDATA[<h3>DevSecOps Project Using IAC : Part 2 (Setting up the project for automated provisioning)</h3><blockquote><em>LinkedIn : </em><a href="http://www.linkedin.com/in/majd-zahran-4314b1235"><em>Majd Zahran</em></a><em> , </em><strong><em>Please Don’t Hesitate to Contact Me</em></strong></blockquote><h3><strong>Part 2: Setting up the project for automated provisioning of Digital Ocean infrastructure.</strong></h3><blockquote><strong><em>This is part of a series of Stores that creates a project to implement automated provisioning of cloud infrastructure in order to deploy The Voting Spring Boot application to the Kubernetes cluster using CI/CD.</em></strong></blockquote><p><strong><em>In this part we set up out development machine for the project.</em></strong></p><p><a href="https://medium.com/@majdnull/devsecops-project-using-iac-overview-project-notes-febf35517839">Follow from the beginning — Introduction</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*78cPL7PpFxUhaXDLwnieig.jpeg" /></figure><h3>Setting up the project</h3><p><a href="https://medium.com/@majdnull/devsecops-project-using-iac-overview-project-notes-febf35517839">Part 1 of this series</a> provided an overview of the project and detailed some of the prerequisites. This story provides details of how to set up your development machine.</p><p>The instructions in this series of articles are given for a Windows 10 .</p><h4>1. Docker</h4><p>Docker is a lightweight virtualization layer that allows you to build virtual machines as images and then to run these images in a Docker container, it’s what called containerization</p><blockquote>Containers provides the virtual image access to resources on the host machine, via its existing OS , such as networking and file systems. A single host machine can run multiple containers</blockquote><p>First u need to download it on your machine , u can refer to the <a href="https://docs.docker.com/desktop/install/mac-install/">official documentation</a> to download it .</p><ul><li>Once you have installed it, you can test it with:</li></ul><pre>docker run hello-world</pre><p>That’s should return a description confirms your installation was successful.</p><h4>2. GitHub</h4><p><em>First u need a account on GitLab , then You will require 3 GitLab repositories ( Projects )</em></p><ul><li>Voting-Iac</li><li>Voting-Application</li><li>Voting-Deployment</li></ul><p>GitLab will make a default README .md on all projects , and it will commit a “initial commit” as a massage by default , no commit will required here .</p><blockquote><strong><em>But to commit or push or pull , u need to connect your git with GitLab ⇒ to do that first with ssh-key u need to generate a private and public key , then copy the public key ( Under “~/.ssh” ) and added it in GitLab ( On User Setting ⇒ select SSH ⇒ then add a new ssh key and paste your public key , then when try to clone from it , it will ask u to login in GitLab so enter your credential and now u can do what u want.</em></strong></blockquote><blockquote>— — — — — — — — — — — — — — — — — — — — — -</blockquote><p>If u use a GitHub , u need to do same thing but first u need to run :</p><ol><li>git config --global user.name &lt;your name&gt; &amp;&amp; git config --global user. Email &lt;your.email@example,com&gt;</li><li>Then copy your public key and add it on GitHub SSH-Key then u can do what ever u want , but on GitHub it will not initiate a commit by default like GitLab , so u need to run this command :</li></ol><pre>- git clone &lt; Repository URL &gt;<br>- cd &lt; Repository Directory &gt;<br>- git checkout -b main<br>- nano README.md<br>- git add .<br>- git commit -m &quot;Initial commit&quot;<br>- git push</pre><p>3. <em>These repositories (repos) will be used as follows :</em></p><ul><li><strong><em>Voting-Iac</em></strong> : is used to hold the Infrastructure as Code (IaC) configuration files that will create each Digital Ocean VPS and then configure them , Within this folder we will create two subfolders “</li></ul><ol><li>folder #1 : terraform</li><li>folder #2 : Ansible</li></ol><ul><li><strong><em>Voting-application</em></strong> : this repo holds the source code for our Voting Spring Boot application .</li><li><strong><em>Voting-Deployment</em></strong> : This repo holds your application deployment manifest files for Kubernetes , The contents are automatically created by the CI/CD Pipeline , ArgoCD then picks up the changes and passes the manifest files to the Kubernetes API to allow the application to be deployed.</li></ul><h4>3. Digital Ocean</h4><blockquote>For my I use Digital Ocean to deploy the project on it and then , when you create the account it come with 200 credit for free .</blockquote><blockquote>For this project you can make the required VPS and VPC , and deploy your kubernetes with Digital Ocean .<em> </em>for sure u can use any prefer cloud provider u want .</blockquote><h4>4. Terraform</h4><p><em>We need to download </em><strong><em>terraform</em></strong> ( why ? <strong><em>To run the Terraform IaC configuration files</em></strong>) , For this project I am using <strong><em>Terraform version v1.7.3</em></strong></p><h4>5. Ansible</h4><p>Ansible will run your automation playbook files for configuring the infrastructure set up by Terraform ( <em>Ansible is Configuration Management</em> ) , For this project I am using <strong><em>Ansible version 2.10.8</em></strong></p><h4>6. Maven</h4><p>For <strong><em>Package Manager</em></strong> i prefer to use <strong><em>Maven</em></strong> for the Voting java application , for sure u can use Gradle , but i prefer Maven , For this project I am using <strong><em>Apache Maven 3.9.6</em></strong> , <strong><em>Java version: 21.0.1</em></strong> Version.</p><h4>7. GitLab token</h4><p>In order for the CI/CD pipeline to push changes to the Voting-Deployment repo, the GitLab Actions require permission. This is given via a GitLab Personal Access Token (PAT)</p><h4>8 . ArgoCD</h4><p>ArgoCD is a declarative, GitOps continuous delivery tool for Kubernetes applications. It enables you to maintain and manage your Kubernetes resources through Git repositories, allowing you to declare the desired state of your applications and infrastructure.</p><p>To install and configure it go through this ( you need to config kubectl first) :</p><ol><li>after u install it in kubernetes run this : kubectl -n argocd get pods</li><li>Then to access ArgoCD UI , you need to change the argocd UI server from <strong><em>ClusterIP</em></strong> to NodePort , so run this : kubectl port-forward svc/argocd-server -n argocd 8080:443</li><li>so then we need the argocd to login and make accounts ..etc. ⇒ so first we need to download <strong><em>Chocolatey CLI</em></strong> to download argocd cli ( because I worked on Windows ) , after install it run this on <strong><em>PowerShell</em></strong>:</li></ol><pre>@&quot;%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe&quot; -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command &quot;[System.Net.ServicePointManager]::SecurityProtocol = 3072; iex ((New-Object System.Net.WebClient).DownloadString(&#39;https://community.chocolatey.org/install.ps1&#39;))&quot; &amp;&amp; SET &quot;PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin&quot;</pre><p>4. Then u need to login in first time , so u need to obtain the password for admin account , so you need to run this ⇒</p><pre>kubectl -n argocd get secret argocd-initial-admin-secret -o jsonpath=&quot;{.data.password}”</pre><p>5. Now you should obtain the admin password return to the ArgoCD UI and login</p><h3>Summary</h3><p>In this article we have set up the initial development machine environment I have used with this project. If you have any problems, check the versions you are using or you may face a problem related to the OS compatibility.</p><blockquote>In addition to the local setup, we have also created the three GitLab repos that we will need to manage the configuration and source code for the Voting project</blockquote><p>Now we are ready to start creating our cloud environment.</p><p><a href="https://medium.com/@majdnull/devsecops-project-using-iac-overview-project-notes-febf35517839">Project Introduction</a></p><p><a href="https://medium.com/@majdnull/devsecops-project-using-iac-overview-project-notes-febf35517839">Previous Story — Part 1 ( Introduction )</a></p><p><a href="https://medium.com/@majdnull/devsecops-project-using-iac-part-3-automatic-creation-of-the-cloud-infrastructure-45b7c2002202">Next — Part 3 ( Automatic creation of the Cloud Infrastructure )</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57b3b264589b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>