K8s Cert-Manager 证书申请

  1. 手动申请证书

    namespace=<项目名称>
    domain=<申请证书的域名>
    domain_name=$(echo ${domain} | sed 's/\./-/g')
    # 在需要使用证书的项目(namespace)下创建Certificate  这里以 kubesphere-system 为例
    cat <<EOF | kubectl apply -f -
    apiVersion: cert-manager.io/v1
    kind: Certificate
    metadata:
    name: cert-${domain_name}
    namespace: ${namespace}
    spec:
    secretName: tls-${domain_name}
    commonName:
    dnsNames:
    - "*.${domain}"
      issuerRef:
      name: letsencrypt-prod
      kind: ClusterIssuer
      EOF
    # 等待几分钟后查看证书 READY 状态
    watch -n 1 "kubectl get certificate -n ${namespace}"    
    
  2. Ingress自动证书

kind: Ingress
apiVersion: networking.k8s.io/v1
metadata:
  name: docs-jsecode-com
  namespace: docs
  annotations:
    cert-manager.io/cluster-issuer: letsencrypt-prod
    kubesphere.io/creator: huangsx
    kubesphere.io/description: 多项目接口文档聚合
spec:
  tls:
    - hosts:
        - docs.jsecode.com
      secretName: tls-docs-jsecode-com 
  rules:
    - host: docs.jsecode.com
      http:
        paths:
          - path: /
            pathType: ImplementationSpecific
            backend:
              service:
                name: knife4j
                port:
                  number: 10000
  1. 避免ModSecurity拦截http01验证
apiVersion: cert-manager.io/v1
kind: ClusterIssuer
metadata:
  name: letsencrypt-http01-prod
spec:
  acme:
    privateKeySecretRef:
      name: letsencrypt-http01-prod-account-key
    server: 'https://acme-v02.api.letsencrypt.org/directory'
    solvers:
      - http01:
          ingress:
            ingressClassName: kubesphere-router-cluster
            ingressTemplate:
              metadata:
                annotations:
                  nginx.ingress.kubernetes.io/modsecurity-snippet: >-
                    SecRule REQUEST_URI "@beginsWith
                    /.well-known/acme-challenge/"
                    "id:1100001,phase:1,log,allow,ctl:ruleEngine=Off"
  1. 手动续期
# 删除旧的失败的 CertificateRequest & Challenge
kubectl delete certificaterequest -n cert-shared cert-xxxx
kubectl delete challenge -n cert-shared --all
# 重新触发证书续期
kubectl annotate certificate cert-xxxx \
  cert-manager.io/renewal-reason="manual" \
  -n cert-shared --overwrite