<?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 Abdessamad Bayzi on Medium]]></title>
        <description><![CDATA[Stories by Abdessamad Bayzi on Medium]]></description>
        <link>https://medium.com/@abdessamad.bayzi?source=rss-885ac976f389------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*FHCibR0SqtqSqcBR1IqRnQ.jpeg</url>
            <title>Stories by Abdessamad Bayzi on Medium</title>
            <link>https://medium.com/@abdessamad.bayzi?source=rss-885ac976f389------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 07:09:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abdessamad.bayzi/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[Add observability to your service in easy steps]]></title>
            <link>https://medium.com/@abdessamad.bayzi/add-observability-to-your-service-in-easy-steps-e2d6a7d6d3a5?source=rss-885ac976f389------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2d6a7d6d3a5</guid>
            <category><![CDATA[sre]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[opentelemetry]]></category>
            <dc:creator><![CDATA[Abdessamad Bayzi]]></dc:creator>
            <pubDate>Mon, 27 Feb 2023 21:17:24 GMT</pubDate>
            <atom:updated>2023-02-28T08:30:48.207Z</atom:updated>
            <content:encoded><![CDATA[<p><em>If observability isn’t one of your main concerns, your services are either not critical as you might think, or you’re missing things.</em></p><p>SRE is all about making your service reliable and available. In order to be very successful with SRE, you have to be able to trace failures and know why they happened. By making the application server and service more observable, it can be made easier for developers to find out what’s going on with their services.</p><p>Observing an application’s performance and understanding the impact it has on user experience can be done by a number of techniques, including tracing and instrumentation. The goal of observability is to expose a service as much as possible so that its internals can be analyzed, studied and debugged.</p><h3>Pillars of Observability</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/0*Vlm2XRS4VkyzIdZS.png" /><figcaption>Pillars of observability</figcaption></figure><p>Traceability is the ability to isolate and attribute problems or errors back to their origin. The Pillars of Observability provide you with a solid foundation for measuring, monitoring and analyzing customer experiences across your application:</p><p>As explained <a href="https://www.oreilly.com/library/view/distributed-systems-observability/9781492033431/ch04.html">here</a>, Observability has three pillars:</p><h4><strong>- Events logs:</strong></h4><p>An <em>event log</em> is an immutable, timestamped record of discrete events that happened over time. They can be either in plaintext, structured or binary as in <a href="https://mariadb.com/kb/en/binary-log/">MariaDb </a>for instance.</p><h4>- Metrics:</h4><p><em>Me</em>trics are a numeric representation of data measured over intervals of time. Metrics can harness the power of mathematical modeling and prediction to derive knowledge of the behavior of a system over intervals of time in the present and future.</p><h4>- Traces:</h4><p>A <em>trace</em> is a representation of a series of causally related distributed events that encode the end-to-end request flow through a distributed system.</p><p>Failures in complex distributed systems rarely arise because of one specific event happening in one specific component of the system. Often, various possible triggers across a highly interconnected graph of components are involved. By simply looking at discrete events that occurred in any given system at some point in time, it becomes impossible to determine all such triggers. To nail down the different triggers, one needs to be able to do the following:</p><blockquote>- Start with a symptom pinpointed by a high-level metric or a log event in a specific system</blockquote><blockquote>- Infer the request lifecycle across different components of the distributed architecture</blockquote><blockquote>- Iteratively ask questions about interactions among various parts of the system</blockquote><p><strong>Traces and metrics are an abstraction built on top of logs that pre-process and encode information along two orthogonal axes, one being request-centric (trace), the other being system-centric (metric).</strong></p><h4>Terms<strong><em>:</em></strong></h4><ul><li><strong>Trace</strong> — A trace is the start to finish activity that your application is doing. An example of this could be an API endpoint that is accessed.</li><li><strong>Span</strong> — A span is part of a trace that could be an internal function or database query or other discrete activity that your program does to complete the action (aka trace)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/0*Zhcn7aH0ZHKXO57R.png" /><figcaption>A trace represented as spans: span A is the root span, span B is a child of span A</figcaption></figure><h3>Prerequisite:</h3><p>Observability infrastructure already in-place:</p><ul><li>Otel pipeline we’ll be using:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff4ebe48193a03dda662154d36debe5e/href">https://medium.com/media/ff4ebe48193a03dda662154d36debe5e/href</a></iframe><p>also can be illustrated as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yeb4obqHGkg3oGFxrCAR7Q.png" /></figure><h3>Getting started with our demo app:</h3><p>For our demo application, we’ll use the following services:</p><ul><li>front service: ReactJS</li><li>backend service: spring boot</li><li>H2 Database</li></ul><p>In term of tools, they vary greatly, however you should keep in mind that there’s a great benefit when using a standard way, instead of being locked and tied to a specific provider. <a href="https://opentelemetry.io/"><strong>OpenTelemetry</strong></a> provides a single, open-source standard and a set of technologies to capture and export metrics, traces, and logs (in the future) from your applications and infrastructure. It is now the second most active CNCF open-source project behind only Kubernetes, and It’s supported by all major APM tools.</p><h4>1. Spring boot service:</h4><p>For Java applications, OpenTelemetry provides three repositories:</p><ul><li><a href="https://github.com/open-telemetry/opentelemetry-java"><strong>opentelemetry-java</strong></a><br>This repo is the main OpenTelemetry Java SDK and provides components for manual instrumentation.</li><li><a href="https://github.com/open-telemetry/opentelemetry-java-instrumentation"><strong>opentelemetry-java-instrumentation</strong></a><br>This project provides a Java agent JAR that can be attached to any Java 8+ application and dynamically injects bytecode to capture telemetry from a number of popular libraries and frameworks.</li><li><a href="https://github.com/open-telemetry/opentelemetry-java-contrib"><strong>opentelemetry-java-contrib</strong></a><br>This project is intended to provide helpful libraries and standalone OpenTelemetry-based utilities that don’t fit the express scope of the <a href="https://github.com/open-telemetry/opentelemetry-java">OpenTelemetry Java</a> or <a href="https://github.com/open-telemetry/opentelemetry-java-instrumentation">Java Instrumentation</a> projects.</li></ul><p>Since this is an introduction to observability, we’ll use auto-instrumentation, which is more than enough to start your Observability journey and get interesting insights about your services.</p><h4>1.1 Traces:</h4><p>Without adding anything to our code, the OpenTelemetry agent is able to capture telemetry data at the edges of an app or service, such as inbound requests, and outbound HTTP calls.</p><p>Steps to use the OpenTelemetry Java agent:</p><ul><li>Download and distribute the <a href="https://github.com/open-telemetry/opentelemetry-java-instrumentation/releases/latest/download/opentelemetry-javaagent.jar">latest Java JAR agent</a> to the java service</li><li>Prepare environment variables like the service name of your monitored service and endpoint to where you will export your data</li><li>Attach the agent to the jar of your application while running it</li></ul><p>The following Dockerfile is self explanatory and uses all steps from above:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3cf7b55901dfdcbc93f067ac5c4c7557/href">https://medium.com/media/3cf7b55901dfdcbc93f067ac5c4c7557/href</a></iframe><p>Next you need to set some environment variables:</p><pre>OTEL_EXPORTER_OTLP_ENDPOINT=http://otel_collector:4317<br>OTEL_RESOURCE_ATTRIBUTES=service.name=middleware-svc,compose_service=middleware-svc<br>OTEL_METRICS_EXPORTER=none</pre><h4>1.2 Metrics:</h4><p>For metrics we’ll use <a href="https://prometheus.io/"><strong>Prometheus</strong></a>, One of the largest and best known tools in the world of metric collection, it is graduated at the CNCF.</p><p>To get these metrics for spring boot, we need:</p><ul><li><a href="https://github.com/spring-projects/spring-boot/tree/v2.7.4/spring-boot-project/spring-boot-actuator">Spring Boot Actuator</a>: Actuator provides a lot of monitoring features by HTTP or JMX endpoints for the Spring Boot applications.</li><li><a href="https://github.com/micrometer-metrics/micrometer">Micrometer</a>: Micrometer provides a general API to collect metrics and transform the format for different monitoring systems, including Prometheus.</li></ul><p>Add these two dependencies to your pom.xml and config to your application.yaml:</p><pre>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-actuator&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;io.micrometer&lt;/groupId&gt;<br>   &lt;artifactId&gt;micrometer-registry-prometheus&lt;/artifactId&gt;<br>   &lt;scope&gt;runtime&lt;/scope&gt;<br>  &lt;/dependency&gt;</pre><pre>management:<br>  endpoints:<br>    web:<br>      exposure:<br>        include: prometheus<br>  metrics:<br>    tags:<br>      application: middleware-svc</pre><p>If you run you service and get to /actuator/prometheus , you can see the exposed metrics:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6VxfBagtPOiuxi1_R-cguw.png" /></figure><p>In order to add some traces and metrics correlation to your metrics, we need to add another component called <strong>Exemplar.</strong> “<a href="https://github.com/OpenObservability/OpenMetrics/blob/main/specification/OpenMetrics.md#exemplars">OpenMetrics</a> introduces the ability for scrape targets to add exemplars to certain metrics. Exemplars are references to data outside of the MetricSet. A common use case are IDs of program traces.”</p><p>Few requirements are needed for using Examplar:</p><ul><li>Spring Boot &gt;= 2.7.0</li><li>Micrometer &gt;= 1.9.0</li><li>o.prometheus.simpleclient_common &gt;= 0.16.0</li></ul><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;io.prometheus&lt;/groupId&gt;<br>    &lt;artifactId&gt;simpleclient_bom&lt;/artifactId&gt;<br>    &lt;version&gt;0.16.0&lt;/version&gt;<br>    &lt;type&gt;pom&lt;/type&gt;<br>    &lt;scope&gt;import&lt;/scope&gt;<br>&lt;/dependency&gt;</pre><p>and finally a configuration class as in <a href="https://github.com/qaware/cloud-observability-grafana-spring-boot/blob/b331b87b1a7f0f5b5d57150e0356e6a26af967a2/spring-boot-app/src/main/java/de/qaware/demo/cloudobservability/PrometheusExemplarSamplerConfiguration.java">here</a>:</p><pre>package de.qaware.demo.cloudobservability;<br><br>import io.prometheus.client.exemplars.tracer.otel_agent.OpenTelemetryAgentSpanContextSupplier;<br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br><br>@Configuration<br>public class PrometheusExemplarSamplerConfiguration {<br>    @Bean<br>    public OpenTelemetryAgentSpanContextSupplier openTelemetryAgentSpanContextSupplier() {<br>        return new OpenTelemetryAgentSpanContextSupplier();<br>    }<br>}</pre><p>Add to your metrics section in application.yaml :</p><pre>management:<br>  metrics:<br>    distribution:<br>      percentiles-histogram:<br>        http:<br>          server:<br>            requests: &#39;true&#39;</pre><p>And you’re good to start getting Examplars in your metrics. An example will look similar to below, where the exemplar is after the #</p><pre>post_timer_seconds_bucket{exception=&quot;None&quot;,method=&quot;GET&quot;,outcome=&quot;SUCCESS&quot;,status=&quot;200&quot;,uri=&quot;root&quot;,le=&quot;0.536870911&quot;} 9588.0 <br># {span_id=&quot;fa128244a04e3167&quot;,trace_id=&quot;fa128244a04e3167&quot;} 0.453905 1654688512.892</pre><p>This will help us navigate between traces and metrics in our visualization tool (Grafana).</p><h4>1.3 Logs:</h4><p>Depending on your deployment infrastructure, you might be using fluentd in kubernetes, you’ll need to forward logs to Loki.</p><p>Since OpenTelemetry logging is still experimental, I’m using <a href="https://grafana.com/docs/loki/latest/clients/docker-driver/configuration/">loki driver for docker-compose</a>.</p><p>Install the plugin:</p><pre>docker plugin install grafana/loki-docker-driver:latest --alias loki --grant-all-permissions</pre><p>Add this code snippet to your docker-compose file:</p><pre>x-logging: &amp;default-logging<br>  driver: loki<br>  options:<br>    loki-url: &#39;http://localhost:3100/api/prom/push&#39;<br>    loki-pipeline-stages: |<br>      - multiline:<br>          firstline: &#39;^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}.\d{3}&#39;<br>          max_wait_time: 3s<br>      - regex:<br>          expression: &#39;^(?P&lt;date&gt;\d{4}-\d{2}-\d{2}) (?P&lt;time&gt;\d{2}:\d{2}:\d{2}.\d{3}) (?P&lt;message&gt;(?s:.*))$$&#39;</pre><p>And whenever you need to collect logs from a docker service, you can add:<br><strong>logging: *default-logging</strong></p><pre>  middleware-svc:<br>    build: ./demo-app/middleware/<br>    environment:<br>      - OTEL_EXPORTER_OTLP_ENDPOINT=http://otel_collector:4317<br>      - OTEL_RESOURCE_ATTRIBUTES=service.name=middleware-svc,compose_service=middleware-svc<br>      - OTEL_METRICS_EXPORTER=none<br>      - MANAGEMENT_METRICS_TAGS_APPLICATION=middleware-svc<br>    ports:<br>      - &quot;8080:8080&quot;<br>    logging: *default-logging<br>    depends_on:<br>      - loki<br>      - otel_collector</pre><p>And in your application.yaml, override logging.pattern.level :</p><pre>logging:<br>  pattern:<br>    level: &quot;trace_id=%mdc{trace_id} span_id=%mdc{span_id} trace_flags=%mdc{trace_flags} %p&quot;</pre><p>OpenTelemetry Agent will add information to each logging automatically.</p><ul><li>trace_id — the current trace id</li><li>span_id — the current span id</li><li>trace_flags — the current trace flags, formatted according to W3C traceflags format</li></ul><h4>2. Frontend service: ReactJS</h4><p>Depending on your needs, you might want to get some instrumentation for loading time of your React components, add custom traces, or simply use the auto-instrumentation and trace all the HTTP Calls. As we did for the backend service, we’ll stick to the latest option, however you can check for more details and examples from <a href="https://github.com/open-telemetry/opentelemetry-js/tree/main/examples/opentelemetry-web">here</a>.</p><p>To instrument your JavaScript code running in the browser, you need to:</p><ul><li>Add following dependencies to your package.json:</li></ul><pre> &quot;@opentelemetry/api&quot;: &quot;^1.4.0&quot;,<br> &quot;@opentelemetry/auto-instrumentations-node&quot;: &quot;^0.36.0&quot;,<br> &quot;@opentelemetry/context-zone&quot;: &quot;^1.9.1&quot;,<br> &quot;@opentelemetry/exporter-collector&quot;: &quot;^0.25.0&quot;,<br> &quot;@opentelemetry/exporter-trace-otlp-http&quot;: &quot;^0.35.1&quot;,<br> &quot;@opentelemetry/instrumentation-document-load&quot;: &quot;^0.31.0&quot;,<br> &quot;@opentelemetry/instrumentation-fetch&quot;: &quot;^0.35.1&quot;,<br> &quot;@opentelemetry/resources&quot;: &quot;^1.9.1&quot;,<br> &quot;@opentelemetry/sdk-trace-web&quot;: &quot;^1.9.1&quot;</pre><p>create a tracer.ts :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/45b93c145a8af1ea26508cea0f8136f7/href">https://medium.com/media/45b93c145a8af1ea26508cea0f8136f7/href</a></iframe><p>You can then call the instrumentation method as early as possible before bootstrapping the react application</p><pre>import React from &#39;react&#39;<br>import ReactDOM from &#39;react-dom/client&#39;<br>import App from &#39;./App&#39;<br>import &#39;./index.css&#39;<br>import { initInstrumentation } from &#39;./tracer/tracer&#39;<br><br>initInstrumentation()<br><br>ReactDOM.createRoot(document.getElementById(&#39;root&#39;) as HTMLElement).render(<br>  &lt;React.StrictMode&gt;<br>    &lt;App /&gt;<br>  &lt;/React.StrictMode&gt;<br>)</pre><h4>3. Results:</h4><p>The complete docker-compose file can be found <a href="https://github.com/bayzi/observability/blob/main/docker-compose.yml">here</a>.</p><p>Once everything is setup, you can do a docker-compose up -d , navigate in your app, and see the magic happen 😄</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nTsbEaPV1uIaJXu7Ng5U0A.png" /></figure><p>This is the representation of a fetch call from the frontend service, to the backend and the SELECT query to the database. You can see the node graph which can help spot performance bottlenecks, also you can see the correlation between, logs, traces and metrics using the trace and spane id:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BHVJFE761PcPvmiT8ki_4g.png" /></figure><p>Based on these traces and metrics, you can create custom dashboards for your app. Here’s one you can use from <a href="https://grafana.com/grafana/dashboards/17175-spring-boot-observability/">Grafana</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6zZRm5wZUxDBHUFXEy2nPw.png" /></figure><h3>Conclusion</h3><p>It is more likely that you are now more aware of the importance of observing your serves and how easy it is to get started. Implementing infrastructure intended for production can be more challenging. That’s what I will cover in an upcoming blog post.</p><p>Happy Coding 😄</p><h4>References:</h4><ul><li><a href="https://github.com/bayzi/observability">https://github.com/bayzi/observability</a></li><li><a href="https://www.oreilly.com/library/view/distributed-systems-observability/9781492033431/ch04.html">https://www.oreilly.com/library/view/distributed-systems-observability/9781492033431/ch04.html</a></li><li><a href="https://github.com/open-telemetry/opentelemetry-java">https://github.com/open-telemetry/opentelemetry-java</a></li><li><a href="https://github.com/qaware/cloud-observability-grafana-spring-boot">https://github.com/qaware/cloud-observability-grafana-spring-boot</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2d6a7d6d3a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prometheus & Microsoft Teams Integration]]></title>
            <link>https://medium.com/ocp-digital-factory/prometheus-microsoft-teams-integration-4858f66e908e?source=rss-885ac976f389------2</link>
            <guid isPermaLink="false">https://medium.com/p/4858f66e908e</guid>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[prometheus]]></category>
            <category><![CDATA[sre]]></category>
            <dc:creator><![CDATA[Abdessamad Bayzi]]></dc:creator>
            <pubDate>Wed, 02 Nov 2022 12:05:55 GMT</pubDate>
            <atom:updated>2022-11-02T12:06:38.759Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kiglfV471Kuyfa3MzyZ_Jw.png" /></figure><p><em>If you’re reading this article then you probably know that monitoring without alerting is useless, just as it’s useless to be alerted about everything.</em></p><p><em>Choosing the right alert and incident management tool is key to a successful monitoring experience. While commercial tools (Datadog, Pagerduty …) offer alerting functionality and integration with third-party platforms as out-of-the-box features, using open-source projects requires setting each component separately. At the end of this tutorial, you will know how to easily and efficiently set up the integration between Prometheus and Microsoft Teams.</em></p><h4>Requirements:</h4><ul><li>Kubernetes</li><li><a href="https://github.com/prometheus-community/helm-charts/tree/main/charts/kube-prometheus-stack">prometheus stack</a> deployed to your cluster</li><li>Helm</li></ul><h4>Designing your alert</h4><p>Believe it or not, alerts should be designed, in a way to get the full benefit from theme, and get the <strong>Direct attention </strong>of those being notified.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*EbXjlKzzxe5ynkqmBkskPQ.jpeg" /></figure><p>To know more about designing alerts, I highly recommend you this talk from <a href="https://monitorama.com/">Monitorama</a> conference</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*1OhNIgt7YgJyO7YudpBfOA.jpeg" /></figure><p>As you can see, this alert has all the mentioned aspects of a good alert, and Its resolution can be automated with the action “Unseal Vault”.</p><p>When an incident is resolved, people should know:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l76NZ_hbnOR_QBfCS0BOFA.png" /></figure><p>You can design your own card templates using <a href="https://learn.microsoft.com/en-us/microsoftteams/platform/task-modules-and-cards/what-are-cards">MS Teams</a>, or you can use <a href="https://github.com/prometheus-msteams/prometheus-msteams/tree/master/examples/templates">this ones</a> and adapt them for your needs.</p><h4>Teams Configuration</h4><p>From your notification channel in Teams</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*-Ygxa_5iaNM4oEKzv8BFdg.png" /><figcaption>Manage connectors</figcaption></figure><p>Select the Incoming Webhook connector from the list of available connectors. Enter a name to identify this webhook later. You can also add an image which will be visible whenever a message is posted using this webhook. Click Create.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hpiAoB3NvjlBsUN7DFPYVQ.png" /><figcaption>Add a webhook connector</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*D_LqoLAEL5DGQWn9OHEgBg.png" /><figcaption>Connector URL</figcaption></figure><h4>Deploy to Kubernetes cluster</h4><p>The <a href="https://github.com/prometheus-community/helm-charts/tree/main/charts/kube-prometheus-stack">prometheus stack </a>uses <a href="https://prometheus.io/docs/alerting/latest/alertmanager/">AlertManager</a> for managing alerts (grouping, silencing, sending …).<br>Alertmanager doesn’t support sending to Microsoft Teams out of the box. Fortunately, they allow you to use a generic <a href="https://prometheus.io/docs/alerting/configuration/#webhook_config">webhook_config</a> for cases like this. So <a href="https://github.com/prometheus-msteams/prometheus-msteams">this project</a> fills in the missing part 🎉</p><p>We’ll use Helm for deployment:</p><pre>$ helm repo add prometheus-msteams <a href="https://prometheus-msteams.github.io/prometheus-msteams/">https://prometheus-msteams.github.io/prometheus-msteams/</a></pre><p>Create your helm config file:</p><pre># config.yaml<br>---<br>replicaCount: 1<br>image:<br>  repository: quay.io/prometheusmsteams/prometheus-msteams<br>  tag: v1.5.1</pre><pre>connectors:<br># in alertmanager, this will be used as <a href="http://prometheus-msteams:2000/bar">http://prometheus-msteams:2000/</a>prometheus-msteams. Replace with value you got from above steps<br>- sec-teams-alert: <a href="https://outlook.office.com/webhook/xxxx/xxxx">https://outlook.office.com/webhook/xxxx/xxxx</a></pre><pre># extraEnvs is useful for adding extra environment variables such as proxy settings<br>extraEnvs:<br>  HTTP_PROXY: <a href="http://corporateproxy:8080/">http://corporateproxy:8080</a><br>  HTTPS_PROXY: <a href="http://corporateproxy:8080/">http://corporateproxy:8080</a></pre><p>By default, the app uses a <a href="https://github.com/prometheus-msteams/prometheus-msteams/blob/master/examples/templates/default-message-card.tmpl">default card template</a> to convert incoming Prometheus alerts to teams message cards. Whether you decide to create your own teams card template or you chose one from <a href="https://github.com/prometheus-msteams/prometheus-msteams/tree/master/examples/templates">her</a>e, you’ll need to use customCardTemplate and set Its content with --set-file flag to set the value from the template file.</p><pre>$ helm upgrade --install prometheus-msteams \<br>  --namespace monitoring -f config.yaml \<br>  --set-file customCardTemplate=custom-card.tmpl \<br>  prometheus-msteams/prometheus-msteams</pre><h4>Configure AlertManager</h4><p>From your monitoring namespace, modify Alertmanager configuration, add a new <strong><em>receiver</em></strong> and <strong><em>rules</em></strong> to forward alerts to <strong><em>prometheus-msteams.</em></strong></p><p>For example in this configuration, I’m forwarding all vault alerts to the security team channel, and when the alert is resolved, a new notification is sent</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a33de9b0ae0de93a37841650c9d79108/href">https://medium.com/media/a33de9b0ae0de93a37841650c9d79108/href</a></iframe><p>Encode file content :</p><pre>$ cat alertmanager-conf.yaml | base64</pre><p>And finally modify Alertmanager secret in your monitoring namespace with the new value.</p><pre>cat &lt;&lt;EOF | kubectl apply -f -<br>apiVersion: v1<br>kind: Secret<br>metadata:<br>  name: alertmanager-main<br>  namespace: monitoring<br>type: Opaque<br>data:<br>  alertmanager.yaml: BASE64 ENCODED VALUE FROM THE ABOVE STEP<br>EOF</pre><p>That’s it, you’ve now configured Alertmanager to send alerts to teams using a custom card template. Happy monitoring 😄.</p><h4>Final thoughts:</h4><p><em>Monitoring is not enough, alerting is not enough, it is continuous work and continuous improvement to detect blind spots in your IT systems. Open source tools can be your starting point, but establishing a culture of monitoring and global adoption of monitoring by all your IT teams (Dev, Ops, Sec, business owners…), will at some point require moving to commercial solutions, due to their intuitiveness and ease of use and implementation.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4858f66e908e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ocp-digital-factory/prometheus-microsoft-teams-integration-4858f66e908e">Prometheus &amp; Microsoft Teams Integration</a> was originally published in <a href="https://medium.com/ocp-digital-factory">OCP digital factory</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Extend your monitoring stack in Openshift 3.11 to monitor MySql Server]]></title>
            <link>https://medium.com/ocp-digital-factory/extend-your-monitoring-stack-in-openshift-3-11-to-monitor-mysql-server-dcd28dca35f?source=rss-885ac976f389------2</link>
            <guid isPermaLink="false">https://medium.com/p/dcd28dca35f</guid>
            <category><![CDATA[openshift]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[grafana]]></category>
            <dc:creator><![CDATA[Abdessamad Bayzi]]></dc:creator>
            <pubDate>Thu, 04 Feb 2021 13:19:20 GMT</pubDate>
            <atom:updated>2021-02-04T14:11:25.648Z</atom:updated>
            <content:encoded><![CDATA[<p><em>OpenShift 3.11 ships with a pre-configured and self-updating monitoring stack based on the Prometheus open source project. The main components are Prometheus, Alertmanager and Grafana. </em>Therefore pods, namespaces and nodes are monitored by default, with a set of pre-configured alert rules<em>. Witch is great. However in OCP 3.11 Grafana is entirely read-only, it cannot be configured beyond what is already there. There is a </em><a href="https://bugzilla.redhat.com/show_bug.cgi?id=1668441"><em>RFE</em></a><em> filed to enable to add custom configuration to Grafana instances. Per statements from engineering in a </em><a href="https://bugzilla.redhat.com/show_bug.cgi?id=1647932"><em>bug</em></a><em>, Grafana is intentionally read-only to prevent issues with upgrades and the lifecycle of the monitoring stack.</em></p><p><em>In other words, you can’t add custom dashboards to your out of the box Grafana.</em></p><p>The need of custom dashboards has been identified when I was doing some performance testing.</p><p>As a DevOps engineer, one of your missions is to cut down number of handoffs. Preparing a good performance testing infrastructure is the first thing to do. You don’t need to rely on Infrastructure team or database administrators to provide you some manual generated reports at the end of your tests, which I’m sure will take some time to provide. Instead, you need to have a 360° view of your application’s behavior, database, network and system metrics, in real time.</p><p><strong>Requirements</strong></p><ul><li>Openshift client</li><li>Helm 3</li></ul><p><strong>Summary</strong>:</p><p>1- Setup MySql exporter in the remote server</p><p>2- Configure Prometheus</p><p>3- Setup Grafana</p><h3>1 — Setup MySql exporter in the remote server</h3><p>Remote machines needs to run exporters to expose metrics. We will be using the following two:</p><ul><li><a href="https://github.com/prometheus/mysqld_exporter">mysqld_exporter</a> — for MySQL server metrics</li></ul><p>Connect to the remote machine and download the exporter</p><pre>$ wget <a href="https://github.com/prometheus/mysqld_exporter/releases/download/v0.11.0/mysqld_exporter-0.11.0.linux-amd64.tar.gz">https://github.com/prometheus/mysqld_exporter/releases/download/v0.11.0/mysqld_exporter-0.11.0.linux-amd64.tar.gz</a><br>$ tar xvzf mysqld_exporter-0.11.0.linux-amd64.tar.gz<br>$ cd mysqld_exporter-0.11.0.linux-amd64<br>$ sudo mv mysqld_exporter /usr/local/bin/</pre><p>add a new system user to your machine</p><pre>$ sudo useradd -rs /bin/false prometheus</pre><p>Connect to mysql and run</p><pre>&gt; CREATE USER &#39;exporter&#39;@&#39;localhost&#39; IDENTIFIED BY &#39;StrongPassword&#39; WITH MAX_USER_CONNECTIONS 3;<br>&gt; GRANT PROCESS, REPLICATION CLIENT, SELECT ON *.* TO &#39;exporter&#39;@&#39;localhost&#39;;</pre><p><em>WITH MAX_USER_CONNECTIONS 3 is used to set a max connection limit for the user to avoid overloading the server with monitoring scrapes under heavy load.</em></p><p>Configure the Database Credentials</p><pre>$ sudo vi /etc/.exporter.cnf<br><br>[client]<br>user=exporter<br>password=StrongPassword</pre><p>Set ownership permissions:</p><pre>$ sudo chown prometheus:prometheus /etc/.exporter.cnf</pre><p>Create systemd Unit File</p><pre>$sudo vi /lib/systemd/system/mysql_exporter.service</pre><p>Add the following content:</p><pre>[Unit]<br> Description=Prometheus MySQL Exporter<br> After=network.target</pre><pre>[Service]<br> User=prometheus<br> Group=prometheus<br> Type=simple<br> Restart=always<br> ExecStart=/usr/local/bin/mysqld_exporter \<br> --config.my-cnf /etc/.exporter.cnf \<br> --collect.global_status \<br> --collect.info_schema.innodb_metrics \<br> --collect.auto_increment.columns \<br> --collect.info_schema.processlist \<br> --collect.binlog_size \<br> --collect.info_schema.tablestats \<br> --collect.global_variables \<br> --collect.info_schema.query_response_time \<br> --collect.info_schema.userstats \<br> --collect.info_schema.tables \<br> --collect.perf_schema.tablelocks \<br> --collect.perf_schema.file_events \<br> --collect.perf_schema.eventswaits \<br> --collect.perf_schema.indexiowaits \<br> --collect.perf_schema.tableiowaits \<br> --collect.slave_status \<br> --web.listen-address=0.0.0.0:9104</pre><pre>[Install]<br> WantedBy=multi-user.target</pre><p><strong><em>web.listen-address=0.0.0.0:9104</em></strong> specifies that the server is listening on port 9104. When done, reload systemd and start mysql_exporter service:</p><pre>$ sudo systemctl daemon-reload<br>$ sudo systemctl enable mysql_exporter<br>$ sudo systemctl start mysql_exporter</pre><p>That’s it, your MySql server is now exposing metrics. In the next step, we’ll configure prometheus to scrap them.</p><h3>2 — Configure Prometheus</h3><p>First export the existing configuration of Prometheus</p><pre>$ oc get secrets prometheus-k8s -n openshift-monitoring --export -o yaml &gt; prometheus-k8s.yaml</pre><p>Secret is in Base64, decode it and add MySql server as a target</p><pre>- job_name: mysql<br>  static_configs:<br>    - targets: [&#39;SERVER_IP:9104&#39;]<br>      labels:<br>        alias: mysql</pre><p>Encode the new secret value, apply the new secret, and finally restart prometheus pods.</p><h3>3 — Setup Grafana</h3><p>In this step we’ll create a new Grafana instance, connected to the existing Prometheus datasource.</p><pre>$ oc new-project df-monitoring</pre><p>Next we export Grafana-Prometheus configuration.</p><pre>$ oc get secrets grafana-datasources -n openshift-monitoring --export -o yaml &gt; grafana-datasources.yaml</pre><p>The value is in Base64, after decoding it</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5da0610a86f662b8ed21ed1f629e8a9d/href">https://medium.com/media/5da0610a86f662b8ed21ed1f629e8a9d/href</a></iframe><p>Get then Grafana chart, we need to get the chart locally as we’ll add some custom dashboards to it. At the moment I’m writing this post, the chart version is 6.2.1</p><pre>$ helm repo add grafana <a href="https://grafana.github.io/helm-charts">https://grafana.github.io/helm-charts</a><br>$ helm pull grafana/grafana<br>$ tar xvzf grafana-6.2.1.tgz</pre><p>Clone my GitHub project <a href="https://github.com/bayzi/openshift-monitoring.git">https://github.com/bayzi/openshift-monitoring.git</a> and copy all json files in dashboards directory to the grafana/dashboards directory.</p><p>From the grafana-datasource file, get the BasicAuthUser and BasicAuthPassword (in Base64), then make necessary changes in values.yaml file, you can also set your grafana admin password there.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0bf8a4cf093af4d7da2031fa2ac97687/href">https://medium.com/media/0bf8a4cf093af4d7da2031fa2ac97687/href</a></iframe><p>I exported and configured all openshift Dashboard, so you can visualize Openshift metrics in the new Grafana instance, I also added some of the dashboards from the Percona Monitoring project.</p><p><strong>NB: If <em>you need to modify this file, make sure to respect the association between providers and dashboards.</em></strong></p><p>Go back to Grafana chart directory and install the chart</p><pre>$ helm install df-grafana . -f PATH_TO_CUSTOM_VALUES_FILE</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G_NLzP-YuSWXvZuLfE1tqw.png" /></figure><p>Wait until pod is in Running state and join this namespace to <strong>openshift-monitoring</strong> namespace</p><pre>$ oc adm pod-network join-projects — to=df-monitoring openshift-monitoring</pre><p><strong>Optional:</strong> you can expose Grafana service using routes</p><pre>$ oc create route passthrough grafana-web --service df-grafana --port service<strong> </strong>— hostname df-grafana.domaine.com</pre><p>Congrats!! Grafana is now ready to be used, and our custom dashboards are uploaded to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YNOnJp2vJ-7ezoVZkOv9lw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vew_Of6lhmaYozhPVEwcFw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LmzSJPZzY_8mx4AGdQavXw.png" /></figure><p>Please let me know If you face any issues applying files I provided.</p><p>Happy Monitoring :✌️😁</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dcd28dca35f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ocp-digital-factory/extend-your-monitoring-stack-in-openshift-3-11-to-monitor-mysql-server-dcd28dca35f">Extend your monitoring stack in Openshift 3.11 to monitor MySql Server</a> was originally published in <a href="https://medium.com/ocp-digital-factory">OCP digital factory</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Set up a production-ready Vault cluster with Kubernetes and Azure]]></title>
            <link>https://medium.com/ocp-digital-factory/set-up-a-production-ready-vault-cluster-with-kubernetes-and-azure-4c2d5e315e47?source=rss-885ac976f389------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c2d5e315e47</guid>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[hashicorp]]></category>
            <category><![CDATA[vault]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Abdessamad Bayzi]]></dc:creator>
            <pubDate>Wed, 23 Sep 2020 08:23:34 GMT</pubDate>
            <atom:updated>2020-09-23T08:23:34.517Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xZWqy_9mlqrMISYj.jpeg" /></figure><p><em>Secret management is not optional, It must be done, and in a good and secure way because:</em></p><ul><li><em>Data breach are a routine occurrence these days</em></li><li><em>This can result in lawsuits and fines that may ruin businesses</em></li><li><em>Securing your secretes prevent or limits scoop of breach</em></li><li><em>Business secrets must also be secured from competition</em></li></ul><p><em>One of the best secret management tools in the market is Vault, unlike other tools, It’s well designed for DevSecOps, security is managed as code, while other tools are driven by manual configurations, and in most cases, a vendor-specific consultant must be hired to maintain this Snowflake server.</em></p><p><em>This blog post is not an introduction to Vault, it’s a practical guide to deploy a production-ready, high available Vault with ease using Kubernetes and some scripted operations.</em></p><p>In this walkthrough, we are respecting <a href="https://learn.hashicorp.com/tutorials/vault/production-hardening">the production hardening recommendations provided by Hashicorp</a>, such as: <strong>End-to-End TLS, Single Tenancy, disable root token, Don’t Run as Root, Restrict Storage Access, Enable Auditing …</strong></p><p>At the end of this post, we’ll have the following architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0U03gupqIuivsuno.png" /></figure><p><strong><em>Requirements:</em></strong></p><ul><li>Kubernetes 16+ with at least 3 nodes</li><li>helm 3</li><li>git clone <a href="https://github.com/bayzi/vault-k8s.git">https://github.com/bayzi/vault-k8s.git</a></li><li>Deployments will be made in the default namespace</li><li>Cloudflare SSL tool kit (<a href="https://pkg.cfssl.org/">cfssl</a> and <a href="https://pkg.cfssl.org/">cfssljson</a>)</li></ul><h3>1 — Setup certificates:</h3><p>As indicated in the production hardening recommendations, communication between Vault and Consul must be encrypted, therefore we will set up certificates to be used by:</p><ul><li>Consul service</li><li>Vault service</li><li>127.0.0.1</li><li>Consul cluster</li></ul><p>For this purpose, We will use Cloudflare SSL tool kit (<a href="https://pkg.cfssl.org/">cfssl</a> and <a href="https://pkg.cfssl.org/">cfssljson</a>), so make sure to install it before proceeding to the next step.</p><p>First, edit the files ca-conf/consul-csr.json and ca-conf/ca-csr.json to change the cert info in the “name” section</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a1d53f5d453c655f752eb6acdedecaa/href">https://medium.com/media/4a1d53f5d453c655f752eb6acdedecaa/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f6099f573e012169f9357b76d863330/href">https://medium.com/media/7f6099f573e012169f9357b76d863330/href</a></iframe><p>Make then all scripts executable</p><pre>$ chmod +x scripts/*.sh</pre><p>And run the create-certs script</p><pre>$ ./01-create-certs.sh</pre><p>This will:</p><ul><li>Initialize a Certificate Authority (CA)</li><li>Create a private key and sign the TLS certificate</li></ul><p>At this point, you should have the following files generated in the ca directory</p><pre>ca-key.pem<br>ca.pem<br>consul-key.pem<br>consul.pem</pre><h3>2 — Setup HA storage backend — Consul cluster</h3><p>Vault relies on an external storage backend for persistence, and this decoupling allows Vault to be managed immutably.</p><p>Currently, there are several storage backends that support high availability mode, including Consul, ZooKeeper and etcd. The Consul backend is the recommended HA backend, as it is used in production by HashiCorp and its customers with commercial support.</p><p>Consul uses a <a href="https://en.wikipedia.org/wiki/Gossip_protocol">gossip protocol</a> to manage membership and broadcast messages to the cluster. In order to secure gossip communication with encryption, we’ll generate and use an encryption key, we’ll use the Consul CLI command, consul keygen, to generate a cryptographically suitable key. So make sure to install Consul CLI command:</p><pre>$ brew install consul</pre><p>and run the setup-consul script</p><pre>$ ./02-setup-consul.sh</pre><p>The script will:</p><ul><li>Create a consul service account</li><li>Create a secret with early created certificates</li><li>Create a secret with the gossip encryption key</li><li>Create Consul StatefulSet and Consul service</li></ul><p>Note that we’re using node anti-affinity for more robustness. So make sure to have enough Kubernetes nodes, at least 3, the minimum number of nodes required to have a quorum in <a href="https://www.consul.io/docs/architecture/consensus">the consensus algorithm used by Consul for leader election.</a></p><p>Once all Consul pods are in Running state:</p><pre>$ kubectl get podsNAME       READY     STATUS    RESTARTS   AGE<br>consul-0   1/1       Running   0          40s<br>consul-1   1/1       Running   0          23s<br>consul-2   1/1       Running   0          11s</pre><p>make a port-forward and check all members are alive:</p><pre>$ kubectl port-forward svc/consul 8500:8500<br>$ consul membersNode      Address          Status  Type    Build  Prot  DC   Segment<br>consul-0  172.17.0.2:8301  alive   server  1.8.0  2     dc1  &lt;all&gt;<br>consul-1  172.17.0.4:8301  alive   server  1.8.0  2     dc1  &lt;all&gt;<br>consul-2  172.17.0.5:8301  alive   server  1.8.0  2     dc1  &lt;all&gt;</pre><p>Visit <a href="http://127.0.0.1:8500/">http://127.0.0.1:8500</a> in your web browser to access Consul Web UI</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EbsNNmWulojXzPiY.png" /></figure><h3>3 — Setup Vault cluster</h3><p>As mentioned above, End-to-End encryption via TLS between the client, Vault, and Consul is recommended, therefore, the first thing to do is to create a secret of certificates created earlier. Then create a config map containing Vault and storage configurations (vault/vault-cm.yaml).</p><p>Node anti-affinity is also used with Vault, so make sure to have enough nodes in your cluster.</p><p>The last thing to mention is the auto-unseal feature. When a Vault server is started, it starts in a <a href="https://www.vaultproject.io/docs/concepts/seal.html"><strong><em>sealed</em></strong></a> state and it does not know how to decrypt data. Before any operation can be performed on the Vault, it must be unsealed. Unsealing is the process of constructing the master key necessary to decrypt the data encryption key.</p><p>The data stored by Vault is stored encrypted. Vault needs the <em>encryption key</em> in order to decrypt the data. The encryption key is also stored with the data (in the <em>keyring</em>), but encrypted with another encryption key known as the <em>master key</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fZiV9ncdmhGQt875.png" /></figure><p>Before the 1.X version of vault, the unsealing operation used to be manual, hopefully it’s now a built-in functionality in the open-source version of Vault. It may be implemented using a cloud provider or the <a href="https://www.vaultproject.io/docs/configuration/seal/transit">vault’s secret transit engine</a> (on-premise unsealing). For this guide, I’m using Azure Key Vault for the auto-unsealing.</p><p>As a prerequisite, I assume:</p><ul><li><em>You have a Microsoft Azure account, and at least, Contributor role in a resource group</em></li><li>Already created a resource group</li><li><em>jq installed, a lightweight and flexible command-line JSON processor</em></li></ul><p>The setup-vault script will do the following:</p><ul><li>Create a service principal in your Microsoft Azure account</li><li>Create a key Vault resource in the specified resource group</li><li>Set a policy for the service principal, to allow it to manage Vault keys in your resource group</li><li>Create the Master key in Azure Key Vault, that will be used for the auto-unseal operation</li><li>Setup Vault configuration in a config map, with the auto-unseal information</li><li>Create a Vault service account in your cluster</li><li>Create secret with required certificates to ensure End-to-End Encryption</li><li>Deploy Vault Statefulset and its services</li></ul><p>After clarifying what the script does, edit the script 03-setup-vault.sh to set the resource group name and the subscription Id.</p><pre>$ ./03-setup-vault.sh</pre><p>Once all pods are in Running state, you can do the same as before, make a port-forward and check all members are alive:</p><pre>$ kubectl port-forward svc/consul 8500:8500<br>$ consul membersNode      Address          Status  Type    Build  Prot  DC   Segment<br>consul-0  172.17.0.2:8301  alive   server  1.8.0  2     dc1  &lt;all&gt;<br>consul-1  172.17.0.4:8301  alive   server  1.8.0  2     dc1  &lt;all&gt;<br>consul-2  172.17.0.5:8301  alive   server  1.8.0  2     dc1  &lt;all&gt;<br>vault-0   172.17.0.7:8301  alive   client  1.7.0  2    dc1 &lt;default&gt;<br>vault-1   172.17.0.8:8301  alive   client  1.7.0  2    dc1 &lt;default&gt;<br>vault-2   172.17.0.9:8301  alive   client  1.7.0  2    dc1 &lt;default&gt;</pre><p>If you visit <a href="http://127.0.0.1:8500/">http://127.0.0.1:8500</a>, you’ll see that you have Vault and Consul services. You may notice that vault checks are Red, and to be exact, the Vault Sealed Status is red.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iCy0FdyzPI9aths3.png" /></figure><p>As explained before, Vault starts in sealed mode. Since this is the first time, we need to unseal it manually. It will be done automatically by vault in the future, thanks to the auto unseal feature.</p><pre>$ kubectl port-forward svc/vault 8200:8200</pre><p>Visit <a href="http://127.0.0.1:8200/">https://127.0.0.1:8200</a> in your web browser to access Vault Web UI</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Co4rh41J9FEBNL8D.png" /></figure><p>Fill the form and download the keys. It’s your responsibility to keeps those keys secret. One of the recommended strategies is to share each key share with a Vault admin.</p><p>Go back to the Consul Web UI: <a href="http://localhost:8500/">http://localhost:8500</a>, you’ll see that all checks are Ok.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9DIH8YPjY_HEyWQD.png" /></figure><p>From now on, the unseal operation will be done automatically. To be sure, delete all Vault pods:</p><pre>$ kubectl delete po -l app=vault</pre><p>Wait for Vault pods to be in Running state, and go to Consul Web UI: <a href="http://127.0.0.1:8500/">http://127.0.0.1:8500</a>, you should see all checks are green.</p><h3>4- Setup Ingress with traefik</h3><p>Since Vault service will be highly used for secret management by other applications/users, we need to make it available. The simplest way is to use NodePort and point your alias DNS to your cluster. The cleanest way is to use <strong>Ingress resources</strong>.</p><p>Traefɪk is a modern HTTP reverse proxy and load balancer made to deploy microservices with ease. I highly recommend you do some searching for it.</p><p>For the deployment, we’ll be using a helm chart, with a custom value file:</p><pre># values.yaml<strong>deployment:<br>  enabled: true<br>  replicas: 1<br>service:<br>  enabled: true<br>  type: NodePort</strong></pre><p>This is to change the number of replicas and create à NodePort Service instead of LoadBalancer.</p><pre>$ cd ..<br>$ helm repo add traefik <a href="https://containous.github.io/traefik-helm-chart">https://containous.github.io/traefik-helm-chart</a><br>$ helm repo update<br>$ helm install traefik traefik/traefik -f traefik/values.yaml</pre><p>This HelmChart does not expose the Traefik dashboard by default, for security concerns. Thus, there are multiple ways to expose the dashboard. For instance, the dashboard access could be achieved through a port-forward :</p><pre>$ kubectl port-forward $(kubectl get pods --selector &quot;app.kubernetes.io/name=traefik&quot; --output=name) 9000:9000</pre><p>Visit <a href="http://127.0.0.1:9000/dashboard/#/">http://127.0.0.1:9000/dashboard/#/</a> to access to traefik dashboard</p><p>You can then expose Vault using traefik by creating an IngressRouteTCP resource:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9bf9c74050684c4ee5f7ad1a6e6b634/href">https://medium.com/media/a9bf9c74050684c4ee5f7ad1a6e6b634/href</a></iframe><pre>$ kubectl apply -f traefik/ingress.yaml<br>$ TRAEFIK_PORT=$(kubectl get svc traefik -o json | jq .spec&#39;.ports[1]&#39;.nodePort)</pre><p>Go to <a href="https://vault.example.com:$TRAEFIK_PORT/">https://vault.example.com:$TRAEFIK_PORT</a>.</p><h3>Conclusion:</h3><p><em>Congratulation! At this point, you have set up a production-ready Vault cluster. I decided to group all the commands into scripts so that you can take your time reading and understanding the purpose of each step, and make it easier to perform. This is the result of many applying and debugging cycles, so you won’t be faced with the same. If at some time you need to make some cleaning, you can find in the script directory the following scripts:</em></p><pre>04-cleanup-vault.sh<br>05-cleanup-consul.sh</pre><p><em>Take your time to read the scripts and adapt them to your needs.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c2d5e315e47" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ocp-digital-factory/set-up-a-production-ready-vault-cluster-with-kubernetes-and-azure-4c2d5e315e47">Set up a production-ready Vault cluster with Kubernetes and Azure</a> was originally published in <a href="https://medium.com/ocp-digital-factory">OCP digital factory</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setup a production-ready Vault cluster with kubernetes and azure]]></title>
            <link>https://faun.pub/setup-a-production-ready-vault-cluster-with-kubernetes-and-azure-30943ff91bf3?source=rss-885ac976f389------2</link>
            <guid isPermaLink="false">https://medium.com/p/30943ff91bf3</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[vault]]></category>
            <dc:creator><![CDATA[Abdessamad Bayzi]]></dc:creator>
            <pubDate>Mon, 21 Sep 2020 20:11:30 GMT</pubDate>
            <atom:updated>2020-09-22T12:08:51.140Z</atom:updated>
            <content:encoded><![CDATA[<h3>Set up a production-ready Vault cluster with Kubernetes and Azure</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a80TcSF69dN2HFRNKOo2RQ.jpeg" /></figure><p><em>Secret management is not optional, It must be done, and in a good and secure way because:</em></p><ul><li><em>Data breach are a routine occurrence these days</em></li><li><em>This can result in lawsuits and fines that may ruin businesses</em></li><li><em>Securing your secretes prevent or limits scoop of breach</em></li><li><em>Business secrets must also be secured from competition</em></li></ul><p><em>One of the best secret management tools in the market is Vault, unlike other tools, It’s well designed for DevSecOps, security is managed as code, while other tools are driven by manual configurations, and in most cases, a vendor-specific consultant must be hired to maintain this Snowflake server.</em></p><p><em>This blog post is not an introduction to Vault, it’s a practical guide to deploy a production-ready, high available Vault with ease using Kubernetes and some scripted operations.</em></p><p>In this walkthrough, we are respecting <a href="https://learn.hashicorp.com/tutorials/vault/production-hardening">the production hardening recommendations provided by Hashicorp</a>, such as: <strong>End-to-End TLS, Single Tenancy, disable root token, Don’t Run as Root, Restrict Storage Access, Enable Auditing …</strong></p><p>At the end of this post, we’ll have the following architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*09aYL34XuNS3PErgyt0DgQ.png" /></figure><p><strong><em>Requirements:</em></strong></p><ul><li>Kubernetes 16+ with at least 3 nodes</li><li>helm 3</li><li>git clone <a href="https://github.com/bayzi/vault-k8s.git">https://github.com/bayzi/vault-k8s.git</a></li><li>Deployments will be made in the default namespace</li><li>Cloudflare SSL tool kit (<a href="https://pkg.cfssl.org/">cfssl</a> and <a href="https://pkg.cfssl.org/">cfssljson</a>)</li></ul><h3>1 - Setup certificates:</h3><p>As indicated in the production hardening recommendations, communication between Vault and Consul must be encrypted, therefore we will set up certificates to be used by:</p><ul><li>Consul service</li><li>Vault service</li><li>127.0.0.1</li><li>Consul cluster</li></ul><p>For this purpose, We will use Cloudflare SSL tool kit (<a href="https://pkg.cfssl.org/">cfssl</a> and <a href="https://pkg.cfssl.org/">cfssljson</a>), so make sure to install it before proceeding to the next step.</p><p>First, edit the files ca-conf/consul-csr.json and ca-conf/ca-csr.json to change the cert info in the “name” section</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a1d53f5d453c655f752eb6acdedecaa/href">https://medium.com/media/4a1d53f5d453c655f752eb6acdedecaa/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f6099f573e012169f9357b76d863330/href">https://medium.com/media/7f6099f573e012169f9357b76d863330/href</a></iframe><p>Make then all scripts executable</p><pre>$ chmod +x scripts/*.sh</pre><p>And run the create-certs script</p><pre>$ ./01-create-certs.sh</pre><p>This will:</p><ul><li>Initialize a Certificate Authority (CA)</li><li>Create a private key and sign the TLS certificate</li></ul><p>At this point, you should have the following files generated in the ca directory</p><pre>ca-key.pem<br>ca.pem<br>consul-key.pem<br>consul.pem</pre><h3>2 - Setup HA storage backend — Consul cluster</h3><p>Vault relies on an external storage backend for persistence, and this decoupling allows Vault to be managed immutably.</p><p>Currently, there are several storage backends that support high availability mode, including Consul, ZooKeeper and etcd. The Consul backend is the recommended HA backend, as it is used in production by HashiCorp and its customers with commercial support.</p><p>Consul uses a <a href="https://en.wikipedia.org/wiki/Gossip_protocol">gossip protocol</a> to manage membership and broadcast messages to the cluster. In order to secure gossip communication with encryption, we’ll generate and use an encryption key, we’ll use the Consul CLI command, consul keygen, to generate a cryptographically suitable key. So make sure to install Consul CLI command:</p><pre>$ brew install consul</pre><p>and run the setup-consul script</p><pre>$ ./02-setup-consul.sh</pre><p>The script will:</p><ul><li>Create a consul service account</li><li>Create a secret with early created certificates</li><li>Create a secret with the gossip encryption key</li><li>Create Consul StatefulSet and Consul service</li></ul><p>Note that we’re using node anti-affinity for more robustness. So make sure to have enough Kubernetes nodes, at least 3, the minimum number of nodes required to have a quorum in <a href="https://www.consul.io/docs/architecture/consensus">the consensus algorithm used by Consul for leader election.</a></p><p>Once all Consul pods are in Running state:</p><pre>$ kubectl get pods</pre><pre>NAME       READY     STATUS    RESTARTS   AGE<br>consul-0   1/1       Running   0          40s<br>consul-1   1/1       Running   0          23s<br>consul-2   1/1       Running   0          11s</pre><p>make a port-forward and check all members are alive:</p><pre>$ kubectl port-forward svc/consul 8500:8500<br>$ consul members</pre><pre>Node      Address          Status  Type    Build  Prot  DC   Segment<br>consul-0  172.17.0.2:8301  alive   server  1.8.0  2     dc1  &lt;all&gt;<br>consul-1  172.17.0.4:8301  alive   server  1.8.0  2     dc1  &lt;all&gt;<br>consul-2  172.17.0.5:8301  alive   server  1.8.0  2     dc1  &lt;all&gt;</pre><p>Visit <a href="http://127.0.0.1:8500/">http://127.0.0.1:8500</a> in your web browser to access Consul Web UI</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7nczFHGn4aENc6Hg0ja0Aw.png" /></figure><h3>3 - Setup Vault cluster</h3><p>As mentioned above, End-to-End encryption via TLS between the client, Vault, and Consul is recommended, therefore, the first thing to do is to create a secret of certificates created earlier. Then create a config map containing Vault and storage configurations (vault/vault-cm.yaml).</p><p>Node anti-affinity is also used with Vault, so make sure to have enough nodes in your cluster.</p><p>The last thing to mention is the auto-unseal feature. When a Vault server is started, it starts in a <a href="https://www.vaultproject.io/docs/concepts/seal.html"><strong><em>sealed</em></strong></a> state and it does not know how to decrypt data. Before any operation can be performed on the Vault, it must be unsealed. Unsealing is the process of constructing the master key necessary to decrypt the data encryption key.</p><p>The data stored by Vault is stored encrypted. Vault needs the <em>encryption key</em> in order to decrypt the data. The encryption key is also stored with the data (in the <em>keyring</em>), but encrypted with another encryption key known as the <em>master key</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tgRMMDSB5dm5JTu823x48Q.png" /></figure><p>Before the 1.X version of vault, the unsealing operation used to be manual, hopefully it’s now a built-in functionality in the open-source version of Vault. It may be implemented using a cloud provider or the <a href="https://www.vaultproject.io/docs/configuration/seal/transit">vault’s secret transit engine</a> (on-premise unsealing). For this guide, I’m using Azure Key Vault for the auto-unsealing.</p><p>As a prerequisite, I assume:</p><ul><li><em>You have a Microsoft Azure account, and at least, Contributor role in a resource group</em></li><li>Already created a resource group</li><li><em>jq installed, a lightweight and flexible command-line JSON processor</em></li></ul><p>The setup-vault script will do the following:</p><ul><li>Create a service principal in your Microsoft Azure account</li><li>Create a key Vault resource in the specified resource group</li><li>Set a policy for the service principal, to allow it to manage Vault keys in your resource group</li><li>Create the Master key in Azure Key Vault, that will be used for the auto-unseal operation</li><li>Setup Vault configuration in a config map, with the auto-unseal information</li><li>Create a Vault service account in your cluster</li><li>Create secret with required certificates to ensure End-to-End Encryption</li><li>Deploy Vault Statefulset and its services</li></ul><p>After clarifying what the script does, edit the script 03-setup-vault.sh to set the resource group name and the subscription Id.</p><pre>$ ./03-setup-vault.sh</pre><p>Once all pods are in Running state, you can do the same as before, make a port-forward and check all members are alive:</p><pre>$ kubectl port-forward svc/consul 8500:8500<br>$ consul members</pre><pre>Node      Address          Status  Type    Build  Prot  DC   Segment<br>consul-0  172.17.0.2:8301  alive   server  1.8.0  2     dc1  &lt;all&gt;<br>consul-1  172.17.0.4:8301  alive   server  1.8.0  2     dc1  &lt;all&gt;<br>consul-2  172.17.0.5:8301  alive   server  1.8.0  2     dc1  &lt;all&gt;<br>vault-0   172.17.0.7:8301  alive   client  1.7.0  2    dc1 &lt;default&gt;<br>vault-1   172.17.0.8:8301  alive   client  1.7.0  2    dc1 &lt;default&gt;<br>vault-2   172.17.0.9:8301  alive   client  1.7.0  2    dc1 &lt;default&gt;</pre><p>If you visit <a href="http://127.0.0.1:8500/">http://127.0.0.1:8500</a>, you’ll see that you have Vault and Consul services. You may notice that vault checks are Red, and to be exact, the Vault Sealed Status is red.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9oHi_YwZDbc07dwtPjaEEw.png" /></figure><p>As explained before, Vault starts in sealed mode. Since this is the first time, we need to unseal it manually. It will be done automatically by vault in the future, thanks to the auto unseal feature.</p><pre>$ kubectl port-forward svc/vault 8200:8200</pre><p>Visit <a href="http://127.0.0.1:8200/">https://127.0.0.1:8200</a> in your web browser to access Vault Web UI</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-B8E9-oBdDlZO2TuKopPSg.png" /></figure><p>Fill the form and download the keys. It’s your responsibility to keeps those keys secret. One of the recommended strategies is to share each key share with a Vault admin.</p><p>Go back to the Consul Web UI: <a href="http://localhost:8500/">http://localhost:8500</a>, you’ll see that all checks are Ok.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QuDnFQ5F6UAolDd_j-b-qQ.png" /></figure><p>From now on, the unseal operation will be done automatically. To be sure, delete all Vault pods:</p><pre>$ kubectl delete po -l app=vault</pre><p>Wait for Vault pods to be in Running state, and go to Consul Web UI: <a href="http://127.0.0.1:8500/">http://127.0.0.1:8500</a>, you should see all checks are green.</p><h3>4- Setup Ingress with traefik</h3><p>Since Vault service will be highly used for secret management by other applications/users, we need to make it available. The simplest way is to use NodePort and point your alias DNS to your cluster. The cleanest way is to use <strong>Ingress resources</strong>.</p><p>Traefɪk is a modern HTTP reverse proxy and load balancer made to deploy microservices with ease. I highly recommend you do some searching for it.</p><p>For the deployment, we’ll be using a helm chart, with a custom value file:</p><pre># values.yaml</pre><pre><strong>deployment:<br>  enabled: true<br>  replicas: 1<br>service:<br>  enabled: true<br>  type: NodePort</strong></pre><p>This is to change the number of replicas and create à NodePort Service instead of LoadBalancer.</p><pre>$ cd ..<br>$ helm repo add traefik <a href="https://containous.github.io/traefik-helm-chart">https://containous.github.io/traefik-helm-chart</a><br>$ helm repo update<br>$ helm install traefik traefik/traefik -f traefik/values.yaml</pre><p>This HelmChart does not expose the Traefik dashboard by default, for security concerns. Thus, there are multiple ways to expose the dashboard. For instance, the dashboard access could be achieved through a port-forward :</p><pre>$ kubectl port-forward $(kubectl get pods --selector &quot;app.kubernetes.io/name=traefik&quot; --output=name) 9000:9000</pre><p>Visit <a href="http://127.0.0.1:9000/dashboard/#/">http://127.0.0.1:9000/dashboard/#/</a> to access to traefik dashboard</p><p>You can then expose Vault using traefik by creating an IngressRouteTCP resource:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9bf9c74050684c4ee5f7ad1a6e6b634/href">https://medium.com/media/a9bf9c74050684c4ee5f7ad1a6e6b634/href</a></iframe><pre>$ kubectl apply -f traefik/ingress.yaml<br>$ TRAEFIK_PORT=$(kubectl get svc traefik -o json | jq .spec&#39;.ports[1]&#39;.nodePort)</pre><p>Go to <a href="https://vault.example.com:$TRAEFIK_PORT">https://vault.example.com:$TRAEFIK_PORT</a>.</p><h3>Conclusion:</h3><p><em>Congratulation! At this point, you have set up a production-ready Vault cluster. I decided to group all the commands into scripts so that you can take your time reading and understanding the purpose of each step, and make it easier to perform. This is the result of many applying and debugging cycles, so you won’t be faced with the same. If at some time you need to make some cleaning, you can find in the script directory the following scripts:</em></p><pre>04-cleanup-vault.sh<br>05-cleanup-consul.sh</pre><p><em>Take your time to read the scripts and adapt them to your needs.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/0*Piks8Tu6xUYpF4DU" /></figure><p><strong>Join FAUN!</strong></p><p><strong>Subscribe to </strong><a href="https://www.faun.dev/join?utm_source=medium.com/faun&amp;utm_medium=medium&amp;utm_campaign=faunmediumprebanner"><strong>FAUN topics</strong></a><strong> and get your weekly dose of the must-read tech stories, news, and tutorials </strong>🗞️</p><p><strong>Follow us on </strong><a href="https://twitter.com/joinfaun"><strong>Twitter</strong></a><strong> </strong>🐦<strong> and </strong><a href="https://www.facebook.com/faun.dev/"><strong>Facebook</strong></a><strong> </strong>👥<strong> and </strong><a href="https://instagram.com/fauncommunity/"><strong>Instagram</strong></a><strong> </strong>📷 <strong>and join our </strong><a href="https://www.facebook.com/groups/364904580892967/"><strong>Facebook</strong></a><strong> and </strong><a href="https://www.linkedin.com/company/faundev"><strong>Linkedin</strong></a><strong> Groups </strong>💬</p><figure><a href="https://www.faun.dev/join?utm_source=medium.com/faun&amp;utm_medium=medium&amp;utm_campaign=faunmediumbanner"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_cT0_laE4iPcqW1qrbstAg.gif" /></a></figure><h4>If this post was helpful, please click the clap 👏 button below a few times to show your support for the author! ⬇</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30943ff91bf3" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/setup-a-production-ready-vault-cluster-with-kubernetes-and-azure-30943ff91bf3">Setup a production-ready Vault cluster with kubernetes and azure</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automate MongoDB ReplicaSet backups with Gitlab CI and Kubernetes]]></title>
            <link>https://medium.com/ocp-digital-factory/automate-mongodb-replicaset-backups-with-gitlab-ci-and-kubernetes-9eade2c805ae?source=rss-885ac976f389------2</link>
            <guid isPermaLink="false">https://medium.com/p/9eade2c805ae</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[shell-script]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Abdessamad Bayzi]]></dc:creator>
            <pubDate>Fri, 29 Nov 2019 21:01:02 GMT</pubDate>
            <atom:updated>2019-11-29T21:01:02.556Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*rsk7vGHk2zak6uDgy4RJIw.jpeg" /></figure><p><em>When working in a DevOps environment, where “you build it, you run it&quot; is your motto, you no longer relay on other teams to do Ops tasks. You either collaborate with them to do the job, or you do it yourself. In my case it was the second option, I chose to do it in my way</em> 😎.</p><p>Before jumping to the implementation, let’s see what a MongoDB Replica Set is.</p><p>A Replica Set in MongoDB is a group of mongod processes that maintain the same data set, which provides both of redundancy and high availability.</p><p><strong>You get it, It’s the basis for all production deployment.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*zqjsOq3Qu1k6vl3d12yx7w.png" /><figcaption>MongoDB Replica sets</figcaption></figure><p>Of the Replica set members, only one node is deemed as <strong>Primary, </strong>while other members are deemed as <strong>secondaries</strong>.</p><p>Read and write operations are exclusively received by the primary node, however clients can specify a read preference to send read operations to secondaries.</p><p>If the primary is unavailable, an eligible secondary will hold an election to elect itself the new primary.</p><h4>How to ?</h4><p>Now that MongoDB Replica Set is clear, let see how to implement the backups operation.</p><p>We’ll be using mainly two scripts for this:</p><ul><li>select_primary.sh</li><li>backup.sh</li></ul><p>In Kubernetes, it is common for a pod to be deleted, scaled, or scheduled on another node. This means that the primary member could be any pod. Therefore, you must run some queries to determine which one is the primary. This is the purpose of the <strong>select_primary</strong> script.</p><p>Once the primary is identified, you run the <strong>backup</strong> script, which needs to be present on each MongoDB pod.</p><p>You either copy past the script on the persistent volume of each pod, or you use the script as a configmap, which will create automatically the script file on the pod.</p><p>For the aim of simplicity of this blog, I’ll do it the first way.</p><pre><strong>$</strong> for i in `kubectl get po -n NAMESPACE | grep mongo | awk &#39;{ print $1}&#39;`; do kubectl cp backup.sh $i:/data/configdb -n NAMESPACE ; done;</pre><pre><strong>$</strong> for i in `kubectl get po -n NAMESPACE | grep mongo | awk &#39;{ print $1}&#39;`; do kubectl exec $i  -n NAMESPACE — sh -c “chmod +x /data/configdb/backup.sh; done;</pre><p>The two commands above copy the backup script and make it executable on all Mongodb pods.</p><p>Let assume that we have a MongoDB StatefulSet of 3 replicas, bellow is the content of the <strong>select_primary</strong> script:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42f6b2dc377c129cf5b2adb174bbb09e/href">https://medium.com/media/42f6b2dc377c129cf5b2adb174bbb09e/href</a></iframe><p>Once executed, it will run the <strong>backup.sh</strong> script deployed on the primary member.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f8f4bb487c39724b7ff2a3e2bf0e5e34/href">https://medium.com/media/f8f4bb487c39724b7ff2a3e2bf0e5e34/href</a></iframe><p>The script does the following:</p><ul><li>It starts by locking the database to avoid any data corruption</li><li>Backup database using mongodump tool</li><li>Unlock the database</li><li>Zip the backup directory and delete unziped backup files</li></ul><p>Eventually, we’ll be checking the database status before and after running the lock/unlock and backup operations.</p><h4>Automation</h4><p>The backup operation must be done automatically, and if things goes wrong, we need to be notified asap.</p><p>One of the implementations would be to use Gitlab CI. In addition of automation, we can schedule the execution, and get the executions history with Gitlab. Better yet, It offers the slack integration to keep us informed of the pipeline status of nightly jobs.</p><p>Keep it simple 😄</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0d3672d570542a7b560f35df3bea714/href">https://medium.com/media/a0d3672d570542a7b560f35df3bea714/href</a></iframe><p>Last thing to do is to schedule the pipeline execution on gitlab:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6yFFhxTEcPBFBA0LTLuRcA.png" /></figure><p>My pipeline will be executed every day at 4 AM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ug2tbsToBfqnpqPyWXWyPA.png" /></figure><p><em>That’s all. I hope you enjoyed reading this post. I’ll be glad to answer your questions if you have any. Loved it? Don’t agree? Talk to me in the comments below.</em></p><p><em>In the next blog I’ll be talking about deploying MongoDb ReplicaSet in kubernetes. See you soon </em>😄</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9eade2c805ae" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ocp-digital-factory/automate-mongodb-replicaset-backups-with-gitlab-ci-and-kubernetes-9eade2c805ae">Automate MongoDB ReplicaSet backups with Gitlab CI and Kubernetes</a> was originally published in <a href="https://medium.com/ocp-digital-factory">OCP digital factory</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Develop the DevOps way — Part 3]]></title>
            <link>https://medium.com/ocp-digital-factory/develop-the-devops-way-part-3-e9fe9f41806f?source=rss-885ac976f389------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9fe9f41806f</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[makefile]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Abdessamad Bayzi]]></dc:creator>
            <pubDate>Mon, 30 Sep 2019 10:26:10 GMT</pubDate>
            <atom:updated>2019-11-04T19:26:03.794Z</atom:updated>
            <content:encoded><![CDATA[<h3>Develop the DevOps way — Part 3</h3><p><em>Welcome to part 3 of this DevOps series where I share about my experience experimenting some technical practices, that aims to ease some tasks when developing, and making development environment more similar to a production one, so the time spent on debugging environment problems may be used for coding and infrastructure improvements.</em></p><p><em>In part 1 we’ve seen the struggle of having a non-automated development environment, what are the benefits of having an automated one, and how we can achieve this easily with Vagrant.</em></p><p><em>In part 2 we’ve seen more details about how this development environment is made, what’s Ansible and how to use it.</em></p><p><em>In part 3 we’ll see other best practices: </em><strong><em>Using Makefile, docker-compose and multi-stage builds in Dockerfiles</em></strong></p><ul><li><a href="https://medium.com/ocp-digital-factory/develop-the-devops-way-part-1-5798603c527a">Develop the DevOps way-Part1</a>: Vagrant</li><li><a href="https://medium.com/ocp-digital-factory/develop-the-devops-way-part-2-819eb0ceffa2">Develop the DevOps way-Part2</a>: Ansible</li><li>Develop the DevOps way-Part3: Makefile and docker</li></ul><p>As a full stack developer, you may be using the following development Kit in your daily activities:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mCYMbV9BKQoHMpu8x2_nKw.png" /></figure><ul><li><strong>ReactJS</strong>: for the frontend</li><li><strong>Spring-boot</strong>: for the backend</li><li>MongoDb and Mysql</li><li>Hopefully <strong>Docker</strong> so you don’t have to handle Mysql and MongoDB installation</li><li><strong>git</strong> as a version control system for your code</li></ul><p>No need to remind you why you should be using docker. Automation and rapidly deploy server environments in containers are the main keys.</p><p>However, in the majority of — in-production — cases there is a separate container platform (Dev, Staging, Prod …). The container we build, test and run locally, is part of a larger context. One issue that often pops up, is that when you share docker code parts within a team, or the world, you will also need to explain how each of your containers (front, backend …) requires to be run.</p><p>Using docker-compose will make for sure things more easier, but it’s not enough :(</p><p>But imagine you only have to provide one line to test, build and run the application:</p><pre>$ make run</pre><p>you can easily ask your colleague to test your product, without having him/her to read a big README. It either works or does not.</p><p>I’m assuming you’re familiar with docker and docker-compose. Let’s see how to get the work done.</p><h4>Makefile</h4><p>As we’ve seen in <a href="https://medium.com/@abdessamad.bayzi/develop-the-devops-way-d5c8fc12a5c3">Part 1</a>, your sandbox contains all necessary tools (Linux, docker, git), if you are note using the sandbox, make sure to install docker, git and a shell tool of your choice. Docker install instructions are here: <a href="https://docs.docker.com/install/linux/docker-ce/ubuntu/#install-docker-ce">Ubuntu</a>, <a href="https://docs.docker.com/docker-for-mac/install/">Mac</a> or <a href="https://docs.docker.com/docker-for-windows/install/">Windows</a></p><p>Makefile is not something new, it’s a 40-year old classic that’s been reborn with automation projects. Here’s my version of the Makefile</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f39f1a79e40d44274967311b889f9a9/href">https://medium.com/media/1f39f1a79e40d44274967311b889f9a9/href</a></iframe><p>And yes, I’ve used docker-compose everywhere (so proud of it 😁 ), It makes the hole automation stuff easier. Before sharing the docker-compose file, let’s see briefly what this Makefile does.</p><p>While the help target in the Makefile says it all, I prefer to provide more clarifications:</p><pre>$ make <strong>run</strong></pre><p>Runs all the application (Frontend, Backend and a mongodb instance), but if you prefer running only the frontend or the backend service, you can run</p><pre>$ make <strong>run</strong> svc=backend</pre><p>the services names are those defined in docker-compose file.</p><p>Behind the scenes, before the run is made, frontend and backend images are built using Dockerfiles, and tagged with your commit sha1 from git log. The two Dockerfiles I’m using benefits from the docker caching layer principles, so you can focus on what matters the most, Development, instead of waiting for image to be rebuilt for each minimal modification in code. Be patient we’ll get to Dockerfiles soon.</p><pre>$ make <strong>build</strong><br>$ make <strong>build</strong> svc=frontend</pre><p>you can use the build target in order to only build the application images (or one of them) without running it.</p><pre>$ make <strong>prune</strong></pre><p>This target will delete all docker images in your system, so be careful with it.</p><pre>$ make <strong>clean-db</strong></pre><p>When using database, It could become easily messy with dummy data that you inject, in order to test the application. So cleaning data is something you’ll be doing very frequently.</p><h4>Docker-compose</h4><p>Here’s the docker-compose file I used in my implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48a86e2006d35d6e88bcf8ab5aeb4178/href">https://medium.com/media/48a86e2006d35d6e88bcf8ab5aeb4178/href</a></iframe><p>I guess everything is clear here, just a simple docker-compose files that defined 3 services: frontend, backend and mongodb. Service definition consists of the path to Dockerfile, ports to map and expose, and some environment variables to use.</p><h4>Dockerfiles</h4><p>Finally, we get to the Dockerfiles. In order to use docker for development, we can’t accept any impact on the developer, either on term of complexity or time to build and make some value fast.</p><p>If you’re using some kind of CD pipelines in your project, you should know that the base image used for build is different from the one used for runtime. Why ? This way you can keep your docker images as small as possible, and save time in your pipeline execution. You can do the same when working with docker in your local machine, it’s called <strong>Multi-stage builds.</strong></p><p>However, if not setup correctly, It will be slow as hell or, even worse, some unnecessary steps will be performed for every simple modification. Imagine having to install npm dependencies for each modification without even affecting package.json file. What a nightmare 😠.</p><p>In order to create images, docker uses layer. Each command that is found in a Dockerfile creates a new layer. Each layer contains the filesystem changes of the image between the state before the execution of the command and the state after the execution of the command.</p><p>So if we make sure that the layer created byRUN npm install doesn’t change unless the file <strong>package.json</strong> changes, we we’ll benefit from the power of docker cache (The same goes for pom.xml for spring boot for example). The following frontend and backend Dockerfiles are implementations of this principle:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/025c35500a04a650d1c15c4d98cdf51c/href">https://medium.com/media/025c35500a04a650d1c15c4d98cdf51c/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/acbcef366c7573b644e01c92ba3383e2/href">https://medium.com/media/acbcef366c7573b644e01c92ba3383e2/href</a></iframe><p>In both Dockerfiles, we copy dependency files (package.json and pom.xml), we install dependencies, then we copy the source code and run the build. This ensure dependencies installation is performed only if a new dependency is added to dependency files, otherwise we use the docker cache layer of the last build.</p><p>The generated artifacts are then used in the next stage, with an Entrypoint command to start the application for example.</p><p>I hope you enjoyed reading this post. I’ll be glad to answer your questions if you have any. Loved it? Don’t agree? Talk to me in the comments below. And Clap clap clap 👏 😁.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9fe9f41806f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ocp-digital-factory/develop-the-devops-way-part-3-e9fe9f41806f">Develop the DevOps way — Part 3</a> was originally published in <a href="https://medium.com/ocp-digital-factory">OCP digital factory</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Develop the DevOps way — Part 2]]></title>
            <link>https://medium.com/ocp-digital-factory/develop-the-devops-way-part-2-819eb0ceffa2?source=rss-885ac976f389------2</link>
            <guid isPermaLink="false">https://medium.com/p/819eb0ceffa2</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[vagrant]]></category>
            <category><![CDATA[ansible]]></category>
            <dc:creator><![CDATA[Abdessamad Bayzi]]></dc:creator>
            <pubDate>Mon, 30 Sep 2019 10:24:59 GMT</pubDate>
            <atom:updated>2019-11-04T19:39:09.631Z</atom:updated>
            <content:encoded><![CDATA[<h3>Develop the DevOps way — Part 2</h3><p><em>In the </em><a href="https://medium.com/ocp-digital-factory/develop-the-devops-way-part-1-5798603c527a"><em>previous post</em></a><em>, we’ve seen the struggle of having a non-automated development environment, what are the benefits of having an automated one, and how we can achieve this easily with Vagrant.</em></p><p><em>Vagrant is used alongside Ansible, to install and configure specific tools that a developer we’ll be using daily. Keep in mind that the purpose of this post is to know better the path I followed to have a sandbox (development environment) fully functional, so you can adapt it easily for your needs.</em></p><ul><li><a href="https://medium.com/ocp-digital-factory/develop-the-devops-way-part-1-5798603c527a">Develop the DevOps way-Part1</a>: Vagrant</li><li>Develop the DevOps way-Part2: Ansible</li><li><a href="https://medium.com/ocp-digital-factory/develop-the-devops-way-part-3-e9fe9f41806f">Develop the DevOps way-Part3</a>: Makefile and docker</li></ul><p>Let’s be honest, server management sucks, especially when you have to manage hundreds to thousands of production servers, and you have to stick to a manual process. Thus patching servers for example may take more time than it really deserves.</p><p>Today, we can’t say that we are going digital if we do not take into account the transformation of our IT department. While developing an MVP may take few weeks, preparing the development and production environment may take longer (creating dev and prod VMs, creating dns records, network traffic management, allocating more resources to the VMs, filling forms for each request …). Therefore, many tools have been designed to solve these problems, foster the DevOps culture and make system management simpler, automated and more standardized. One of this tools is Ansible.</p><h3>What’s Ansible ?</h3><p>Ansible is an open source automation platform which is used to customize and configure multiple servers in a consistent manner. Ansible Playbooks are used to declare the desired configuration of servers. Any server that is already in the declared state is left unchanged. The configuration of all other servers is adjusted to match the declared configuration. As a result, Ansible Playbooks are describe as <strong>idempotent</strong>. An idempotent playbook can be executed repeatedly and result in the same final configuration.</p><h4>What can’I use Ansible for?</h4><p>Nearly anything, you can do:</p><ul><li>Configuration management</li><li>Applications deployment</li><li>Provisionning</li><li>Continuous Delivery</li><li>Security and Compliance</li><li>Orchestration</li></ul><h4>Architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4EAyz9C-fQWFUUlXoXFS-A.png" /></figure><p>To execute actions on hosts, we need two things:</p><ul><li><strong>Inventories</strong>: List of hosts, that can be static, or dynamically generated using an inventory script that pulls hosts list from an external source (Cloud provider, Change Management databases (CMDB) …)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Mokba6wfcXjHKVzpOtEoSg.png" /></figure><ul><li>Playbook which describes desired actions, It contains plays, plays contains tasks, and tasks call <strong>modules</strong></li></ul><p>Ansible then takes actions using SSH for linux and WinRM for windows Systems</p><p><strong>Modules:</strong></p><p>There are over 450 ansible-provided modules that automate nearly every part of your environment.</p><p>Modules generally follow the same structure:</p><blockquote>module: directive1=value directive2=value</blockquote><ul><li><em>Example:</em></li></ul><p>Let’s use what we call ad-hoc command to call directly the ping module using Ansible, to ping all hosts from the workers group</p><blockquote>$ ansible workers -m ping</blockquote><p>Or, let’s install apache on all infra-nodes using the yum module:</p><blockquote>$ ansible infra-nodes -m yum -a “name=httpd state=latest”</blockquote><p>To get a list of the provided modules, you can run:</p><blockquote>$ ansible-doc -l</blockquote><p>If the 450 modules aren’t enough for you, you can develop your own module using any programming language. You can start from <a href="https://docs.ansible.com/ansible/latest/dev_guide/developing_modules_general.html">here</a>.</p><h4>Ansible playbook</h4><p>Now that we know what modules are, how to use them in ad-hoc commands, let‘s see how to call them in a playbook:</p><p>Let’s assume that we want to do the following actions on infra-nodes servers:</p><ul><li>Install and configure Docker</li><li>Ensure Docker is started and enabled at boot</li><li>Ensure docker users are added to the docker group</li></ul><p>Here is what the final result of the playbook looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FzX5r-FfXfE-hdqbhMpb2Q.png" /></figure><p>Let’s see in detail what each line is for:</p><p><strong><em>2:</em> </strong>Group of hosts as defined in the inventory file.</p><p><strong><em>3 to 5</em>:</strong> When running this playbook, the user <strong>abdessamad</strong> will be used to connect to the hosts via ssh. Ansible allows you to ‘become’ another user, different from the user that logged into the machine (remote user), and use system privilege escalation to run some actions.</p><p><strong><em>6:</em></strong> You can define explicitly variables or include them from another file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EKM2FUVL5KyzvCaonIndtw.png" /></figure><p><strong><em>8 to 32:</em></strong> Get the GPG key, add docker repo to the hosts, disable test repo, install docker package and enable docker service at boot.</p><p><strong><em>33 to 42:</em></strong> Add docker_users (Its content is defined in the variables file) to docker group, so they can manage docker service. Finally restart docker service.</p><p><em>What if we want to share docker installation steps with other users, in the simplest way ? This what roles are used for.</em></p><h4>Roles</h4><p>Roles are ways of automatically loading certain vars_files, tasks, and handlers based on a known file structure. Grouping content by roles also allows easy sharing of roles with other users. Here’s the role structure:</p><pre>role/<br>  tasks/<br>  handlers/<br>  files/<br>  templates/<br>  vars/<br>  defaults/<br>  meta/</pre><ul><li>tasks - contains the main list of tasks to be executed by the role.</li><li>handlers - contains handlers, which may be used by this role or even anywhere outside this role.</li><li>defaults - default variables for the role (see <a href="https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html">Using Variables</a> for more information).</li><li>vars - other variables for the role (see <a href="https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html">Using Variables</a> for more information).</li><li>files - contains files which can be deployed via this role.</li><li>templates - contains templates which can be deployed via this role.</li><li>meta - defines some meta data for this role.</li></ul><p>Now instead of defining everything in the playbook, you can include only the docker role:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*PcvO4vbWjWLRWNZwt51TtA.png" /></figure><p><strong><em>You can find the role definition </em></strong><a href="https://github.com/bayzi/docker_role"><strong><em>here</em></strong></a></p><p>From now on, to use or share the role, you can easily download it and include it in your playbook, using ansible-galaxy <a href="https://galaxy.ansible.com/docs/">(I let you discover what it is )</a>.</p><h3>Back to the Sandbox</h3><p>As you can see, Ansible is simple, anyone can understand what a playbook is used for, no more complex scripts to be used, <strong>Dev</strong>elopers can work easily with <strong>Op</strong>erations Guys. <strong>This is DevOps.</strong></p><p>In <a href="https://medium.com/@abdessamad.bayzi/develop-the-devops-way-d5c8fc12a5c3">Part O</a>ne, we’ve seen the usage of <a href="https://github.com/bayzi/sandbox/blob/master/Vagrantfile">Vagrantfile</a>, you can see how we install all used roles in the roles directory using this command:</p><blockquote>$ ansible-galaxy install -r /vagrant/provisioning/requirements.yml -p /vagrant/provisioning/roles — force</blockquote><p>Since all roles definitions are in Github, We only need to specify in the requirements file the source, version and name of role to install:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*JYUMSG0HzKE0h98lKRW37A.png" /></figure><p>As we did earlier, we include the roles in the playbook, and we override the default variables with variables we defined in <strong><em>defaults/main.yml</em></strong> file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9sjXOb3_aNhYCVb5D4UeRQ.png" /></figure><p><strong>NB: You don’t need to install a role ? Delete it from the playbook :)</strong></p><p>The final project structure looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*CaK46ly2YSk2s5o27YXdTA.png" /></figure><p>Be free to start using this project, experiment new things and adapt it for your needs.</p><p>All used scripts can be found in my <a href="https://github.com/bayzi/sandbox">Github repo</a></p><p>Got questions? Loved it? Don’t agree? Talk to me in the comments below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=819eb0ceffa2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ocp-digital-factory/develop-the-devops-way-part-2-819eb0ceffa2">Develop the DevOps way — Part 2</a> was originally published in <a href="https://medium.com/ocp-digital-factory">OCP digital factory</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Develop the DevOps way — Part 1]]></title>
            <link>https://medium.com/ocp-digital-factory/develop-the-devops-way-part-1-5798603c527a?source=rss-885ac976f389------2</link>
            <guid isPermaLink="false">https://medium.com/p/5798603c527a</guid>
            <category><![CDATA[devops-tool]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[vagrant]]></category>
            <dc:creator><![CDATA[Abdessamad Bayzi]]></dc:creator>
            <pubDate>Mon, 30 Sep 2019 10:23:29 GMT</pubDate>
            <atom:updated>2019-11-19T18:44:04.308Z</atom:updated>
            <content:encoded><![CDATA[<h3>Develop the DevOps way — Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XIcKDKD8xa74XaDLa7Q9Zg.png" /></figure><p><em>Welcome to this DevOps series where I share about my experience experimenting some technical practices, that aims to ease some tasks when developing, and make development environment more similar to a production one, so the time spent on debugging environment problems may be used in code and infrastructure improvements.</em></p><ul><li>Develop the DevOps way-Part1: Vagrant</li><li><a href="https://medium.com/ocp-digital-factory/develop-the-devops-way-part-2-819eb0ceffa2">Develop the DevOps way-Part2:</a> Ansible</li><li><a href="https://medium.com/ocp-digital-factory/develop-the-devops-way-part-3-e9fe9f41806f">Develop the DevOps way-Part3</a>: Makefile and docker</li></ul><p>When starting or joining a project that’s been going on for a while, the first thing to do is to setup a development environment, which by the way might be time expensive, especially when no documentation is provided.</p><p>In the past, using a WAMP or MAMP stack was a common approach to setup quickly and easily a local development environment all to yourself. However this scenario is dirty, what if you need a specific version of PHP that differs from what MAMP provides? What if you want to use N<a href="http://nginx.org/">ginx</a> instead of Apache? Such environment is way far from a production one, and doesn’t promote standardization practices across development teams. For new joiners it’s difficult to know which version to install, since each member is using a different one, and if you’re solo and trying to innovate, It’s better to have a machine where you’ll find all you need already installed. So you can see how using the old approach quickly become problematic.</p><h3>Vagrant is here</h3><p>In the DevOps era, using a sandbox for development is a best practice. One of the implementations is using <a href="https://www.vagrantup.com/intro/index.html">Vagrant</a>, in addition you will use <a href="https://www.docker.com/resources/what-container">Docker</a> and <a href="https://www.ansible.com/overview/it-automation">Ansible</a>.</p><h4>What’s Vagrant</h4><p>Quoting Mitchell Hashimoto its creator: “Vagrant is a tool for managing virtual machines”. Vagrant generalizes virtual machine creation across multiple virtualization tools such as VirtualBox or VMware and even provides remote options for AWS, OpenStack or GCE. Vagrant configures and provisions virtual machines, based on configuration file called <strong><em>Vagrantfile</em></strong><em>. </em>The syntax of this file is the Ruby programming language and as it is a simple text file we can easily commit it to our project VCS repository.</p><h4>Implementation</h4><p>First, here’s an overview of what we’ll be implementing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GDv9kLv3dBtTtXYdMcls5g.png" /><figcaption>Sandbox Setup</figcaption></figure><h4>Step 1: Download and install required tools</h4><p>First, Install Virtualbox via this <a href="https://www.virtualbox.org/wiki/Downloads">link</a></p><ul><li>For Windows users, install git bash from <a href="https://gitforwindows.org/">here</a>, and make sure that Hyper-V is not enabled. You can turn off the feature by running this <a href="https://www.isunshare.com/windows-10/5-ways-to-open-windows-powershell-in-windows-10.html">Powershell</a> command:</li></ul><blockquote>Disable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V-All</blockquote><p>Depending on your OS, refer to this <a href="https://www.vagrantup.com/downloads.html">link</a> to install Vagrant</p><p>After installing vagrant, make sure to install <strong>vagrant-vbguest. </strong>It’s a <a href="http://vagrantup.com/">Vagrant</a> plugin which automatically installs the host’s VirtualBox Guest Additions on the guest system.</p><blockquote>vagrant plugin install vagrant-vbguest</blockquote><p>All done? Great! You now have more power than you know.</p><h4>Step 2:</h4><p>Using your terminal or Git Bash for windows users,</p><ul><li>create a directory named dev_env</li><li>change directory with</li></ul><blockquote>cd dev_env</blockquote><ul><li>Create a directory named <strong>data</strong> in dev_env directory. This is a shared folder between the VM and the host. This folder is where you’ll be creating your projects, so you can access it directly from your host using your preferred IDE.</li><li>clone the repo inside dev_env</li></ul><blockquote>git clone <a href="https://github.com/bayzi/sandbox.git">https://github.com/bayzi/sandbox.git</a></blockquote><p>Go to the repo, you’ll find a bunch of files and directories. We’ll get to know the usage of each one of them soon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*dWdQS8o39ftiD9EacLkDqQ.png" /></figure><p>Edit the email field in the provisioning/defaults/main.yml file. <strong><em>I suppose you’re using your email to connect to your VCS</em></strong>. If not, leave it empty and you’ll need then to setup git manually after the provisioning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sSZI7SihNQDapfelZje-mA.png" /></figure><p>Finally take a break and let the magic happen by running:</p><blockquote>vagrant up</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0O9lwvpQP_b8LpsMw0f6qw.png" /></figure><p><em>If you are on Windows, then you may get the following error</em></p><pre><em>==&gt; default: Booting VM... <br>There was an error while executing `VBoxManage`, a CLI used by Vagrant <br>for controlling VirtualBox. The command and stderr is shown below. <br> <br>Command: [&quot;startvm&quot;, &quot;1fe83aa1-2f23-4ddd-ad77-b7e7e00aabe6&quot;, &quot;--type&quot;, &quot;headless&quot;] <br> <br>Stderr: VBoxManage.exe: error: Failed to open/create the internal network &#39;HostInterfaceNetworking-VirtualBox Host-Only <br>Ethernet Adapter #3&#39; (VERR_INTNET_FLT_IF_NOT_FOUND). <br>VBoxManage.exe: error: Failed to attach the network LUN (VERR_INTNET_FLT_IF_NOT_FOUND) <br>VBoxManage.exe: error: Details: code E_FAIL (0x80004005), component ConsoleWrap, interface IConsole</em></pre><p><em>Note the Adapter referred here:</em></p><pre><em>VirtualBox Host-Only Ethernet Adapter #3</em></pre><p><em>Open Control Panel &gt;&gt; Network and Sharing Center. Now click on Change Adapter Settings. Right click on the adapter whose Name or the Device Name matches with VirtualBox Host-Only Ethernet Adapter # 3 and click on Properties. Click on the Configure button.</em></p><p><em>Now click on the Driver tab. Click on Update Driver. Select Browse my computer for drivers. Now choose Let me pick from a list of available drivers on my computer. Select the choice you get and click on Next. Click Close to finish the update. Now go back to your Terminal/Powershell/Command window and repeat the </em><strong><em>vagrant up</em></strong><em> command. It should work fine this time.</em></p><p>Once the provisioning is done, you can access your sandbox using:</p><blockquote>vagrant ssh</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*lwS9nEK65UwOaEtpoT19Eg.png" /></figure><p><strong><em>Bonus</em></strong><em>: If you’re wondering by chance, why the output indicates that my last login was from 10.0.2.2, refer to this </em><a href="https://stackoverflow.com/questions/33777041/why-10-0-2-2-was-not-there-with-running-ifconfig#answer-33777246"><em>link</em></a></p><p>BOOOM, now you’re officially in a new virtual world, happy coding :)</p><h3>What happens under the hood?</h3><p>The provisioned VM uses Centos 7 as base box and store it locally. Since we’re using IaC (<strong>Infrastructure as Code</strong>), all resource specifications are defined using code. This is what’s the <em>Vagrantfile</em> is for.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rQMsnPDMqZ34IuKK3k2iDQ.png" /></figure><p>In this file, we give the VM a name, we define the amount of memory to use, we fix the IP address of the VM, and we define the path to the shared folder.</p><p>The last part is <strong>provisioners. </strong>Vagrant offers a number of provisioners by default, including one for Shell, Ansible, Chef or Puppet, I’ve used the Shell provisioner so that the developer doesn’t have to use tools that he doesn’t really need on his machine . This provisioner will first <strong>update packages</strong> in the VM, install <strong>Ansible</strong>, <strong>git</strong>, <strong>python3</strong>, and finally <strong>use Ansible</strong> to do the rest.</p><p>In this blog post, I tried to show how beneficial is to use vagrant for setting a development environment on the fly. In the next post, we’ll take a closer look on Ansible, and how it’s used to install and configure:</p><ul><li>Git</li><li>Java</li><li>Maven</li><li>Nodejs</li><li>Docker</li><li>Kubectl (kubernetes cli)</li></ul><p>Got questions? Loved it? Don’t agree? Talk to me in the comments below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5798603c527a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ocp-digital-factory/develop-the-devops-way-part-1-5798603c527a">Develop the DevOps way — Part 1</a> was originally published in <a href="https://medium.com/ocp-digital-factory">OCP digital factory</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>