<?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 Tin Plavec on Medium]]></title>
        <description><![CDATA[Stories by Tin Plavec on Medium]]></description>
        <link>https://medium.com/@tinplavec?source=rss-ab4361e8ec33------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*WCi_Zc7kq7ZFooYfeYPPnA.jpeg</url>
            <title>Stories by Tin Plavec on Medium</title>
            <link>https://medium.com/@tinplavec?source=rss-ab4361e8ec33------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 07:57:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tinplavec/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[Overview of MicroK8s — Deploy Your Own Kubernetes Cluster With Just One Command]]></title>
            <link>https://itnext.io/overview-of-microk8s-deploy-your-own-kubernetes-cluster-with-just-one-command-0e65fd803f3e?source=rss-ab4361e8ec33------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e65fd803f3e</guid>
            <category><![CDATA[kubernetes-cluster]]></category>
            <category><![CDATA[microk8s]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[ubuntu]]></category>
            <dc:creator><![CDATA[Tin Plavec]]></dc:creator>
            <pubDate>Sun, 22 Sep 2024 22:10:41 GMT</pubDate>
            <atom:updated>2024-09-22T22:10:41.448Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fO3zQyGUwAgA2eJr" /><figcaption>Photo by <a href="https://unsplash.com/@theshubhamdhage?utm_source=medium&amp;utm_medium=referral">Shubham Dhage</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Overview of MicroK8s — Deploy Your Own Kubernetes Cluster With Just One Command</h3><h3>Introduction</h3><p>MicroK8s is a user-friendly package for deploying and running a Kubernetes cluster. It is developed by Canonical, the company behind Ubuntu, but it works on other Linux systems, and you can even run it on Windows and MacOS. The basic MicroK8s cluster deployment uses just 540 MB of memory, but obviously you will need more to run your own workloads in the cluster. You can install MicroK8s on your personal computer or, if you want to run it long-term, on a server. Today, you can get yourself a VPS for cheap.</p><p>According to their website, MicroK8s is suitable for running production-grade clusters. You can install it on multiple machines and then join the nodes into a high-availability cluster. Personally I don’t know anyone who is using MicroK8s in production — most companies rely on big cloud providers like AWS, Azure and GCP. In this article I will focus on running a simple cluster that you can use for experimenting with Kubernetes or running some workloads that are not super important. This will not be a step-by-step tutorial, but an overview on what MicroK8s has to offer.</p><h3>The basics</h3><p>After a simple snap install, you can run microk8s status to check if the cluster is properly running.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*X6_GJu43Fs-Iw-p0ivOTvQ.png" /><figcaption>MicroK8s running status and addons list</figcaption></figure><p>If the cluster is not running, you can run it with just one command: microk8s start . To stop it, run microk8s stop . By default, MicroK8s will automatically start running when your OS starts running, so you don’t have to worry about restarts. When the cluster starts again after a restart, the old state will be restored — no data will be lost. Detailed steps on how to install MicroK8s can be found <a href="https://microk8s.io/docs/getting-started">here</a>. If you’re not using Linux, look <a href="https://microk8s.io/docs/install-alternatives">here</a>.</p><h3>Kubectl</h3><p>MicroK8s provides a simple and straightforward access to Kubernetes API with microk8s kubectl . It’s the normal kubectl CLI that uses Kubeconfig of your MicroK8s cluster. Let’s make a simple deployment using the CLI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*klqP9_mKoltZCsCpHnXmUQ.png" /><figcaption>Creating deployment with Kubectl</figcaption></figure><p>In case you want to access the cluster from outside world or using kubectl of your host machine, you will need to extract the Kubeconfig. The command microk8s config will output the Kubeconfig file that you can simply copy-paste wherever you need it. Note that this Kubeconfig has admin privileges on the cluster. Additionally, to access your cluster from outside world, you will need to configure host’s firewall to pass traffic to the Kubernetes API.</p><h3>Addons</h3><p>MicroK8s offers numerous useful built-in addons. I’ll cover some of them.</p><h4><a href="https://microk8s.io/docs/addon-dns">DNS</a></h4><p>This is the most basic addon that enables internal DNS (CoreDNS). Without it, Kubernetes Service resource will not be able to route the traffic to pods. You should definitely enable this addon. Also, this addon is required for other network addons.</p><h4><a href="https://microk8s.io/docs/addon-ingress">Ingress</a></h4><p>This addon will install NGINX Ingress Controller. Now you can create Ingress resources and access your cluster services from outside the cluster.</p><h4><a href="https://microk8s.io/docs/addon-hostpath-storage">Hostpath Storage</a></h4><p>In case you’re deploying a database or any other stateful app with persistent storage, you should enable this addon. It will enable the creation of PVCs bound to the node storage, i.e. hostpath storage. Set the storageClassName of a PVC to microk8s-hostpath , and the PVC will be stored in a directory on the host machine.</p><h4><a href="https://microk8s.io/docs/multi-user">RBAC</a></h4><p>This addon enables role based access to the cluster. You are now able to create roles and role bindings. Note that you will have to implement user authentication by yourself.</p><h4><a href="https://microk8s.io/docs/registry-built-in">Registry</a></h4><p>In case you don’t already have a Docker registry, you can use the built-in registry. The registry will be deployed inside the cluster at the port 32000 . So, to push a Docker image to the registry, tag it like localhost:32000/app:tag .</p><h4><a href="https://kubernetes-sigs.github.io/metrics-server/">Metrics Server</a></h4><p>The Metrics Server enables you to use kubectl top command to quickly check basic metrics of the nodes and the pods. You can check CPU and memory usage. These metrics are also used by Kubernetes to autoscale deployments.</p><h4><a href="https://prometheus.io/">Prometheus</a></h4><p>To get a better overview of the metrics, enable the Prometheus addon that will deploy Prometheus Server to the cluster. Furthermore, the metrics can be sent <a href="https://microk8s.io/docs/external-lma">outside the cluster</a>.</p><p>There are more built-in addons like <strong>Host Access</strong>, <strong>Minio</strong>, <strong>MetalLB</strong>, <strong>NVIDIA</strong> <strong>GPU </strong>and so on.<strong> </strong>The full list is <a href="https://microk8s.io/docs/addons">here</a>.</p><h4>Community</h4><p>The Community addon enables you to enable addons made by the community. These addons install a third-party service like <strong>Argo CD</strong>, <strong>Istio</strong>, <strong>Knative</strong>, <strong>ngrok</strong>, <strong>Portainer</strong>, <strong>Trivy</strong> and so on. The full list is <a href="https://microk8s.io/docs/addons#heading--community">here</a>.</p><h3>Upgrading Kubernetes</h3><p>The version of the Kubernetes cluster is dictated by the version of the MicroK8s snap package. So, to upgrade Kubernetes you need to upgrade the snap package, i.e. select a different snap channel. A channel represents one minor version of Kubernetes. For example, channel 1.29/stable runs on Kubernetes 1.29. Patch versions are automatically updated by snap in the background. So, to upgrade from 1.29 to 1.30, you would run a command like this:</p><pre>snap refresh microk8s --channel=1.30/stable</pre><p>Never skip versions — always upgrade one minor version at a time.</p><p>Canonical offers different tiers of channels. stable channels are tracking stable Kubernetes releases with a one-week delay. beta channels are tracking beta Kubernetes releases with a few-hour delay, while edge channels are tracking alpha releases. There are also candidate channels that track candidate Kubernetes releases. These are versions of Kubernetes that are just about to be released as stable. Most likely you will use stable channels.</p><h3>Conclusion</h3><p>I use MicroK8s to run my own personal Kubernetes cluster, on an Ubuntu VPS. It’s useful when you quickly want to deploy some simple project and expose it to the world. It’s actually quite reliable, while not using too much system resources. The only downside is that you need snap to install it — it’s not available with other package managers. As mentioned, MicroK8s is usually not used in production, but you can try their HPA clusters, and see if it works for you. One advantage of MicroK8s service compared to Kubernetes services on big cloud providers is that you can get the latest Kubernetes release almost instantly after it’s been released. Thank you for reading and I hope that you now have a better idea of what Canonical’s MicroK8s has to offer. It’s a fairly simple tool to deploy your own Kubernetes cluster, including useful addons for the cluster.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e65fd803f3e" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/overview-of-microk8s-deploy-your-own-kubernetes-cluster-with-just-one-command-0e65fd803f3e">Overview of MicroK8s — Deploy Your Own Kubernetes Cluster With Just One Command</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Keep Your Remote Directory Up To Date With Rsync And Unison]]></title>
            <link>https://itnext.io/keep-your-remote-directory-up-to-date-with-rsync-and-unison-86811532ad83?source=rss-ab4361e8ec33------2</link>
            <guid isPermaLink="false">https://medium.com/p/86811532ad83</guid>
            <category><![CDATA[ssh]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[rsync]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[unison]]></category>
            <dc:creator><![CDATA[Tin Plavec]]></dc:creator>
            <pubDate>Tue, 20 Feb 2024 14:35:55 GMT</pubDate>
            <atom:updated>2024-02-20T14:35:55.904Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re reading this article, you’ve most likely used SSH to connect to a remote server and SCP (Secure copy protocol) to copy files between the computers. This works great if you just need to copy one file (or a directory) that you will not modify later. But, if you’re developing an app or a machine learning program that you want to run on a remote server, you will find yourself constantly copying files and directories. The easiest way is to copy the root directory of your project, but this means that each file in the directory will be copied every time, even if you change just one line in one of the files. If you have big files, this process will be quite inefficient. That’s why you should use Rsync or Unison.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7-Fp-q8OOaanY0Ct" /><figcaption>Photo by <a href="https://unsplash.com/@viktortalashuk?utm_source=medium&amp;utm_medium=referral">Viktor Talashuk</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Rsync</h3><p>Rsync, quite literally <em>remote sync</em>, is a Unix tool for syncing files over the network. It comes built-in with many Linux systems, and it’s also ported to Windows. It uses SSH to transport files on demand. Rsync checks your source directory and compares it with the remote directory. When it detects that the modification time of a source file doesn’t match the modification time of the remote file, it initiates file copying. Files that are already up to date will not be copied to the remote machine.</p><p>Rsync is very simple to use. To sync a directory, run:</p><pre>rsync -a mydir/ user@remote:mydir</pre><p>This will copy the contents of local mydir to remote mydir . You need to have SSH access to the remote server to do this. The option -a means that copying is recursive and that symbolic links are preserved. I also recommend to always put trailing slash for the source directory. If there’s no slash after the source directory, then the source directory itself will copied into the destination directory. With the slash, the content of the source directory is copied. You can also put ./ for the source directory. In that case, the content of the current directory will be copied into the remote mydir . Remote destination is specified in the same way as for SCP: user@server:/absolute_path or user@server:relative_path_from_user_home .</p><p>You can also sync directories the other way around, from remote to local, however you can’t sync both ways at the same time:</p><pre>rsync -a user@remote:mydir/ mydir</pre><p>By default, Rsync doesn’t delete files. To enable deletion, use --delete flag. All files that exist in thedestination directory, but don’t exist in source directory will be deleted from the destination directory. Be cautious when using this flag, and actually, don’t use it if it’s not necessary.</p><h3>Unison</h3><p>Unison is made for syncing files simultaneously in both ways. You can think of Rsync as <em>half-duplex</em> and Unison as <em>full-duplex</em>. Unison doesn’t come preinstalled, but it’s available in almost every package manager on Linux, macOS and Windows. The list is <a href="https://github.com/bcpierce00/unison/wiki/Obtaining-Unison-Sources-and-Binaries#packaging-systems">here</a>. On Ubuntu, you can install it with:</p><pre>sudo apt install unison</pre><p>Don’t forget to install it on both local and remote computer. The basic command to sync two directories using SSH protocol is:</p><pre>unison source/ ssh://user@remote/destination</pre><p>The slash after source directory is not necessary. To specify an absolute path for the remote destination, put two slashes after the remote hostname: ssh://user@remote//home/user/destination .</p><h4>OK, let’s try it out.</h4><p>Create a local mydir with files afile and bfile .</p><pre>plavy@local:~$ ls mydir<br>afile  bfile</pre><p>Next, make sure you have SSH access to the remote server and that the remote server has Unison installed. Now, we can run Unison locally.</p><pre>plavy@local:~$ unison mydir ssh://plavy@remote/mydir</pre><p>On the first run, you will get a prompt like this:</p><pre>Looking for changes<br>Warning: No archive files were found for these roots, whose canonical names are:<br> /home/plavy/mydir<br> //remote//home/plavy/mydir<br>This can happen either<br>because this is the first time you have synchronized these roots, <br>or because you have upgraded Unison to a new version with a different<br>archive format.</pre><p>This happens because Unison didn’t find a state file for synchronization of these two directories.</p><blockquote><em>Unison uses a </em><strong><em>state file</em></strong><em> to track what computer makes what changes to the files. It is somewhat similar to how Git and other version control systems work. Imagine two people committing to the same branch. Git needs to track changes and make sure that the two people are not trying to make a conflicting change to some file. Yes, Unison can also encounter conflicts when syncing files.</em></blockquote><p>You can press return to dismiss the previous prompt. Unison will now show you what changes will be made. In our case, a directory will be copied from the local to the remote computer. You need to type y to confirm the update.</p><pre>local          remote       <br>dir      ----&gt;              [f] <br><br>Proceed with propagating updates? [] y<br>Propagating updates</pre><p>Now SSH to the remote server and check out mydir in your home directory.</p><pre>plavy@local:~$ ssh remote<br>plavy@remote:~$ ls mydir<br>afile  bfile</pre><p>Let’s create a new file on both the remote and local computer, and sync it.</p><pre>plavy@remote:~$ touch mydir/cfile<br>---<br>plavy@local:~$ touch mydir/dfile <br>plavy@local:~$ unison mydir ssh://remote/mydir</pre><p>Make sure that you’re always running Unison on the same computer, i.e. on the local computer.</p><pre>local          remote       <br>         &lt;---- new file   cfile  [f] <br>new file ----&gt;            dfile  [f] <br><br>Proceed with propagating updates? [] y<br>Propagating updates</pre><p>Unison detected new files and will sync them simultaneously. Both local and remote directory now have all four files. That was easy, but what if we create a conflict? Let’s add different text to the same file and try to sync.</p><pre>plavy@remote:~$ echo &quot;important&quot; &gt; mydir/cfile<br>---<br>plavy@local:~$ echo &quot;more important&quot; &gt; mydir/cfile <br>plavy@local:~$ unison mydir ssh://remote/mydir</pre><p>We need to resolve a conflict. Type either &lt; or &gt; to indicate direction of overwriting the file.</p><pre>local          remote       <br>changed  &lt;-?-&gt; changed    cfile  [] &gt;</pre><p>I typed &gt; , which means that the local file will take precedence. Finally, you can check the files to make sure the content is the same on both computers.</p><pre>plavy@remote:~$ cat mydir/cfile<br>more important<br>---<br>plavy@local:~$ cat mydir/cfile <br>more important</pre><h3>Conclusion</h3><p>To conclude, both Rsync and Unison are good options for synchronizing directories on different computers. If you’ll be copying files only in one direction, use Rsync. If you’ll need to copy files both ways, use Unison. For example, Unison would be useful if you’re training an AI model on a remote server. First, you write the code locally, then copy the directory to the remote server with Unison, run the training, and copy the model data back to your computer with the same Unison command. No need to do manual copying with SCP. Also, Unison will always inform you about the changes that it’s going to apply, which is a good safety mechanism.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86811532ad83" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/keep-your-remote-directory-up-to-date-with-rsync-and-unison-86811532ad83">Keep Your Remote Directory Up To Date With Rsync And Unison</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[4 Free, Easy-To-Use Tools For Docker Vulnerability Scanning]]></title>
            <link>https://itnext.io/4-free-easy-to-use-tools-for-docker-vulnerability-scanning-bb73342c0faa?source=rss-ab4361e8ec33------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb73342c0faa</guid>
            <category><![CDATA[snyk]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[devsecops]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Tin Plavec]]></dc:creator>
            <pubDate>Fri, 22 Dec 2023 14:39:21 GMT</pubDate>
            <atom:updated>2023-12-22T14:45:28.734Z</atom:updated>
            <content:encoded><![CDATA[<h4>Run them locally or easily integrate them into your CI/CD pipeline, in line with DevSecOps principles.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*s-peJcCAeLXLf8PbGdBn2A.png" /><figcaption>Generated by Stable Diffusion</figcaption></figure><p>I was recently looking for a tool that scans Docker images for vulnerabilities and that can be easily integrated into CI/CD. I’ve found a lot of the tools, but some were quite old and not so intuitive. Here is a list of the tools that are free, up to date, and — easy to use.</p><p>All of these tools work similarly. They use a two-step process:</p><ol><li>Generate Software Bill of Materials (SBOM).</li><li>Compare the SBOM with different vulnerability databases.</li></ol><p>The first step sounds fancy, but it’s actually not that interesting. SBOM is a list of all the dependency packages that are installed in order to run an app. In this case all the packages in a Docker image, both system and application packages. The system packages are often overlooked, so it’s important to have Docker scanning in your pipeline. That leads us to the second step where every package from SBOM is tested against multiple vulnerability databases to find out if the package is vulnerable. Version of the package is taken into account when looking for a match.</p><h3>1. Docker Scout</h3><p>This tool is develop by Docker, Inc. It’s already built-in into Docker Desktop app. Unfortunately, it is not bundled with docker CLI, so you need to install it manually. Thankfully, you can install it with one-liner, assuming you already have docker CLI installed:</p><pre>curl -sSfL https://raw.githubusercontent.com/docker/scout-cli/main/install.sh | sh -s --</pre><p>If you don’t trust my one-liner, copy it from their official GitHub <a href="https://github.com/docker/scout-cli">repo</a>. Now you should be able to run docker scout . To scan an image and get a quick look at how secure the image is, run docker scout quickview . I really like the quickview, as a lot of the times you’re not interested in the specific vulnerabilities, but you want to know how many vulnerabilities there are and how serious they are.</p><pre>~❯ docker scout quickview ubuntu:20.04<br>    ✓ Image stored for indexing<br>    ✓ Indexed 127 packages<br><br>  Target   │  ubuntu:20.04  │    0C     0H     3M    10L   <br>    digest │  bf40b7bc7a11  │</pre><p>As we can see, Ubuntu 20.04 image has 0 vulnerabilities of critical and high severity, but has a few medium severity vulnerabilities. To get details for each vulnerability, run docker scout cves . This will show a list of CVEs related to vulnerabilities together with a link where you can find out more. Docker Scout will also tell you if there is a newer version of the affected package where the vulnerability is fixed.</p><pre>~❯ docker scout cves ubuntu:20.04<br>...<br>pkg:deb/ubuntu/gnutls28@3.6.13-2ubuntu1.8?os_distro=focal&amp;os_name=ubuntu&amp;os_version=20.04<br><br>    ✗ MEDIUM CVE-2023-5981<br>      https://scout.docker.com/v/CVE-2023-5981<br>      Affected range : &lt;3.6.13-2ubuntu1.9                            <br>      Fixed version  : 3.6.13-2ubuntu1.9                             <br>      CVSS Score     : 5.9                                           <br>      CVSS Vector    : CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:N/A:N<br>...</pre><p>In the example above, one of the medium vulnerabilities comes from gnutls package, version 3.6.13–2ubuntu1.8 . The vulnerability is fixed in version 3.6.13–2ubuntu1.9 , but the maintainers of this Ubuntu Docker image obviously haven’t updated the image yet. <em>I ran the scan again before publishing the post, and now the image only has low severity vulnerabilities </em>🥳<em>.</em></p><p>Docker Scout is also built-in into <a href="https://hub.docker.com/">DockerHub</a>, an image registry hosted by Docker, Inc. You can enable image scanning for 3 of your images for free. To scan more images, you will need to upgrade to a paid plan. DockerHub will perform vulnerability scanning each time a new tag is pushed. To enable it, open a repo of an image, go to Settings, and enable Docker Scout image analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*g9VkledgEMKnuAuHjNvdmw.png" /><figcaption>Docker Scout scan report on DockerHub</figcaption></figure><p>Docker Scout has a quite good support for CI/CD services. They provide <a href="https://github.com/docker/scout-cli?tab=readme-ov-file#ci-integration">templates</a> for GitHub Actions, GitLab CI/CD, CircleCI, Azure DevOps, Jenkins, and even BitBucket Pipelines.</p><h3>2. Trivy</h3><p><a href="https://github.com/aquasecurity/trivy">Trivy</a> is an open-source tool developed by Aqua Security. It’s more powerful than Docker Scout as it offers secret detection and IaC misconfiguration scanning next to Docker image scanning. You can install Trivy with a bunch of package managers (apt, yum, brew, pacman, port, nix, ) or just download binary. Look <a href="https://aquasecurity.github.io/trivy/v0.48/getting-started/installation/">here</a>. When you first run it, it will download all the vulnerability databases to your local environment. To scan an image, run trivy image . This time we’ll create a custom image from the Dockerfile:</p><pre>FROM alpine:3.18<br><br>RUN mkdir /app<br>COPY &lt;&lt;EOF /app/aws-creds<br>[default]<br>aws_access_key_id = AKIA5432112345XXXXPP<br>aws_secret_access_key = P9YXdfASASDfdsfdldFdfdfs4sldkfksfsdle3vg<br>EOF</pre><p>The Dockerfile uses alpine as the base image, and creates aws-creds file with hard-coded AWS secretes. Let’s build the image and run the scan.</p><pre>~❯ docker build -t test-image -f Dockerfile .<br>~❯ trivy image test-image<br>test-image (alpine 3.18.5)<br><br>Total: 0 (UNKNOWN: 0, LOW: 0, MEDIUM: 0, HIGH: 0, CRITICAL: 0)<br><br>/app/aws-creds (secrets)<br><br>Total: 2 (UNKNOWN: 0, LOW: 0, MEDIUM: 0, HIGH: 0, CRITICAL: 2)<br><br>CRITICAL: AWS (aws-access-key-id)<br>═══════════════════════════════════════════════════════════════════════<br>AWS Access Key ID<br>───────────────────────────────────────────────────────────────────────<br> /app/aws-creds:2 (added by &#39;COPY &lt;&lt;EOF /app/aws-creds # buildkit&#39;)<br>───────────────────────────────────────────────────────────────────────<br>   2 [ aws_access_key_id = ********************<br>   3   aws_secret_access_key = ****************************************<br>───────────────────────────────────────────────────────────────────────</pre><p>Trivy ran two types of scans: vulnerability scan for installed packages and secret detection for finding secrets in files. Vulnerability scan found no issues. This is expected since we used alpine image, which only has very basic OS packages and nothing else, not even Bash. However, secret detection found hard-coded secrets in aws-creds . Trivy also catches secrets in environment variables, so the image built with the following Dockerfile will also produce report with critical issues.</p><pre>FROM alpine:3.18<br><br>ENV AWS_ACCESS_KEY_ID=AKIA5432112345XXXXPP<br>ENV AWS_SECRET_ACCESS_KEY=P9YXdfASASDfdsfdldFdfdfs4sldkfksfsdle3vg</pre><p>Moreover, you can define your own <a href="https://aquasecurity.github.io/trivy/v0.27.1/docs/secret/configuration/">custom</a> matchers for secret scanning. It is also possible to scan the Dockerfile itself, not the image. Navigate to the directory with a Dockerfile and run trivy config .</p><pre>~❯ trivy config .<br>Dockerfile (dockerfile)<br><br>Tests: 26 (SUCCESSES: 24, FAILURES: 2, EXCEPTIONS: 0)<br>Failures: 2 (UNKNOWN: 0, LOW: 1, MEDIUM: 0, HIGH: 1, CRITICAL: 0)<br><br>HIGH: Specify at least 1 USER command in Dockerfile with non-root user<br>════════════════════════════════════════════════════════════════════════════=<br>Running containers with &#39;root&#39; user can lead to a container escape situation.<br>It is a best practice to run containers as non-root users,<br>which can be done by adding a &#39;USER&#39; statement to the Dockerfile.<br><br>See https://avd.aquasec.com/misconfig/ds002<br>─────────────────────────────────────────────────────────────────────────────</pre><p>In the case of the Dockerfile from above, a high severity issue is found since all the commands are executed as the root user. trivy config also <a href="https://aquasecurity.github.io/trivy/v0.27.1/docs/misconfiguration/iac/">scans</a> Kubernetes, Terraform and CloudFormation manifests and checks if they follow best practices. If you want to integrate Trivy into your CI/CD, you have a lot of <a href="https://aquasecurity.github.io/trivy/latest/ecosystem/cicd/">options</a>.</p><h3>3. Grype</h3><p><a href="https://github.com/anchore/grype">Grype</a> is like a younger brother of Trivy. Still not as mature as Trivy, but it’s constantly getting better. It doesn’t have functionalities like configuration scanning and secret detection, but does the primary functionality of scanning packages of Docker image well. It is developed by Anchore, and actually, it uses <a href="https://github.com/anchore/syft">Syft</a>, also by Anchore, to generate SBOM. Then, it compares the packages with vulnerability databases. Here is a one-liner to install it.</p><pre>curl -sSfL https://raw.githubusercontent.com/anchore/grype/main/install.sh | sudo sh -s -- -b /usr/local/bin</pre><p>To scan an image, just run grype .</p><pre> ~❯ grype aquasec/trivy<br> ✔ Scanned for vulnerabilities     [14 vulnerability matches]  <br>   ├── by severity: 0 critical, 0 high, 14 medium, 0 low, 0 negligible<br>   └── by status:   2 fixed, 12 not-fixed, 0 ignored <br>NAME                              INSTALLED  FIXED-IN  TYPE       VULNERABILITY        SEVERITY <br>busybox                           1.36.1-r5            apk        CVE-2023-42366       Medium    <br>busybox                           1.36.1-r5            apk        CVE-2023-42365       Medium    <br>busybox                           1.36.1-r5            apk        CVE-2023-42364       Medium    <br>busybox                           1.36.1-r5            apk        CVE-2023-42363       Medium<br>...</pre><p>In this example, I used Grype to test Trivy’s image. Just like Docker Scout and Trivy, Grype will also let you know if the vulnerability is fixed in the newer version of the package. What I like about Grype is that vulnerability list is not cluttered. Each vulnerability takes one line on screen. If you want to find out more about a vulnerability, use grype explain .</p><pre>grype -o json aquasec/trivy | grype explain --id CVE-2023-42366</pre><p>Unfortunately, Grype doesn’t cache SBOM of an image, so it will have to load and scan an image from zero each time, even though you just scanned the image moments ago. Regarding CI/CD, there is only a <a href="https://github.com/anchore/grype?tab=readme-ov-file#github-actions">template</a> for GitHub Actions. For other CI/CD services, you will have to create a scan job manually.</p><h3>4. Snyk Container</h3><p>And of course — Snyk. Snyk can do all sorts of things to streamline security of an app, but I’m gonna focus on Snyk Container, a tool for Docker image scanning. Snyk is not open-source and has a paid plan, but some of the functionalities are offered for free, including Snyk Container. You need to have an account on <a href="https://snyk.io/">snyk.io</a>, though.</p><blockquote>NOTE: Snyk is free for individual use only.</blockquote><p>To install Snyk CLI look <a href="https://docs.snyk.io/snyk-cli/install-or-update-the-snyk-cli">here</a>, or run:</p><pre>curl --compressed https://static.snyk.io/cli/latest/snyk-linux -o snyk<br>chmod +x ./snyk<br>sudo mv ./snyk /usr/local/bin/</pre><p>Before running any command, you need to authenticate. This will open your web-browser.</p><pre>snyk auth</pre><p>Now we can finally scan an image with snyk container test. This command name is a bit misleading since it scans an image, not a running container.</p><pre>~❯ synk container test anchore/grype<br>Testing anchore/grype...<br><br>✗ Medium severity vulnerability found in google.golang.org/protobuf/encoding/protojson<br>  Description: Stack-based Buffer Overflow<br>  Info: https://security.snyk.io/vuln/SNYK-GOLANG-GOOGLEGOLANGORGPROTOBUFENCODINGPROTOJSON-6137908<br>  Introduced through: google.golang.org/protobuf/encoding/protojson@v1.31.0<br>  From: google.golang.org/protobuf/encoding/protojson@v1.31.0<br><br>✗ Medium severity vulnerability found in golang.org/x/crypto/ssh<br>  Description: Authentication Bypass by Capture-replay<br>  Info: https://security.snyk.io/vuln/SNYK-GOLANG-GOLANGORGXCRYPTOSSH-6130669<br>  Introduced through: golang.org/x/crypto/ssh@v0.16.0<br>  From: golang.org/x/crypto/ssh@v0.16.0<br>  Fixed in: 0.17.0<br><br>Tested 827 dependencies for known issues, found 2 issues.</pre><p>This time I used Snyk to test Grype’s image. As we can see, Snyk found 2 issues of medium severity. I like how Snyk gives a summary at the end of the vulnerability list. Both Trivy and Grype put the summary at the top, which is really inconvenient when the vulnerability list is long. Snyk can also <a href="https://docs.snyk.io/snyk-cli/scan-and-maintain-projects-using-the-cli/snyk-cli-for-iac/test-your-iac-files">scan</a> all sorts of IaC files: Terraform, CloudFormation, Kubernetes, Kustomize, Helm, ARM, and Serverless files, with the command snyk iac test . Snyk also has a web app GUI which can be connected to a Git repo and then scan for vulnerabilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ksV13Tw1p1B9V_qh" /><figcaption>Vulnerability information for a Snyk project from <a href="https://docs.snyk.io/scan-using-snyk/snyk-container/scan-container-images">docs.snyk.io</a></figcaption></figure><p>As expected, Snyk has a lot of CI/CD <a href="https://docs.snyk.io/integrate-with-snyk/snyk-ci-cd-integrations">integrations</a>.</p><h3>Conclusion</h3><p>Overall, all the tools that I listed here seem useful to me. Snyk is definitely the most powerful, but requires an account and it’s only free for individual use. If you’re looking for an open-source tool, Trivy is the way to go. It has more functionalities than Docker Scout and Grype, but it’s still fast. In any case, all of these tools will make your app more secure and I would highly recommend implementing at least one in your CI/CD pipeline.</p><p>If you found this post helpful, be sure to follow me. I write about DevOps, Docker, Bash, security and tech in general.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb73342c0faa" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/4-free-easy-to-use-tools-for-docker-vulnerability-scanning-bb73342c0faa">4 Free, Easy-To-Use Tools For Docker Vulnerability Scanning</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Free, Open, Open-Source, Libre And FOSS — What’s The Difference And What Does It All Mean]]></title>
            <link>https://itnext.io/free-open-open-source-libre-and-foss-whats-the-difference-and-what-does-it-all-mean-a3b2d18a9ce0?source=rss-ab4361e8ec33------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3b2d18a9ce0</guid>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[open-data]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[freedom]]></category>
            <category><![CDATA[free-software]]></category>
            <dc:creator><![CDATA[Tin Plavec]]></dc:creator>
            <pubDate>Tue, 05 Dec 2023 23:05:40 GMT</pubDate>
            <atom:updated>2023-12-05T23:05:40.387Z</atom:updated>
            <content:encoded><![CDATA[<h3>Free, Open, Open-Source, Libre And FOSS — What’s The Difference And What Does It All Mean</h3><p>There is a lot of terminology in software engineering — and a lot of confusion. Everybody has heard of terms like open, open-source and free, but these terms are not the same. In fact, one of these terms actually has two meanings. No wonder the confusion. Let’s start with the broadest term.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MDE5GhUiCzUOjLge" /><figcaption>A bird enjoying freedom | Photo by <a href="https://unsplash.com/@federize?utm_source=medium&amp;utm_medium=referral">Federico Beccari</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Open</h3><p>An open system is a system that is based on a standard, making it easy to interact with, at the lowest possible cost. The standard (or specification) doesn’t have to be approved by a standardization body, but it has to be well documented and publicly available. Some related terms are:</p><ul><li><a href="https://www.openapis.org/">OpenAPI</a> — defines a formal specification for APIs</li><li><a href="https://www.opengovpartnership.org/">Open government </a>— an initiative to make public government data easily accessible on the web in a machine-readable format</li><li><a href="https://en.wikipedia.org/wiki/Open_science">Open science</a> — an initiative to make science more accessible by making research articles available online at no cost</li><li>and of course, open-source software</li></ul><p>Making a system open isn’t a one-time thing, but instead a continuous effort. Here are some principles of openness, based on <a href="https://public.resource.org/8_principles.html">principles</a> of Open government data:</p><ul><li>Accessible — available for widest range of users</li><li>Non-discriminatory —available to anyone, no need to pay or register</li><li>Non-proprietary — available in an open format with non-proprietary software</li><li>Copyright-free — free to reuse</li><li>Timely — continuously updated with relevant information</li><li>Machine-readable — well structured for machine processing</li></ul><p>There are various degrees of openness. An interesting comparison is between Office Open XML Document .docx format by Microsoft and Open Document Format .odt by OpenOffice. Both of these formats are open in a sense that they are documented, free to use, and can created freely by any program. But .odt is more open. <a href="https://www.iso.org/standard/66363.html">Specification</a> for .odt is only 800 pages long and references other specifications (for date, time, etc.), while <a href="https://www.iso.org/standard/71691.html">specification</a> for .docx is more than 5000 pages long because it rarely references other specifications. The other problem is, while .docx is an open format, rendering of the format is not open. That’s the reason why only MS Word can fully render .docx files, while other programs have to reverse engineer the rendering.</p><h3>Free / Libre</h3><blockquote>To understand the concept, you should think of “free” as in “free speech,” not as in “free beer.”</blockquote><p>As explained by <a href="https://www.gnu.org/philosophy/free-sw.html">GNU</a>, one of the most prominent free software, the term free means freedom. Freedom to do anything you want with the software. To avoid the confusion in English language, free software is sometimes called libre software (for example LibreOffice). The four essential <a href="https://www.gnu.org/philosophy/free-sw.html">freedoms</a> are:</p><ul><li>The freedom to run the program as you wish, for any purpose.</li><li>The freedom to study how the program works, and change it.</li><li>The freedom to redistribute copies so you can help others.</li><li>The freedom to distribute copies of your modified versions to others, so that the whole community can benefit.</li></ul><p>To achieve all these freedoms, the software has to be open-source, otherwise you cannot investigate how it works. Because of this, free software respects privacy, while backdoor cannot be secretly implemented. It’s interesting to note that, since you can do anything with free software, it seems that you can also make a profit off it. However, this doesn’t apply in all cases and under all licenses. It really is a good question: Is software more free if those who redistribute it can make a profit off it, or is it more free if those who redistribute it have to obey by the four essential freedoms, and thus cannot make a profit. Free software enthusiasts would probably argue for the latter.</p><p>There are more gray areas in free software philosophy. For example, Ubuntu respects all four freedoms, but it’s usually not considered free software. That’s because Ubuntu has an option to install proprietary drivers during setup. Also, Ubuntu offers proprietary software in its package repository. Therefore, it is not purely free. <a href="https://www.gnu.org/distros/free-distros.en.html">Purely free operating systems</a> are not that popular actually, since they have no proprietary drivers, making them hard to use in practice.</p><p>The philosophy of free software has a deeper meaning. It is a sociopolitical movement to protect people from the <a href="https://www.fsf.org/blogs/community/help-others-find-free-software-watch-and-share-escape-to-freedom"><em>darkness</em></a> of proprietary software. In their view, proprietary software wants to manipulate you and profit as much as possible. Advocates of free software would argue that promoting the four freedoms is important for human rights and a free society.</p><h3>Open-source</h3><p>As you probably know, open-source is software whose code is freely available. You can also contribute to an open-source project. The idea of open-source emerged after the idea of free software. Activist elements of free software were obviously not so favorable for the for-profit companies. That’s why the <a href="https://opensource.org/">Open Source Initiative</a> was established, with a focus on making the software appealing to companies. For example, widely used MIT license allows commercial use of free software. Programming languages are licensed in a similar way — otherwise you would have to pay when you use Python in your app that you sell. Almost all frameworks are also licensed like this, look at <a href="https://github.com/facebook/react/blob/main/LICENSE">React</a> for example.</p><p>There is a catch, however. Companies and individuals that release open-source software can change its license when they please. Just look at the recent <a href="https://www.forbes.com/sites/rscottraynovich/2023/08/17/hashicorp-licensing-firestorm-fuels-open-source-debate/">drama</a> surrounding Terraform. HashiCorp, the creator and owner of Terraform, decided to change its open-source license to a business-source license. This means that for-profit companies will most likely have to pay to use Terraform, while individual non-commercial use will remain free. However, the open-source community went into a rage and even created new, open-source version of Terraform from the current version of Terraform that was still open-source at the time. On the other hand, some open-source projects, like Kubernetes, are much better protected from the previous scenario. Kubernetes was developed internally in Google, but then released as an open-source project. The product was still owned by Google, though. So, to remove the risk of license change, in 2015 Google created a new non-profit organization, Cloud Native Computing Foundation (CNCF), in collaboration with Linux Foundation and a few other companies. The new organization was effectively independent from Google. Then, Google donated entire Kubernetes project to CNCF, making it truly open-source, and making community eager to contribute.</p><h3>FOSS</h3><p>FOSS means free open-source software. As we’ve learned, free means freedom, not $0. To make things more clear, FLOSS is also used, where L stands for libre. As I’ve mentioned before, free software is at odds with open-source software when it comes to sociopolitical activism and emphasis of software freedom. The concepts are basically rivals — one is about rights and fundamental freedom, while the other one is about pragmatism and commercial use. The term FOSS wants to reconcile and promote both concepts. The only problem is, it’s not exactly clear how to reconcile these concepts, making the term FOSS ambiguous. Furthermore, the four freedoms require that the source code is available, which means that any free software must be open-source as well, so the term FOSS is not really needed.</p><h3>Conclusion</h3><p>I hope I managed to demystify all these terms and that you can now use them appropriately. The history behind these terms is fascinating to me. At the surface, they all seem sort of similar, but actually, there is some real friction, like in the case of free software and open-source software. Still, all of the terms are promoting openness, an idea to make things accessible and transparent, and to improve collaboration.</p><p>I’m sure you learned something new reading this article. If you are interested in tech, development tips, DevOps practices, etc., be sure to follow me.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3b2d18a9ce0" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/free-open-open-source-libre-and-foss-whats-the-difference-and-what-does-it-all-mean-a3b2d18a9ce0">Free, Open, Open-Source, Libre And FOSS — What’s The Difference And What Does It All Mean</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 Different Ways to Handle Errors in Bash]]></title>
            <link>https://itnext.io/5-different-ways-to-handle-errors-in-bash-b1b79ca08fdb?source=rss-ab4361e8ec33------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1b79ca08fdb</guid>
            <category><![CDATA[scripting]]></category>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[bash]]></category>
            <dc:creator><![CDATA[Tin Plavec]]></dc:creator>
            <pubDate>Wed, 22 Nov 2023 09:02:21 GMT</pubDate>
            <atom:updated>2023-11-22T09:02:21.644Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5yXYI3fMOd9pNbbh" /><figcaption>Photo by <a href="https://unsplash.com/@brett_jordan?utm_source=medium&amp;utm_medium=referral">Brett Jordan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Bash knows no exceptions. Exception handling like in other programming languages is not an option. But, at least, we have exit codes of commands, which will help us detect errors.</h4><p>Let’s look at a few ways of error handling in Bash scripting. Out options are limited, but the handling is still possible.</p><h3>Evaluate exit code</h3><p>The simplest method to check for errors is to evaluate exit code of a command. After a command runs, you can check the variable $? for its exit code. Code 0 signals no errors.</p><pre>cat ./nonexistent<br>exit_code=$?<br>if [[ ${exit_code} -ne 0 ]]; then<br>  echo &quot;Command failed with exit code ${exit_code}&quot;<br>else<br>  echo &quot;No errors detected&quot;<br>fi</pre><p>Or, even shorter using the command directly in if condition:</p><pre>if cat ./nonexistent; then<br>  echo &quot;No errors detected&quot;<br>else<br>  echo &quot;Command failed with exit code $?&quot;<br>fi</pre><p>The method of evaluating exit code goes nicely with case statement. A Bash case statement is analogous to switch statement in other programming languages. Let’s look at an example with docker run :</p><pre>container_image=nonexistent<br>container_command=nonexistent<br><br>docker run -it ${container_image} ${container_command}<br>exit_code=$?<br>case ${exit_code} in<br>  125)<br>    echo &quot;Image does not exist or access is denied&quot;<br>    ;;<br>  127)<br>    echo &quot;Command not found&quot;<br>    ;;<br>esac</pre><p>Command docker run pulls the specified image and runs the container with the specified command. In case the image does not exist docker run will return code 125. If the image is successfully pulled, but the specified command does not exist in the image’s file system, code 127 will be returned. If you have Docker installed, try the above example with different combinations of variables:</p><pre>container_image=ubuntu:22.04<br>container_command=nonexistent</pre><pre>container_image=ubuntu:22.04<br>container_command=bash</pre><p>Since the script is now checking for errors, you may want to suppress error output of the commands in the script. This is our current output if the image does not exist:</p><pre>Unable to find image &#39;nonexistent:latest&#39; locally<br>docker: Error response from daemon: pull access denied for nonexistent, repository does not exist or may require &#39;docker login&#39;: denied: requested access to the resource is denied.<br>See &#39;docker run --help&#39;.<br>Image does not exist or access is denied</pre><p>You can do that with 2&gt;/dev/null . Number 2 refers to error output, which is being redirected to null location, i.e. it is being thrown away.</p><pre>docker run -it ${container_image} ${container_command} 2&gt;/dev/null</pre><p>The output of the script will now look like this:</p><pre>Image does not exist or access is denied</pre><h3>Use operators</h3><p>Some people prefer to use <em>and</em> (&amp;&amp;) and <em>or</em> (||) operators. This method can give nice one-liners, but it’s less readable than a simple if statement. Nevertheless, this is an example how to use it:</p><pre>cat ./nonexistent || echo &quot;No file to show&quot;</pre><p>This <em>or</em> operator works similar as in other programming languages. If the first command fails, then the second command is run, otherwise not. You can also use <em>and </em>operator:</p><pre>cat ./exists &amp;&amp; echo &quot;I run only if the file exists&quot;</pre><p>And, you can combine the two:</p><pre>test -f filename &amp;&amp; echo &quot;File exists&quot; || echo &quot;File does not exist&quot;</pre><p>Command test is a Bash command for testing if a file or a directory exists, if a file is writable, if some expression is equal to another and so on. Of course, in the example above, test can be replaced with any other command.</p><h3>Trap error signal</h3><p>Command trap is used in Bash to <em>trap</em> signals, i.e. when a specific signal is raised, trap function is invoked. An example of a signal would be CTRL+C, which is represented by SIGINT .</p><pre>trap &#39;echo -e &quot;\nNope :)&quot;&#39; SIGINT<br>while true; do sleep infinity; done</pre><p>Try running the above script, and then try to exit it by pressing CTRL+C (If you encounter some problems, don’t worry, you can exit it with CTRL+Z).</p><p>To catch errors, we need to <em>trap</em> the error signal, ERR . A callback function is normally used.</p><pre>trap &#39;error-callback $? $LINENO&#39; ERR<br><br>function error-callback() {<br>  echo &quot;Taking care of error $1 at line $2&quot;<br>  exit $1<br>}<br><br>cat ./nonexistent</pre><p>This method is the closest to standard try-catch blocks in other languages. Unfortunately, since Bash has no objects, we cannot do much with the <em>exception</em> we caught. We can just get the exit code and the number of problematic line. Another problem is that <em>trapping</em> doesn’t propagate to subshells.</p><pre>trap &#39;error-callback $? $LINENO&#39; ERR<br><br>function error-callback() {<br>  echo &quot;Taking care of error $1 at line $2&quot;<br>  exit $1<br>}<br><br>function cat-file() {<br>  cat $1<br>  echo &quot;Done&quot;<br>}<br><br>cat-file ./nonexistent</pre><p>Running this example script will print out Done , even though intuitively the cat error should have been caught and the callback function should have stopped further execution. You could fix this error by copying trap line into the beginning of cat-file function, but this isn’t really a good coding practice.</p><h3>Evaluate error message</h3><p>In some cases you need to evaluate error message, not the error code. A lot of commands throw the same error code for different types of errors. Look no further than cat command.</p><pre>$ cat ./nonexistent || echo $?<br>cat: ./nonexistent: No such file or directory<br>1</pre><pre>$ cat ./nonreadable || echo $?<br>cat: ./nonreadable: Permission denied<br>1</pre><p>In both cases, the exit code is 1. Inconvenient. So let’s evaluate the error message as well.</p><pre>output=$(cat ./file 2&gt;&amp;1)<br>exit_code=$?<br><br>if [[ ${exit_code} -ne 0 ]]; then<br>  echo &quot;Comamnd failed with exit code ${exit_code}&quot;<br>  if [[ ${output} =~ &quot;Permission&quot; ]]; then<br>    echo &quot;${output}&quot;<br>    exit 2<br>  fi<br>fi</pre><p>We have redirected error output to standard output with 2&gt;&amp;1. Then, we evaluated the exit code, and then the error message if the code is non-zero. In this example I tested if the error message contains string Permission , in that case I want my script to exit with the code 2. This is just a simple example, but in real world some complex situations in error handling can happen.</p><p>The only problem with this approach is that error messages may change with the update. Well, that’s probably not the case for cat , but it is the potential case for kubectl or docker , for example.</p><h3>Catch errors in pipeline</h3><p>Catching errors in pipeline is tricky. In fact, it’s not enabled by default. Exit code of a pipeline will be inherited from the last command in the pipeline.</p><pre>nocommand | echo</pre><p>Even though nocommand failed since it doesn’t exist, and echo returned an empty line, the final exit code is 0. This is because echo returned 0, since echoing an empty line produces no errors. To make a pipeline fail if any command fails, we need to add a special set command to our script:</p><pre>set -o pipefail<br><br>if nocommand | echo; then<br>  echo &quot;No errors occured&quot;<br>else<br>  echo &quot;An error occured!&quot;<br>fi</pre><p>This script will detect nocommand error. Try commenting out set -o pipefail line to see what will happen in the default case.</p><p>I should also not forget to mention option set -e . Usually, when you run a script, Bash will execute all commands in the script, no matter if error occurred somewhere in the process. With the option, however, script will exit immediately when an error occurs. This is more intuitive because other programming languages work like that.</p><pre>set -eo pipefail<br>echo &quot;No problems&quot;<br>nocommand | echo<br>echo &quot;I will not be executed since an error occured before&quot;</pre><h3>Conclusion</h3><p>I showed you some ways how to handle errors in Bash. Handling errors in Bash is a bit tedious, but it’s doable. I personally prefer a simple if statement, or a case expression. Trap looks cool, but it’s implicit and can cause some strange errors hard to debug, as I’ve mentioned before. Decide what’s best for you, but make sure to always do some kind of error handling in your scripts.</p><p>I hope you learnt something from my article, and you can apply it to your use case. If you would like to read more about Bash, Docker and DevOps tools, be sure to follow me.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1b79ca08fdb" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/5-different-ways-to-handle-errors-in-bash-b1b79ca08fdb">5 Different Ways to Handle Errors in Bash</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Run a Jupyter Notebook on a Chromebook]]></title>
            <link>https://tinplavec.medium.com/how-to-run-a-jupyter-notebook-on-a-chromebook-e080380fafb9?source=rss-ab4361e8ec33------2</link>
            <guid isPermaLink="false">https://medium.com/p/e080380fafb9</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[jupyter-notebook]]></category>
            <category><![CDATA[chromebook]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[Tin Plavec]]></dc:creator>
            <pubDate>Wed, 15 Nov 2023 23:30:21 GMT</pubDate>
            <atom:updated>2023-11-15T23:30:21.613Z</atom:updated>
            <content:encoded><![CDATA[<p>Chromebooks run ChromeOS, a cloud-first operating system based on the Linux kernel, that is known for its super-fast booting. The initial version of ChromeOS, in 2009, was so cloud and web-oriented that the entire OS was actually the Chrome browser. You had no desktop, just a Chrome window with web apps. In 2016 ChromeOS got wide support for Android apps and the Play Store. And then in 2018 it finally got official support for Linux apps. It’s funny how ChromeOS is based on Linux, but it couldn’t run Linux apps for a long time. However, thanks to this ability, we can today easily run Jupyter notebooks on Chromebooks. So, let’s try it out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*S182gAicbf_tXlBo" /><figcaption>Photo by <a href="https://unsplash.com/@brookecagle?utm_source=medium&amp;utm_medium=referral">Brooke Cagle</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>1. Enable Linux development environment</h3><p>First, we need to enable running Linux apps on the Chromebook. Simply go to Settings and, under Advanced, choose Developers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MMtuMQD7MTYMvi__IKBQ9w.png" /><figcaption>ChromeOS Settings</figcaption></figure><p>Turn the development environment on, choose your username and stick with the default disk size. The initialization of the environment will take a few minutes since your Chromebook needs to download image of Debian Linux distribution. After this is done, you should see a new terminal window.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*q2Mc6iTdmLeOY3oGGYJSsg.png" /><figcaption>ChromeOS Terminal</figcaption></figure><p>You may recognize this terminal uses BASH shell. If you accidentally close this window, just look for Terminal app and open it.</p><h3>2. Install Python and venv module</h3><p>As I’ve already mentioned, the ChromeOS’ Linux environment is Debian based, so before we install anything, let’s update apt repositories. In the terminal, run:</p><pre>sudo apt update</pre><p>Now we need to install Python. Actually, Python is already preinstalled, to verify that, run:</p><pre>python3 --version</pre><p>Jupyter notebooks are usually run inside a virtual environment, so we’ll need that as well. To install virtual environment module, run:</p><pre>sudo apt install python3-venv</pre><h3>3. Create a Python virtual environment</h3><p>We can now create a virtual environment inside our Linux environment. Simply run:</p><pre>python3 -m venv venv</pre><p>To active the created venv:</p><pre>source venv/bin/activate</pre><p>Your BASH console should now indicate that you are inside the virtual environment:</p><pre>(venv) plavy@penguin:~$</pre><h3>4. Install Jupyter and open a notebook</h3><p>We are almost done. Inside the virtual environment run:</p><pre>pip install jupyter</pre><p>This may take some time, depending on how powerful your Chromebook is. After Jupyter has been successfully installed, run it in a new directory:</p><pre>mkdir my-project<br>cd my-project<br>jupyter notebook</pre><p>The familiar Jupyter dashboard should be opened in a new Chrome tab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*OrfxeRb5eGGd20BfvZSJfQ.png" /><figcaption>Jupyter dashboard</figcaption></figure><p>And that’s it 😄. If you want to open an existing notebook, you can install Git (sudo apt install git) and clone your repository with the notebook. Or if your notebook is on your Chromebook and you want to move it to the Linux environment, you can <a href="https://chromeos.dev/en/linux/setup#sharing-files-to-linux">set up a shared folder</a>. When working with Jupyter notebooks on a Chromebook, take in mind the processing power of your Chromebook, i.e. don’t expect some stellar speeds.</p><p>This was a simple how-to guide. I also write about best practices for various Dev and DevOps technologies, and I like to discuss tech in general. If that sounds interesting, be sure to follow me.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e080380fafb9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimize Your Dockerfile With These 6 Tips]]></title>
            <link>https://levelup.gitconnected.com/optimize-your-dockerfile-with-these-6-tips-73393af3d0a4?source=rss-ab4361e8ec33------2</link>
            <guid isPermaLink="false">https://medium.com/p/73393af3d0a4</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[dockerfiles]]></category>
            <dc:creator><![CDATA[Tin Plavec]]></dc:creator>
            <pubDate>Tue, 07 Nov 2023 21:33:10 GMT</pubDate>
            <atom:updated>2023-11-10T13:18:06.785Z</atom:updated>
            <content:encoded><![CDATA[<p>Docker was released in 2013 — just 10 years ago. Today it has become a de facto standard for containers and is available on all major operating systems and all major cloud platforms. You can <em>dockerize</em> almost any kind of app, making your app easily portable from machine to machine, from cluster to cluster, and from cloud to cloud. Journey of every Docker container starts with a Dockerfile. That’s why it’s important to follow best practices when writing it. Let’s look at some of these practices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GUrBO0FuYEPmc8QE" /><figcaption>Photo by <a href="https://unsplash.com/@ventiviews?utm_source=medium&amp;utm_medium=referral">Venti Views</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>1. Add files as you need them</h3><p>The most important thing when writing a Dockerfile is to think about the cache. Every time you build a Docker image from a Dockerfile, Docker will store the cache of that build. When you build the image again, this cache will be used, which can significantly improve build speed. For example, one command that takes some time to run is npm install . This command downloads and installs all the dependencies of a Node.js project, which can take a few minutes. That’s why you want to cache this command when running docker build so that it’s pulled from the cache in less than a second — otherwise you will have to wait a few minutes for every build, which quickly gets annoying and counter-productive. If you don’t care about caching, you would write your Dockerfile like this:</p><pre>FROM node:20<br>COPY . .<br>RUN npm install<br>RUN npm build</pre><p>This Dockerfile simply adds all project files (including source code) to the image with Docker&#39;s COPY instruction, then runs npm install , and then npm build to build the actual application from the source code. The outcome is valid, but it’s not optimized. Let’s assume that you run docker build , change some business logic in project files, and now you want to build again. The first line FROM node:20 will be built using Docker cache since nothing changed here, but caching will break at the second line COPY . . since files have been changed. Docker uses layer caching. One <a href="https://docs.docker.com/build/guide/layers/">layer</a> is usually represented by one line in a Dockerfile. This means that once the cache is broken at one line, all the following lines will be built without using cache. That’s because Docker assumes a line depends on all of the previous lines in the Dockerfile, which actually makes perfect sense to assume. In our example, npm install will run each time a project file is changed. However, npm install doesn’t actually depend on the project’s source code, but only on package.json and its lock file. package.json defines all the required dependencies that npm should install. So, let’s fix our Dockerfile:</p><pre>FROM node:20<br>COPY package*.json .<br>RUN npm install<br>COPY . .<br>RUN npm build</pre><p>Here I used package*.json to include both package.json and package-lock.json . As you see, I copied the entire source code of the app only after npm install , but before npm build , since npm build depends on the source code. This way, if the source code is changed, npm install will be pulled from the cache since package.json is still the same. Only if we change some dependencies in package.json , npm install will have to run again.</p><blockquote>NOTE: The example Dockerfile is here to illustrate how caching works. The actual Dockerfile for a Node.js application would look different. For example, you should change WORKDIR before adding files and running npm .</blockquote><h3>2. Add .dockerignore</h3><p>When you don’t want to push a file to your Git repo, you add it to .gitignore . When you don’t want to add a file to Docker build context, you add it to .dockerignore . When building a Docker image, build context path is specified: docker build -t image_tag . . The last dot tells Docker that the current working directory should be used as the build context. Build context is then sent (copied) to Docker daemon that builds the image. Let’s use the Node.js example again. Suppose that, before building the Docker image, we’ve run our app locally using npm install and npm start . Since we are executing these commands directly on our machine, npm will create node_modules directory, where all of the downloaded dependencies are placed, in our project directory, on our machine. Project directory now looks something like this:</p><pre>node_modules/<br>public/<br>src/<br>package.json<br>package-lock.json</pre><p>Note that node_modules directory can easily reach the size of 1 GB. OK, so after we’ve tested the app locally with npm start , we now want to build the Docker image of the app. Therefore, we will create the Dockerfile in our project directory similar to the one mentioned in the previous tip. Then, we will run docker build -t image_tag . . But looking at logs, the build context is huge at almost 1 GB:</p><pre> =&gt; [internal] load build context<br> =&gt; =&gt; transferring context: 893.00MB</pre><p>This is because the entire project directory, including node_modules , got sent as the build context. We want to avoid sending node_modules , so let’s create .dockerignore and add node_modules as one line in the file. When building the Docker image now, logs show a much smaller build context:</p><pre> =&gt; [internal] load build context<br> =&gt; =&gt; transferring context: 11.41kB</pre><p>Our project structure now looks like this:</p><pre>node_modules/<br>public/<br>src/<br>Dockerfile<br>.dockerignore<br>package.json<br>package-lock.json</pre><p>Remember that .dockerignore should be always placed in the root of the build context.</p><p>You may be thinking why did we want to exclude node_modules from the build context. This is because node_modules is a directory built by npm and does not contain source code of our app. It was created by local npm on our machine. The npm running in Docker should create its own node_modules inside the Docker image. Adding local node_modules to our Docker image is not an optimization, but an anti-pattern. You should only give app’s source code to Docker and then run build commands inside Docker to build the app. This way, Docker build won’t conflict with your local build.</p><h3>3. Run all commands at once</h3><p>This one is simple. More often than not, you will find yourself using apt or some other package manager to install the required packages. Before running apt install , apt update must be run. Instead of using multiple RUN instructions in Dockerfile, use just one:</p><pre>RUN apt-get update &amp;&amp; apt-get install -y \<br>  git \<br>  jq \<br>  kubectl</pre><p>Notice how I split packages into multiple lines and ordered them alphabetically for better readability. If you would use multiple RUN instructions, each instruction would create a new layer. This would make the build a little slower and more storage consuming.</p><h3>4. Set environment variables and versions</h3><p>With ENV you can set the environment variables during the build process that will persist in the image and therefore be available when the container is run. For example, you can elegantly modify PATH variable with this instruction:</p><pre>ENV PATH=/opt/maven/bin:${PATH}</pre><p>Or, if you’re running Node.js and reading process.env.PORT when starting the server, you can set server’s port in your Dockerfile:</p><pre>ENV PORT=8080</pre><p>It’s generally advisable to make your app configurable with environment variables as much as possible. When the app is deployed, it’s always easier to change an environment variable than to change some file in the code and then redeploy the app. You can also use ENV to set the version of some dependency in a visible way:</p><pre>ENV KUBECTL_VERSION=1.27<br>RUN curl -fsSL https://pkgs.k8s.io/core:/stable:/v${KUBECTL_VERSION}/deb/Release.key | sudo gpg --dearmor -o /etc/apt/keyrings/kubernetes-apt-keyring.gpg<br>...</pre><p>Speaking of versions and Docker, it is highly recommended not to use the latest tag of an image. You should also not use very specific version like 1.27.4 , because in this case you will not get important patch updates that resolve bugs or improve security. Instead use major (x) or minor version (x.y):</p><pre>FROM python:3.10</pre><p>Writing just python would also work, but then Docker would always pull the latest version which could brake your application if there is some breaking change in the new version.</p><h3>5. Use multi-stage build</h3><p><a href="https://docs.docker.com/build/building/multi-stage/">Multi-stage build</a> is a great and probably an underused feature of Docker. The idea is to build an image in multiple stages. Ultimately, only the last stage will be incorporated into the image while previous stages will be discarded. Typical use case is to build a binary in the first stage using build tools and source code, and then copy only the binary to the next stage. Final image will not have source code nor build tools — which makes sense since the final image should be able to run the app, not build it.</p><pre>FROM mcr.microsoft.com/dotnet/sdk:7.0 AS build-env<br>WORKDIR /App<br><br># Build the app<br>COPY . ./<br>RUN dotnet restore<br>RUN dotnet publish -c Release -o out<br><br># Build runtime image<br>FROM mcr.microsoft.com/dotnet/aspnet:7.0<br>WORKDIR /App<br>COPY --from=build-env /App/out .<br>ENTRYPOINT [&quot;dotnet&quot;, &quot;DotNet.Docker.dll&quot;]</pre><p>This <a href="https://learn.microsoft.com/en-us/dotnet/core/docker/build-container?tabs=linux&amp;pivots=dotnet-7-0">official example Dockerfile</a> is used to build an ASP.NET application and run it. Notice the instruction COPY --from=build-env /App/out . . This instruction copies the binary files from the first stage into the second stage. The first stage is based on image mcr.microsoft.com/dotnet/sdk:7.0 that has tools for building the app, while the second stage is based on smaller, runtime image mcr.microsoft.com/dotnet/aspnet:7.0 . Also notice how they specified minor version of the image.</p><h3>6. Take a look at Slim and Alpine images</h3><p>Alpine images are based on Alpine Linux which is known for its compact size. That makes Alpine images faster to build, pull and run, in theory at least.</p><pre>REPOSITORY   TAG           SIZE<br>python       3.10-alpine   50.4MB<br>python       3.10-slim     128MB<br>python       3.10          1GB</pre><p>In the case of python, the Alpine image has 20 times smaller size than the full Debian-based image. Python also offers Slim image, which is Debian-based, but lacks most of the standard packages. The general problem with these small images is that if your application is just a bit more complex, you will need to install additional packages, which will inevitably prolong build time and increase image size, defeating the initial promise. For example, Alpine image doesn’t have PyPI wheels by default. I even argued against using Alpine images for CI/CD in <a href="https://medium.com/@tinplavec/gitlab-ci-cd-best-practices-i-recommend-after-2-years-of-experience-dfc0e349e4d6">my other article</a>. The point that I want to make is that you shouldn’t use small images by default, or discard them by default, but instead you should be aware that they exist and can be useful in some simple cases.</p><p>Thank you for reading. In this article I talked about good practices for Docker, but I also talk about Bash, CI/CD and other DevOps and Dev matters. If that sounds interesting to you, be sure to follow me.</p><p><a href="https://levelup.gitconnected.com/my-tips-and-tricks-for-bash-scripting-after-writing-hundreds-of-scripts-59987855b20a">My Tips and Tricks for Bash Scripting After Writing Hundreds of Scripts</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73393af3d0a4" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/optimize-your-dockerfile-with-these-6-tips-73393af3d0a4">Optimize Your Dockerfile With These 6 Tips</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Reached 100 Followers on Medium Posting Once a Week]]></title>
            <link>https://tinplavec.medium.com/how-i-reached-100-followers-on-medium-posting-once-a-week-27b1c5d24caf?source=rss-ab4361e8ec33------2</link>
            <guid isPermaLink="false">https://medium.com/p/27b1c5d24caf</guid>
            <category><![CDATA[100-followers]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[writing]]></category>
            <category><![CDATA[medium]]></category>
            <dc:creator><![CDATA[Tin Plavec]]></dc:creator>
            <pubDate>Sat, 28 Oct 2023 20:11:50 GMT</pubDate>
            <atom:updated>2023-10-28T20:11:50.728Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rZnPUXcFp2zKbx36" /><figcaption>Photo by <a href="https://unsplash.com/@storyfuel?utm_source=medium&amp;utm_medium=referral">Melanie Deziel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>And how you can do it, too.</h4><p>I’ve read of a lot of posts like this one you’re currently reading — posts where writers explain how they achieved the magical number of 100 followers. While I was reading these posts, I was wondering if perhaps one day I could share my story of reaching 100 followers on Medium. Well, the day has come.</p><p>Since all of my posts are structured with chapters, this one will be as well. Let’s start with my very first post.</p><h3>My first post</h3><p>If you look at my profile page, you’ll see that I published my first post in March 2023. I had actually started writing that post 6 months earlier, but could never find the time to finish it. The first one is always the hardest. Finally, at some point I decided to finish it and publish it. Of course, the post didn’t get a lot of views, but some of my friends and colleagues read it and were really impressed by the post. I immediately thought I had to continue writing. In fact, I already had a few ideas for my next post. But, unfortunately, I didn’t have enough time and determination to write a new post, until…</p><h3>Setting a goal</h3><p>During summer, when I had more free time, I thought about what kind of content could I write for Medium, who is my ideal reader. It was clear to me that DevOps was the way to go as I’ve already had a few years of experience doing all kinds of DevOps stuff. I set a goal that I will start writing regularly when the summer ends and the fall starts. As I was going to the university (and I still do), I knew I couldn’t write every day. If you read any other <em>How I Reached 100 Followers </em>post, you’ll see that almost everyone says you should write a post every day and the success will come. I set my goal to write once a week, so I was worried that my follower count will grow very slowly, but…</p><h3>Consistency</h3><p>As per my plan, I have started writing consistently at the end of September. Today, just four weeks later, I am at 150 followers, even though I have been writing a post every 6–7 days. That feels amazing! It means that being consistent is the most important for a writer. It doesn’t matter if you’re writing once a week or once a day, or even twice a day as some do. You need to write consistently. And, if your content is engaging, people will follow you.</p><h3>Publications</h3><p>I mostly submit my posts to a publication. By submitting a post to a publication on Medium you don’t lose anything, not even income if you’re monetizing your stories. On the other hand, your post will have an increased reach, which is quite helpful when you’re just starting. The problem is you have to wait until your post gets approved, making it harder to stick to your schedule of posting. Some writers always publish to a publication, while some prefer to self-publish. I decide on an individual basis: if I think my post is a great fit for some publication, and I can wait for an approval, I submit it, otherwise I don’t. I recommend you to try out the publications and see if they make sense for you. My most viral post that significantly contributed to my follower count was published in a publication.</p><h3>Promoting posts</h3><p>Promoting your posts outside Medium can also help you get more reach. For example, I recently shared my first published Medium post on Reddit. Yes, I shared the post 7 months after it was published. I wanted to see what will happen. The post received overwhelmingly positive feedback and accumulated 700 views in the following 4 days. The drawback here is that most of those viewers were not registered Medium users so they couldn’t follow me. But still, this activity gave a positive signal to the Medium algorithm that started to recommend my post to Medium users, and I managed to get some followers. I also share my posts to LinkedIn and X sometimes, but if you don’t have so many followers there, Reddit is more effective. Find an appropriate subreddit for your post and, if your post is good, it will get attention.</p><h3>Never stop reading</h3><p>To improve a skill, you should simply do it more often. Therefore, to improve your writing, you should simply write more. But there is another important thing that people usually forget: reading. By reading posts from other people, you can see what works and streamline your writing. Before publishing my first post, I had been on Medium for more than a year. I was just reading both tech and non-tech posts, and was thinking that maybe one day I could write a post.</p><h3>Conclusion</h3><p>This was my experience of reaching 100 followers. I didn’t post every day, but I posted consistently. I hope my experience motivates the people who don’t have the time to write every day, to still start writing. After I’ve become consistent, I reached 100 followers within a month. If you’re determined to do something, you will achieve it.</p><p>Start writing. Thank you for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27b1c5d24caf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Open an Image Directly Inside The Terminal]]></title>
            <link>https://tinplavec.medium.com/how-to-open-an-image-directly-inside-the-terminal-0c730b2f1f04?source=rss-ab4361e8ec33------2</link>
            <guid isPermaLink="false">https://medium.com/p/0c730b2f1f04</guid>
            <category><![CDATA[bash]]></category>
            <category><![CDATA[terminal]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[terminology]]></category>
            <dc:creator><![CDATA[Tin Plavec]]></dc:creator>
            <pubDate>Sun, 22 Oct 2023 23:50:32 GMT</pubDate>
            <atom:updated>2023-10-22T23:50:32.017Z</atom:updated>
            <content:encoded><![CDATA[<h4>It’s possible and it saves resources, so why not?</h4><p>It never stops to amaze me how many things you can do in the terminal. A few days ago I was browsing some files in my terminal on Ubuntu, but then I wanted to open a PNG image. To do this, I would of course open the image with some GUI application. But this time I thought: What if there is some program that can open images directly in terminal?</p><p>In fact, there’s more than one program that can do just that. I will show you some of the useful programs I’ve found. Let’s first start with those that are super simple and show pixelated images, and then move on to those more powerful that can even play videos, directly in your terminal.</p><h3>Catimg</h3><p><a href="https://github.com/posva/catimg">Catimg</a> is a simple C program that renders the image (png, jpeg, gif) using only Unicode characters. The program requires no dependencies, meaning it’s fast to install it and even faster to run it. The quality of the image is obviously not so good (even though it looks retro-cool), but perhaps you can use this tool if you want to see a thumbnail of an image. Since this program uses Unicode characters, it works even over an SSH connection. This means you can connect to your remote server via SSH, simply install this tool, and then look at the previews of the images on your server, all without any additional configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*-4QYDsyB7mw4oLIW4Iy2Gg.png" /><figcaption>An image rendered by Catimg</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*sF4MFlv-dtBP7SDr0t8f7w.gif" /><figcaption>A GIF rendered by Catimg</figcaption></figure><p>There are several options to install this program:</p><pre>brew install catimg # Homebrew<br>yaourt -S catimg # Arch<br>dnf -y install catimg # Fedora</pre><p>If you’re on Ubuntu (like I am) or some other system, you can install the program from source, which is pretty straightforward since there are no additional dependencies.</p><pre><br>git clone https://github.com/posva/catimg.git<br>cd catimg<br>cmake .<br>sudo make install</pre><p>To view an image, run:</p><pre>catimg image.png</pre><p>There are a few other similar programs that show pixelated images: <a href="https://github.com/stolk/imcat">imcat</a>, <a href="https://github.com/stefanhaustein/TerminalImageViewer">tiv</a>, <a href="https://github.com/hzeller/timg">timg</a>, and <a href="https://github.com/hpjansson/chafa">chafa</a>.</p><h3>Fim</h3><p><a href="https://www.nongnu.org/fbi-improved/">Fim</a> is Fbi IMproved, while Fbi means <em>framebuffer imageviewer</em>. You can simply remember it as Vim for images. Fim is a command-line tool, but it opens images in a new window, which is a drawback compared to other tools that preview the image in the terminal window. Nevertheless, using Fim feels exactly like using Vim. And it shows images in full resolution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*8EebbwD0Z4dARHM_O4PtVw.png" /><figcaption>An image rendered by Fim</figcaption></figure><p>To install it:</p><pre>sudo apt install fim # Debian/Ubuntu</pre><p>For other Linux distributions look <a href="https://www.nongnu.org/fbi-improved/#download">here</a>. To open an image:</p><pre>fim image.png # One image<br>fim *.png # Multiple images at once</pre><p>Now that you’ve opened an image, you can use the Fim console by typing : . Try it.</p><pre>:narrow<br>:flip<br>:mirror<br>:q # Exit</pre><p>To see all commands, type : , and then press tab. Apart from the console, there are also keyboard shortcuts, for example:</p><ul><li>f — Flips image</li><li>m — Mirrors image</li><li>r — Rotates image clockwise</li><li>-/+ — Zooms image</li><li>n/p — Goes to the next/previous image</li><li>q — Quits the program</li></ul><p>You can also check out <a href="https://github.com/derf/feh">Feh</a> which works similarly, as well as <a href="https://github.com/xyb3rt/sxiv">Sxiv</a>.</p><h3>Terminology</h3><p><a href="https://github.com/borisfaure/terminology">Terminology</a> is the next-level terminal of its kind. It’s quite aesthetic and powerful. It can show you images and even play videos inside the terminal. However, it’s definitely not lightweight and has a lot of dependencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*LYEkfe7i4N4vvBjorDhLtA.png" /><figcaption>An image rendered by Terminology</figcaption></figure><p>To install it:</p><pre>sudo apt install terminology # Debian/Ubuntu</pre><p>Terminology should also work on most other Linux distributions, look <a href="https://www.enlightenment.org/download">here</a>. When running it for the first time, it will ask you for some configuration options which you can leave on default value, except for scale which I recommend setting to 1.5 (You can change the configuration later by pressing right click inside Terminology terminal and going to Settings). So, let’s start it:</p><pre>terminology</pre><p>A new terminal window will pop up. Notice that it’s still your default shell, but now with animations. Try typing ls and pressing tab to see something cool. Now navigate to some directory with images and type tyls .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*0pMEHspH8der5uLTcKnoNg.png" /><figcaption>A list rendered by Terminology</figcaption></figure><p>This command will show you list of files, but with little thumbnails. Even PDF files will have a thumbnail. To open an image, type:</p><pre>tycat image.png # One image<br>tycat *.png # Multiple images at once</pre><p>You can also use tycat to play a video. You can even play multiple videos at the same time in your terminal:</p><pre>tycat video.mp4 # One video playing<br>tycat *.mp4 # Multiple videos playing at once</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*uQ4B1Qv3aioBTq0soj2r_Q.png" /><figcaption>A video playing in Terminology</figcaption></figure><p>In the lower right corner, there are some neat basic video and audio controls.</p><p>If you want to pop an image or a video out of terminal, use typop command. The image will be shown as an overlay over your terminal window.</p><h3>XDG-open</h3><p>After all those terminal tools, maybe you want to go back to GUI. In that case, simply run:</p><pre>xdg-open image.png</pre><p>This command will open the image, or any file actually, in the default application for that file type. In case of Ubuntu, it will open Eye of GNOME for images.</p><h3>Conclusion</h3><p>When researching for this article, I really didn’t think there’s gonna be so many programs and ways to open an image in the terminal. But, the Internet showed me I was wrong. It seems there are a lot of people that want to see their images directly inside the terminal. I like how most of these programs are lightweight and some of them even work over SSH connection. They save computer resources and time. Well, Terminology isn’t so lightweight, but it’s looks really cool to me and it bugs me that I didn’t know about it before.</p><p>Thank you for reading. I hope you learned something new. If so, be sure to follow me.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0c730b2f1f04" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Tips and Tricks for Bash Scripting After Writing Hundreds of Scripts]]></title>
            <link>https://levelup.gitconnected.com/my-tips-and-tricks-for-bash-scripting-after-writing-hundreds-of-scripts-59987855b20a?source=rss-ab4361e8ec33------2</link>
            <guid isPermaLink="false">https://medium.com/p/59987855b20a</guid>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[bash]]></category>
            <category><![CDATA[tips-and-tricks]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Tin Plavec]]></dc:creator>
            <pubDate>Sun, 15 Oct 2023 16:48:12 GMT</pubDate>
            <atom:updated>2023-10-15T16:48:12.581Z</atom:updated>
            <content:encoded><![CDATA[<p>As a DevOps engineer, I’ve often encountered with Bash. Doing something on a server, writing CI/CD pipelines, or automating some manual task are all regular activities that regularly include writing some Bash scripts. Here I’ll share my tips and best practices to follow when scripting in Bash.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FIlY4CNDO7OUgK-x" /><figcaption>Photo by <a href="https://unsplash.com/@6heinz3r?utm_source=medium&amp;utm_medium=referral">Gabriel Heinzer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>1. Distinguish variables</h3><p>When it comes to variables in Bash, there are two well-known good practices.</p><ol><li>Always put curly brackets {} around the variable name.</li><li>Always put double quotes &quot;&quot; around the variable.</li></ol><p>Therefore, a variable should look like this: &quot;${variable_name}&quot; . This way variables are clearly distinguished from the rest of the code and spaces inside a variable value will not cause problems. Let’s illustrate the problem with spaces on an example.</p><pre>mkdir tips<br>echo &quot;File content&quot; &gt; &quot;tips/Filename with spaces&quot;<br>ls -l tips</pre><p>After running the commands, we have tips directory that contains one file, however, the file has spaces in its name. Let’s now try to iterate over files in tips directory. There should only be one file.</p><pre>for filename in $(ls tips); do<br>  echo Found: ${filename}<br>  cat tips/${filename}<br>done</pre><p>The for loop will generate:</p><pre>Found: Filename<br>cat: tips/Filename: No such file or directory<br>Found: with<br>cat: tips/with: No such file or directory<br>Found: spaces<br>cat: tips/spaces: No such file or directory</pre><p>Obviously the output is not what we wanted. Try now the same for loop, but with double quotes added.</p><pre>for filename in &quot;$(ls tips)&quot;; do<br>  echo Found: &quot;${filename}&quot;<br>  cat tips/&quot;${filename}&quot;<br>done</pre><p>Notice that double quotes should also be put around command outputs, in this case: &quot;$(ls tips)&quot; . Final output should now be correct:</p><pre>Found: Filename with spaces<br>File content</pre><p>In this example, echo and cat could also be written like this:</p><pre>  echo &quot;Found: ${filename}&quot;<br>  cat &quot;tips/${filename}&quot;</pre><p>There is one more thing to note about the variables. Local variables are usually written in lowercase. Environment variables are written in uppercase. Run env to see current env variables of your terminal — they are all in uppercase. So, when using export to export a variable from your script to the environment, use uppercase.</p><pre>export cluster_name=&quot;r2d2&quot; # bad<br>export CLUSTER_NAME=&quot;r2d2&quot; # good</pre><h3>2. Handle errors</h3><p>Unfortunately, Bash doesn’t have an intuitive, straight-forward error handling mechanism. Catching an exception with try-catch block is not possible. The only way to check for errors is to evaluate the exit code of a command. No matter if you’re running your script interactively or non-interactively, the script should check these error codes. The simplest way is to use if and check the exit code in $?:</p><pre>if cat file; then<br>  echo &quot;Exit code 0. No problems.&quot;<br>else<br>  echo &quot;Exit code $?&quot;<br>  echo &quot;Handling error..&quot;<br>fi</pre><p>If you’re not using the if check, then add set -e to your script. With this option, Bash script will exit when some command fails. This is expected behavior in other programming languages, but Bash by default doesn’t exit if a command fails inside a script.</p><pre>set -e<br>cat no_file # Throws error<br>cat no_file2 # This part is not reached</pre><p>With set -e , only cat no_file will be run and the script will exit. Now try removing set -e . You’ll see that both cat commands are run in this case, even tough both of them fail.</p><p>You should also add set -o pipefail , so that pipe fails if one of the commands in the pipe fails. By default, pipe will fail only if the last command fails.</p><pre>set -eo pipefail<br>cat no_file | echo # Throws error<br>echo &quot;End&quot; # This part is not reached</pre><p>And there is also set -u that treats use of an undefined (unbound) variable as error.</p><pre>set -euo pipefail<br>echo &quot;${var}&quot; # Throws error and exits</pre><p>If you remove -u option, script will exit successfully, while echo will print empty string.</p><p>There are more options beyond those mentioned, however, this article would get too long. I will just tell you that you can also use case for determining the exit code, operators || and &amp;&amp; for controlling the flow, and even trap to achieve some kind of error catching. I personally prefer using a simple if as that’s very easy to read.</p><h3>3. Use indentation and multiple lines</h3><p>In Bash, you can literally fit an entire script in a single line of text using ; . Obviously, nobody does that, but a lot of people write long commands with a lot of arguments in a single line. This isn’t good practice as you can’t easily see the entire command. Instead, split that line into multiple lines and add indentation. For example:</p><pre>az aks create \<br>  --resource-group my-resource-group \<br>  --name my-aks-cluster \<br>  --enable-managed-identity \<br>  --node-count 1 \<br>  --enable-addons monitoring \<br>  --generate-ssh-keys</pre><p>Some may say that you can fit two or three arguments in a line, but I prefer every argument in a separate line, as it’s more clear. Funnily enough, I took the above command from Microsoft Azure docs, where they put everything into single line, so you have to scroll horizontal to see the command you’re about to copy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*Zv1nV7LeaD6ahGphI6w0BQ.png" /><figcaption><a href="https://learn.microsoft.com/en-us/azure/aks/learn/quick-kubernetes-deploy-cli#create-an-aks-cluster">learn.microsoft.com</a></figcaption></figure><p>On the other hand, Google Cloud docs do split a command into multiple lines so it’s easier to read:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*AuUlFNBsQNkiVrsnw2fiRg.png" /><figcaption><a href="https://cloud.google.com/kubernetes-engine/docs/how-to/creating-a-zonal-cluster#creating-a-cluster">cloud.google.com</a></figcaption></figure><p>Furthermore, I highly recommend to use indentation when writing if-else blocks and loops. Here are a few examples:</p><pre>if [[ &quot;${PASSWORD}&quot; == &quot;${ADMIN_PASSWORD}&quot; ]]; then<br>  echo &quot;Access granted&quot;<br>else<br>  echo &quot;Access denied&quot;<br>fi</pre><pre>while &quot;${RUN}&quot;; do<br>  if [[ -f new_file ]]; then<br>    break<br>  fi<br>  sleep 1<br>done</pre><p>Also, be sure to standardize if indentation should be two or four spaces. I prefer two spaces, but you or your team may prefer four. Just be sure to stay consistent.</p><h3>4. Test with Shellcheck</h3><p>Shellcheck is a linter for Bash. You can install it with apt, dnf, pkg and brew, use <a href="https://www.shellcheck.net/">online version</a>, or install it directly to your <a href="https://github.com/koalaman/shellcheck#user-content-in-your-editor">editor</a>.</p><pre>sudo apt install shellcheck</pre><p>To check a script, simply execute:</p><pre>shellcheck script.sh</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*omXCZdBd9SFGt_wX5-BomQ.png" /><figcaption>Feedback from Shellcheck</figcaption></figure><p>Shellcheck will conveniently remind you to add a shebang (#!/bin/bash ) , add double quotes, warn you if you misused quotes or used an unassigned variable, tell you about problems in conditional expressions, and <a href="https://github.com/koalaman/shellcheck#gallery-of-bad-code">more</a>. It’s really useful, especially if you’re new to Bash. I also recommend to add Shellcheck to your CI/CD pipeline.</p><h3>5. Add comments where necessary</h3><p>Comments help other people when they read your script. Comments can also help you when you read your own old script that you forgot about, but now need it. You don’t have to spend time writing some in-depth comments, but be sure to add comments to lines that are a bit hard to grasp. With time, you will develop a habit of writing these comments automatically, without even thinking about it.</p><pre># Get all deployments that have prometheus scraping enabled<br>kubectl get deployments \<br>  --all-namespaces \<br>  -o=jsonpath=&#39;{.items[?(@.spec.template.metadata.annotations.prometheus\.io/scrape==&quot;true&quot;)].metadata.name}&#39;</pre><p>This is a sample command I found on <a href="https://stackoverflow.com/questions/62264658/filter-kubectl-get-based-on-annotation">Stack Overflow</a> that definitely needs a comment if you’re gonna use it in your script.</p><h3>6. Use a timeout</h3><p>I’ve encountered many situations where the script has to wait for some external task to finish. For example, it has to wait until a file is created, until a Kubernetes pod is running, until a VM is up, until some job is finished and so on. In cases like these, you should define a timeout for that command or a loop, because something may fail in the cloud (or any external service) and the resource may never get provisioned. To add timeout to a command, you can simply use timeout . If time runs out, exit status is 124. Play with the next example and reduce sleep time so that Done is printed out.</p><pre>timeout 2s sleep 5 &amp;&amp; echo Done</pre><p>For a loop you can do the following trick:</p><pre># Wait for new_file for 10 seconds<br>timeout 10s bash -c \<br>  &#39;until [[ -f new_file ]]; do<br>    echo &quot;User ${USER} is waiting a file..&quot;<br>    sleep 1<br>  done&#39;</pre><p>Double quotes inside single quotes will work here, because bash -c launches a new shell and then everything in between the single quotes is parsed the same way your shell input is parsed. Try running the loop and see how timeout will kill it after 10 seconds. Run the loop again and quickly create new_file in the same directory. The loop should exit successfully without timing out.</p><h3>7. Find an appropriate tool</h3><p>When scripting, it is important to know there are really a lot of tools that can help you. I remember an intern who had the task to parse YAML with a Bash script. He had to evaluate all the files in a directory. If a file had a specific YAML key that had an array as the value, he had to evaluate all the elements of the array. To simplify the example, let’s say he had to evaluate if each element had character r .</p><pre>yamlKey:<br>  - first<br>  - second<br>  - third<br>anotherKey: &quot;val&quot;</pre><p>So, he used grep -n to find if a file contains yamlKey and to save the line number of the key. Then, he used sed to read the next line and checked if it begins with two spaces and a minus — meaning it’s element of an array. In that case, he would check with regex if line contains r . Then, he would go to the next line. If the line doesn’t start with two spaces and a minus, it means the array is over. Reading the code was painful. The code actually worked, but only for so long. In YAML, there is another way to define an array:</p><pre>yamlKey: [first, second, third]<br>anotherKey: &quot;val&quot;</pre><p>That’s why you should always google a little bit before writing some hacky solution. Most likely there is a program that can solve your problem. In this case it’s <a href="https://github.com/mikefarah/yq">yq</a>, a command-line interface for processing YAML syntax.</p><h3>8. Consider Python for complex tasks</h3><p>There is a never ending debate on Python versus Bash — which one is better in which situation. Python is more powerful, but Bash is more universal and lightweight. Bash is available on basically every Linux server and CI/CD tool by default. Knowledge of Bash is for sure useful. But when it comes to complex tasks like sending a lot of GET and POST requests, interacting with APIs and processing a lot of data, Python is just easier to write. In Bash, you would have to do a lot of text parsing and error checking. Nevertheless, Bash is still a popular choice among DevOps engineers. Most DevOps tutorials and a lot of docs use primarily command-line interface to explain how to do some task. For example, Kubernetes has a <a href="https://github.com/kubernetes-client/python">Python client</a>, but when googling how to do something in Kubernetes, you will always find kubectl commands that you can run in Bash.</p><p>Thank you for reading! I hope you learnt something new. Now that you’ve read about best practices for Bash scripting, maybe you want to have some fun with the Bash terminal. In that case check out my other article and follow me.</p><p><a href="https://tinplavec.medium.com/12-super-cool-terminal-easter-eggs-edf6b48eb32c">12 Super Cool Terminal Easter Eggs You Need To Try</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59987855b20a" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/my-tips-and-tricks-for-bash-scripting-after-writing-hundreds-of-scripts-59987855b20a">My Tips and Tricks for Bash Scripting After Writing Hundreds of Scripts</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>