<?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[Coding Kubernetes - Medium]]></title>
        <description><![CDATA[You just got a ticket that requires you to use Kubernetes libraries. Now you’re drowning in imports and interfaces. I’ve been there. These blogs are meant to give you back those hours you spend squinting at dependencies and directory structures. - Medium]]></description>
        <link>https://medium.com/coding-kubernetes?source=rss----f547712f7497---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Coding Kubernetes - Medium</title>
            <link>https://medium.com/coding-kubernetes?source=rss----f547712f7497---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 02:12:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/coding-kubernetes" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Using K8s Label Selectors in Go — the right way!]]></title>
            <link>https://medium.com/coding-kubernetes/using-k8s-label-selectors-in-go-the-right-way-733cde7e8630?source=rss----f547712f7497---4</link>
            <guid isPermaLink="false">https://medium.com/p/733cde7e8630</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[labels]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[k8s]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[John Montroy]]></dc:creator>
            <pubDate>Sun, 24 Jan 2021 03:10:18 GMT</pubDate>
            <atom:updated>2021-01-24T15:16:39.467Z</atom:updated>
            <content:encoded><![CDATA[<h3>Using K8s Label Selectors in Go without doing it wrong</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5dWN6cMCN_fvc_YtFsBmTg.png" /><figcaption>This is the good stuff.</figcaption></figure><p>Labels are how we group objects together in Kubernetes. Label selectors are how we use those labels to retrieve our grouped objects. There are a <a href="https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/">bazillion</a> <a href="https://kubernetesbyexample.com/labels/">articles</a> <a href="https://www.tutorialspoint.com/kubernetes/kubernetes_labels_selectors.htm">out</a> <a href="https://medium.com/faun/node-labels-and-selectors-in-kubernetes-76fbd8a8940c">there</a> on the subject, so if you’re not familiar, start there.</p><p>Instead, our focus here is: <strong>how do I use Kubernetes libraries to work with labels via label selectors?</strong></p><p>If you’re just looking for quick help, the Cheatsheet section will give you top-level summary info. Otherwise, read on.</p><blockquote><strong>Important: </strong>all Go Playground examples here might need to be run a few times for the dependencies to load in. Go Playground has an unforgiving timeout.</blockquote><h3>Cheatsheet</h3><p>There are two Go types for working with label selectors: the <a href="https://github.com/kubernetes/apimachinery/blob/460d10991a520527026863efae34f49f89c2f4e1/pkg/labels/selector.go#L45">labels.Selector</a> interface, and the <a href="https://github.com/kubernetes/apimachinery/blob/460d10991a520527026863efae34f49f89c2f4e1/pkg/apis/meta/v1/types.go#L1096">LabelSelector</a> struct. They are different.</p><ol><li><a href="https://github.com/kubernetes/apimachinery/blob/460d10991a520527026863efae34f49f89c2f4e1/pkg/labels/selector.go#L45">labels.Selector</a> is used for <strong>filtering</strong> <strong>client reads</strong>. It’s like the client-go equivalent of kubectl label ... -l service=backend. Use <a href="https://github.com/kubernetes/apimachinery/blob/460d10991a520527026863efae34f49f89c2f4e1/pkg/labels/selector.go#L96">labels.NewSelector</a> + <a href="https://github.com/kubernetes/apimachinery/blob/460d10991a520527026863efae34f49f89c2f4e1/pkg/labels/selector.go#L152">labels.NewRequirement</a> to construct something the client-go can query with.</li><li>The <a href="https://github.com/kubernetes/apimachinery/blob/460d10991a520527026863efae34f49f89c2f4e1/pkg/apis/meta/v1/types.go#L1096">LabelSelector</a> struct is used as part of individual Resources as the <strong>API type</strong>. You’d <a href="https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#resources-that-support-set-based-requirements">write this struct in your object’s YAML</a> before applying. So you might get this <strong>from</strong> a read (as part of a returned object, e.g. <a href="https://github.com/kubernetes/api/blob/fedd331d628e80908d201b026e3f3dd32f702478/apps/v1beta2/types.go#L341">Deployment</a>), but don’t use this struct <strong>for</strong> client reads.</li><li>You can <strong>convert</strong> from a LabelSelector (what you get from a read) to a label.Selector (what you use to read) with <a href="https://github.com/kubernetes/apimachinery/blob/460d10991a520527026863efae34f49f89c2f4e1/pkg/apis/meta/v1/helpers.go#L34">LabelSelectorAsSelector</a> . But if you’re doing this, you’re either doing something Controller-esque (if so, fine) OR you should just be using labels.Selector directly.</li></ol><h3>Using labels.Selector</h3><p>The labels.Selector interface is located in the <a href="https://github.com/kubernetes/apimachinery">apimachinery</a> repo under <a href="https://github.com/kubernetes/apimachinery/blob/master/pkg/labels/selector.go">pkg/labels/selector.go</a>. It’s used to read and query Kubernetes Objects via their labels.</p><p>You should use it because:</p><ol><li>It provides standard validation for requirements, keys, and values.</li><li>It’s what Kubernetes libraries uses, so it’s battle-tested to the extreme.</li></ol><p>Initialize a new selector with labels.NewSelector() , and then add labels.Requirements as desired. Think of each Requirement as akin to the normal kubectl label operations you might use for <a href="https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#equality-based-requirement">equality-based</a> and <a href="https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#set-based-requirement">set-based</a> label selection (<a href="https://play.golang.org/p/pZtDqfDmC8i">Go Playground</a>):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b19b189762d01e2d71174b99ee421fc/href">https://medium.com/media/7b19b189762d01e2d71174b99ee421fc/href</a></iframe><p>apimachinery gives you a few additional perks out of the box:</p><ol><li><a href="https://github.com/kubernetes/apimachinery/blob/460d10991a520527026863efae34f49f89c2f4e1/pkg/labels/selector.go#L152">Requirement validation</a> (e.g. Equals shouldn’t have two values).</li><li><a href="https://github.com/kubernetes/apimachinery/blob/460d10991a520527026863efae34f49f89c2f4e1/pkg/util/validation/validation.go#L42">Key validation</a> (e.g. can’t lead with characters like - or _ )</li><li><a href="https://github.com/kubernetes/apimachinery/blob/460d10991a520527026863efae34f49f89c2f4e1/pkg/util/validation/validation.go#L166">Value validation</a> (e.g. label values can’t exceed 63 characters)</li></ol><p>(Note: these key / value validations are widely used and worth perusing in full.)</p><p>apimachinery also provides helpful additional functionality (<a href="https://play.golang.org/p/1RPOPJRCYwX">Go Playground for both</a>):</p><ul><li><strong>labels.Parse</strong> allows you to use the same kubectl label syntax you might already be familiar with.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d47271dbc3664f94a2812c30f9bd9335/href">https://medium.com/media/d47271dbc3664f94a2812c30f9bd9335/href</a></iframe><ul><li><strong>labels.ValidatedSelectorFromSet</strong> is a validated convenience for the simplest label selection use case: give me all objects that match this label set exactly, AND’d together. Pass a Set object (under the hood, just map[string]string like labels themselves), it validates client-side (early errors, no extra load on the API Server), and gives you a Selector you can use to query:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31dba88e452538eeda9dd6f5e1d202e4/href">https://medium.com/media/31dba88e452538eeda9dd6f5e1d202e4/href</a></iframe><h3>What about LabelSelector?</h3><p>LabelSelector is an API type. That means it’s used as part of various Kubernetes Resource Specs. It’s not for client usage or library code, it’s part of the API, just like Pods and ConfigMaps.</p><p>This fact is reflected by where it lives: in apimachinery, but under pkg/apis/v1/meta/types.go. Indeed, comments in that file indicate:</p><blockquote>The package contains two categories of types:</blockquote><blockquote>— external (serialized) types that lack their own version (e.g TypeMeta)</blockquote><blockquote>— internal (never-serialized) types that are needed by several different api groups, and so live here, to avoid duplication and/or import loops (e.g. LabelSelector).</blockquote><p>So when you create an Object, you’re probably going to write out a LabelSelector struct in YAML, and when you retrieve Objects from the API Server using labels.Selector as above, your returned Objects might contain the LabelSelector struct as a field. Modified example from the docs:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: nginx-deployment<br>spec:<br>  replicas: 3<br>  selector:<br>    matchLabels:<br>      app: nginx<br>  template:<br>    &lt;snip&gt;</pre><p>That spec.selector is a LabelSelector struct object behind the scenes. The Deployment controller will use it (converting it to labels.Selector , more below) to query the Deployment’s Pods.</p><p>If this all sounds very obvious to you, good. The key point to understand here is the difference between normal library code and API types. labels.Selector is library code used to read and filter Kubernetes Objects. LabelSelector is part of the API type you get back from those reads.</p><h3>Converting between the two</h3><p>Say you use a labels.Selector to query Deployments . You get back matching Deployment Objects, all of which have their own LabelSelector data at spec.selector. Maybe you want to now use those LabelSelector objects to query the Pods programmatically. So we need to convert from LabelSelector to labels.Selector (API type -&gt; library type for querying).</p><p>LabelsSelectorAsSelector is your ticket here (r.i.p. Go Playground, not a chance on these dependencies):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95d5fc7967060d7ef73a75c61ec2a0d8/href">https://medium.com/media/95d5fc7967060d7ef73a75c61ec2a0d8/href</a></iframe><p>Why do we need to do this? Well, controllers do it all the time! In order for the Deployment controller to get all Pods it owns, it will:</p><ol><li>Get the LabelSelector API type from a Deployment at spec.selector .</li><li>Convert it to a labels.Selector using LabelsSelectorAsSelector .</li><li>Query Pods using the newly-converted labels.Selector.</li></ol><p>See for yourself in the <a href="https://github.com/kubernetes/kubernetes/blob/fb276ce2015a8bab93dd2d6ff96ca23a657df67b/pkg/controller/deployment/deployment_controller.go#L536">Deployment Controller</a>, reproduced and shortened here:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a5e6456817ecb3071e37fb5a5381742/href">https://medium.com/media/9a5e6456817ecb3071e37fb5a5381742/href</a></iframe><p>This also serves as a great example of everything we’ve discussed here, including actually passing a labels.Selector to a Pod client and querying away!</p><h3>Conclusions</h3><p>labels.Selector is library code for filtering reads. LabelSelector is an API type used in other Objects like Deployments and StatefulSets. If you’re writing Go code, you probably want to work with labels.Selector, unless you’re writing controller code that needs to work with some Resource’s selector field!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=733cde7e8630" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coding-kubernetes/using-k8s-label-selectors-in-go-the-right-way-733cde7e8630">Using K8s Label Selectors in Go — the right way!</a> was originally published in <a href="https://medium.com/coding-kubernetes">Coding Kubernetes</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>