DEV Community

Lucien Boix
Lucien Boix

Posted on

Go snippet for creating an Ingress rule

You probably need to migrate to apiVersion networking.k8s.io/v1 for your Ingress rules (given that after Kubernetes 1.22, the old apiVersion extensions/v1beta1 and networking.k8s.io/v1beta1 will simply disappear). If you are managing your Ingress rules through Go, here is a snippet to generate a valid Ingress rule if that can help you (I struggled a little to find the correct template so I am sharing this post).

Please let me know it this snippet was useful or if you see some improvements that we can make to it.

Have a great day!

import (
    v1Networking "k8s.io/api/networking/v1"
    v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

func MapIngress(ingressName string, hostName string) *v1Networking.Ingress {

    annotations := map[string]string{}
    annotations["kubernetes.io/ingress.provider"] = "nginx"
    annotations["kubernetes.io/ingress.class"] = "yourIngressClass"
    annotations["kubernetes.io/tls-acme"] = "true"
    // add other annotations you need

    meta := v1.ObjectMeta{
        Name:        ingressName,
        Annotations: annotations,
    }

    pathTypeImplementationSpecific := v1Networking.PathTypeImplementationSpecific

    return &v1Networking.Ingress{
        ObjectMeta: meta,
        Spec: v1Networking.IngressSpec{
            TLS: []v1Networking.IngressTLS{
        v1Networking.IngressTLS{
            Hosts:      []string{hostName},
            SecretName: "yourSecretName",
        },
            Rules: []v1Networking.IngressRule{
                v1Networking.IngressRule{
                    Host: hostName,
                    IngressRuleValue: v1Networking.IngressRuleValue{
                        HTTP: &v1Networking.HTTPIngressRuleValue{
                            Paths: []v1Networking.HTTPIngressPath{
                                v1Networking.HTTPIngressPath{
                                    Path: "/",
                                    PathType: &pathTypeImplementationSpecific,
                                    Backend: v1Networking.IngressBackend{
                                        Service: &v1Networking.IngressServiceBackend{
                                            Name: "yourServiceName",
                                            Port: v1Networking.ServiceBackendPort{
                                                Number: 80,
                                            },
                                        },
                                    },
                                },
                            },
                        },
                    },
                },
            },
        },
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)