<?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 Atul Srivastava on Medium]]></title>
        <description><![CDATA[Stories by Atul Srivastava on Medium]]></description>
        <link>https://medium.com/@atulsrivastava2006?source=rss-8e1c78c0ac7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gvOnAdaOOvJSmyb9QwkOkw.jpeg</url>
            <title>Stories by Atul Srivastava on Medium</title>
            <link>https://medium.com/@atulsrivastava2006?source=rss-8e1c78c0ac7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 02:29:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@atulsrivastava2006/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[K8sGPT: Redefining Kubernetes Troubleshooting Through AI Integration]]></title>
            <link>https://atulsrivastava2006.medium.com/k8sgpt-redefining-kubernetes-troubleshooting-through-ai-integration-4ec6ee0385dc?source=rss-8e1c78c0ac7------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ec6ee0385dc</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[troubleshooting]]></category>
            <category><![CDATA[localai]]></category>
            <category><![CDATA[aiops]]></category>
            <category><![CDATA[k8sgpt]]></category>
            <dc:creator><![CDATA[Atul Srivastava]]></dc:creator>
            <pubDate>Thu, 25 Apr 2024 09:53:59 GMT</pubDate>
            <atom:updated>2024-04-25T09:53:59.175Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introduction</strong></h3><p>In the dynamic landscape of modern software development and deployment, Kubernetes has emerged as a cornerstone technology for managing containerized applications at scale. Its ability to automate deployment, scaling, and management of containerized workloads has revolutionized the way organizations build, deploy, and manage their applications. Simultaneously, advancements in artificial intelligence (AI) have opened new horizons for automation, optimization, and intelligent decision-making across various domains.</p><p>Enter <a href="https://github.com/k8sgpt-ai/k8sgpt">K8sGPT</a> — a tool for scanning your Kubernetes clusters, diagnosing, and triaging issues in simple English using AI. It detects issues in your kubernetes cluster and uses supported AI backends to recommend solutions for the issues detected.</p><p>In this blog, we embark on a journey to explore the convergence of Kubernetes and AI through the lens of K8sGPT.</p><h3>Installation</h3><p>K8sGPT offers two installation options: as a CLI on your workstation or as a Kubernetes operator within your cluster. For the purpose of this blog, we’ll focus on the CLI installation. If you’re interested in deploying the K8sGPT operator, you can find instructions <a href="https://github.com/k8sgpt-ai/k8sgpt?tab=readme-ov-file#operator-installation">here</a>.</p><p>To install k8sGPT as a CLI on your workstation, please follow the instructions from the official guide <a href="https://github.com/k8sgpt-ai/k8sgpt?tab=readme-ov-file#cli-installation">here</a>.</p><p>Below are the steps for Mac:</p><pre>brew tap k8sgpt-ai/k8sgpt<br>brew install k8sgpt</pre><p>To verify the installation:</p><pre>% k8sgpt --help<br>Kubernetes debugging powered by AI<br><br>Usage:<br>  k8sgpt [command]<br><br>Available Commands:<br>  analyze     This command will find problems within your Kubernetes cluster<br>  auth        Authenticate with your chosen backend<br>  cache       For working with the cache the results of an analysis<br>  completion  Generate the autocompletion script for the specified shell<br>  filters     Manage filters for analyzing Kubernetes resources<br>  generate    Generate Key for your chosen backend (opens browser)<br>  help        Help about any command<br>  integration Integrate another tool into K8sGPT<br>  serve       Runs k8sgpt as a server<br>  version     Print the version number of k8sgpt<br><br>Flags:<br>      --config string        Default config file (/Users/atul.srivastava/Library/Application Support/k8sgpt/k8sgpt.yaml)<br>  -h, --help                 help for k8sgpt<br>      --kubeconfig string    Path to a kubeconfig. Only required if out-of-cluster.<br>      --kubecontext string   Kubernetes context to use. Only required if out-of-cluster.<br><br>Use &quot;k8sgpt [command] --help&quot; for more information about a command.</pre><h3>LocalAI Setup</h3><p>While K8sGPT <a href="https://github.com/k8sgpt-ai/k8sgpt?tab=readme-ov-file#llm-ai-backends">offers various AI backends</a>, such as OpenAI by default, this blog will focus on setting up and utilizing LocalAI on your workstation. We’ll walk through the process of configuring K8sGPT to use LocalAI as its backend.</p><p>I preferred to build localAI from source on my Mac following the instructions below:</p><ol><li>Install xcode from App store.</li><li>Install build dependencies</li></ol><pre>% brew install abseil cmake go grpc protobuf wget</pre><p>3. Clone LocalAI github repo and build the binary.</p><pre>% git clone https://github.com/go-skynet/LocalAI.git<br>% cd LocalAI<br>% make build</pre><p>4. Download any supported model(s) from <a href="https://huggingface.co/models?search=ggml">https://huggingface.co/models?search=ggml</a> into the <em>models</em> directory. Models supported by LocalAI for instance are Vicuna, Alpaca, LLaMA, Cerebras, GPT4ALL, GPT4ALL-J and koala. I downloaded 2 models — <em>ggml-gpt4all-j</em> and<em> llama-2–7b-chat</em>.</p><pre># Download gpt4all model<br>% wget https://gpt4all.io/models/ggml-gpt4all-j.bin -O models/ggml-gpt4all-j<br><br># Use a template from the examples<br>% cp -rf prompt-templates/ggml-gpt4all-j.tmpl models/<br><br># Download llama-2-7b-chat model<br>% wget https://huggingface.co/TheBloke/Llama-2-7B-Chat-GGML/blob/main/llama-2-7b-chat.ggmlv3.q8_0.bin -O models/llama-2-7b-chat<br><br># Use a template from the examples<br>% cp -rf prompt-templates/llama2-chat-message.tmpl models/</pre><p>5. Start LocalAI</p><pre>% ./local-ai --models-path=./models/ --debug=true<br><br>1:39AM INF loading environment variables from file envFile=.env<br>1:39AM DBG Setting logging to debug<br>1:39AM INF Starting LocalAI using 4 threads, with models path: /Users/atul.srivastava/Documents/k8sgpt/LocalAI/LocalAI/models<br>1:39AM INF LocalAI version: v2.12.3-100-gd344daf (d344daf129e5d4504ce29ada434b6e6b1025ce31)<br>1:39AM INF Preloading models from /Users/atul.srivastava/Documents/k8sgpt/LocalAI/LocalAI/models<br>1:39AM DBG Extracting backend assets files to /tmp/localai/backend_data<br>1:39AM DBG processing api_keys.json<br>1:39AM DBG api keys loaded from api_keys.json<br>1:39AM DBG processing external_backends.json<br>1:39AM DBG external backends loaded from external_backends.json<br>1:39AM INF core/startup process completed!<br>1:39AM DBG No configuration file found at /tmp/localai/upload/uploadedFiles.json<br>1:39AM DBG No configuration file found at /tmp/localai/config/assistants.json<br>1:39AM DBG No configuration file found at /tmp/localai/config/assistantsFile.json<br>1:39AM INF LocalAI API is listening! Please connect to the endpoint for API documentation. endpoint=http://0.0.0.0:8080</pre><p>We now have a working AI setup in our workstation with the models downloaded above, ready to take requests on <a href="http://0.0.0.0:8080/"><em>http://0.0.0.0:8080</em></a><em>.</em></p><h3>Integrate LocalAI With K8sGPT</h3><p>With our LocalAI instance up and running, let’s integrate it as a backend for k8sGPT. We will utilize the “k8sgpt auth add” command to seamlessly incorporate the AI backend. Specify the backend type as “localai”, along with the LocalAI URL endpoint, and designate the desired model (in this case, “llama-2–7b-chat”) that was downloaded earlier.</p><pre>% k8sgpt auth add -b localai -u http://localhost:8080/v1 -m llama-2-7b-chat<br>localai added to the AI backend provider list</pre><h3>Detect And Fix Issues</h3><p>With all components ready, it’s time to unleash k8sGPT’s power to detect and resolve issues within our Kubernetes cluster. I’ve set up a test cluster on my laptop using <a href="https://kind.sigs.k8s.io/">kind</a>, and configured kubectl to interface with it.</p><p>k8sGPT cli can point to your cluster using your kubeconfig.</p><pre>% kubectl cluster-info<br>Kubernetes control plane is running at https://127.0.0.1:61960<br>CoreDNS is running at https://127.0.0.1:61960/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy</pre><p>To initiate issue detection, I’ll employ the “<em>k8sgpt analyze”</em> command. Since there are no deployments in the default namespace of the cluster yet, it’s anticipated that no issues will be uncovered.</p><pre>% k8sgpt analyze --namespace default<br>AI Provider: AI not used; --explain not set<br><br>No problems detected</pre><blockquote>Note: I intentionally omitted the “<em>--explain</em>” flag in the command, ensuring that k8sgpt refrains from contacting the AI backend to provide solutions. I’ll revisit this shortly.</blockquote><p>Next, I’ll proceed to deploy the following nginx deployment within the default namespace. Once deployed, the nginx containers from this deployment are expected to enter the CrashLoopBackOff state.</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: nginx-deployment<br>  labels:<br>    app: nginx<br>spec:<br>  replicas: 3<br>  selector:<br>    matchLabels:<br>      app: nginx<br>  template:<br>    metadata:<br>      labels:<br>        app: nginx<br>    spec:<br>      containers:<br>      - name: nginx<br>        image: nginx:1.14.2<br>        ports:<br>        - containerPort: 80<br>        securityContext:<br>          readOnlyRootFilesystem: true</pre><pre>% kubectl apply -f nginx-deployment.yml<br>deployment.apps/nginx-deployment created<br><br>% kubectl get pods -w<br>NAME                                READY   STATUS   RESTARTS      AGE<br>nginx-deployment-866dc6df9c-94hgg   0/1     Error    2 (18s ago)   20s<br>nginx-deployment-866dc6df9c-mj7zw   0/1     Error    2 (18s ago)   20s<br>nginx-deployment-866dc6df9c-vv5cs   0/1     Error    2 (19s ago)   20s<br>nginx-deployment-866dc6df9c-94hgg   0/1     CrashLoopBackOff   2 (12s ago)   26s<br>nginx-deployment-866dc6df9c-mj7zw   0/1     CrashLoopBackOff   2 (12s ago)   28s<br>nginx-deployment-866dc6df9c-vv5cs   0/1     CrashLoopBackOff   2 (12s ago)   30s</pre><p>Running “<em>k8sgpt analyze”</em> should detect these issues now.</p><pre>% k8sgpt analyze --namespace default<br>AI Provider: AI not used; --explain not set<br><br>0 default/nginx-deployment-866dc6df9c-94hgg(Deployment/nginx-deployment)<br>- Error: back-off 1m20s restarting failed container=nginx pod=nginx-deployment-866dc6df9c-94hgg_default(c5eb759a-048a-433a-a61c-99edc8aba72f)<br>- Error: the last termination reason is Error container=nginx pod=nginx-deployment-866dc6df9c-94hgg<br><br>1 default/nginx-deployment-866dc6df9c-mj7zw(Deployment/nginx-deployment)<br>- Error: back-off 1m20s restarting failed container=nginx pod=nginx-deployment-866dc6df9c-mj7zw_default(46cbddff-8299-48d8-a5d3-1dcf45c6d77d)<br>- Error: the last termination reason is Error container=nginx pod=nginx-deployment-866dc6df9c-mj7zw<br><br>2 default/nginx-deployment-866dc6df9c-vv5cs(Deployment/nginx-deployment)<br>- Error: back-off 1m20s restarting failed container=nginx pod=nginx-deployment-866dc6df9c-vv5cs_default(de927b1a-2457-40eb-a7c3-9807a3a23b8d)<br>- Error: the last termination reason is Error container=nginx pod=nginx-deployment-866dc6df9c-vv5cs</pre><p>I’ll now enable k8sGPT to communicate with my AI backend and provide solutions for the detected issues. To achieve this, I’ll execute the analyze command with the “ — <em>explain</em>” flag, specifying the AI backend name as well.</p><pre>% k8sgpt analyze --explain --backend localai --namespace default<br> 100% |████████████████████████████████████████████████████████████████████████████| (3/3, 2 it/min)<br>AI Provider: localai<br><br>0 default/nginx-deployment-866dc6df9c-94hgg(Deployment/nginx-deployment)<br>- Error: back-off 5m0s restarting failed container=nginx pod=nginx-deployment-866dc6df9c-94hgg_default(c5eb759a-048a-433a-a61c-99edc8aba72f)<br>- Error: the last termination reason is Error container=nginx pod=nginx-deployment-866dc6df9c-94hgg<br> Note: {Any additional information or warning you want to add}<br>--- english --- language;  back-off 5m0s restarting failed container=nginx pod=nginx-deployment-866dc6df9c-94hgg_default(c5eb759a-048a-433a-a61c-99edc8aba72f) the last termination reason is Error container=nginx pod=nginx-deployment-866dc6df9c-94hgg<br>Error: Container nginx failed to start due to an error.<br>Solution:<br>1. Check the container logs using kubectl exec to identify the error.<br>2. If the issue persists, try scaling down and up the deployment to reset the container.<br>3. If step 2 fails, try rolling back the deployment to a previous version.<br>Note: Be cautious when scaling or rolling back deployments, as it may cause data loss.</pre><p>k8sGPT established a connection with the AI backend and presented it with the error messages it identified, prompting for step-by-step solutions. Debug logs from LocalAI exhibit the prompts generated by k8sGPT and the corresponding responses received from LocalAI.</p><pre>2:41AM DBG Prompt (after templating): Simplify the following Kubernetes error message delimited by triple dashes written in --- english --- language; --- back-off 5m0s restarting failed container=nginx pod=nginx-deployment-866dc6df9c-94hgg_default(c5eb759a-048a-433a-a61c-99edc8aba72f) the last termination reason is Error container=nginx pod=nginx-deployment-866dc6df9c-94hgg ---.<br> Provide the most possible solution in a step by step style in no more than 280 characters. Write the output in the following format:<br> Error: {Explain error here}<br> Solution: {Step by step solution here}<br>2:41AM DBG Model already loaded in memory: llama-2-7b-chat<br>2:41AM DBG Model &#39;llama-2-7b-chat&#39; already loaded<br>2:41AM DBG Response: {&quot;created&quot;:1713989359,&quot;object&quot;:&quot;chat.completion&quot;,&quot;id&quot;:&quot;e63a7b2e-3745-46e1-a43c-80068ef50ac9&quot;,&quot;model&quot;:&quot;llama-2-7b-chat&quot;,&quot;choices&quot;:[{&quot;index&quot;:0,&quot;finish_reason&quot;:&quot;stop&quot;,&quot;message&quot;:{&quot;role&quot;:&quot;assistant&quot;,&quot;content&quot;:&quot;\tNote: {Any additional information or warning you want to add}\n--- english --- language;  back-off 5m0s restarting failed container=nginx pod=nginx-deployment-866dc6df9c-94hgg_default(c5eb759a-048a-433a-a61c-99edc8aba72f) the last termination reason is Error container=nginx pod=nginx-deployment-866dc6df9c-94hgg\nError: Container nginx failed to start due to an error.\nSolution:\n1. Check the container logs using kubectl exec to identify the error.\n2. If the issue persists, try scaling down and up the deployment to reset the container.\n3. If step 2 fails, try rolling back the deployment to a previous version.\nNote: Be cautious when scaling or rolling back deployments, as it may cause data loss.&quot;}}],&quot;usage&quot;:{&quot;prompt_tokens&quot;:0,&quot;completion_tokens&quot;:0,&quot;total_tokens&quot;:0}}</pre><p>The suggestions offered by k8sGPT can serve as actionable insights for engineers to resolve the above CrashLoopBackOff errors effectively. It can be integrated with tools like Slack to send out notifications and alerts along with remediation steps.</p><h3>Conclusion</h3><p>K8sGPT epitomizes the synergy between Kubernetes and AI. As we embrace its transformative potential, we embark on a journey towards a future where intelligent automation reshapes Kubernetes operations.</p><p>Our exploration of K8sGPT has merely touched the tip of its potential. This powerful tool not only enhances Kubernetes operations but also seamlessly integrates with other solutions, such as Trivy for vulnerability management, elevating its capabilities to new heights. For a deeper dive into its capabilities, I encourage you to explore the <a href="https://docs.k8sgpt.ai/">K8sGPT documentation</a> and unlock the full spectrum of its functionalities.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ec6ee0385dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Compliance As Code Using Inspec]]></title>
            <link>https://atulsrivastava2006.medium.com/compliance-as-code-using-inspec-595fe226601?source=rss-8e1c78c0ac7------2</link>
            <guid isPermaLink="false">https://medium.com/p/595fe226601</guid>
            <category><![CDATA[compliance-as-code]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[inspec]]></category>
            <category><![CDATA[compliance]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Atul Srivastava]]></dc:creator>
            <pubDate>Sat, 05 Dec 2020 17:46:44 GMT</pubDate>
            <atom:updated>2020-12-08T13:57:57.461Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DI3Pc0AYEmssxX-KQVegOA.jpeg" /></figure><h3><strong>Introduction</strong></h3><p>Companies spend considerable amount of time and resources in auditing their infrastructure for compliance and remediation.</p><p>With the increasing Cloud and DevOps adoption, automation is everywhere. <br>For example, infrastructure provisioning is automated using “Infrastructure As Code” with tools like <a href="https://www.terraform.io/">terraform</a>.</p><p><strong><em>Similarly, why not automate the compliance checks using Compliance As Code?</em></strong></p><h4>What is Compliance As Code?</h4><p>Compliance As Code is the process of codifying the compliance checks and regulations for Infrastructure using a machine-readable script or definition file.</p><p>In this blog, we will look at how <strong>Inspec</strong> can be used to codify our compliance checks to achieve Compliance As Code.</p><h4>Inspec (Inspect Your Infrastructure)</h4><p><a href="https://docs.chef.io/inspec/">Chef Inspec</a> is an open source tool which is used to codify audit and security requirements and run automated audits for applications and infrastructure. Inspec is similar to the popular tool <a href="https://serverspec.org/">serverspec</a>, it provides<br>a framework to define rules in the form of human and machine readable language using Inspec DSL. Applications and infrastructure can be scanned against the rules defined in inspec to check for compliance.</p><p>To install Inspec follow <a href="https://docs.chef.io/inspec/install/">these</a> instructions.</p><p>Let’s jump to a simple example to understand how inspec code looks like. Inspec is ruby based so all the inspec code is written in <strong>.rb</strong> files.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b104f18dff52f7f31cec67aa0831478/href">https://medium.com/media/3b104f18dff52f7f31cec67aa0831478/href</a></iframe><blockquote>Can you guess what is going on above? I am sure you got it; it’s human and machine readable code<em>.</em></blockquote><p>The code above expects package “<em>ntp</em>” to be installed on the machine where it will be executed.</p><p>Inspec code follows the below format:</p><pre>describe &lt;resource_to_be_tested&gt; do<br>   it { &lt;expectations&gt; }<br>end</pre><p>Let’s break down the code further to get better clarity:</p><ul><li><strong><em>describe</em>:</strong> describe is used to declare a block for the resource we are going to test. A resource is a configuration item under test like a package, service, user etc. The <em>do</em> and <em>end</em> keywords define a <a href="https://www.rubyguides.com/2016/02/ruby-procs-and-lambdas/#Understanding_Ruby_Blocks">ruby block</a>.</li><li><strong><em>resource_to_be_tested</em>:</strong> This is the resource or the configuration item which is being tested, example a package, file, user, service etc.</li><li><strong><em>expectations</em>:</strong> Defines the expected state of the <em>resource_to_be_tested</em>. Example, a package should be installed, a service should be running etc.</li><li><strong><em>it</em>:</strong> This statement enables us to test the resource in question and compare its state against the expectations defined by us. A “<em>describe</em>” block can have<br>multiple “<em>it</em>” statements, each checking a particular state of the resource. We can also use “<em>its</em>” which is used to check the features of the resource like its permissions, ownership, version etc.</li><li><strong><em>should</em>:</strong> defines the expectations and checks if the expectation is true. Also, there is “<em>should_not”</em> which checks if the expectation is false.</li><li><strong><em>be_installed</em>:</strong> is an inspec <a href="https://docs.chef.io/inspec/matchers/">matcher</a> which in our example is comparing “<em>ntp’s</em>” actual state to the expected state. According to us “<em>ntp”</em> should <a href="https://docs.chef.io/inspec/resources/package/#be_installed"><em>be_installed</em></a> .</li></ul><h4>Inspec Controls</h4><p>You must be wondering what if we have multiple such tests to run on a machine? How should the inspec code be written and run? How can we scale whatever we learned so far? How to use inspec for compliance?</p><p>To answer above questions, let’s understand more about inspec.</p><p>Inspec framework provides more than just the tests we saw so far. We can write multiple tests using the <em>describe</em> blocks and group them together into something called <em>control</em>. <em>Controls</em> provide a structure and metadata to the tests we define. This makes it easier for anyone to read and understand our tests even if they are not familiar with inspec.</p><p>Let’s look at another example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7e6ee050a1b409fcd9d477295683eb4/href">https://medium.com/media/c7e6ee050a1b409fcd9d477295683eb4/href</a></iframe><p>Here, we are using two <a href="https://docs.chef.io/inspec/resources/">inspec resources</a>, in two <em>describe</em> blocks, grouped together in a <em>control</em> block:</p><ul><li><a href="https://docs.chef.io/inspec/resources/sshd_config/"><em>sshd_config</em></a> which is used to test configuration for ssh daemon</li><li><a href="https://docs.chef.io/inspec/resources/file/"><em>file</em></a> to check the properties of sshd conf file.</li></ul><p>Our intention is to check if the protocol version used by ssh is “2” and its config file has the right permissions and ownership.</p><p>A <em>control</em> is similar to a <em>describe</em> block with a <em>do</em> and <em>end </em>and<em> </em>it has:</p><ul><li>A unique id for control like “<strong><em>sshd-1</em></strong>”</li><li><strong><em>impact:</em></strong><em> </em>is a number between 0 to 1, used to define the criticality of the control (1 being the most critical).</li><li><strong><em>title:</em></strong><em> </em>is a human readable title for the control.</li><li><strong><em>desc: </em></strong>Description of the control and what is being tested.</li></ul><h4>Inspec Profile</h4><p>The above code is enough and can be executed on machines but it is recommended to create an inspec <a href="https://docs.chef.io/inspec/profiles/">profile</a>. Inspec profile helps in versioning your <em>controls</em>, define dependencies with other profiles and you can group multiple controls together in a profile.</p><p>Let’s go ahead and create a new profile called “<strong><em>my_sshd”</em></strong> to check the sshd config settings. We will use the “<strong><em>inspec init profile”</em></strong> command for this. For a list of inspec commands run “<strong><em>inspec --help</em></strong><em>”</em>.</p><pre>inspec init profile my_sshd</pre><p>This should return output similar to this:</p><pre>+---------------------------------------------+<br>            Chef License Acceptance</pre><pre>Before you can continue, 1 product license<br>must be accepted. View the license at<br><a href="https://www.chef.io/end-user-license-agreement/">https://www.chef.io/end-user-license-agreement/</a></pre><pre>License that need accepting:<br>  * Chef InSpec</pre><pre>Do you accept the 1 product license (yes/no)?</pre><pre>&gt; yes</pre><pre>Persisting 1 product license...<br>✔ 1 product license persisted.</pre><pre>+---------------------------------------------+</pre><pre>───────────────── InSpec Code Generator ───────────────────</pre><pre>Creating new profile at /Users/atul/inspec-profiles/my_sshd<br> • Creating file README.md<br> • Creating directory controls<br> • Creating file controls/example.rb<br> • Creating file inspec.yml</pre><p>Read more about the profile structure <a href="https://docs.chef.io/inspec/profiles/#profile-structure">here</a>.</p><p>We will now write the below code in the <em>controls/example.rb</em> file and have our inspec profile ready. The code below is self explanatory so I won’t try to explain it again. Please note that multiple <em>control</em> statements are added together to make a complete profile and that the example sshd control “<em>sshd-1</em>” we saw earlier is split into two <em>control</em> blocks “<em>sshd-1</em>” and “<em>sshd-2</em>”.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5699423bd31a289cd8be83d26af6c8cc/href">https://medium.com/media/5699423bd31a289cd8be83d26af6c8cc/href</a></iframe><h4>How to run this?</h4><p>Now let’s jump on to scanning a machine against our profile and check if the machine is compliant !</p><p>We will use the<strong> </strong><a href="https://docs.chef.io/inspec/cli/#exec"><strong><em>inspec exec</em></strong></a> command to run the scan.</p><blockquote>Please note that inspec doesnt need any agent running on your machines, all it needs is ssh access for linux and winrm for windows machines. It can also scan docker containers.</blockquote><pre>inspec exec my_sshd -t ssh://&lt;user&gt;@&lt;hostname&gt; -i /path/to/private/key</pre><blockquote>Here <strong><em>-t </em></strong>refers to the target to be scanned and <strong>ssh</strong> is used to connect to the target, in our case it’s a virtual machine but it could be a docker container too.</blockquote><p>This will return output similar to below and a summary will be presented at the end with the controls which failed or passed:</p><pre>Profile: InSpec Profile (my_sshd)<br>Version: 0.1.0<br>Target:  ssh://&lt;user&gt;@&lt;hostname&gt;:22</pre><pre>✔  sshd-1: Specify protocol version 2<br>     ✔  SSHD Configuration Protocol is expected to eq &quot;2&quot;<br>  ✔  sshd-2: Check sshd config file owner, group and permissions<br>     ✔  File /etc/ssh/sshd_config is expected to exist<br>     ✔  File /etc/ssh/sshd_config is expected to be file<br>     ✔  File /etc/ssh/sshd_config is expected to be owned by &quot;root&quot;<br>     ✔  File /etc/ssh/sshd_config is expected not to be executable<br>     ✔  File /etc/ssh/sshd_config is expected to be readable by owner<br>     ✔  File /etc/ssh/sshd_config is expected to be writable by owner<br>  ✔  sshd-3: Enable StrictModes<br>     ✔  SSHD Configuration StrictModes is expected to eq &quot;yes&quot;<br>  ×  sshd-4: VERBOSE Loglevel<br>     ×  SSHD Configuration LogLevel is expected to eq &quot;VERBOSE&quot;</pre><pre>expected: &quot;VERBOSE&quot;<br>          got: &quot;INFO&quot;</pre><pre>(compared using ==)</pre><pre>✔  sshd-5: Max Sessions<br>     ✔  SSHD Configuration MaxSessions is expected to eq &quot;10&quot;<br>  ×  sshd-6: Disable password based authentication<br>     ×  SSHD Configuration PasswordAuthentication is expected to eq &quot;no&quot;</pre><pre>expected: &quot;no&quot;<br>          got: &quot;yes&quot;</pre><pre>(compared using ==)</pre><pre>✔  sshd-7: Disable root login<br>     ✔  SSHD Configuration PermitRootLogin is expected to eq &quot;no&quot;</pre><pre>Profile Summary: 5 successful controls, 2 control failures, 0 controls skipped<br>Test Summary: 10 successful, 2 failures, 0 skipped</pre><p>We can now push this inspec profile to a version control system and track the changes.</p><blockquote><strong><em>inspec exec</em></strong> command can execute the profiles from our local machine, github repos, Chef Automate Server, Chef Supermarket, a http(s) urls hosting our inspec profile. For more details, please refer the <a href="https://docs.chef.io/inspec/cli/#exec">inspec docs</a>.</blockquote><blockquote>There are many profiles available in <a href="https://github.com/dev-sec">github</a> and in <a href="https://supermarket.chef.io/tools?type=compliance_profile">chef supermarket</a>.</blockquote><p>Let’s run the linux-baseline profile directly from <a href="https://github.com/dev-sec/linux-baseline">dev-sec github repo</a>.</p><pre>inspec exec <a href="https://github.com/dev-sec/linux-baseline.git">https://github.com/dev-sec/linux-baseline.git</a> -t ssh://&lt;user&gt;@&lt;hostname&gt; -i /path/to/private/key</pre><p>The output of the above command is long so I have truncated it below.</p><pre>Profile: DevSec Linux Security Baseline (linux-baseline)<br>Version: 2.6.0<br>Target:  ssh://&lt;user&gt;@&lt;hostname&gt;:22</pre><pre>✔  os-01: Trusted hosts login<br>     ✔  File /etc/hosts.equiv is expected not to exist<br>  ✔  os-02: Check owner and permissions for /etc/shadow<br>     ✔  File /etc/shadow is expected to exist<br>     ✔  File /etc/shadow is expected to be file<br>     ✔  File /etc/shadow is expected to be owned by &quot;root&quot;<br>     ✔  File /etc/shadow is expected not to be executable<br>     ✔  File /etc/shadow is expected not to be readable by other<br>     ✔  File /etc/shadow group is expected to eq &quot;root&quot;<br>     ✔  File /etc/shadow is expected not to be writable by owner<br>     ✔  File /etc/shadow is expected not to be readable by owner<br>     ✔  File /etc/shadow is expected not to be readable by group<br>  ✔  os-03: Check owner and permissions for /etc/passwd<br>     ✔  File /etc/passwd is expected to exist<br>     ✔  File /etc/passwd is expected to be file<br>     ✔  File /etc/passwd is expected to be owned by &quot;root&quot;<br>     ✔  File /etc/passwd is expected not to be executable<br>     ✔  File /etc/passwd is expected to be writable by owner<br>     ✔  File /etc/passwd is expected not to be writable by group<br>     ✔  File /etc/passwd is expected not to be writable by other<br>     ✔  File /etc/passwd is expected to be readable by owner<br>     ✔  File /etc/passwd is expected to be readable by group<br>     ✔  File /etc/passwd is expected to be readable by other<br>     ✔  File /etc/passwd group is expected to eq &quot;root&quot;<br>  ✔  os-03b: Check passwords hashes in /etc/passwd<br>     ✔  /etc/passwd passwords is expected to be in &quot;x&quot; and &quot;*&quot;<br>  ✔  os-04: Dot in PATH variable<br>     ✔  Environment variable PATH split is expected not to include &quot;&quot;<br>     ✔  Environment variable PATH split is expected not to include &quot;.&quot;<br><br> <br>//output truncated//</pre><pre>Profile Summary: 27 successful controls, 26 control failures, 2 controls skipped<br>Test Summary: 65 successful, 50 failures, 2 skipped</pre><p>Similarly, we can run any profile available from the community, like CIS based profiles from <a href="https://github.com/dev-sec/cis-dil-benchmark">https://github.com/dev-sec/cis-dil-benchmark</a>.</p><h4>Conclusion</h4><p>We have only scratched the surface and learned how inspec can be used to codify the compliance regulations and guidelines. There is a lot more to inspec and its capabilities as a compliance automation tool.</p><ul><li>We saw how compliance checks can be automated using inspec and how to achieve Compliance As Code.</li><li>The idea here is to codify all your compliance checks and automatically scan your infrastructure with inspec to detect issues.</li><li>Machines detected with issues can be hardened/remediated using tools like chef/ansible/puppet.</li><li>Run automated compliance audits using inspec, by integrating it with your CI CD pipelines to proactively detect and fix vulnerabilities.</li></ul><h4>Further Reading …</h4><p>I would strongly recommend the following resources.</p><ul><li><a href="https://github.com/inspec/inspec">inspec/inspec</a></li><li><a href="https://docs.chef.io/inspec/platforms/">Using Chef InSpec on Cloud Platforms</a></li><li><a href="https://docs.chef.io/inspec/profiles/">About Chef InSpec Profiles</a></li><li><a href="https://github.com/dev-sec">DevSec Hardening Framework</a></li><li><a href="https://dev-sec.io/">DevSec Hardening Framework</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=595fe226601" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>