ALB Ingress: redirect traffic to HTTPS

One of the beauties of using an ALB Ingress controller on AWS is that you can configure SSL certificates for your Ingress by just defining you want to use HTTPS

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    kubernetes.io/ingress.class: alb
    alb.ingress.kubernetes.io/listen-ports: '[{"HTTP":80},{"HTTPS":443}]'

But this is going to serve the same content using HTTP and HTTPS. Configuring a SSL redirect it is also pretty straightforward but involves two steps:

First you need to annotate the Ingres with alb.ingress.kubernetes.io/actions.ssl-redirect telling that you want to redirect traffic to HTTPS:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    kubernetes.io/ingress.class: alb
    alb.ingress.kubernetes.io/listen-ports: '[{"HTTP":80},{"HTTPS":443}]'
    alb.ingress.kubernetes.io/actions.ssl-redirect: '{"Type": "redirect", "RedirectConfig":
      { "Protocol": "HTTPS", "Port": "443", "StatusCode": "HTTP_301"}}'

Then, you'll have to add the following on the relevant host as the first specified path:

        - path: /*
          backend:
            serviceName: ssl-redirect
            servicePort: use-annotation

An sample spec section would be:

spec:
  rules:
  - host: sonarqube.pet2cattle.com
    http:
      paths:
      - path: /*
        backend:
          serviceName: ssl-redirect
          servicePort: use-annotation
      - backend:
          serviceName: sonarqube-sonarqube
          servicePort: 9000
        path: /*
  tls:
  - hosts:
    - sonarqube.pet2cattle.com

Posted on 22/03/2021