<?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 Mattia Forcellese on Medium]]></title>
        <description><![CDATA[Stories by Mattia Forcellese on Medium]]></description>
        <link>https://medium.com/@mattiaforc?source=rss-5873485b5000------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Ox7IKl1SRz5EsfAOsry7Tw.png</url>
            <title>Stories by Mattia Forcellese on Medium</title>
            <link>https://medium.com/@mattiaforc?source=rss-5873485b5000------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 03:30:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mattiaforc/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[Private kubernetes ingress with tailscale operator, cert-manager and external-dns]]></title>
            <link>https://medium.com/@mattiaforc/zero-trust-kubernetes-ingress-with-tailscale-operator-cert-manager-and-external-dns-8f42272f8647?source=rss-5873485b5000------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f42272f8647</guid>
            <category><![CDATA[tailscale]]></category>
            <category><![CDATA[vpn]]></category>
            <category><![CDATA[dns]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[cloud]]></category>
            <dc:creator><![CDATA[Mattia Forcellese]]></dc:creator>
            <pubDate>Sun, 23 Jun 2024 20:47:17 GMT</pubDate>
            <atom:updated>2024-06-25T21:51:43.028Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*Lgg3qJBiLxpbPumF6ZgcpA@2x.jpeg" /></figure><p>In this article you will learn how to expose an ingress privately on a tailnet that is accessible only via Tailscale, with a custom domain, automatic DNS records and valid Let’s Encrypt certificates.<br>If you don’t need a custom domain to expose ingresses and you are ok using the default Tailscale <a href="https://tailscale.com/kb/1081/magicdns">MagicDNS</a>, you can skip some of the following steps because you won’t need external-dns and cert-manager.</p><p>What do we want to achieve? We want to be able to access some service on kubernetes only from devices connected to tailscale. Suppose we have the domain foo.com, we want to configure an ingress for Grafana that responds to grafana.foo.com .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HJxS4j9Cm37gFwsueFf9Wg.png" /></figure><p><strong>Requirements</strong>:</p><ul><li>A <a href="https://login.tailscale.com/start">tailscale account</a>: I am using a free plan, so any other plan works as well.</li><li>A kubernetes cluster: I am running a cloud managed kubernetes, hosted on Aruba Cloud (based in Italy), but you can also run it locally with minikube/kind or any other kubernetes distribution.</li><li>A registered domain: in this example I am using a domain on Cloudflare, and I will be using external-dns with Cloudflare, but any of the <a href="https://github.com/kubernetes-sigs/external-dns?tab=readme-ov-file">supported providers</a> should be fine as well.</li></ul><h3>Let’s deploy what we need</h3><blockquote>Note that we are doing lots of manual installation with helm and the kubectl CLI; it would be wiser to use a CD tool like Argo CD or Flux CD and keep manifests/values versioned in a Git repository.</blockquote><p>First, we are going to install the tailscale operator. The <a href="https://tailscale.com/kb/1236/kubernetes-operator#setting-up-the-kubernetes-operator">official docs</a> for deploying the operator are very thorough and accurate, so I suggest you follow that to be sure you use the most up-to-date version. You can install it via helm and there are no values to set other than the OAuth credentials that tailscale requires you to setup. An example values.yaml file could look this:</p><pre>oauth:<br>  clientId: xxxx<br>  clientSecret: xxxx</pre><p>Second, we are going to deploy cert-manager; again this is pretty straightforward if you look at <a href="https://cert-manager.io/docs/installation/">their documentation</a>, you can deploy it via Helm with no particular configuration or via static manifests. This is optional if you plan to use the default Tailscale MagicDNS.</p><p>Next comes external-dns: in this case the configuration pretty much depends on your DNS provider; there are <a href="https://github.com/kubernetes-sigs/external-dns?tab=readme-ov-file#deploying-to-a-cluster">many to choose from</a>, follow the configuration steps according. For Cloudflare, an example values.yaml file would be like this:</p><pre>provider: <br>  name: cloudflare<br>env:<br>  - name: CF_API_TOKEN<br>    value: xxxx<br>serviceMonitor:<br>  enabled: true<br>txtOwnerId: &lt;a static ID that identifies this k8s cluster&gt;<br>domainFilters:<br>  - domain.com<br>policy: sync # Important to note that if not set to sync (by default is write-only), DNS records wont&#39;t be deleted when we delete ingress resources</pre><p>Lastly, we need to install and expose the ingress controller only on the Tailscale private network. That’s where the interesting part begins, but before that let’s take a small step back and talk about the Tailscale operator and how it works for services and ingresses.</p><h3>Tailscale operator</h3><p>The tailscale operator can expose workloads to the tailnet in three different ways:</p><ul><li>Create a LoadBalancer type Service with the tailscale <a href="https://tailscale.com/kb/1236/kubernetes-operator#loadbalancerclass">loadBalancerClass</a> that fronts your workload.</li><li><a href="https://tailscale.com/kb/1236/kubernetes-operator#annotations">Annotate</a> an existing Service that fronts your workload</li><li>Create an <a href="https://tailscale.com/kb/1236/kubernetes-operator#ingress-resource">Ingress resource</a> fronting a Service or Services for the workloads you wish to expose.</li></ul><p>I want to focus mainly on the first and the third option. If you create an ingress resource with the tailscale ingress class, you will automatically get a tailnet IP, like <em>100.xxx.xxx.xxx</em>, and a MagicDNS record, if enabled, that you can call when you are connected to tailnet. The FQDN for ingress will be like this: grafana.tailxxxx.ts.net.<br>This would the easiest option; you simply need to enable HTTPS on tailscale and all traffic will be encrypted via Let’s Encrypt certificates that are handled directly by Tailscale. There are a few limitations though: you can only use the tailxxxx.ts.net domain, so it’s harder to remember and if used for internal services by a company, it’s probably an unwanted result. Another downside is that you can’t use all the regular features of your ingress controller (in this example I am using Nginx but any other ingress controller is also fine) because traffic is handled directly by a Tailscale pod that serves that specific ingress. <br>If you are fine with the limitations above, than you are already good to go: if you deployed everything from the previous steps, you can create an ingress with tailscale class and you should see the newly added ingress in the tailscale Machines in the Tailscale control panel, and be able to reach it via its FQDN or IP.</p><p>This brings us to the first way of exposing workloads to tailnet, which is creating LoadBalancer Services that get automatically assigned an IP inside the tailnet, just as a normal LoadBalancer would assign the service an IP in a managed Kubernetes clusters (AKS, EKS, etc…). That’s exactly what we want to do to expose the ingress controller: so that we only have one service exposed in the tailnet that will respond to various ingresses (this is the normal ingress controller scenario). Remember that we want to be able to call our services via the URL grafana.foo.com , so we also need to configure DNS records that point to the tailscale private IP for the ingress controller.</p><h3>Back to the ingress controller</h3><p>Now that we know how to expose the ingress controller, we can deploy it (or simply reconfigure the service) with a tailscale LoadBalancer . Let’s deploy <a href="https://github.com/kubernetes/ingress-nginx">nginx ingress</a> with the following values.yaml file:</p><pre>controller:<br>  config:<br>    ssl-redirect: &quot;true&quot;<br>    force-ssl-redirect: &quot;true&quot;<br>  replicaCount: 1<br>  service:<br>    type: LoadBalancer<br>    loadBalancerClass: tailscale<br>  ingressClassResource:<br>    default: false<br>  watchIngressWithoutClass: false<br>  metrics:<br>    enabled: true<br>    serviceMonitor:<br>      enabled: true</pre><p>The ssl-redirect is enabled because I want to force services to work only via HTTPS. Note that we don’t need to specify a default TLS certificate because we will be using cert-manager to generate certificates on demand for every ingress.<br>You should see the deployment up and running, with 1 pod ready, and a Service like this:</p><pre>NAME                                 TYPE           CLUSTER-IP       EXTERNAL-IP                                                       PORT(S)                      AGE<br>ingress-nginx-controller             LoadBalancer   10.109.177.63    100.xxx.xxx.xxx,ingress-ingress-nginx-controller.tailxxxx.ts.net   80:31164/TCP,443:31468/TCP   21h</pre><p>After deploying the nginx ingress, <a href="https://cert-manager.io/docs/tutorials/acme/nginx-ingress/#step-6---configure-a-lets-encrypt-issuer">we can configure a Let’s Encrypt Issuer</a> (you could also start with the staging environment, because production has strict rate limits):</p><pre>apiVersion: cert-manager.io/v1<br>kind: ClusterIssuer<br>metadata:<br>  name: letsencrypt-prod<br>spec:<br>  acme:<br>    email: &quot;&lt;email&gt;&quot;<br>    server: https://acme-v02.api.letsencrypt.org/directory<br>    privateKeySecretRef:<br>      name: letsencrypt-prod<br>    solvers:<br>      - dns01:<br>          cloudflare:<br>            apiTokenSecretRef:<br>              name: cloudflare-api-token-secret<br>              key: api-token</pre><p>The most important thing to note is that we are using the dns01 challenge solver, since the ingress won’t be exposed publicly on the internet it would be impossible to use a normal HTTP challenge. Please refer to the <a href="https://cert-manager.io/docs/configuration/acme/dns01/">exhaustive cert-manager documentation about dns01 challenge</a> and all the DNS providers that can be used. In this case, I am using Cloudflare because the example domain foo.bar I am using is registered with Cloudflare.</p><h3>Configure an ingress</h3><p>Now that we have everything in place we can test the whole architecture, so we are going to create an ingress for whatever application we want to expose. If you have no application and want to try it out, I suggest you install the <a href="https://github.com/stefanprodan/podinfo"><em>classic</em> podinfo application</a>. <br>You need to define the ingress with a few annotations, to let external-dns and cert-manager do their jobs:</p><pre>apiVersion: networking.k8s.io/v1<br>kind: Ingress<br>metadata:<br>  annotations:<br>    cert-manager.io/cluster-issuer: letsencrypt-prod # name of the issuer we defined before<br>    external-dns.alpha.kubernetes.io/hostname: grafana.foo.com<br>    kubernetes.io/tls-acme: &quot;true&quot;<br>  name: prometheus-kps-grafana<br>  namespace: prometheus<br>spec:<br>  ingressClassName: nginx<br>  rules:<br>  - host: grafana.foo.com<br>    http:<br>      paths:<br>      - backend:<br>          service:<br>            name: prometheus-kps-grafana<br>            port:<br>              number: 80<br>        path: /<br>        pathType: Prefix<br>  tls:<br>  - secretName: grafana.foo.com<br>    hosts:<br>    - grafana.foo.com</pre><p>Once you create the ingress, the following will happen:</p><ul><li>cert-manager will generate the requested certificate for grafana.foo.com. You can check this simply by looking at the secrets in the same namespace of the ingress: you should see a secret named grafana.foo.com.</li><li>Tailscale operator will expose the new ingress on the tailnet (via the IP of the nginx ingress controller that we deployed before). Again, you should see this in the Machines section of the Tailscale control panel.</li><li>External-dns will publish a DNS A record for grafana.foo.com pointing to the tailnet IP (100.xxx.xxx.xxx)</li></ul><p>You can now try to connect to Tailscale with any registered device (you can <a href="https://tailscale.com/download">download the client here</a>), and cURL the ingress:</p><pre>curl -v https://grafana.foo.com<br><br>*   Trying 100.xxx.xxx.xxx:443...<br>* Connected to grafana.foo.com (100.xxx.xxx.xxx) port 443 (#0)<br>* ALPN, offering h2<br>* ALPN, offering http/1.1<br>*  CAfile: /etc/ssl/certs/ca-certificates.crt<br>*  CApath: /etc/ssl/certs<br>* TLSv1.0 (OUT), TLS header, Certificate Status (22):<br>* TLSv1.3 (OUT), TLS handshake, Client hello (1):<br>* TLSv1.2 (IN), TLS header, Certificate Status (22):<br>* TLSv1.3 (IN), TLS handshake, Server hello (2):<br>* TLSv1.2 (IN), TLS header, Finished (20):<br>* TLSv1.2 (IN), TLS header, Supplemental data (23):<br>* TLSv1.3 (IN), TLS handshake, Encrypted Extensions (8):<br>* TLSv1.2 (IN), TLS header, Supplemental data (23):<br>* TLSv1.3 (IN), TLS handshake, Certificate (11):<br>* TLSv1.2 (IN), TLS header, Supplemental data (23):<br>* TLSv1.3 (IN), TLS handshake, CERT verify (15):<br>* TLSv1.2 (IN), TLS header, Supplemental data (23):<br>* TLSv1.3 (IN), TLS handshake, Finished (20):<br>* TLSv1.2 (OUT), TLS header, Finished (20):<br>* TLSv1.3 (OUT), TLS change cipher, Change cipher spec (1):<br>* TLSv1.2 (OUT), TLS header, Supplemental data (23):<br>* TLSv1.3 (OUT), TLS handshake, Finished (20):<br>* SSL connection using TLSv1.3 / TLS_AES_256_GCM_SHA384<br>* ALPN, server accepted to use h2<br>* Server certificate:<br>*  subject: CN=grafana.foo.com<br>*  start date: Jun 22 13:47:21 2024 GMT<br>*  expire date: Sep 20 13:47:20 2024 GMT<br>*  subjectAltName: host &quot;grafana.foo.com&quot; matched cert&#39;s &quot;grafana.foo.com&quot;<br>*  issuer: C=US; O=Let&#39;s Encrypt; CN=R10<br>*  SSL certificate verify ok.<br>...<br>* Connection #0 to host grafana.foo.com left intact</pre><h3>Final thoughts</h3><p>We exposed a private ingress on the tailnet, on a custom domain foo.bar with Let’s Encrypt valid certificates and a zero-trust posture. The configuration is all automatic due to the integration with external-dns and cert-manager, so it’s a really easy and rapid solution for enabling access to private ingresses in kubernetes clusters (wherever they are located, whether on prem or on cloud) only to authorized devices via Tailscale.</p><p>I’d really like to hear your thoughts and experiences on zero-trust architectures in Kubernetes, VPNs and networking related stuff, especially in small to medium startups; feel free to reach out to me via email or by commenting this article if you want to have a chat on this topic or others :)</p><p>Thanks so much for reading, you can follow me here on Medium, on <a href="http://www.linkedin.com/in/mattia-forcellese-353887144">Linkedin</a> or <a href="https://github.com/mattiaforc">Github</a> for more! See you next time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f42272f8647" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cilium Cluster Mesh + CoreDNS]]></title>
            <link>https://medium.com/@mattiaforc/cilium-cluster-mesh-coredns-17e0c4f108b4?source=rss-5873485b5000------2</link>
            <guid isPermaLink="false">https://medium.com/p/17e0c4f108b4</guid>
            <category><![CDATA[cilium]]></category>
            <category><![CDATA[coredns]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[kubernetes-networking]]></category>
            <category><![CDATA[multi-cluster]]></category>
            <dc:creator><![CDATA[Mattia Forcellese]]></dc:creator>
            <pubDate>Sun, 03 Dec 2023 17:35:08 GMT</pubDate>
            <atom:updated>2023-12-03T17:35:08.743Z</atom:updated>
            <content:encoded><![CDATA[<h3>A smooth multicluster statefulset solution</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*OZ92X7R6csKQSMblF1aRYg.png" /></figure><p>In this article we will see how Cilium Cluster Mesh can be enhanced by using CoreDNS, to get a nice multi cluster experience that will let you distribute and access workloads across multiple Kubernetes clusters and that will also work for StatefulSet resources and headless services.</p><h3>Introduction</h3><p>If you ever fiddled with multiple Kubernetes clusters, whatever the reasons, you know there are lots of different parts and the overall architecture may get complex very fast. There are many different tools out there that can help you set up communication and load balancing across clusters, such as Istio, Linkerd, Cilium, Submariner and K8GB, just to name a few. However, most of them are complex both in the installation and the configuration, and others are too simplistic and do not cover all use cases. Even if there is no one-size-fits-all solution, I believe that Cilium offers a nice trade-off between ease of use, features and complexity, and shines when combined with other open source tools.</p><p>One challenge that you probably faced if you have stateful workloads in Kubernetes, like databases, is to handle complex topologies for HA, resiliency, DR and so on, whilst automating everything (GitOps) and keeping manual action as minimum as possible.</p><p>At work we tried Submariner and it was fine for a while — it had all that we needed: support for overlapping Pod CIDR ranges, service discovery, and more — but when we switched from OpenShift to Kubernetes, changing the CNI from OpenShift SDN to Cilium we began having some troubles. I also want to point out that most of them were due to some of our legacy OpenShift Pod CIDR configurations, and the incompatibility (or guaranteed support) of Submariner with Cilium, and that Submariner itself is a great product that has really nice networking features, and if you have all the prerequisites to deploy it you should probably give it a try! We then decided to go fully down the Cilium road, and have been using Cilium cluster mesh for a while now.</p><p>Every multi-cluster solution handles service discovery and communication in a different way, but something that is indispensable if you want to have a smooth multi cluster experience is the capability of calling services from specific clusters. Why is that? Let’s introduce the example that will be used throughout the whole article:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*l3S6ONuonMzwVyhA6_sQrQ.png" /><figcaption>Two kubernetes clusters where a stateful workload is deployed — with one or more replicas (members of the same “stateful cluster”)</figcaption></figure><p>The stateful workload could be anything (a MongoDB cluster, for example) that needs to be replicated/stretched in multiple clusters. Let’s say that our workload needs to explicitly state in its configuration all the participating members, for example, in pseudocode:</p><pre>members {<br>  member-0.cluster.A<br>  member-1.cluster.A<br>  member-2.cluster.A<br><br>  member-3.cluster.B<br>  member-4.cluster.B<br>  member-5.cluster.B<br>}</pre><p>Now, we have to make a few assumptions on the underlying infrastructure/requirements for this setup:</p><ul><li>Pod CIDR ranges must be unique between clusters (as a simplified example, we consider Cluster A to have 10.255.1.0/24 and Cluster B 10.255.2.0/24).</li><li>Cilium must be installed with the cluster mesh enabled and setup properly (you can find more <a href="https://docs.cilium.io/en/stable/network/clustermesh/clustermesh/">on their documentation</a>).</li><li>If you have any firewall, there is a number of ports to open to let Cilium work its magic — the overall idea is that Kubernetes nodes and pods between Cluster A and B must be able to communicate — either via Encapsulation or via Native-Routing.</li></ul><h3>Cilium with CoreDNS</h3><p>So, Cilium Cluster Mesh is great: it’s tightly integrated with the other features that make cilium a great CNI (Hubble, Network Policies, etc…), it’s powerful and easy to configure. Yet, it lacks the capability (at the moment, maybe in the future they will add something like this!) to specify the cluster when accessing a service — so there is no way to actually call from cluster A the pod member-4 of a stateful workload, with an headless service foo that resides in cluster B, something like member-4.foo.namespace.cluster.B — you can only load balance the service foo between cluster A and B (round robin, local first or remote first). This is where <strong>CoreDNS</strong> comes into play and help us solve this problem!</p><p>With Cluster Mesh we already have routing + policies for infra-cluster traffic, meaning that member-1 can call directly member-4 , like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*LuabHvD-ZIa36NazKdPLWg.png" /><figcaption>The curl command is just an example to understand the network flow</figcaption></figure><p>So our main goal is to have a proper way of calling member-4 without having to rely on its IP (because obviously Pod IPs are volatile and may change anytime when the pod is destroyed/moved/etc), without the hassle of configuring it manually. Even though if something like <a href="https://github.com/kubernetes-sigs/external-dns">external-dns</a> could be used, or even LoadBalancer services with restrictive selectors (to match only member-1 , member-2 , and so on), it is complicated and requires manual intervention and many virtual IPs (or private/public IPs, in case of cloud providers).</p><p>We already have a DNS service that runs inside Kubernetes and works exactly as we need, and that is <a href="https://coredns.io/">CoreDNS</a>: an incredibly flexible DNS server written in Go that works by composition of plugins, which makes it really easy to configure and to adapt to a various range of use cases. We want to exploit the internal CoreDNS of the two clusters to be able to resolve dynamically the IPs of the pods (there are different queries that can be resolved inside Kubernetes, <a href="https://kubernetes.io/docs/concepts/services-networking/dns-pod-service/">check the documentation</a> for all the possibilities!) and to let Cilium handle all the rest. We can picture it like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*QgjHC6qSF7bNTzfmZC3cug.png" /></figure><p>The idea here is to expose the CoreDNS service (there are plenty of options: from LoadBalancer , NodePort to more sophisticated ones — and you can protect/restrict access to it however you like) so that Cluster A will forward requests for a “fake” domain like cluster.B (you can choose whatever fits you) to the CoreDNS of Cluster B, where it will be resolved to the pod address — which, again, is routable and perfectly valid for Cilium Cluster Mesh.</p><h3>Implementation</h3><p>There a few things to configure, but overall this is a really simple customization of the Corefile (the CoreDNS file that configures the DNS server) and the exposure of the CoreDNS service. For this example, CoreDNS will simply be exposed as a NodePort service.</p><p>Let’s start by exposing the NodePort service for CoreDNS: this can be done with a simple manifest:</p><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  labels:<br>    k8s-app: core-dns-nodeport<br>    kubernetes.io/name: CoreDNS<br>  name: core-dns-nodeport<br>  namespace: kube-system<br>spec:<br>  ports:<br>  - name: dns<br>    port: 53<br>    protocol: UDP<br>    targetPort: 53<br>    nodePort: 30053<br>  - name: dns-tcp<br>    port: 53<br>    protocol: TCP<br>    targetPort: 53<br>    nodePort: 30053<br>  selector:<br>    k8s-app: kube-dns<br>  sessionAffinity: None<br>  type: NodePort</pre><blockquote>Again, this is just an example; you could expose the CoreDNS service in many other ways, and you should always think about how to secure/limit the access when doing so.</blockquote><p>Then, we can edit the <a href="https://kubernetes.io/docs/tasks/administer-cluster/dns-custom-nameservers/#coredns-configmap-options">default CoreDNS configuration</a> of Cluster A (which is by default a ConfigMap named coredns in the namespace kube-system) and add the following snippet:</p><pre>...<br># This means that every query for the &quot;fake&quot; zone cluster.B will be<br># handled by this configuration.<br>cluster.B:53 {<br><br>    # This will substitute the cluster.B string in the query with <br>    # svc.cluster.local, that can be handled correctly by the remote CoreDNS.<br>    rewrite name substring cluster.B svc.cluster.local<br>    <br>    # We exposed the coredns service as a NodePort (30053).<br>    # This is an example of nodes static IPs, but you could also use<br>    # a DNS record, a load balancer, etc...<br>    forward . 192.168.2.1:30053 192.168.2.2:30053 {<br>        expire 10s<br>        policy round_robin<br>    }<br>    cache 10<br>}<br><br>...<br><br>:53 {<br>    ...<br>    # We also add the rewrite for cluster.A (self)<br>    # Add this line before the default &quot;kubernetes&quot; block<br>    rewrite name substring cluster.A svc.cluster.local<br>    kubernetes cluster.local in-addr.arpa ip6.arpa {<br>        ...<br>    }<br>    ...<br>}</pre><p>The same configuration, but with the opposite cluster forwarding, is done for Cluster B:</p><pre>...<br>cluster.A:53 {<br>    rewrite name substring cluster.A svc.cluster.local<br>    <br>    # Note that this IPs are different because they are the IPs of cluster A!<br>    forward . 192.168.1.1:30053 192.168.1.2:30053 {<br>        expire 10s<br>        policy round_robin<br>    }<br>    cache 10<br>}<br><br>...<br><br>:53 {<br>    ...<br>    rewrite name substring cluster.B svc.cluster.local<br>    ...<br>}</pre><p>This is what the configuration does:</p><ul><li>We defined the zone cluster.B that will answer to queries on port 53 (UDP by default, but TCP can also be used with the option force_tcp).</li><li>The zone will rewrite the DNS query before forwarding it to the other cluster CoreDNS: it will simply substitute the substring cluster.B with svc.cluster.local, so that the query that will go to Cluster B will still be a valid query.</li><li>We forward the query to the NodePort CoreDNS service, which will get us the IP of the requested pod.</li><li>We also have to define a rule for rewriting cluster.A into svc.cluster.local — remember we specified in our ideal statefulset the members member-1.cluster.A , member-2.cluster.A , etc… So pods in cluster A still need to be able to contact pods in the same cluster via this name and not only pods in cluster B.</li></ul><p>At this point, everything is setup, and we can restart the Coredns pods in the kube-system namespace. If the ConfigMap is correct, the pod will be ready in a matter of seconds. You can test if everything is working by simply doing a cURL or a nslookup from a pod inside cluster A to an headless service in cluster B and you should see that the IP of the pod in cluster B is correctly resolved and routable!</p><h4>Conclusion</h4><p>We saw how Cilium cluster mesh can be enhanced by simply combining it with CoreDNS, so that you are able to call specific services in specific clusters. Not only that: since the solution is basically based only on Cilium, you can still leverage all the features that Cilium offers for multicluster traffic, such as Hubble, or Network Policies, that will be still valid.</p><p>Thanks so much for reading, you can follow me here on Medium, on <a href="http://www.linkedin.com/in/mattia-forcellese-353887144">Linkedin</a> or <a href="https://github.com/mattiaforc">Github</a> for more! See you next time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17e0c4f108b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying Thanos for monitoring multiple Openshift/Kubernetes clusters]]></title>
            <link>https://medium.com/@mattiaforc/deploying-thanos-for-monitoring-multiple-openshift-kubernetes-clusters-1f2e3d212ab6?source=rss-5873485b5000------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f2e3d212ab6</guid>
            <category><![CDATA[prometheus]]></category>
            <category><![CDATA[grafana]]></category>
            <category><![CDATA[thanos]]></category>
            <category><![CDATA[openshift]]></category>
            <category><![CDATA[multi-cluster]]></category>
            <dc:creator><![CDATA[Mattia Forcellese]]></dc:creator>
            <pubDate>Tue, 29 Nov 2022 17:51:23 GMT</pubDate>
            <atom:updated>2022-12-07T12:16:18.353Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://thanos.io/">Thanos</a> is a highly available Prometheus setup, capable of offloading storage to a deep storage (like S3) for persisting all the metrics from your clusters for an indefinite amount of time, aggregating them and even downsampling them (and much more!). One of Thanos nicest features, the one that we will look into today, is the capability of fetching metrics from other Prometheus instances (or, in the particular case for OpenShift clusters, Thanos instances) thus allowing us to monitor and filter all the fancy metrics that we already had from different clusters, from a single Thanos instance.</p><p><em>Note: This guide will explain some of the pain points of configuring such a Thanos instance for scraping Openshift clusters — but all the reasoning should be perfectly applicable to vanilla Kubernetes clusters too.</em></p><h3>Overall architecture</h3><figure><img alt="A graph describing the desiderata architecture" src="https://cdn-images-1.medium.com/max/1024/1*qXk9x8s6mpK2TyjGV-9zUA.png" /><figcaption>The desiderata architecture, from top to bottom: the main Thanos querier instance that will scrape every other cluster (this instance could be placed in an external cluster, as in the picture, but also in one of the monitored clusters). This main thanos can write to an external storage in order not to accumulate all the metrics data on the monitored clusters. Lastly, we have the OCP clusters that we want to scrape, with their Thanos instance and the corresponding prometheus instances. For an overview of the Openshift monitoring architecture, and the separation between user workload and cluster monitoring, please refer to its official documentation: <a href="https://docs.openshift.com/container-platform/4.11/monitoring/monitoring-overview.html#understanding-the-monitoring-stack_monitoring-overview">https://docs.openshift.com/container-platform/4.11/monitoring/monitoring-overview.html#understanding-the-monitoring-stack_monitoring-overview</a></figcaption></figure><p>Let’s try to figure out what we need for achieving this architecture, in small steps. For brevity I will call OCP1 and OCP2 the two Openshift clusters that will be monitored in this example.</p><ul><li>Configure some common labels for the metrics of each cluster (e.g. cluster name, location, etc)</li><li>Configure (if not done already) our ingress controller to support gRPC and HTTP/2</li><li>Create an Ingress/Route to let Main Thanos scrape from OCP1/OCP2 Thanos instances</li><li>Deploy the Main Thanos and configure it with static stores to scrape from OCP1/OCP2</li><li>Enjoy!</li></ul><p>…Wait, is it <em>this </em>simple? <br>Actually, <strong>no</strong>, if you are on Openshift. If you are on a vanilla Kubernetes or you have total control over the Thanos instances, yes, it should be this easy — configure the ingress, let Thanos scrape the other Thanos instances, and you’re done. But if you are on Openshift and want to leverage the pre-existing Thanos deployments (as I did) there are a few other extra steps to take, to overcome some of the limitations of the operator-managed Thanos configurations.</p><p>Before diving in, a quick note on how Thanos will try to scrape metrics, what ports will it need and the protocol it will use. Thanos will need to contact the configured <em>stores </em>via gRPC. <em>Stores</em> could be anything implementing the Store API, like Prometheus, or another Thanos (they can be stacked). Thanos will call these gRPC API for fetching metadata about the metrics that the store provides, and <a href="https://thanos.io/tip/thanos/design.md/#stores--data-sources---its-all-the-same">other infos</a>. Tipically, Thanos will serve gRPC metrics by binding itself on 0.0.0.0:10901 — this is not the case for Openshift, as we will see later. Why don’t we scrape Prometheus directly? It is a bit harder, due to Prometheus being protected by Openshift oauth proxy, and we would need to scrape the two prometheus instances separately (User workload and Cluster) in both the OCP clusters. Obviously if you are on Kubernetes or in any other case, where you are able to connect and scrape directly metrics from prometheus, you could and probably should! As you may already know, gRPC works with HTTP/2 protocol, which is supported by the majority of ingress controllers — whatever you are using should be fine — but requires (in theory, as we will see later) TLS for protocol negotiation (known as <a href="https://www.keycdn.com/support/alpn">ALPN</a>). What you may not know, is that HTTP/2 can work <em>without </em>TLS; this is known as h2c (HTTP/2 over TCP, instead of TLS). Keep this in mind, because if you are on Openshift, you will be <em>in trouble</em> :)</p><p>Anyway, let’s start with our first cluster, OCP1, and modify the user workload monitoring configuration by adding some labels for identifying the cluster (and <a href="https://thanos.io/tip/components/query.md/#deduplication">de-duplicating data</a>):</p><pre>oc -n openshift-user-workload-monitoring edit configmap user-workload-monitoring-config<br><br>apiVersion: v1<br>data:<br>  config.yaml: |+<br>    prometheus:<br>      externalLabels:<br>        cluster: ocp1<br>        region: xxxxxx<br>        cluster_replica: ocp1<br>...</pre><p>Then, the cluster monitoring config:</p><pre> oc -n openshift-monitoring edit configmap cluster-monitoring-config<br><br>apiVersion: v1<br>data:<br>  config.yaml: |<br>    prometheusK8s:<br>      externalLabels:<br>        cluster: ocp1<br>        region: xxxxx<br>        cluster_replica: ocp1</pre><p>Next, configure our ingress controller (on Openshift by default it will be HAProxy) for allowing HTTP/2 connections, this can be done by following the <a href="https://docs.openshift.com/container-platform/4.11/networking/ingress-operator.html#nw-http2-haproxy_configuring-ingress">official documentation</a> (<em>n</em>ote: <em>this works on OCP 4.6+</em>)— it should simply be done by annotating the cluster ingress configuration:</p><pre>oc annotate ingresses.config/cluster ingress.operator.openshift.io/default-enable-http2=true</pre><p>If you are using another ingress controller, please refer to its specific documentation about HTTP/2 and gRPC services.</p><p>Now, set the current project to <strong>openshift-monitoring </strong>(this is where Thanos, Prometheus and everything handled by OCP monitoring reside) and start by creating our route pointing at the Thanos service exposing the gRPC port. Wait… there <strong>is none!</strong> As of this OCP monitoring version, Thanos will not expose the gRPC port on the service, and <a href="https://github.com/openshift/cluster-monitoring-operator/issues/772#issuecomment-620110404">there is no plan for changing this in the imminent future</a>. But this should be no problem, since declaring a port on the container specs of the pod, is mostly for informational purposes —<a href="https://kubernetes.io/docs/reference/kubernetes-api/workload-resources/pod-v1/#ports"> every port can be reached, even if the container does not expose them, as long as they listen on all interfaces (i.e. 0.0.0.0).</a> Altough this is true, it’s not possible for this Thanos service, unfortunately if you look inside the Thanos pod (for the container thanos-query), you will see that Thanos is started with:</p><pre>...<br>- &#39;--grpc-address=127.0.0.1:10901&#39;<br>...</pre><p>This means that Thanos is listening for gRPC queries on port 10901, but will only respond to the local interface (127.0.0.1) — only to the other containers. In fact, as I anticipated before, the Thanos instance managed by Openshift is sitting behind a oauth proxy container, that will be able to speak to the query container on the local interface because <strong>they are on the same pod. </strong>So, we can’t directly access this — but we still need to create a Service pointing at this port (remember: the service can reference any numbered port, it does not matter if the container port is actually listening or open). Let’s create it with this manifest:</p><pre>kind: Service<br>apiVersion: v1<br>metadata:<br>  name: thanos-querier-grpc<br>  namespace: openshift-monitoring<br>spec:<br>  ports:<br>    - name: grpc<br>      protocol: TCP<br>      port: 10901<br>      targetPort: 10901<br>  type: ClusterIP<br>  selector:<br>    app.kubernetes.io/component: query-layer<br>    app.kubernetes.io/instance: thanos-querier<br>    app.kubernetes.io/name: thanos-query<br>    app.kubernetes.io/part-of: openshift-monitoring</pre><p>If you try now, locally, to access this service with <em>kubectl port-forward</em>, <em>oc port-forward</em>, etc… you will notice that the service will respond correctly! (you could even try to query the <a href="https://github.com/fullstorydev/grpcurl">gRPC service with gRPCurl</a> and see what happens). This is because the kubernetes port-forwarding command works a <a href="https://stackoverflow.com/questions/51468491/how-kubectl-port-forward-works">bit differently than you may expect</a>.</p><p>The problem is, as we said before, that any other pod trying to reach for that service, would not be able to communicate (the port is closed!), you can even try that with a running pod with a docker image of gRPCurl.</p><p>As a solution, an <em>ugly</em> yet necessary workaround, we have to create another pod, running kubectl, that will do the port-forwarding for us, and then expose this pod via service for letting the Main Thanos scrape the metrics from the OCP1 Thanos. Wait, <strong>what?</strong> Let’s try to explain it with a diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ILp0s3x-TbOtCIRMVIBvew.png" /><figcaption>Note that port-forwarding in general is slow and not very reliable, but we’ll stick with it, because we need to access the “hidden” port of that container.</figcaption></figure><p>In order to do this, we need to create a few resources: a Deployment, a Service, and finally the route (also, depending on your RBAC, a service account/role/role binding may be needed):</p><pre>kind: Deployment<br>apiVersion: apps/v1<br>metadata:<br>  name: thanos-grpc-port-forwarder<br>  namespace: openshift-monitoring<br>spec:<br>  replicas: 2<br>  selector:<br>    matchLabels:<br>      name: thanos-grpc-port-forwarder<br>  template:<br>    metadata:<br>      labels:<br>        name: thanos-grpc-port-forwarder<br>    spec:<br>      serviceAccountName: thanos-port-forwarder<br>      restartPolicy: Always<br>      containers:<br>        - name: kubectl<br>          image: bitnami/kubectl:latest<br>          command:<br>            - kubectl<br>            - port-forward<br>            - svc/thanos-querier-grpc<br>            - &quot;--address=0.0.0.0&quot;<br>            - &quot;10901:10901&quot;<br>          ports:<br>            - containerPort: 10901<br>              protocol: TCP<br>          imagePullPolicy: IfNotPresent<br><br>---<br>kind: Service<br>apiVersion: v1<br>metadata:<br>  name: thanos-grpc-port-forwarder<br>  namespace: openshift-monitoring<br>spec:<br>  ports:<br>    - protocol: TCP<br>      port: 10901<br>      targetPort: 30901<br>      appProtocol: h2c<br>  type: ClusterIP<br>  selector:<br>    name: thanos-grpc-port-forwarder<br><br>---<br><br>kind: Role<br>apiVersion: rbac.authorization.k8s.io/v1<br>metadata:<br>  name: thanos-port-forwarder<br>  namespace: openshift-monitoring<br>rules:<br>  - verbs:<br>      - get<br>      - watch<br>      - list<br>    apiGroups:<br>      - &#39;&#39;<br>    resources:<br>      - services<br>  - verbs:<br>      - get<br>      - watch<br>      - list<br>    apiGroups:<br>      - &#39;&#39;<br>    resources:<br>      - pods<br>  - verbs:<br>      - get<br>      - watch<br>      - list<br>      - create<br>      - update<br>    apiGroups:<br>      - &#39;&#39;<br>    resources:<br>      - pods/portforward<br><br>---<br><br>kind: ServiceAccount<br>apiVersion: v1<br>metadata:<br>  name: thanos-port-forwarder<br>  namespace: openshift-monitoring<br><br>---<br><br>kind: RoleBinding<br>apiVersion: rbac.authorization.k8s.io/v1<br>metadata:<br>  name: thanos-port-forwarder<br>  namespace: openshift-monitoring<br>subjects:<br>  - kind: ServiceAccount<br>    name: thanos-port-forwarder<br>    namespace: openshift-monitoring<br>roleRef:<br>  apiGroup: rbac.authorization.k8s.io<br>  kind: Role<br>  name: thanos-port-forwarder<br></pre><p>Remember the HTTP/2 protocol needed for gRPC? Notice that the <em>thanos-grpc-port-forwarder </em>service specifies an appProtocol of type <strong>h2c</strong>. This is HTTP/2 over TCP, and it’s necessary due to the way the thanos container is run. If you check all its argument, you will notice that there is no flag for configuring the gRPC server (it makes sense, since it won’t be reachable anyway). This gRPC server is running on HTTP/2 <em>without TLS</em>, and this is a problem if you are using OCP version &lt; 4.10, because the ingress controller did not support HTTP/2 routes other than TLS — Re-encrypt and Passthrough — and you would be stuck because you could not create a HTTP/2 insecure or edge route. Note that at this point the <em>thanos-grpc-port-forwarder </em>service could also be a LoadBalancer/NodePort service, thus <strong>not needing a route at all</strong>; this may depend on your infrastructure, but it could be your best way to expose Thanos if you are on OCP version &lt; 4.10. Although not documented, OCP 4.10 introduces the possibility of edge encrypted routes for HTTP/2 via h2c (<a href="https://github.com/openshift/router/pull/328">see this merged pull request for more details</a>).</p><p>Finally, the <strong>Route</strong>!</p><pre>kind: Route<br>apiVersion: route.openshift.io/v1<br>metadata:<br>  name: thanos-grpc-port-forwarder<br>  namespace: openshift-monitoring<br>spec:<br>  host: &lt;redacted&gt;<br>  to:<br>    kind: Service<br>    name: thanos-grpc-port-forwarder<br>    weight: 100<br>  port:<br>    targetPort: 10901<br>  tls:<br>    termination: edge<br>    insecureEdgeTerminationPolicy: Allow<br>  wildcardPolicy: None</pre><p>At this point, to check if everything is correct, you can still use gRPCurl:</p><pre>grpcurl &lt;route&gt;:443 list</pre><p>It should respond with a list of the methods available on Thanos service.</p><p>Done! You can repeat the exact same steps for OCP2, and any other cluster that you want to monitor, and then you are ready to go.</p><p>For the Main Thanos deploy, I would suggest you to look at the <a href="https://github.com/bitnami/charts/tree/main/bitnami/thanos">Helm chart mantained by Bitnami</a> — its configuration are out of the scope of this article, but the relevant part, regarding the scraping of our freshly configured stores, is the <strong>query.stores </strong>parameter. For example:</p><pre>helm install thanos bitnami/thanos --set &quot;query.replicaLabel={prometheus_replica,cluster_replica}&quot; --set &quot;query.stores={&lt;ocp1-route&gt;:443,&lt;ocp2-route&gt;:443}&quot;</pre><p>Also <strong>note</strong> the <em>query.replicaLabel</em> parameter in the helm values: this is needed for de-duplication of data when fetching from multiple prometheus/thanos instances. <em>prometheus_replica</em> is a default annotation that is used by the Thanos managed by OCP, and the <em>cluster_replica</em> is the one that we set before on each OCP cluster.<br>To check that the stores are working fine, you should be see a log like this in the thanos-query container:</p><pre>level=info ts=2022-11-29T17:41:22.948335452Z caller=endpointset.go:381 component=endpointset msg=&quot;adding new query with [storeAPI rulesAPI exemplarsAPI targetsAPI MetricMetadataAPI QueryAPI]&quot; address=&lt;ocp1-route&gt;:443 extLset=&quot;{cluster=\&quot;ocp1\&quot;, prometheus=\&quot;openshift-monitoring/k8s\&quot;, prometheus_replica=\&quot;prometheus-k8s-0\&quot;, region=\&quot;XXXXX\&quot;},{cluster=\&quot;ocp1\&quot;, prometheus=\&quot;openshift-monitoring/k8s\&quot;, prometheus_replica=\&quot;prometheus-k8s-1\&quot;, region=\&quot;XXXXX\&quot;},{cluster=\&quot;ocp1\&quot;, prometheus=\&quot;openshift-user-workload-monitoring/user-workload\&quot;, prometheus_replica=\&quot;prometheus-user-workload-0\&quot;, XXXXXX\&quot;},{cluster=\&quot;ocp1\&quot;, prometheus=\&quot;openshift-user-workload-monitoring/user-workload\&quot;, prometheus_replica=\&quot;prometheus-user-workload-1\&quot;, region=\&quot;XXXXXX\&quot;},{thanos_ruler_replica=\&quot;thanos-ruler-user-workload-0\&quot;},{thanos_ruler_replica=\&quot;thanos-ruler-user-workload-1\&quot;}&quot;<br>level=debug ts=2022-11-29T17:41:22.948379345Z caller=endpointset.go:389 component=endpointset msg=&quot;updated endpoints&quot; activeEndpoints=1</pre><p>Thanks for reading this! Let me know if you found it useful, if something can be done better — and how! <br>See you next time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f2e3d212ab6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>