prompt
stringlengths
65
38.7k
response
stringlengths
41
29.1k
<p>when I change the <code>replicas: x</code> in my .yaml file I can see GKE autopilot boots pods up/down depending on the value, but what will happen if the load on my deployment gets too big. Will it then autoscale the number of pods and nodes to handle the traffic and then reduce back to the value specified in replicas when the request load is reduced again?</p> <p>I'm basically asking how does autopilot horizontal autoscaling works? and how do I get a minimum of 2 pod replicas that can horizontally autoscale in autopilot?</p>
<p>GKE autoscale only <strong>Nodes</strong> by default, while you have to take care of your HPA deployment scaling.</p> <blockquote> <p>Autopilot: GKE provisions and manages the cluster's underlying infrastructure, including nodes and node pools, giving you an optimized cluster with a hands-off experience.</p> </blockquote> <p>We need to configure both scaling options for deployment <strong>VPA</strong> and <strong>HPA</strong>.</p> <blockquote> <p>Pre-configured: Autopilot handles all the scaling and configuring of your nodes.</p> <p>Default: You configure Horizontal pod autoscaling (HPA) You configure Vertical Pod autoscaling (VPA)</p> </blockquote> <p>GKE will manage the scaling up/down of your nodes in node pools, without worrying about the infrastructure you just have to start deploying the application with HPA &amp; VPA auto-scaling.</p> <p>You can read more about the options here : <a href="https://cloud.google.com/kubernetes-engine/docs/concepts/autopilot-overview#comparison" rel="nofollow noreferrer">https://cloud.google.com/kubernetes-engine/docs/concepts/autopilot-overview#comparison</a></p>
<p>Application is deployed on K8s using StatefulSet because of stateful in nature. There is around 250+ pods are running and HPA has been implemented on it too that can scale upto 400 pods.</p> <p>When new deployment occurs, it takes longer time (~ 10-15m) to update all pods in Rolling Update fashion.</p> <p><strong>Problem:</strong> End user get response from 2 version of pods until all pods are replaced with new revision.</p> <p>I am googling for an architecture where overall deployment time can be reduced and getting the best possible solutions to use <code>BLUE/GREEN</code> strategy but it has bunch of impact with integrated services like monitoring, logging, telemetry etc because of 2 naming conventions.</p> <p>Ideally I am looking for a solutions like <code>maxSurge</code> for Deployment in which firstly new pods are created and then traffic are shifted to it at a time but in case of StatefulSet, it won't support maxSurge with RollingUpdate strategy &amp; controller will delete and recreate each Pod in the StatefulSet based on ordinal index from bigger to smaller.</p>
<p>The solution is to do a <a href="https://cloud.google.com/kubernetes-engine/docs/concepts/statefulset#partitioning_rolling_updates" rel="nofollow noreferrer">partitioning rolling update</a> along with a <a href="https://cloud.google.com/architecture/implementing-deployment-and-testing-strategies-on-gke#perform_a_canary_test" rel="nofollow noreferrer">canary deployment</a>.</p> <p>Let’s suppose we have the statefulset workload defined by the following yaml file:</p> <pre><code>apiVersion: v1 kind: Service metadata: name: nginx labels: app: nginx version: &quot;1.20&quot; spec: ports: - port: 80 name: web clusterIP: None selector: app: nginx version: &quot;1.20&quot; --- apiVersion: apps/v1 kind: StatefulSet metadata: name: web spec: selector: matchLabels: app: nginx # Label selector that determines which Pods belong to the StatefulSet # Must match spec: template: metadata: labels serviceName: &quot;nginx&quot; replicas: 3 template: metadata: labels: app: nginx # Pod template's label selector version: &quot;1.20&quot; spec: terminationGracePeriodSeconds: 10 containers: - name: nginx image: nginx:1.20 ports: - containerPort: 80 name: web volumeMounts: - name: www mountPath: /usr/share/nginx/html volumeClaimTemplates: - metadata: name: www spec: accessModes: [ &quot;ReadWriteOnce&quot; ] resources: requests: storage: 1Gi </code></pre> <p>You could patch the statefulset to create a partition, and change the image and version label for the remaining pods: (In this case, since there are only 3 pods, the last one will be the one that will change its image.)</p> <pre><code>$ kubectl patch statefulset web -p '{&quot;spec&quot;:{&quot;updateStrategy&quot;:{&quot;type&quot;:&quot;RollingUpdate&quot;,&quot;rollingUpdate&quot;:{&quot;partition&quot;:2}}}}' $ kubectl patch statefulset web --type='json' -p='[{&quot;op&quot;: &quot;replace&quot;, &quot;path&quot;: &quot;/spec/template/spec/containers/0/image&quot;, &quot;value&quot;:&quot;nginx:1.21&quot;}]' $ kubectl patch statefulset web --type='json' -p='[{&quot;op&quot;: &quot;replace&quot;, &quot;path&quot;: &quot;/spec/template/metadata/labels/version&quot;, &quot;value&quot;:&quot;1.21&quot;}]' </code></pre> <p>At this point, you have a pod with the new image and version label ready to use, but since the version label is different, the traffic is still going to the other two pods. If you change the version in the yaml file and apply the new configuration, the rollout will be transparent, since there is already a pod ready to migrate the traffic:</p> <pre><code>apiVersion: v1 kind: Service metadata: name: nginx labels: app: nginx version: &quot;1.21&quot; spec: ports: - port: 80 name: web clusterIP: None selector: app: nginx version: &quot;1.21&quot; --- apiVersion: apps/v1 kind: StatefulSet metadata: name: web spec: selector: matchLabels: app: nginx # Label selector that determines which Pods belong to the StatefulSet # Must match spec: template: metadata: labels serviceName: &quot;nginx&quot; replicas: 3 template: metadata: labels: app: nginx # Pod template's label selector version: &quot;1.21&quot; spec: terminationGracePeriodSeconds: 10 containers: - name: nginx image: nginx:1.21 ports: - containerPort: 80 name: web volumeMounts: - name: www mountPath: /usr/share/nginx/html volumeClaimTemplates: - metadata: name: www spec: accessModes: [ &quot;ReadWriteOnce&quot; ] resources: requests: storage: 1Gi </code></pre> <pre><code>$ kubectl apply -f file-name.yaml </code></pre> <p>Once traffic is migrated to the pod containing the new image and version label, you should patch again the statefulset and remove the partition with the command <code>kubectl patch statefulset web -p '{&quot;spec&quot;:{&quot;updateStrategy&quot;:{&quot;type&quot;:&quot;RollingUpdate&quot;,&quot;rollingUpdate&quot;:{&quot;partition&quot;:0}}}}'</code></p> <p>Note: You will need to be very careful with the size of the partition, since the remaining pods will handle the whole traffic for some time.</p>
<p>when I change the <code>replicas: x</code> in my .yaml file I can see GKE autopilot boots pods up/down depending on the value, but what will happen if the load on my deployment gets too big. Will it then autoscale the number of pods and nodes to handle the traffic and then reduce back to the value specified in replicas when the request load is reduced again?</p> <p>I'm basically asking how does autopilot horizontal autoscaling works? and how do I get a minimum of 2 pod replicas that can horizontally autoscale in autopilot?</p>
<p>GKE autopilot by default will not scale the replicas count beyond what you specified. This is the default behavior of Kubernetes in general.</p> <p>If you want automatic autoscaling you have to use Horizental Pod Autoscaler (<a href="https://cloud.google.com/kubernetes-engine/docs/how-to/horizontal-pod-autoscaling" rel="nofollow noreferrer">HPA</a>) which is supported in <a href="https://cloud.google.com/kubernetes-engine/docs/concepts/autopilot-overview#comparison" rel="nofollow noreferrer">Autopilot</a></p> <p>If you deploy HPA to scale up and down your workload, Autopilot will scale up and down the nodes automatically and that's transparent for you as the nodes are managed by Google.</p>
<p>I installed <a href="https://github.com/kubernetes-sigs/kind" rel="nofollow noreferrer">kind</a> to play around with Kubernetes.</p> <p>If I use <code>top</code> and sort by CPU usage (key <code>C</code>), then I see that <code>kube-apiserver</code> is constantly consuming 5 to 10% CPU.</p> <p>Why?</p> <p>I don't have installed something up to now:</p> <pre><code>guettli@p15:~$ kubectl get pods --all-namespaces NAMESPACE NAME READY STATUS RESTARTS AGE kube-system coredns-558bd4d5db-ntg7c 1/1 Running 0 40h kube-system coredns-558bd4d5db-sx8w9 1/1 Running 0 40h kube-system etcd-kind-control-plane 1/1 Running 0 40h kube-system kindnet-9zkkg 1/1 Running 0 40h kube-system kube-apiserver-kind-control-plane 1/1 Running 0 40h kube-system kube-controller-manager-kind-control-plane 1/1 Running 0 40h kube-system kube-proxy-dthwl 1/1 Running 0 40h kube-system kube-scheduler-kind-control-plane 1/1 Running 0 40h local-path-storage local-path-provisioner-547f784dff-xntql 1/1 Running 0 40h guettli@p15:~$ kubectl get services --all-namespaces NAMESPACE NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE default kubernetes ClusterIP 10.96.0.1 &lt;none&gt; 443/TCP 40h kube-system kube-dns ClusterIP 10.96.0.10 &lt;none&gt; 53/UDP,53/TCP,9153/TCP 40h guettli@p15:~$ kubectl get nodes NAME STATUS ROLES AGE VERSION kind-control-plane Ready control-plane,master 40h v1.21.1 guettli@p15:~$ kubectl get nodes --all-namespaces NAME STATUS ROLES AGE VERSION kind-control-plane Ready control-plane,master 40h v1.21.1 </code></pre> <p>I am curious. Where does the CPU usage come from? How can I investigate this?</p>
<p>Even in an empty cluster with just one master node, there are at least 5 components that reach out to the API server on a regular basis:</p> <ul> <li>kubelet for the master node</li> <li>Controller manager</li> <li>Scheduler</li> <li>CoreDNS</li> <li>Kube proxy</li> </ul> <p>This is because API Server acts as the only entry point for all components in Kubernetes to know what the cluster state should be and take action if needed.</p> <p>If you are interested in the details, you could enable audit logs in the API server and get a very verbose file with all the requests being made. How to do so is not the goal of this answer, but you can start from the <a href="https://kubernetes.io/docs/reference/command-line-tools-reference/kube-apiserver/" rel="noreferrer">apiserver documentation</a>.</p>
<p>I'm using Google Cloud Load Balancer as the ingress controller to my GCP Kubernetes application. I want all requests to <code>www.my_domain.com</code> to be redirected to <code>my_domain_.com</code>. </p> <p>Note: My GCLB is configured with an SSL certificate that is valid for both <code>www.my_domain.com</code> and <code>my_domain.com</code>.</p> <p>I know this is possible using an http redirect in my external DNS management console, but an issue arises because of SSL termination. </p> <ol> <li><p>I create an http redirect rule in my DNS management console to route all <code>www.my_domain.com</code> traffic to <code>https://my_domain.com</code>. </p></li> <li><p>If a client browses to domain <code>https://www.my_domain.com</code>, they will get a browser warning because the request will first go to server of my DNS management tool, which is not configured with a matching SSL cert.</p></li> </ol> <p>I know that GCLB has limitations for redirecting http traffic to https, but that's not my main concern here. What I want to know is if it's possible in GCLB to configure a routing rule so that any request for <code>www.my_domain.com</code> is redirected to <code>my_domain.com</code>.</p> <p>Thanks for any help!</p>
<p>Redirect rules are supported when you switch your &quot;Host and path rules&quot; from the &quot;Simple host and path rule&quot; to the &quot;Advanced host and path rule&quot; option now. This advanced option allows for URL redirect and URL rewrite.</p> <p>Edit your Load Balancer, go to &quot;Host and path rules&quot;, click &quot;Add host and path rule&quot;.</p> <p>Host: <code>www.my_domain.com</code></p> <p>Path: <code>/*</code></p> <p>Action: <code>Redirect the client to different host/path</code> and specify your host <code>my_domain.com</code></p> <p>Path redirect: <code>Full path redirect</code></p> <p>Redirect response code: <code>301</code></p> <p>HTTPS redirect: <code>Enable</code></p> <p>Check this Google Cloud page (no screenshots unfortunately) here <a href="https://cloud.google.com/load-balancing/docs/https/setting-up-url-redirects-classic" rel="nofollow noreferrer">https://cloud.google.com/load-balancing/docs/https/setting-up-url-redirects-classic</a></p>
<p>I am trying to create a network policy for the following conditions but does not seem to work. What am I doing wrong? Any help is much appreciated</p> <ul> <li>create a network policy namespace project-e</li> <li>the policy should allow all pods in namespace <strong>project-app</strong> to connect to <strong>port 8000</strong> of Pods in namespace <strong>project-e</strong></li> <li>the policy should not allow access to pods that don't listen on port 8000</li> <li>the policy does not allow access from pods that are not in namespace project-app</li> </ul> <pre><code>apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: test-network-policy namespace: project-e spec: podSelector: matchLabels: {} policyTypes: - Ingress ingress: - from: - namespaceSelector: matchLabels: name: project-app - podSelector: matchLabels: {} ports: - protocol: TCP port: 8000 </code></pre>
<ul> <li><p>since you want to allow all the pods from namespace which has a label &quot;name: project-app&quot; to namespace <code> project-e</code>.</p> </li> <li><p>You can remove the the <code> matchLables:{}</code> in <code>podSelector</code> as following :</p> </li> </ul> <pre><code>kind: NetworkPolicy metadata: name: test-network-policy namespace: project-e spec: podSelector: {} policyTypes: - Ingress ingress: - from: - namespaceSelector: matchLabels: name: project-app - podSelector: {} ports: - protocol: TCP port: 8000 </code></pre> <ul> <li>Make sure namespace <code>project-app</code> has a label <code>name: project-app</code>. Otherwise change it to appropriate label in above manifest.</li> </ul>
<p>I'm learning Kubernetes and below are the yaml configuration files: mongo-config.yaml</p> <pre><code>apiVersion: v1 kind: ConfigMap metadata: name: mongo-config data: mongo-url: mongo-service </code></pre> <p>mongo-secret.yaml:</p> <pre><code>apiVersion: v1 kind: Secret metadata: name: mongo-secret type: Opaque data: mongo-user: bW9uZ291c2Vy mongo-password: bW9uZ29wYXNzd29yZA== </code></pre> <p>mongo.yaml:</p> <pre><code>apiVersion: apps/v1 kind: Deployment metadata: name: mongo-deployment labels: app: mongo spec: replicas: 1 selector: matchLabels: app: mongo template: metadata: labels: app: mongo spec: containers: - name: mongodb image: mongo:5.0 ports: - containerPort: 27017 env: - name: MONGO_INITDB_ROOT_USERNAME valueFrom: secretKeyRef: name: mongo-secret key: mongo-user - name: MONGO_INITDB_ROOT_PASSWORD valueFrom: secretKeyRef: name: mongo-secret key: mongo-password --- apiVersion: v1 kind: Service metadata: name: mongo-service spec: selector: app: webapp ports: - protocol: TCP port: 27017 targetPort: 27017 </code></pre> <p>webapp.yaml:</p> <pre><code>apiVersion: apps/v1 kind: Deployment metadata: name: webapp-deployment labels: app: webapp spec: replicas: 1 selector: matchLabels: app: webapp template: metadata: labels: app: webapp spec: containers: - name: webapp image: nanajanashia/k8s-demo-app:v1.0 ports: - containerPort: 3000 env: - name: USER_NAME valueFrom: secretKeyRef: name: mongo-secret key: mongo-user - name: USER_PWD valueFrom: secretKeyRef: name: mongo-secret key: mongo-password - name: DB_URL valueFrom: secretKeyRef: name: mongo-config key: mongo-url --- apiVersion: v1 kind: Service metadata: name: webapp-service spec: type: NodePort selector: app: webapp ports: - protocol: TCP port: 3000 targetPort: 3000 nodePort: 30100 </code></pre> <p>After starting a test webapp i came across the below error:</p> <pre><code>NAME READY STATUS RESTARTS AGE mongo-deployment-7875498c-psn56 1/1 Running 0 100m my-go-app-664f7475d4-jgnsk 1/1 Running 1 (7d20h ago) 7d20h webapp-deployment-7dc5b857df-6bx4s 0/1 CreateContainerConfigError 0 29m </code></pre> <p>which if i try to get more details about the CreateContainerConfigError i get:</p> <pre><code>~/K8s/K8s-demo$ kubectl describe pod webapp-deployment-7dc5b857df-6bx4s Name: webapp-deployment-7dc5b857df-6bx4s Namespace: default Priority: 0 Node: minikube/192.168.49.2 Start Time: Thu, 06 Jan 2022 12:20:02 +0200 Labels: app=webapp pod-template-hash=7dc5b857df Annotations: &lt;none&gt; Status: Pending IP: 172.17.0.5 IPs: IP: 172.17.0.5 Controlled By: ReplicaSet/webapp-deployment-7dc5b857df Containers: webapp: Container ID: Image: nanajanashia/k8s-demo-app:v1.0 Image ID: Port: 3000/TCP Host Port: 0/TCP State: Waiting Reason: CreateContainerConfigError Ready: False Restart Count: 0 Environment: USER_NAME: &lt;set to the key 'mongo-user' in secret 'mongo-secret'&gt; Optional: false USER_PWD: &lt;set to the key 'mongo-password' in secret 'mongo-secret'&gt; Optional: false DB_URL: &lt;set to the key 'mongo-url' in secret 'mongo-config'&gt; Optional: false Mounts: /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-wkflh (ro) Conditions: Type Status Initialized True Ready False ContainersReady False PodScheduled True Volumes: kube-api-access-wkflh: Type: Projected (a volume that contains injected data from multiple sources) TokenExpirationSeconds: 3607 ConfigMapName: kube-root-ca.crt ConfigMapOptional: &lt;nil&gt; DownwardAPI: true QoS Class: BestEffort Node-Selectors: &lt;none&gt; Tolerations: node.kubernetes.io/not-ready:NoExecute op=Exists for 300s node.kubernetes.io/unreachable:NoExecute op=Exists for 300s Events: Type Reason Age From Message ---- ------ ---- ---- ------- Normal Scheduled 30m default-scheduler Successfully assigned default/webapp-deployment-7dc5b857df-6bx4s to minikube Warning Failed 28m (x12 over 30m) kubelet Error: secret &quot;mongo-config&quot; not found Normal Pulled 27s (x142 over 30m) kubelet Container image &quot;nanajanashia/k8s-demo-app:v1.0&quot; already present on machine </code></pre> <p>which seems that the issue with configuration is:</p> <pre><code> Warning Failed 28m (x12 over 30m) kubelet Error: secret &quot;mongo-config&quot; not found </code></pre> <p>I don't have a secret with name &quot;mongo-config&quot; but there is a ConfigMap with &quot;mongo-config&quot; name:</p> <pre><code>&gt;:~/K8s/K8s-demo$ kubectl get secret NAME TYPE DATA AGE default-token-gs25h kubernetes.io/service-account-token 3 5m57s mongo-secret Opaque 2 5m48s &gt;:~/K8s/K8s-demo$ kubectl get configmap NAME DATA AGE kube-root-ca.crt 1 6m4s mongo-config 1 6m4s </code></pre> <p>Could you please advice what is the issue here?</p>
<p>You have <code>secretKeyRef</code> in:</p> <pre><code>- name: DB_URL valueFrom: secretKeyRef: name: mongo-config key: mongo-url </code></pre> <p>You have to use <code>configMapKeyRef</code></p> <pre><code> - name: DB_URL valueFrom: configMapKeyRef: name: mongo-config key: mongo-url </code></pre>
<p>I have a 3-node OKE cluster setup in Oracle cloud.</p> <p>I deployed an nginx ingress controller in the cluster. I'm mapping the FQDN test.myapp.com to the EXTERNAL_IP of that nginx ingress controller service.</p> <p>Whenever I re-install the ingress controller during the time of testing, it gets different EXTERNAL_IP and I have to map the FQDN again to that new IP.</p> <p>So it will be better if I can specify a static loadBalancer IP during the time of nginx ingress controller installation. Like this:</p> <pre><code>nginx-ingress: controller: service: loadBalancerIP: &quot;125.23.119.23&quot; </code></pre> <p>How can I achieve this in Oracle cloud (with OKE)?</p>
<p>Oracle cloud Infrastructure(OCI) supports creating <code>LoadBalancer</code> services in kubernetes clusters, and allows setting the <code>LoadBalancerIP</code> parameter too.</p> <p>But first, you have to create a <strong>Reserved Public IP address</strong> in OCI, and then specify that IP address as <code>LoadBalancerIP</code> of your service.</p> <p>You can do it as :</p> <ul> <li><p>Go to OCI console :<br> <code>Networking -&gt; IP management -&gt; Reserved Public IPs</code>.<br> Click on <code>Reserve Public IP Address</code><br> Provide a name, and select source <code>Oracle</code> if that is the only public IP pool you have (default).<br> Click on the Reserve button to get a reserved public IP address.</p> </li> <li><p>In OCI console, look at : <br> <code>Networking -&gt; IP management -&gt; Reserved Public IPs</code> <br> ( You can see a <strong>Reserved Public IP</strong> there, but not attached to any VNIC) <br> <code>Networking -&gt; Load Balancers</code> <br> ( No Loadbalancers are listed with the IP address that we reserved )</p> </li> <li><p>Create a <code>LoadBalancer</code> type service in kubernetes cluster using <code>kubectl</code> with <code>LoadbalancerIP</code> provided with value of our Reserved IP Address.</p> </li> <li><p>Check <code>kubectl get svc</code>, and you can see that the Reserved Public IP address is assigned to the service.</p> </li> <li><p>In OCI console, look at : <br> <code>Networking -&gt; IP management -&gt; Reserved Public IPs</code> <br> ( You can see a public IP address reserved, attached to a VNIC for an LB) <br> <code>Networking -&gt; Load Balancers</code> <br> ( A layer-4 Loadbalancer is added automatically with the IP address that we reserved )</p> </li> </ul> <p>That means, when you create a <code>Reserved Public IP</code>, you are just reserving it for future use. A layer-4 load balancer is created and associated with that IP address only when a <code>LoadBalancer</code> type service is created with this Reserved IP address.</p> <p>If you delete that LoadBalancer type service, the layer-4 loadbalancer also gets deleted. But the Reserved public IP still remains there. You can assign that IP address to another service next time.</p> <p>These documentations have explanations regarding this topic :</p> <ul> <li><p><a href="https://docs.oracle.com/en-us/iaas/Content/ContEng/Tasks/contengcreatingloadbalancer.htm#contengcreatingloadbalancer_topic_Specifying_Load_Balancer_Reserved_IP" rel="nofollow noreferrer">https://docs.oracle.com/en-us/iaas/Content/ContEng/Tasks/contengcreatingloadbalancer.htm#contengcreatingloadbalancer_topic_Specifying_Load_Balancer_Reserved_IP</a></p> </li> <li><p><a href="https://docs.oracle.com/en-us/iaas/Content/Network/Tasks/managingpublicIPs.htm#console-reserved" rel="nofollow noreferrer">https://docs.oracle.com/en-us/iaas/Content/Network/Tasks/managingpublicIPs.htm#console-reserved</a></p> </li> </ul>
<p>I have several secrets that are mounted and need to be read as a properties file. It seems kubernetes can't mount them as a single file so I'm trying to concatenate the files after the pod starts. I tried running a cat command in a postStart handler but it seems execute before the secrets are mounted as I get this error:</p> <pre><code>Error: failed to create containerd task: OCI runtime create failed: container_linux.go:380: starting container process caused: exec: &quot;cat /properties/S3Secret /properties/S3Key &gt;&gt; /properties/dbPassword&quot;: stat cat /properties/S3Secret /properties/S3Key &gt;&gt; /properties/dbPassword: no such file or directory: unknown </code></pre> <p>Then here is the yaml.</p> <pre><code>apiVersion: apps/v1 kind: Deployment metadata: name: K8S_ID spec: selector: matchLabels: app: K8S_ID replicas: 1 template: metadata: labels: app: K8S_ID spec: containers: - name: K8S_ID image: IMAGE_NAME ports: - containerPort: 8080 env: - name: PROPERTIES_FILE value: &quot;/properties/dbPassword&quot; volumeMounts: - name: secret-properties mountPath: &quot;/properties&quot; lifecycle: postStart: exec: command: [&quot;cat /properties/S3Secret /properties/S3Key &gt;&gt; /properties/dbPassword&quot;] volumes: - name: secret-properties secret: secretName: secret-properties items: - key: SECRET_ITEM path: dbPassword - key: S3Key path: S3Key - key: S3Secret path: S3Secret </code></pre>
<p>You need a shell session for your command like this:</p> <pre><code>... lifecycle: postStart: exec: command: [&quot;/bin/sh&quot;,&quot;-c&quot;,&quot;cat /properties/S3Secret /properties/S3Key &gt;&gt; /properties/dbPassword&quot;] ... </code></pre>
<p>While running a spark job with a Kubernetes cluster, we get the following error:</p> <pre><code>2018-11-30 14:00:47 INFO DAGScheduler:54 - Resubmitted ShuffleMapTask(1, 58), so marking it as still running. 2018-11-30 14:00:47 WARN TaskSetManager:66 - Lost task 310.0 in stage 1.0 (TID 311, 10.233.71.29, executor 3): ExecutorLostFailure (executor 3 exited caused by one of the running tasks) Reason: The executor with id 3 exited with exit code -1. The API gave the following brief reason: Evicted The API gave the following message: The node was low on resource: ephemeral-storage. Container executor was using 515228Ki, which exceeds its request of 0. The API gave the following container statuses: </code></pre> <p>How to configure the job so we can increase the ephemeral storage size of each container ?</p> <p>We use spark 2.4.0 and Kubernetes 1.12.1</p> <p>The spark submit option is as follow</p> <pre><code>--conf spark.local.dir=/mnt/tmp \ --conf spark.executor.instances=4 \ --conf spark.executor.cores=8 \ --conf spark.executor.memory=100g \ --conf spark.driver.memory=4g \ --conf spark.driver.cores=1 \ --conf spark.kubernetes.memoryOverheadFactor=0.1 \ --conf spark.kubernetes.container.image=spark:2.4.0 \ --conf spark.kubernetes.namespace=visionlab \ --conf spark.kubernetes.authenticate.driver.serviceAccountName=spark \ --conf spark.kubernetes.container.image.pullPolicy=Always \ --conf spark.kubernetes.driver.volumes.persistentVolumeClaim.myvolume.options.claimName=pvc \ --conf spark.kubernetes.driver.volumes.persistentVolumeClaim.myvolume.mount.path=/mnt/ \ --conf spark.kubernetes.driver.volumes.persistentVolumeClaim.myvolume.mount.readOnly=false \ --conf spark.kubernetes.executor.volumes.persistentVolumeClaim.myvolume.options.claimName=pvc \ --conf spark.kubernetes.executor.volumes.persistentVolumeClaim.myvolume.mount.path=/mnt/ \ --conf spark.kubernetes.executor.volumes.persistentVolumeClaim.myvolume.mount.readOnly=false </code></pre>
<p>This is because of your spark job do not have enough storage to store temporary cache data</p> <p>First you need to inspect your pod deployment, to identify the volume name that will be used for mounting such as <code>spark-local-dir-1</code> Then dive into your spark executor pod, print out <code>$SPARK_LOCAL_DIR</code> to identify location of current temporary spark data location, modify the path with <code>&quot;spark.local.dir&quot;: &quot;/tmp/spark-temp/&quot;</code> (to change the <code>$SPARK_LOCAL_DIR</code>) in your config, and finally mount your directory with existing pvc claim (notice give large storage e.g. <code>100GB</code>). The below code is spark config when submit job on kubernetes.</p> <pre><code>&quot;spark.kubernetes.driver.volumes.persistentVolumeClaim.spark-local-dir-1.options.claimName&quot;: &quot;spark-temp-local&quot;, &quot;spark.kubernetes.driver.volumes.persistentVolumeClaim.spark-local-dir-1.mount.path&quot;: &quot;/tmp/spark-temp&quot;, &quot;spark.kubernetes.driver.volumes.persistentVolumeClaim.spark-local-dir-1.mount.readOnly&quot;: &quot;false&quot;, &quot;spark.kubernetes.executor.volumes.persistentVolumeClaim.spark-local-dir-1.options.claimName&quot;: &quot;spark-temp-local&quot;, &quot;spark.kubernetes.executor.volumes.persistentVolumeClaim.spark-local-dir-1.mount.path&quot;: &quot;/tmp/spark-temp&quot;, &quot;spark.kubernetes.executor.volumes.persistentVolumeClaim.spark-local-dir-1.mount.readOnly&quot;: &quot;false&quot;, &quot;spark.local.dir&quot;: &quot;/tmp/spark-temp/&quot; </code></pre>
<p>I have the following file:</p> <pre><code># HELP container_cpu_usage_seconds_total [ALPHA] Cumulative cpu time consumed by the container in core-seconds # TYPE container_cpu_usage_seconds_total counter container_cpu_usage_seconds_total{container=&quot;coredns&quot;,namespace=&quot;kube-system&quot;,pod=&quot;coredns-64897985d-qzvj8&quot;} 1075.30302335 1641411355244 container_cpu_usage_seconds_total{container=&quot;etcd&quot;,namespace=&quot;kube-system&quot;,pod=&quot;etcd-minikube&quot;} 7948.244422673 1641411341787 container_cpu_usage_seconds_total{container=&quot;kindnet-cni&quot;,namespace=&quot;kube-system&quot;,pod=&quot;kindnet-v9rn4&quot;} 253.401092815 1641411342227 container_cpu_usage_seconds_total{container=&quot;kube-apiserver&quot;,namespace=&quot;kube-system&quot;,pod=&quot;kube-apiserver-minikube&quot;} 21314.526032702 1641411341706 container_cpu_usage_seconds_total{container=&quot;kube-controller-manager&quot;,namespace=&quot;kube-system&quot;,pod=&quot;kube-controller-manager-minikube&quot;} 9960.616171401 1641411346752 container_cpu_usage_seconds_total{container=&quot;kube-proxy&quot;,namespace=&quot;kube-system&quot;,pod=&quot;kube-proxy-ktclh&quot;} 220.17024815 1641411352327 container_cpu_usage_seconds_total{container=&quot;kube-scheduler&quot;,namespace=&quot;kube-system&quot;,pod=&quot;kube-scheduler-minikube&quot;} 1216.162832124 1641411355059 container_cpu_usage_seconds_total{container=&quot;metrics-server&quot;,namespace=&quot;kube-system&quot;,pod=&quot;metrics-server-6b76bd68b6-lpx4q&quot;} 715.97119974 1641411344274 container_cpu_usage_seconds_total{container=&quot;storage-provisioner&quot;,namespace=&quot;kube-system&quot;,pod=&quot;storage-provisioner&quot;} 47.685435216 1641411354429 # HELP container_memory_working_set_bytes [ALPHA] Current working set of the container in bytes # TYPE container_memory_working_set_bytes gauge container_memory_working_set_bytes{container=&quot;coredns&quot;,namespace=&quot;kube-system&quot;,pod=&quot;coredns-64897985d-qzvj8&quot;} 1.5364096e+07 1641411355244 container_memory_working_set_bytes{container=&quot;etcd&quot;,namespace=&quot;kube-system&quot;,pod=&quot;etcd-minikube&quot;} 5.9752448e+07 1641411341787 container_memory_working_set_bytes{container=&quot;kindnet-cni&quot;,namespace=&quot;kube-system&quot;,pod=&quot;kindnet-v9rn4&quot;} 1.0326016e+07 1641411342227 container_memory_working_set_bytes{container=&quot;kube-apiserver&quot;,namespace=&quot;kube-system&quot;,pod=&quot;kube-apiserver-minikube&quot;} 2.66002432e+08 1641411341706 container_memory_working_set_bytes{container=&quot;kube-controller-manager&quot;,namespace=&quot;kube-system&quot;,pod=&quot;kube-controller-manager-minikube&quot;} 5.9129856e+07 1641411346752 container_memory_working_set_bytes{container=&quot;kube-proxy&quot;,namespace=&quot;kube-system&quot;,pod=&quot;kube-proxy-ktclh&quot;} 2.00704e+07 1641411352327 container_memory_working_set_bytes{container=&quot;kube-scheduler&quot;,namespace=&quot;kube-system&quot;,pod=&quot;kube-scheduler-minikube&quot;} 2.3130112e+07 1641411355059 container_memory_working_set_bytes{container=&quot;metrics-server&quot;,namespace=&quot;kube-system&quot;,pod=&quot;metrics-server-6b76bd68b6-lpx4q&quot;} 2.6923008e+07 1641411344274 container_memory_working_set_bytes{container=&quot;storage-provisioner&quot;,namespace=&quot;kube-system&quot;,pod=&quot;storage-provisioner&quot;} 1.4209024e+07 1641411354429 </code></pre> <p>A few questions:</p> <ul> <li>What format is this? I know it isn't JSON.</li> <li>Can I use jq to parse/filter this data? I would like to get all metrics on the <code>coredns</code> container:</li> </ul> <pre><code>container_cpu_usage_seconds_total{container=&quot;coredns&quot;,namespace=&quot;kube-system&quot;,pod=&quot;coredns-64897985d-qzvj8&quot;} 1075.30302335 1641411355244 container_memory_working_set_bytes{container=&quot;coredns&quot;,namespace=&quot;kube-system&quot;,pod=&quot;coredns-64897985d-qzvj8&quot;} 1.5364096e+07 1641411355244 </code></pre>
<p>You could convert your file to JSON using <a href="https://github.com/prometheus/prom2json" rel="nofollow noreferrer">https://github.com/prometheus/prom2json</a></p> <p>Then it's jq all the way down, if you wish. E.g. with your input:</p> <pre><code>prom2json sample.prom | jq ' .[] | .metrics |= map(select(.labels.container==&quot;coredns&quot;) )' </code></pre> <p>yields</p> <pre><code>{ &quot;name&quot;: &quot;container_memory_working_set_bytes&quot;, &quot;help&quot;: &quot;[ALPHA] Current working set of the container in bytes&quot;, &quot;type&quot;: &quot;GAUGE&quot;, &quot;metrics&quot;: [ { &quot;labels&quot;: { &quot;container&quot;: &quot;coredns&quot;, &quot;namespace&quot;: &quot;kube-system&quot;, &quot;pod&quot;: &quot;coredns-64897985d-qzvj8&quot; }, &quot;timestamp_ms&quot;: &quot;1641411355244&quot;, &quot;value&quot;: &quot;1.5364096e+07&quot; } ] } { &quot;name&quot;: &quot;container_cpu_usage_seconds_total&quot;, &quot;help&quot;: &quot;[ALPHA] Cumulative cpu time consumed by the container in core-seconds&quot;, &quot;type&quot;: &quot;COUNTER&quot;, &quot;metrics&quot;: [ { &quot;labels&quot;: { &quot;container&quot;: &quot;coredns&quot;, &quot;namespace&quot;: &quot;kube-system&quot;, &quot;pod&quot;: &quot;coredns-64897985d-qzvj8&quot; }, &quot;timestamp_ms&quot;: &quot;1641411355244&quot;, &quot;value&quot;: &quot;1075.30302335&quot; } ] } </code></pre>
<p>Trying to use Varnish operator to setup Varnish cache in Kubernetes, added Helm chart and deployed repo but pod status is still pending.</p> <p>Here is the link I followed <a href="https://ibm.github.io/varnish-operator/quick-start.html" rel="nofollow noreferrer">https://ibm.github.io/varnish-operator/quick-start.html</a></p> <p>Kubernetes version - 1.21.5</p> <p><a href="https://i.stack.imgur.com/VRg2R.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VRg2R.png" alt="enter image description here" /></a></p>
<p>Thanks @Eugene i had look for events in namespace</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>LAST SEEN</th> <th>TYPE</th> <th>REASON</th> <th>OBJECT</th> <th>MESSAGE</th> </tr> </thead> <tbody> <tr> <td>2m29s</td> <td>Warning</td> <td>FailedScheduling</td> <td>pod/varnish-operator-5596dbb797-s6ncq</td> <td>0/2 nodes are available: 2 Insufficient cpu.</td> </tr> <tr> <td>4m34s</td> <td>Normal</td> <td>NotTriggerScaleUp</td> <td>pod/varnish-operator-5596dbb797-s6ncq</td> <td>pod didn't trigger scale-up:</td> </tr> </tbody> </table> </div> <p>I have increased CPU, issue solved thanks every one.</p>
<p>We are thinking about migrating our infrastructure to Kubernetes. All our Source-code is in GitHub, Docker containers are in Docker Hub.</p> <p>I would like to have a CI/CD pipeline for Kubernetes only using GitHub and Docker Hub. Is there a way?</p> <p>If not, what tools (as few as possible) should we use?</p>
<p>You can go it as per need using the Github Action and Docker hub only.</p> <p>You should also checkout the keel with GitHub :<a href="https://github.com/keel-hq/keel" rel="nofollow noreferrer">https://github.com/keel-hq/keel</a></p> <p><strong>Step: 1</strong></p> <pre><code>name: Stable Build on: push: tags: - &quot;*.*.*&quot; ... - name: Set tag in env run: echo &quot;TAG=${GITHUB_REF#refs/*/}&quot; &gt;&gt; $GITHUB_ENV ... tags: runq/go-kube:${{ env.TAG }}, runq/go-kube:latest </code></pre> <p><strong>Step : 2</strong></p> <p>Once build is done you can push it to Docker Hub</p> <p><strong>Step : 3</strong></p> <p>Keel can auto-update the deployment, but if you don't want that you can each time apply the YAML config from Github action also.</p> <p>Read more at : <a href="https://dev.to/achu1612/ci-cd-for-kubernetes-using-github-actions-and-keel-4b7c" rel="nofollow noreferrer">https://dev.to/achu1612/ci-cd-for-kubernetes-using-github-actions-and-keel-4b7c</a></p> <p>If you are planning to use Azure you should checkout : <a href="https://github.com/marketplace/actions/deploy-to-kubernetes-cluster" rel="nofollow noreferrer">https://github.com/marketplace/actions/deploy-to-kubernetes-cluster</a></p>
<p>I got an alert while configuring the monitoring module using <code>prometheus/kube-prometheus-stack 25.1.0</code>.</p> <p><strong>Alert</strong></p> <pre><code>[FIRING:1] KubeProxyDown - critical Alert: Target disappeared from Prometheus target discovery. - critical Description: KubeProxy has disappeared from Prometheus target discovery. Details: • alertname: KubeProxyDown • prometheus: monitoring/prometheus-kube-prometheus-prometheus • severity: critical </code></pre> <p>I think it is a new default rule in <code>kube-prometheus-stack 25.x.x</code>. It does not exist in <code>prometheus/kube-prometheus-stack 21.x.x</code>.</p> <p>The same issue happened in the EKS and minikube.</p> <p><strong>KubeProxyDown</strong> Rule</p> <pre><code>alert: KubeProxyDown expr: absent(up{job=&quot;kube-proxy&quot;} == 1) for: 15m labels: severity: critical annotations: description: KubeProxy has disappeared from Prometheus target discovery. runbook_url: https://runbooks.prometheus-operator.dev/runbooks/kubernetes/kubeproxydown summary: Target disappeared from Prometheus target discovery. </code></pre> <p>How can I resolve this issue?</p> <p>I would be thankful if anyone could help me</p>
<p>There was a change in <code>metrics-bind-address</code> in <code>kube-proxy</code>. Following the issues posted <a href="https://stackoverflow.com/questions/60734799/all-kubernetes-proxy-targets-down-prometheus-operator">here</a>, <a href="https://github.com/helm/charts/issues/16476" rel="noreferrer">here</a> and <a href="https://github.com/kubernetes/kubernetes/pull/74300" rel="noreferrer">here</a>. I can suggest the following. Change <code>kube-proxy</code> ConfigMap to different value:</p> <pre><code>$ kubectl edit cm/kube-proxy -n kube-system ## Change from metricsBindAddress: 127.0.0.1:10249 ### &lt;--- Too secure ## Change to metricsBindAddress: 0.0.0.0:10249 $ kubectl delete pod -l k8s-app=kube-proxy -n kube-system </code></pre>
<p>Per Flink's doc, we can deploy a standalone Flink cluster on top of Kubernetes, using Flink’s standalone deployment, or deploy Flink on Kubernetes using native Kubernetes deployments.</p> <p>The document says</p> <blockquote> <p>We generally recommend <strong>new</strong> users to deploy Flink on Kubernetes using native Kubernetes deployments.</p> </blockquote> <p>Is it because native Kubernetes is easier to get start with, or is it because standalone mode is kind of legacy ?</p> <p>In native Kubernetes mode, Flink is able to dynamically allocate and de-allocate TaskManagers depending on the required resources. While in standalone mode, task managers have to be provisioned manually.</p> <p>It sounds to me that native Kubernetes mode is a better choice.</p>
<p>Posted community wiki based on other answers - <a href="https://stackoverflow.com/questions/63270800/how-different-is-the-flink-deployment-on-kubernetes-and-native-kubernetes/63272753#63272753">David Anderson answer</a> and <a href="https://stackoverflow.com/questions/67142140/flink-on-kubernetes/67154143#67154143">austin_ce answer</a>. Feel free to expand it.</p> <hr /> <p>Good explanation from the <a href="https://stackoverflow.com/questions/63270800/how-different-is-the-flink-deployment-on-kubernetes-and-native-kubernetes/63272753#63272753">David Anderson answer</a>:</p> <p><a href="https://nightlies.apache.org/flink/flink-docs-release-1.14/docs/deployment/resource-providers/standalone/kubernetes/" rel="nofollow noreferrer">Standalone mode</a>:</p> <blockquote> <p>In a <a href="https://ci.apache.org/projects/flink/flink-docs-stable/ops/deployment/kubernetes.html" rel="nofollow noreferrer">Kubernetes session or per-job deployment</a>, Flink has no idea it's running on Kubernetes. In this mode, Flink behaves as it does in any standalone deployment (where there is no cluster framework available to do resource management). Kubernetes just happens to be how the infrastructure was created, but as far as Flink is concerned, it could have been bare metal. You will have to arrange for kubernetes to create the infrastructure that you will have configured Flink to expect.</p> </blockquote> <p><a href="https://nightlies.apache.org/flink/flink-docs-release-1.14/docs/deployment/resource-providers/native_kubernetes/" rel="nofollow noreferrer">Native mode</a>:</p> <ul> <li>Session deployment <blockquote> <p>In a <a href="https://ci.apache.org/projects/flink/flink-stable/ops/deployment/native_kubernetes.html" rel="nofollow noreferrer">Native Kubernetes session deployment</a>, Flink uses its <code>KubernetesResourceManager</code>, which submits a description of the cluster it wants to the Kubernetes ApiServer, which creates it. As jobs come and go, and the requirements for task managers (and slots) go up and down, Flink is able to obtain and release resources from kubernetes as appropriate.</p> </blockquote> </li> <li>Application mode <blockquote> <p>In <a href="https://ci.apache.org/projects/flink/flink-docs-stable/ops/deployment/#application-mode" rel="nofollow noreferrer">Application Mode</a> (<a href="https://flink.apache.org/news/2020/07/14/application-mode.html" rel="nofollow noreferrer">blog post</a>) (<a href="https://ci.apache.org/projects/flink/flink-docs-stable/ops/deployment/native_kubernetes.html#flink-kubernetes-application" rel="nofollow noreferrer">details</a>) you end up with Flink running as a kubernetes application, which will automatically create and destroy cluster components as needed for the job(s) in one Flink application.</p> </blockquote> </li> </ul> <p>The native mode is recommended <a href="https://stackoverflow.com/questions/67142140/flink-on-kubernetes/67154143#67154143">because it is just simpler</a>, I would not say it is legacy:</p> <blockquote> <p>The <code>Native</code> mode is the current recommendation for starting out on Kubernetes as it is the simplest option, like you noted. In Flink 1.13 (to be released in the coming weeks), there is added support for <a href="https://ci.apache.org/projects/flink/flink-docs-release-1.13/docs/deployment/resource-providers/native_kubernetes/#pod-template" rel="nofollow noreferrer">specifying Pod templates</a>. One of the drawbacks to this approach is its limited ability to integrate with CI/CD.</p> </blockquote>
<p>I would like to provide secrets from a Hashicorp Vault for the Apache Flink jobs running in a Kubernetes cluster. These credits will be used to access a state-backend for checkpointing and savepoints. The state-backend could be for example Minio S3 storage. Could someone provide a working example for a <a href="https://github.com/lyft/flinkk8soperator/blob/master/docs/crd.md" rel="nofollow noreferrer">FlinkApplication operator</a> please given the following setup?</p> <p>Vault secrets for username and password (or an access key):</p> <pre><code>vault kv put vvp/storage/config username=user password=secret vault kv put vvp/storage/config access-key=minio secret-key=minio123 </code></pre> <p>k8s manifest of the Flink application custom resource:</p> <pre class="lang-yaml prettyprint-override"><code>apiVersion: flink.k8s.io/v1beta1 kind: FlinkApplication metadata: name: processor namespace: default spec: image: stream-processor:0.1.0 deleteMode: None template: metadata: annotations: vault.hashicorp.com/agent-inject: &quot;true&quot; vault.hashicorp.com/role: vvp-flink-job vault.hashicorp.com/agent-inject-secret-storage-config.txt: vvp/data/storage/config flinkConfig: taskmanager.memory.flink.size: 1024mb taskmanager.heap.size: 200 taskmanager.network.memory.fraction: 0.1 taskmanager.network.memory.min: 10mb web.upload.dir: /opt/flink jobManagerConfig: resources: requests: memory: &quot;1280Mi&quot; cpu: &quot;0.1&quot; replicas: 1 taskManagerConfig: taskSlots: 2 resources: requests: memory: &quot;1280Mi&quot; cpu: &quot;0.1&quot; flinkVersion: &quot;1.14.2&quot; jarName: &quot;stream-processor-1.0-SNAPSHOT.jar&quot; parallelism: 3 entryClass: &quot;org.StreamingJob&quot; programArgs: &gt; --name value </code></pre> <p>Docker file of the flink application:</p> <pre><code>FROM maven:3.8.4-jdk-11 AS build ARG revision WORKDIR / COPY src /src COPY pom.xml / RUN mvn -B -Drevision=${revision} package # runtime FROM flink:1.14.2-scala_2.12-java11 ENV FLINK_HOME=/opt/flink ENTRYPOINT [&quot;/docker-entrypoint.sh&quot;] EXPOSE 6123 8081 CMD [&quot;help&quot;] </code></pre> <p>The flink-config.yaml contains the following examples:</p> <pre class="lang-yaml prettyprint-override"><code># state.backend: filesystem # Directory for checkpoints filesystem, when using any of the default bundled # state backends. # # state.checkpoints.dir: hdfs://namenode-host:port/flink-checkpoints # Default target directory for savepoints, optional. # # state.savepoints.dir: hdfs://namenode-host:port/flink-savepoints </code></pre> <p>The end goal is to replace the hardcoded secrets or set them somehow from the vault:</p> <pre class="lang-yaml prettyprint-override"><code>state.backend: filesystem s3.endpoint: http://minio:9000 s3.path.style.access: true s3.access-key: minio s3.secret-key: minio123 </code></pre> <p>Thank you.</p>
<p>Once you have vault variables set</p> <p>You can add the annotation in deployment to get variables out of the vault to deployment</p> <pre><code>annotations: vault.hashicorp.com/agent-image: &lt;Agent image&gt; vault.hashicorp.com/agent-inject: &quot;true&quot; vault.hashicorp.com/agent-inject-secret-secrets: kv/&lt;Path-of-secret&gt; vault.hashicorp.com/agent-inject-template-secrets: |2 {{- with secret &quot;kv/&lt;Path-of-secret&gt;&quot; -}} #!/bin/sh set -e {{- range $key, $value := .Data.data }} export {{ $key }}={{ $value }} {{- end }} exec &quot;$@&quot; {{- end }} vault.hashicorp.com/auth-path: auth/&lt;K8s cluster for auth&gt; vault.hashicorp.com/role: app </code></pre> <p>this will create the file inside your POD.</p> <p>When you application run it should execute this file first and the environment variable will get injected to POD.</p> <p>So vault annotation will create one file the same as you are getting as <strong>txt</strong> but instead, we will be doing it like</p> <pre><code>{{- range $key, $value := .Data.data }} export {{ $key }}={{ $value }} {{- end }} </code></pre> <p>it will keep and inject the <strong>export</strong> before key &amp; value. Now the file is a kind of shell script and once it will get executed on the startup of the application it will inject variables to the <strong>OS</strong> level.</p> <p>Keep this file in reop and add it in Docker <strong>./bin/runapp</strong></p> <pre><code>#!/bin/bash if [ -f '/vault/secrets/secrets' ]; then source '/vault/secrets/secrets' fi node &lt;path-insnide-docker&gt;/index.js #Sorry dont know scala or Java </code></pre> <p><strong>package.json</strong></p> <pre><code>&quot;start&quot;: &quot;./bin/runapp&quot;, </code></pre> <p><strong>Dockerfile</strong></p> <pre><code>ADD ./bin/runapp ./ EXPOSE 4444 CMD [&quot;npm&quot;, &quot;start&quot;] </code></pre> <p>Your vault injected file will be something like inside pod at <code>/vault/secrets/secrets</code> or your configured path.</p> <pre><code>#!/bin/sh set -e export development=false export production=true exec &quot;$@&quot; </code></pre>
<p>I have generated a list of keyspaces along with their size and ttl (715 keyspaces) and trying to analyze which keyspace is consuming huge memory. I can see that total memory occupied by the keyspaces is 1.2 MB but my Redis PVC is filled up to 13 GB. So, what is occupying so much memory in Redis container ?</p> <p>Redis Version: 6.0.9 Image: bitnami/redis:6.0.9-debian-10-r0</p> <p>Script I used to generate the list:</p> <pre><code>#!/bin/bash NAMESPACE=$1 SECRET=$2 POD=$3 CONTAINER=$4 PASSWORD_REDIS=$(kubectl get secrets -n $NAMESPACE $SECRET -o jsonpath='{.data.secret'} | base64 -d ) kubectl exec -it -n $NAMESPACE $POD -c $CONTAINER -- redis-cli -a ${PASSWORD_REDIS} KEYS '*' | tail -n +2 &gt; keylist.csv keylist.csv declare -a KEYS; arraylen=0; i=0; j=0; test2(){ arraylen=${#KEYS[@]} echo &quot;kubectl exec -i -n ${NAMESPACE} ${POD} -c ${CONTAINER} -- redis-cli -h 127.0.0.1 -a ${PASSWORD_REDIS} MEMORY USAGE ${KEYS[j]}&quot; &gt; keys.sh chmod +x keys.sh ./keys.sh &gt; size.txt 2&gt; /dev/null echo &quot;kubectl exec -i -n ${NAMESPACE} ${POD} -c ${CONTAINER} -- redis-cli -h 127.0.0.1 -a ${PASSWORD_REDIS} TTL ${KEYS[j]}&quot; &gt; ttl.sh chmod +x ttl.sh ./ttl.sh &gt; ttl.txt 2&gt; /dev/null SIZE=$(cat size.txt) TTL=$(cat ttl.txt) ((j=$j+1)) echo &quot;$j,${KEYS[j]},${SIZE},${TTL}&quot; &gt;&gt; output.csv if [ $j -ge $arraylen ]; then exit fi test2 } while IFS=') ' read -r slno line; do LINE=${line}; KEYS+=([i]=$LINE) i=$[$i+1] done &lt; keylist.csv test2 </code></pre> <p>Output looks like this (3rd column is size in bytes and 4th column is TTL in ms): <a href="https://i.stack.imgur.com/hvcpB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hvcpB.png" alt="enter image description here" /></a></p>
<p>Documentation of what is stored in GitLab's redis cache can be found <a href="https://docs.gitlab.com/ee/development/redis.html#redis-instances" rel="nofollow noreferrer">here</a> and <a href="https://gitlab.com/gitlab-com/runbooks/-/blob/master/docs/redis/redis-survival-guide-for-sres.md#what-do-we-store" rel="nofollow noreferrer">here</a>.</p> <p>It changes over time and depends on the version of GitLab you are using.</p> <p>It's also worth mentioning that GitLab has built a tool, <a href="https://gitlab.com/gitlab-com/gl-infra/redis-keyspace-analyzer/" rel="nofollow noreferrer">redis-keyspace-analyzer</a> for analyzing the keyspace of GitLab redis instances. You can use this to find the keys taking up the most space. (see also <a href="https://gitlab.com/gitlab-com/gl-infra/redis_bigkeys" rel="nofollow noreferrer">redis-bigkeys</a> and its <a href="https://gitlab.com/gitlab-com/runbooks/-/blob/master/docs/redis/redis-survival-guide-for-sres.md#bigkeys" rel="nofollow noreferrer">infra notes</a>). These tools are built by gitlab.com engineers for use with gitlab.com but should be adaptable to self-hosted gitlab instances.</p>
<p>Is there any existing ansible module I can use for the following. I can wait for <code>kubectl get nodes</code> <code>STATUS</code>=<code>Ready</code>?</p> <pre><code>$ kubectl get nodes NAME STATUS ROLES AGE VERSION master1 NotReady master 42s v1.8.4 </code></pre>
<h2> The <code>kubectl wait</code> command </h2> <p>Kubernetes supports the use of <a href="https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands#wait" rel="noreferrer">kubectl wait</a> from version v1.11.<br> It waits for a specific condition on one or many resources.</p> <p>Using the kubectl wait command with ansible tasks:</p> <pre><code> - name: Wait for all k8s nodes to be ready shell: kubectl wait --for=condition=Ready nodes --all --timeout=600s register: nodes_ready - debug: var=nodes_ready.stdout_lines </code></pre> <p>If you want to check the condition for some particular nodes only, you can use a <code>--selector</code> instead of <code>--all</code> like this:</p> <pre><code> - name: Wait for k8s nodes with node label 'purpose=test' to be ready shell: kubectl wait --for=condition=Ready nodes --selector purpose=test --timeout=600s register: nodes_ready - debug: var=nodes_ready.stdout_lines </code></pre>
<p>I'm following the quickstart guide <a href="https://kubernetes.github.io/ingress-nginx/deploy/#aws" rel="nofollow noreferrer">https://kubernetes.github.io/ingress-nginx/deploy/#aws</a> to install it on an aws eks cluster. The cluster runs in a private subnet and will receive traffic via a cloudflare argo tunnel.</p> <pre><code>kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-v1.1.0/deploy/static/provider/aws/deploy.yaml </code></pre> <p>When I then check the service I can see that it is pending:</p> <pre><code> kubectl get svc --namespace=ingress-nginx NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE ingress-nginx-controller LoadBalancer 10.100.64.86 &lt;pending&gt; 80:31323/TCP,443:31143/TCP 2d5h </code></pre> <p>The service generated seems ok, with valid annotations:</p> <pre><code> kubectl describe svc ingress-nginx-controller --namespace=ingress-nginx Name: ingress-nginx-controller Namespace: ingress-nginx Labels: app.kubernetes.io/component=controller app.kubernetes.io/instance=ingress-nginx app.kubernetes.io/managed-by=Helm app.kubernetes.io/name=ingress-nginx app.kubernetes.io/version=1.1.0 helm.sh/chart=ingress-nginx-4.0.10 Annotations: service.beta.kubernetes.io/aws-load-balancer-backend-protocol: tcp service.beta.kubernetes.io/aws-load-balancer-cross-zone-load-balancing-enabled: true service.beta.kubernetes.io/aws-load-balancer-type: nlb Selector: app.kubernetes.io/component=controller,app.kubernetes.io/instance=ingress-nginx,app.kubernetes.io/name=ingress-nginx Type: LoadBalancer IP Family Policy: SingleStack IP Families: IPv4 IP: 10.100.64.86 IPs: 10.100.64.86 Port: http 80/TCP TargetPort: http/TCP NodePort: http 31323/TCP Endpoints: 192.168.193.149:80 Port: https 443/TCP TargetPort: https/TCP NodePort: https 31143/TCP Endpoints: 192.168.193.149:443 Session Affinity: None External Traffic Policy: Local HealthCheck NodePort: 30785 Events: Type Reason Age From Message ---- ------ ---- ---- ------- Normal EnsuringLoadBalancer 2m23s (x646 over 2d5h) service-controller Ensuring load balancer </code></pre> <p>Not sure how to troubleshoot or fix</p>
<p>what worked for me was to download the installation file (<a href="https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-v1.1.0/deploy/static/provider/aws/deploy.yaml" rel="nofollow noreferrer">https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-v1.1.0/deploy/static/provider/aws/deploy.yaml</a>) and add an annotation to the controller-service and then reapply the installation.</p> <p>service.beta.kubernetes.io/aws-load-balancer-internal: &quot;true&quot;</p> <p>not sure why it doesnt work as-is.</p>
<p>I use aws-load-balancer-eip-allocations assign static IP to LoadBalancer service using k8s on AWS. The version of EKS is v1.16.13. The doc at <a href="https://github.com/kubernetes/kubernetes/blob/v1.16.0/staging/src/k8s.io/legacy-cloud-providers/aws/aws.go#L208-L211" rel="nofollow noreferrer">https://github.com/kubernetes/kubernetes/blob/v1.16.0/staging/src/k8s.io/legacy-cloud-providers/aws/aws.go#L208-L211</a>, line 210 and 211 says &quot;static IP addresses for the NLB. Only supported on elbv2 (NLB)&quot;. I do not know what the elbv2 is. I use the code below. But, I did not get static IP. Is elbv2 the problem? How do I use elbv2? Please also refer to <a href="https://github.com/kubernetes/kubernetes/pull/69263" rel="nofollow noreferrer">https://github.com/kubernetes/kubernetes/pull/69263</a> as well.</p> <pre><code>apiVersion: v1 kind: Service metadata: name: ingress-service annotations: service.beta.kubernetes.io/aws-load-balancer-type: &quot;nlb&quot; service.beta.kubernetes.io/aws-load-balancer-eip-allocations: &quot;eipalloc-0187de53333555567&quot; service.beta.kubernetes.io/aws-load-balancer-cross-zone-load-balancing-enabled: &quot;true&quot; </code></pre>
<p>have in mind that you need 1 EIP per subnet/zone and by default EKS uses a minimum of 2 zones.</p> <p>This is a working example you may found useful:</p> <pre><code>metadata: annotations: service.beta.kubernetes.io/aws-load-balancer-backend-protocol: tcp service.beta.kubernetes.io/aws-load-balancer-cross-zone-load-balancing-enabled: 'true' service.beta.kubernetes.io/aws-load-balancer-type: nlb service.beta.kubernetes.io/aws-load-balancer-subnets: &quot;subnet-xxxxxxxxxxxxxxxx,subnet-yyyyyyyyyyyyyyyyy&quot; service.beta.kubernetes.io/aws-load-balancer-eip-allocations: &quot;eipalloc-wwwwwwwwwwwwwwwww,eipalloc-zzzzzzzzzzzzzzzz&quot; </code></pre> <p>I hope this is useful to you</p>
<p>I generated a private key and and a new certificate from SSL.com and now I want to use these to sign the certificates in my Kubernetes cluster. I followed the below method to create the new issuer.</p> <p><a href="https://cert-manager.io/docs/configuration/ca/" rel="nofollow noreferrer">https://cert-manager.io/docs/configuration/ca/</a></p> <p>Once I create the new issuer, it gives an error. Any help would be appreciated. Below is the error message.</p> <pre><code>Events: Type Reason Age From Message ---- ------ ---- ---- ------- Warning ErrInvalidKeyPair 17m (x2 over 17m) cert-manager Error getting keypair for CA issuer: certificate is not a CA </code></pre>
<p>CA certificates have a <strong>basicConstraint</strong> extension which is set to <strong>CA:True</strong>. Your normal, run of the mill, end-entity certificate does not have this extension set as above, which is why you are seeing this error. That is, you cannot sign other certificates with an end-entity certificate's private key.</p> <p>This is by design. A CA is required to certify that the holder of the certificate is who/what they are. They cannot delegate that responsibility to a user who's carried out minimal authentication and simply paid a few dollars/euros/rubles for a certificate. If they permitted this and issued CA certificates to every subscriber, then anyone and everyone could issue themselves certificates that claimed to be from your bank, or from Google etc. - the security of the Internet would soon fail.</p> <p>Your options are limited:</p> <ol> <li>Find a commercial CA who allows you to issue your own certificates - this is likely to be prohibitively expensive and would involve regular auditing of your extensive processes and procedures.</li> <li>Operate your own private PKI - you can do whatever you want with this. Do bear in mind that external users would not trust this and you would need to persuade others that your PKI is trustworthy. Depending on the size and security stance of your user base, this may also entail defining extensive processes and procedures and regular auditing of those to ensure you PKI remains trustworthy to your users.</li> </ol>
<p>What is the default value for the allowVolumeExpansion? I create my volumes through a statefulset from apiVersion: apps/v1 volumeClaimTemplates In the case that the answer is false, how can I change it to true?</p> <p>Potentially relevant info: the cluster running on GKE autopilot.</p>
<p>You can find out by looking into the StorageClass that your claim is using <code>kubectl describe StorageClass &lt;name&gt;</code></p> <pre><code>volumeClaimTemplates: - ... spec: storageClassName: &lt;name&gt; # &lt;-- check using this name </code></pre> <p>Recent version of GKE the default is true. More about this field can be found <a href="https://cloud.google.com/kubernetes-engine/docs/how-to/persistent-volumes/volume-expansion" rel="nofollow noreferrer">here</a>.</p>
<p>I have some kubernetes applications that log to files rather than stdout/stderr, and I collect them with Promtail sidecars. But since the sidecars execute with &quot;localhost&quot; target, I don't have a <code>kubernetes_sd_config</code> that will apply pod metadata to labels for me. So I'm stuck statically declaring my labels.</p> <pre class="lang-yaml prettyprint-override"><code># ConfigMap apiVersion: v1 kind: ConfigMap metadata: labels: app: promtail name: sidecar-promtail data: config.yml: | client: url: http://loki.loki.svc.cluster.local:3100/loki/api/v1/push backoff_config: max_period: 5m max_retries: 10 min_period: 500ms batchsize: 1048576 batchwait: 1s external_labels: {} timeout: 10s positions: filename: /tmp/promtail-positions.yaml server: http_listen_port: 3101 target_config: sync_period: 10s scrape_configs: - job_name: sidecar-logs static_configs: - targets: - localhost labels: job: sidecar-logs __path__: &quot;/sidecar-logs/*.log&quot; ---- # Deployment apiVersion: apps/v1 kind: Deployment metadata: name: test-logger spec: selector: matchLabels: run: test-logger template: metadata: labels: run: test-logger spec: volumes: - name: nfs persistentVolumeClaim: claimName: nfs-claim - name: promtail-config configMap: name: sidecar-promtail containers: - name: sidecar-promtail image: grafana/promtail:2.1.0 volumeMounts: - name: nfs mountPath: /sidecar-logs - mountPath: /etc/promtail name: promtail-config - name: simple-logger image: foo/simple-logger volumeMounts: - name: nfs mountPath: /logs </code></pre> <p>What is the best way to label the collected logs based on the parent pod's metadata?</p>
<p>You can do the following:</p> <p>In the sidecar container, expose the pod name, node name and other information you need as environment variables, then add the flag <code>'-config.expand-env'</code> to enable environment expansion inside promtail config file, e.g.:</p> <pre class="lang-yaml prettyprint-override"><code>... - name: sidecar-promtail image: grafana/promtail:2.1.0 # image: grafana/promtail:2.4.1 # use this one if environment expansion is not available in 2.1.0 args: # Enable environment expansion in promtail config file - '-config.expand-env' env: - name: NODE_NAME valueFrom: fieldRef: fieldPath: spec.nodeName - name: POD_NAME valueFrom: fieldRef: fieldPath: metadata.name ... </code></pre> <p>Then in your configMap, add the environment variables in your static_config labels as such:</p> <pre class="lang-yaml prettyprint-override"><code>... scrape_configs: - job_name: sidecar-logs static_configs: - targets: - localhost labels: job: sidecar-logs pod: ${POD_NAME} node_name: ${NODE_NAME} __path__: &quot;/sidecar-logs/*.log&quot; ... </code></pre>
<p>we are testing out the Ambassador Edge Stack and started with a brand new GKE private cluster in autopilot mode.</p> <p>We installed from scratch following the quick start tour to get a feeling of it and ended up with the following error</p> <pre><code>Error from server: error when creating &quot;mapping-test.yaml&quot;: conversion webhook for getambassador.io/v3alpha1, Kind=Mapping failed: Post &quot;https://emissary-apiext.emissary-system.svc:443/webhooks/crd-convert?timeout=30s&quot;: net/http: request canceled while waiting for connection (Client.Timeout exceeded while awaiting headers) </code></pre> <p>We did a few rounds of DNS testing and deployed a few different test pods in different namespaces to validate that kube-dns is working properly, everything looks good at that end. Also the resolv.conf looks good.</p> <p>Ambassador is using the hostname <code>emissary-apiext.emissary-system.svc:443</code> (without the cluster.local) which should resolve fine. Doing a lookup with the FQN (with cluster.local) works fine btw.</p> <p>Any clues?</p> <p>Thanks a lot and take care.</p>
<p>I think i found the solution, posting here if someone come across this later on.</p> <p>So i followed <a href="https://www.getambassador.io/docs/edge-stack/latest/tutorials/getting-started/" rel="noreferrer">this</a> to deploy Ambassador Edge Stack in a Autopilot private cluster. I was getting the same error when i was trying to deploy the Mapping object (step 2.2).</p> <p>The issue is that the control plane (API Server) is trying to call emissary-apiext.emissary-system.svc:443 but the pods behind it are listening on port 8443 (figured that out by describing the Service).</p> <p>So i added a firewall rule to allow the GKE control plane to talk to the nodes on port 443.</p> <p>The firewall rule in question is called <strong>gke-gke-ap-xxxxx-master</strong>. The xxxx is called the cluster hash and is different for each cluster. To make sure you are editing the proper rule, double check that source IP Range matches the &quot;Control plane address range&quot; from the cluster details page. And that it's the rule that has a name ending with master.</p> <p>Just edit that rule and add 8443 to the tcp ports. It should work</p>
<p>How can I configure internode encryption (i.e., TLS) for Cassandra in K8ssandra?</p>
<p>K8ssandra 1.4.0 included some changes that should make it possible to configure TLS. For reference this is the <a href="https://github.com/k8ssandra/k8ssandra-operator/issues/235" rel="nofollow noreferrer">ticket</a>, and this is the corresponding <a href="https://github.com/k8ssandra/k8ssandra/pull/1180" rel="nofollow noreferrer">PR</a>.</p> <p>There is chart property, <code>cassandraYamlConfigMap</code>, with which you can specify a ConfigMap that contains your custom <code>cassandra.yaml</code>. The properties that you supply will be merged with those generated by k8ssandra with yours taking precedence.</p> <p>Note that your <code>cassandra.yaml</code> does not need to be a complete config file. It is sufficient to specify only the properties you are interested in since it will get merged with the based configuration file generated by K8ssandra.</p> <p>There are some additional properties required for internode and client encryption because you need to specify the keystore and truststore secrets so that volume mounts can be created. Note that you need to create the keystore and truststore secrets in advance.</p> <p>See the inline docs for the new chart properties <a href="https://github.com/k8ssandra/k8ssandra/blob/v1.4.1/charts/k8ssandra/values.yaml#L138" rel="nofollow noreferrer">here</a>.</p> <p>Here is an example chart properties file that demonstrates the new properties:</p> <pre class="lang-yaml prettyprint-override"><code>cassandra: version: 4.0.1 cassandraYamlConfigMap: cassandra-config encryption: keystoreSecret: keystore keystoreMountPath: /mnt/keystore truststoreSecret: truststore truststoreMountPath: /mnt/truststore heap: size: 512M datacenters: - name: dc1 size: 1 </code></pre> <p>There are a couple things to note about the charts properties. First, <code>keystoreSecret</code> and <code>truststoreSecret</code> refer to secrets that should live in the same namespace in which k8ssandra is installed. The user should create those secrets before installing (or upgrading k8ssandra).</p> <p>Secondly, <code>keystoreMountPath</code> and <code>truststoreMountPath</code> specify where those secrets should be mounted in the Cassandra pods. These properties must be specified and must match what is specified in <code>cassandra.yaml</code>.</p> <p>Here is an example of a ConfigMap that contains my custom cassandra.yaml:</p> <pre class="lang-yaml prettyprint-override"><code>apiVersion: v1 kind: ConfigMap metadata: name: cassandra-config data: cassandra.yaml: |- server_encryption_options: internode_encryption: all keystore: /mnt/keystore/keystore.jks keystore_password: cassandra truststore: /mnt/truststore/truststore.jks truststore_password: cassandra </code></pre> <p>K8ssandra uses <a href="https://github.com/k8ssandra/cass-operator" rel="nofollow noreferrer">Cass Operator</a> to manage Cassandra. With that in mind I recommend the following for further reading:</p> <ul> <li>This <a href="https://thelastpickle.com/blog/2021/10/28/cassandra-certificate-management-part_2-cert-manager-and-k8s.html" rel="nofollow noreferrer">article</a> covers configuring TLS for a cass-operator managed cluster using cert-manager.</li> <li>This <a href="https://github.com/k8ssandra/cass-operator/issues/217#issuecomment-949779469" rel="nofollow noreferrer">ticket</a> provides a detailed explanation of how Cass Operator configure internode encryption.</li> </ul>
<p>In one of our customer's kubernetes cluster(v1.16.8 with kubeadm) RBAC does not work at all. We creating a ServiceAccount, read-only ClusterRole and ClusterRoleBinding with the following yamls but when we login trough dashboard or kubectl user can almost do anything in the cluster. What can cause this problem?</p> <pre class="lang-yaml prettyprint-override"><code>kind: ServiceAccount apiVersion: v1 metadata: name: read-only-user namespace: permission-manager secrets: - name: read-only-user-token-7cdx2 </code></pre> <pre class="lang-yaml prettyprint-override"><code>kind: ClusterRoleBinding apiVersion: rbac.authorization.k8s.io/v1 metadata: name: read-only-user___template-namespaced-resources___read-only___all_namespaces labels: generated_for_user: '' subjects: - kind: ServiceAccount name: read-only-user namespace: permission-manager roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: template-namespaced-resources___read-only </code></pre> <pre class="lang-yaml prettyprint-override"><code>kind: ClusterRole apiVersion: rbac.authorization.k8s.io/v1 metadata: name: template-namespaced-resources___read-only rules: - verbs: - get - list - watch apiGroups: - '*' resources: - configmaps - endpoints - persistentvolumeclaims - pods - pods/log - pods/portforward - podtemplates - replicationcontrollers - resourcequotas - secrets - services - events - daemonsets - deployments - replicasets - ingresses - networkpolicies - poddisruptionbudgets </code></pre> <p>Here is the cluster's kube-apiserver.yaml file content:</p> <pre class="lang-yaml prettyprint-override"><code>apiVersion: v1 kind: Pod metadata: creationTimestamp: null labels: component: kube-apiserver tier: control-plane name: kube-apiserver namespace: kube-system spec: containers: - command: - kube-apiserver - --advertise-address=192.168.1.42 - --allow-privileged=true - --authorization-mode=Node,RBAC - --client-ca-file=/etc/kubernetes/pki/ca.crt - --enable-admission-plugins=NodeRestriction - --enable-bootstrap-token-auth=true - --etcd-cafile=/etc/kubernetes/pki/etcd/ca.crt - --etcd-certfile=/etc/kubernetes/pki/apiserver-etcd-client.crt - --etcd-keyfile=/etc/kubernetes/pki/apiserver-etcd-client.key - --etcd-servers=https://127.0.0.1:2379 - --insecure-port=0 - --kubelet-client-certificate=/etc/kubernetes/pki/apiserver-kubelet-client.crt - --kubelet-client-key=/etc/kubernetes/pki/apiserver-kubelet-client.key - --kubelet-preferred-address-types=InternalIP,ExternalIP,Hostname - --proxy-client-cert-file=/etc/kubernetes/pki/front-proxy-client.crt - --proxy-client-key-file=/etc/kubernetes/pki/front-proxy-client.key - --requestheader-allowed-names=front-proxy-client - --requestheader-client-ca-file=/etc/kubernetes/pki/front-proxy-ca.crt - --requestheader-extra-headers-prefix=X-Remote-Extra- - --requestheader-group-headers=X-Remote-Group - --requestheader-username-headers=X-Remote-User - --secure-port=6443 - --service-account-key-file=/etc/kubernetes/pki/sa.pub - --service-cluster-ip-range=10.96.0.0/12 - --tls-cert-file=/etc/kubernetes/pki/apiserver.crt - --tls-private-key-file=/etc/kubernetes/pki/apiserver.key image: k8s.gcr.io/kube-apiserver:v1.16.8 imagePullPolicy: IfNotPresent livenessProbe: failureThreshold: 8 httpGet: host: 192.168.1.42 path: /healthz port: 6443 scheme: HTTPS initialDelaySeconds: 15 timeoutSeconds: 15 name: kube-apiserver resources: requests: cpu: 250m volumeMounts: - mountPath: /etc/ssl/certs name: ca-certs readOnly: true - mountPath: /etc/ca-certificates name: etc-ca-certificates readOnly: true - mountPath: /etc/kubernetes/pki name: k8s-certs readOnly: true - mountPath: /usr/local/share/ca-certificates name: usr-local-share-ca-certificates readOnly: true - mountPath: /usr/share/ca-certificates name: usr-share-ca-certificates readOnly: true hostNetwork: true priorityClassName: system-cluster-critical volumes: - hostPath: path: /etc/ssl/certs type: DirectoryOrCreate name: ca-certs - hostPath: path: /etc/ca-certificates type: DirectoryOrCreate name: etc-ca-certificates - hostPath: path: /etc/kubernetes/pki type: DirectoryOrCreate name: k8s-certs - hostPath: path: /usr/local/share/ca-certificates type: DirectoryOrCreate name: usr-local-share-ca-certificates - hostPath: path: /usr/share/ca-certificates type: DirectoryOrCreate name: usr-share-ca-certificates status: {} </code></pre>
<p>What you have defined is only control the service account. Here's a tested spec; create a yaml file with:</p> <pre><code>apiVersion: v1 kind: Namespace metadata: name: test --- apiVersion: v1 kind: ServiceAccount metadata: name: test-sa namespace: test --- kind: ClusterRoleBinding # &lt;-- REMINDER: Cluster wide and not namespace specific. Use RoleBinding for namespace specific. apiVersion: rbac.authorization.k8s.io/v1 metadata: name: test-role-binding subjects: - kind: ServiceAccount name: test-sa namespace: test - kind: User name: someone apiGroup: rbac.authorization.k8s.io roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: test-cluster-role --- kind: ClusterRole apiVersion: rbac.authorization.k8s.io/v1 metadata: name: test-cluster-role rules: - verbs: - get - list - watch apiGroups: - '*' resources: - configmaps - endpoints - persistentvolumeclaims - pods - pods/log - pods/portforward - podtemplates - replicationcontrollers - resourcequotas - secrets - services - events - daemonsets - deployments - replicasets - ingresses - networkpolicies - poddisruptionbudgets </code></pre> <p>Apply the above spec: <code>kubectl apply -f &lt;filename&gt;.yaml</code></p> <p>Work as expected:</p> <p><a href="https://i.stack.imgur.com/OmWuP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OmWuP.png" alt="enter image description here" /></a></p> <p>Delete the test resources: <code>kubectl delete -f &lt;filename&gt;.yaml</code></p>
<p>We want to fetch cost at namespace level in a K8S cluster Azure (AKS), we are using a tool called kubecost to get cost incurred by each namespace, kubecost is an efficient tool which provides these information. I have setup the secrets for kubecost to access the Rate API, so will the cost of resources be fetched based on our account or is it just a generic cost ? (from what i read its just a generic cost fetched from public azure doc) Has anyone used it in AKS, or is there any better way to it ?</p> <p>Thanks !</p>
<p>I have used Kubecost and have found that it is best out there for namespace level cost reporting.</p> <blockquote> <p>Kubecost provides accurate Spot pricing using the AWS Spot Instance data feed. It can also assist with pod right-sizing. It tracks the declared requests for containers and provides recommendations based on usage. The included Grafana dashboards show you resource utilization in your cluster.</p> </blockquote> <p><a href="https://aws.amazon.com/blogs/containers/how-to-track-costs-in-multi-tenant-amazon-eks-clusters-using-kubecost/" rel="nofollow noreferrer">https://aws.amazon.com/blogs/containers/how-to-track-costs-in-multi-tenant-amazon-eks-clusters-using-kubecost/</a></p> <p><a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-data-feeds.html" rel="nofollow noreferrer">https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-data-feeds.html</a></p>
<p>I am running spark 3.1.1 on kubernetes 1.19. Once job finishes executor pods get cleaned up but driver pod remains in completed state. How to clean up driver pod once it is completed? any configuration option to set?</p> <pre><code>NAME READY STATUS RESTARTS AGE my-job-0e85ea790d5c9f8d-driver 0/1 Completed 0 2d20h my-job-8c1d4f79128ccb50-driver 0/1 Completed 0 43h my-job-c87bfb7912969cc5-driver 0/1 Completed 0 43h </code></pre>
<p>Concerning the initial question &quot;Spark on Kubernetes driver pod cleanup&quot;, it seems that there is no way to pass, at spark-submit time, a TTL parameter to kubernetes for avoiding the never-removal of driver pods in completed status.</p> <p>From Spark documentation: <a href="https://spark.apache.org/docs/latest/running-on-kubernetes.html" rel="nofollow noreferrer">https://spark.apache.org/docs/latest/running-on-kubernetes.html</a> <em>When the application completes, the executor pods terminate and are cleaned up, but the driver pod persists logs and remains in “completed” state in the Kubernetes API until it’s eventually garbage collected or manually cleaned up.</em></p> <p>It is not very clear who is doing this 'eventually garbage collected'.</p>
<p>I'm following the quickstart guide <a href="https://kubernetes.github.io/ingress-nginx/deploy/#aws" rel="nofollow noreferrer">https://kubernetes.github.io/ingress-nginx/deploy/#aws</a> to install it on an aws eks cluster. The cluster runs in a private subnet and will receive traffic via a cloudflare argo tunnel.</p> <pre><code>kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-v1.1.0/deploy/static/provider/aws/deploy.yaml </code></pre> <p>When I then check the service I can see that it is pending:</p> <pre><code> kubectl get svc --namespace=ingress-nginx NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE ingress-nginx-controller LoadBalancer 10.100.64.86 &lt;pending&gt; 80:31323/TCP,443:31143/TCP 2d5h </code></pre> <p>The service generated seems ok, with valid annotations:</p> <pre><code> kubectl describe svc ingress-nginx-controller --namespace=ingress-nginx Name: ingress-nginx-controller Namespace: ingress-nginx Labels: app.kubernetes.io/component=controller app.kubernetes.io/instance=ingress-nginx app.kubernetes.io/managed-by=Helm app.kubernetes.io/name=ingress-nginx app.kubernetes.io/version=1.1.0 helm.sh/chart=ingress-nginx-4.0.10 Annotations: service.beta.kubernetes.io/aws-load-balancer-backend-protocol: tcp service.beta.kubernetes.io/aws-load-balancer-cross-zone-load-balancing-enabled: true service.beta.kubernetes.io/aws-load-balancer-type: nlb Selector: app.kubernetes.io/component=controller,app.kubernetes.io/instance=ingress-nginx,app.kubernetes.io/name=ingress-nginx Type: LoadBalancer IP Family Policy: SingleStack IP Families: IPv4 IP: 10.100.64.86 IPs: 10.100.64.86 Port: http 80/TCP TargetPort: http/TCP NodePort: http 31323/TCP Endpoints: 192.168.193.149:80 Port: https 443/TCP TargetPort: https/TCP NodePort: https 31143/TCP Endpoints: 192.168.193.149:443 Session Affinity: None External Traffic Policy: Local HealthCheck NodePort: 30785 Events: Type Reason Age From Message ---- ------ ---- ---- ------- Normal EnsuringLoadBalancer 2m23s (x646 over 2d5h) service-controller Ensuring load balancer </code></pre> <p>Not sure how to troubleshoot or fix</p>
<p>i would suggest try applying this changes,</p> <p><code>kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-0.32.0/deploy/static/provider/aws/deploy.yaml</code></p> <p>The change that you have is for <strong>internal</strong> load balancer that wont give you a public exposed IP or Loabalancer.</p> <pre><code>service.beta.kubernetes.io/aws-load-balancer-internal: &quot;true&quot; </code></pre> <p>You can follow this Guide and this will create the NLB loadbalancer for you and the ingress tutorial also.</p> <p>Read more at : <a href="https://aws.amazon.com/blogs/opensource/network-load-balancer-nginx-ingress-controller-eks/" rel="nofollow noreferrer">https://aws.amazon.com/blogs/opensource/network-load-balancer-nginx-ingress-controller-eks/</a></p>
<p>I have a microservice application in one repo that communicates with another service that's managed by another repo. This is not an issue when deploying to cloud, however, when devving locally the other service needs to be deployed too.</p> <p>I've read this documentation: <a href="https://skaffold.dev/docs/design/config/#remote-config-dependency" rel="nofollow noreferrer">https://skaffold.dev/docs/design/config/#remote-config-dependency</a> and this seems like a clean solution, but I only want it to depend on the git skaffold config if deploying locally (i.e. current context is &quot;minikube&quot;).</p> <p>Is there a way to do this?</p>
<p>Profiles can be <a href="https://skaffold.dev/docs/environment/profiles/#activation" rel="nofollow noreferrer">automatically activated</a> based on criteria such as environment variables, kube-context names, and the Skaffold command being run.</p> <p>Profiles are processed after resolving the config dependencies though. But you could have your remote config include a profile that is contingent on a <code>kubeContext: minikube</code>.</p> <p>Another alternative is to have several <code>skaffold.yaml</code>s: one for prod, one for dev.</p>
<p>my containers run in kubernetes and I saw lots of OOM from kubernetes Node log. All the logs only have process id information. it's hard to dig what containers OOM. I don't know how to find container id by the host process Id.</p> <p>Is there any way i can get host process id within container so that i can get a mapping.</p> <p>this is node log</p> <pre><code>2020-04-28 09:27:15.530 HKT I0428 01:27:15.530763 1627 log_monitor.go:115] New status generated: &amp;{Source:kernel-monitor Events:[{Severity:warn Timestamp:2020-04-28 01:27:08.060896434 +0000 UTC m=+89600.088785273 Reason:OOMKilling Message:Memory cgroup out of memory: Kill process 2493556 (node) score 1432 or sacrifice child 2020-04-28 09:29:15.000 HKT Memory cgroup out of memory: Kill process 2493562 (node) score 1529 or sacrifice child Killed process 2493562 (node) total-vm:14009952kB, anon-rss:3146688kB, file-rss:28720kB, shmem-rss:0kB 2020-04-28 09:29:15.000 HKT Memory cgroup out of memory: Kill process 2496433 (node) score 1275 or sacrifice child Killed process 2496433 (node) total-vm:7183684kB, anon-rss:1833580kB, file-rss:28804kB, shmem-rss:0kB 2020-04-28 09:29:15.309 HKT I0428 01:29:15.309829 1627 log_monitor.go:115] New status generated: &amp;{Source:kernel-monitor Events:[{Severity:warn Timestamp:2020-04-28 01:29:07.829961434 +0000 UTC m=+89719.857850273 Reason:OOMKilling Message:Memory cgroup out of memory: Kill process 2493562 (node) score 1529 or sacrifice child 2020-04-28 09:29:15.330 HKT I0428 01:29:15.329925 1627 log_monitor.go:115] New status generated: &amp;{Source:kernel-monitor Events:[{Severity:warn Timestamp:2020-04-28 01:29:07.849907434 +0000 UTC m=+89719.877796273 Reason:OOMKilling Message:Memory cgroup out of memory: Kill process 2496433 (node) score 1275 or sacrifice child 2020-04-28 09:48:29.000 HKT Memory cgroup out of memory: Kill process 3086395 (monitor) score 237 or sacrifice child Killed process 3086395 (monitor) total-vm:130128kB, anon-rss:9204kB, file-rss:15488kB, shmem-rss:0kB </code></pre>
<p>How to find pod name by the host process Id?</p> <blockquote> <p>nsenter -t $PID -u hostname</p> </blockquote> <p>Then you can find container id easily, I think.</p>
<h3>What I'm trying to achieve</h3> <p>I'm trying to deploy an elixir (phoenix) application in a microk8s cluster namespace with TLS using let's encrypt. The cluster is hosted on an AWS EC2 instance.</p> <h3>The problem I'm facing</h3> <ul> <li>The ingress is created in the namespace</li> <li>ingress routes to the correct domain</li> <li>the application is working and displayed on the given domain</li> </ul> <p><strong>The TLS secret is not being created in the namespace and a 'default' one is created</strong></p> <p>The secrets after deploying both phoenix app and httpbin app:</p> <pre class="lang-sh prettyprint-override"><code>me@me:~/Documents/kubernetes-test$ kubectl get secret -n production NAME TYPE DATA AGE default-token-jmgrg kubernetes.io/service-account-token 3 20m httpbin-tls kubernetes.io/tls 2 81s </code></pre> <p><strong>The domain is insecure, i.e the TLS is not working.</strong></p> <p>Logs from the ingress controller after applying the yml files:</p> <pre><code>W0106 17:26:36.967036 6 controller.go:1192] Error getting SSL certificate &quot;production/phoenix-app-tls&quot;: local SSL certificate production/phoenix-app-tls was not found. Using default certificate W0106 17:26:46.445248 6 controller.go:1192] Error getting SSL certificate &quot;production/phoenix-app-tls&quot;: local SSL certificate production/phoenix-app-tls was not found. Using default certificate W0106 17:26:49.779680 6 controller.go:1192] Error getting SSL certificate &quot;production/phoenix-app-tls&quot;: local SSL certificate production/phoenix-app-tls was not found. Using default certificate I0106 17:26:56.431925 6 status.go:281] &quot;updating Ingress status&quot; namespace=&quot;production&quot; ingress=&quot;phoenix-app-ingress&quot; currentValue=[] newValue=[{IP:127.0.0.1 Hostname: Ports:[]}] I0106 17:26:56.443405 6 event.go:282] Event(v1.ObjectReference{Kind:&quot;Ingress&quot;, Namespace:&quot;production&quot;, Name:&quot;phoenix-app-ingress&quot;, UID:&quot;REDACTED&quot;, APIVersion:&quot;networking.k8s.io/v1beta1&quot;, ResourceVersion:&quot;1145907&quot;, FieldPath:&quot;&quot;}): type: 'Normal' reason: 'Sync' Scheduled for sync W0106 17:26:56.443655 6 backend_ssl.go:46] Error obtaining X.509 certificate: no object matching key &quot;production/phoenix-app-tls&quot; in local store W0106 17:26:56.443781 6 controller.go:1192] Error getting SSL certificate &quot;production/phoenix-app-tls&quot;: local SSL certificate production/phoenix-app-tls was not found. Using default certificate </code></pre> <p>The description of the created ingress, note that here at the bottom it says <code>Successfully created Certificate &quot;phoenix-app-tls&quot; but the secret does not exist</code>:</p> <pre class="lang-sh prettyprint-override"><code>me@me:~/Documents/kubernetes-test$ kubectl describe ing phoenix-app-ingress -n production Name: phoenix-app-ingress Labels: app=phoenix-app Namespace: production Address: 127.0.0.1 Default backend: default-http-backend:80 (&lt;error: endpoints &quot;default-http-backend&quot; not found&gt;) TLS: phoenix-app-tls terminates phoenix.sub.mydomain.com Rules: Host Path Backends ---- ---- -------- phoenix.sub.mydomain.com / phoenix-app-service-headless:8000 (REDACTED_IP:4000,REDACTED_IP:4000) Annotations: cert-manager.io/cluster-issuer: letsencrypt nginx.ingress.kubernetes.io/cors-allow-credentials: true nginx.ingress.kubernetes.io/cors-allow-methods: GET, POST, OPTIONS nginx.ingress.kubernetes.io/cors-allow-origin: * nginx.ingress.kubernetes.io/enable-cors: true Events: Type Reason Age From Message ---- ------ ---- ---- ------- Normal CreateCertificate 29m cert-manager Successfully created Certificate &quot;phoenix-app-tls&quot; Normal Sync 8m43s (x3 over 29m) nginx-ingress-controller Scheduled for sync </code></pre> <h3>Resources</h3> <p>The deployment yml:</p> <pre class="lang-yaml prettyprint-override"><code>apiVersion: apps/v1 kind: Deployment metadata: name: phoenix-app labels: app: phoenix-app spec: replicas: 2 selector: matchLabels: app: phoenix-app strategy: rollingUpdate: maxSurge: 1 maxUnavailable: 1 type: RollingUpdate template: metadata: labels: app: phoenix-app spec: containers: - name: phoenix-app image: REDACTED imagePullPolicy: Always command: [&quot;./bin/hello&quot;, &quot;start&quot;] lifecycle: preStop: exec: command: [&quot;./bin/hello&quot;, &quot;stop&quot;] ports: - containerPort: 4000 env: - name: POD_IP valueFrom: fieldRef: fieldPath: status.podIP envFrom: - configMapRef: name: phoenix-app-config - secretRef: name: phoenix-app-secrets imagePullSecrets: - name: gitlab-pull-secret </code></pre> <p>The service yml:</p> <pre><code>apiVersion: v1 kind: Service metadata: name: phoenix-app-service-headless labels: app: phoenix-app spec: clusterIP: None selector: app: phoenix-app ports: - name: http port: 8000 targetPort: 4000 # The exposed port by the phoenix app </code></pre> <p>Note: I removed my actual domain</p> <p>The ingress yml:</p> <pre class="lang-yaml prettyprint-override"><code>apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: phoenix-app-ingress labels: app: phoenix-app annotations: nginx.ingress.kubernetes.io/enable-cors: &quot;true&quot; nginx.ingress.kubernetes.io/cors-allow-methods: &quot;GET, POST, OPTIONS&quot; nginx.ingress.kubernetes.io/cors-allow-origin: &quot;*&quot; nginx.ingress.kubernetes.io/cors-allow-credentials: &quot;true&quot; cert-manager.io/cluster-issuer: &quot;letsencrypt&quot; spec: tls: - hosts: - &quot;phoenix.sub.mydomain.com&quot; secretName: phoenix-app-tls rules: - host: &quot;phoenix.sub.mydomain.com&quot; http: paths: - path: / pathType: Prefix backend: service: name: phoenix-app-service-headless port: number: 8000 # Same port as in service.yml </code></pre> <h3>Tested with different service</h3> <p>I deployed a sample service using httpbin (is not a headless service) and the TLS works fine in the same namespace. Here are the resources that I used to deploy it:</p> <p>deplyoment.yml</p> <pre><code>apiVersion: apps/v1 kind: Deployment metadata: name: httpbin labels: app: httpbin spec: replicas: 1 selector: matchLabels: app: httpbin version: v1 template: metadata: labels: app: httpbin version: v1 spec: containers: - image: docker.io/kennethreitz/httpbin imagePullPolicy: Always name: httpbin ports: - containerPort: 80 </code></pre> <p>The service yml:</p> <pre class="lang-yaml prettyprint-override"><code>apiVersion: v1 kind: Service metadata: name: httpbin labels: app: httpbin spec: ports: - name: http port: 8000 targetPort: 80 selector: app: httpbin </code></pre> <p>The ingress yml:</p> <pre class="lang-yaml prettyprint-override"><code>apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: httpbin labels: app: httpbin annotations: cert-manager.io/cluster-issuer: &quot;letsencrypt&quot; spec: tls: - hosts: - &quot;httpbin.sub.mydomain.com&quot; secretName: httpbin-tls rules: - host: &quot;httpbin.sub.mydomain.com&quot; # This is a subdomain we want to route these requests to http: paths: - path: / pathType: Prefix backend: service: name: httpbin port: number: 8000 </code></pre> <p>My best guess is that it has something to do with the fact that the service is headless, but I have no clue as to how I can resolve the issue.</p>
<p>I found out that you can actually check for certificates with kubectl: <code>kubectl get certificate -n production</code></p> <p>The status of this certificate was READY = FALSE.</p> <p>I checked the description: <code>kubectl describe certificate &lt;certificate_name&gt; -n production</code></p> <p>At the bottom it said: Too many certificates have been created in the last 164 hours for this exact domain.</p> <p>I just changed the domain and voila! It works.</p>
<p>I want to create a Kubernetes CronJob that deletes resources (Namespace, ClusterRole, ClusterRoleBinding) that may be left over (initially, the criteria will be &quot;has label=Something&quot; and &quot;is older than 30 minutes&quot;. (Each namespace contains resources for a test run).</p> <p>I created the CronJob, a ServiceAccount, a ClusterRole, a ClusterRoleBinding, and assigned the service account to the pod of the cronjob.</p> <p>The cronjob uses an image that contains kubectl, and some script to select the correct resources.</p> <p>My first draft looks like this:</p> <pre class="lang-yaml prettyprint-override"><code>--- apiVersion: v1 kind: ServiceAccount metadata: name: my-app namespace: default labels: app: my-app --- apiVersion: batch/v1beta1 kind: CronJob metadata: name: my-app namespace: default labels: app: my-app spec: concurrencyPolicy: Forbid schedule: &quot;*/1 * * * *&quot; jobTemplate: # job spec spec: template: # pod spec spec: serviceAccountName: my-app restartPolicy: Never containers: - name: my-app image: image-with-kubectl env: - name: MINIMUM_AGE_MINUTES value: '2' command: [sh, -c] args: # final script is more complex than this - | kubectl get namespaces kubectl get clusterroles kubectl get clusterrolebindings kubectl delete Namespace,ClusterRole,ClusterRoleBinding --all-namespaces --selector=bla=true --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: my-app labels: app: my-app roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: my-app subjects: - kind: ServiceAccount name: my-app namespace: default apiGroup: &quot;&quot; --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: my-app labels: app: my-app rules: - apiGroups: [&quot;&quot;] resources: - namespaces - clusterroles - clusterrolebindings verbs: [list, delete] </code></pre> <p>The cronjob is able to list and delete namespaces, but not cluster roles or cluster role bindings. What am I missing?</p> <p>(Actually, I'm testing this with a Job first, before moving to a CronJob):</p> <pre><code>NAME STATUS AGE cattle-system Active 16d default Active 16d fleet-system Active 16d gitlab-runner Active 7d6h ingress-nginx Active 16d kube-node-lease Active 16d kube-public Active 16d kube-system Active 16d security-scan Active 16d Error from server (Forbidden): clusterroles.rbac.authorization.k8s.io is forbidden: User &quot;system:serviceaccount:default:my-app&quot; cannot list resource &quot;clusterroles&quot; in API group &quot;rbac.authorization.k8s.io&quot; at the cluster scope Error from server (Forbidden): clusterrolebindings.rbac.authorization.k8s.io is forbidden: User &quot;system:serviceaccount:default:my-app&quot; cannot list resource &quot;clusterrolebindings&quot; in API group &quot;rbac.authorization.k8s.io&quot; at the cluster scope Error from server (Forbidden): clusterroles.rbac.authorization.k8s.io is forbidden: User &quot;system:serviceaccount:default:my-app&quot; cannot list resource &quot;clusterroles&quot; in API group &quot;rbac.authorization.k8s.io&quot; at the cluster scope Error from server (Forbidden): clusterrolebindings.rbac.authorization.k8s.io is forbidden: User &quot;system:serviceaccount:default:my-app&quot; cannot list resource &quot;clusterrolebindings&quot; in API group &quot;rbac.authorization.k8s.io&quot; at the cluster scope` </code></pre>
<p>You need to change your ClusterRole like this :</p> <pre><code>apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: my-app labels: app: my-app rules: - apiGroups: [&quot;&quot;] resources: - namespaces verbs: [list, delete] - apiGroups: [&quot;rbac.authorization.k8s.io&quot;] resources: - clusterroles - clusterrolebindings verbs: [list, delete] </code></pre> <p>The ressources are now in the right apiGroup</p>
<p>Evening!</p> <p>I'm wondering if anyone could share the steps for updating the certificates on OpenShift + Kubernetes 4.6? I've checked using the below command and some are expired.</p> <p><code>find /etc/kubernetes/ -type f -name &quot;*.crt&quot; -print|egrep -v 'ca.crt$'|xargs -L 1 -t -i bash -c 'openssl x509 -noout -text -in {}|grep After'</code></p> <p>I'm not able to find relevant steps to my UPN install. The following certificates are expired as well.</p> <p><code>81789506 lrwxrwxrwx. 1 root root 59 Jan 9 00:32 kubelet-server-current.pem -&gt; /var/lib/kubelet/pki/kubelet-server-2021-06-18-20-35-33.pem 81800208 lrwxrwxrwx. 1 root root 59 Jan 9 00:32 kubelet-client-current.pem -&gt; /var/lib/kubelet/pki/kubelet-client-2021-06-19-13-16-00.pem</code></p> <p>Since the API server is offline, I'm not able to renew the certificates via oc commands. All OC commands return an error since the API server ( port 6443 ) is offline. This cluster is installed on VMware using the UPI method. There was a failure sometime back taking the cluster offline. When the cluster was brought back up, the certs were already expired and could not renew since services needed for that were offline I think?</p> <p>Wondering if anyone managed to recover from this scenario and would be able to help?</p>
<p>Did you check the official doc on that subject?<br /> It may help you<br /> <a href="https://docs.openshift.com/container-platform/4.6/backup_and_restore/control_plane_backup_and_restore/disaster_recovery/scenario-3-expired-certs.html" rel="nofollow noreferrer">https://docs.openshift.com/container-platform/4.6/backup_and_restore/control_plane_backup_and_restore/disaster_recovery/scenario-3-expired-certs.html</a><br /> But if you can't login to your cluster, it may be quite difficult...</p>
<p>I want to set up a EKS cluster, enabling other IAM users to connect and tinker with the cluster. To do so, <a href="https://docs.aws.amazon.com/eks/latest/userguide/add-user-role.html" rel="nofollow noreferrer">AWS recommends patching a config map</a>, which I did. Now I want to enable the same “feature” using terraform.</p> <p>I use terraforms EKS provider and read <a href="https://registry.terraform.io/modules/terraform-aws-modules/eks/aws/latest#general-notes" rel="nofollow noreferrer">in the documentation</a> in section &quot;Due to the plethora of tooling a...&quot; that basically authentication is up to myself.</p> <p>Now I use the <a href="https://registry.terraform.io/providers/hashicorp/kubernetes/latest/docs" rel="nofollow noreferrer">Terraform Kubernetes provider</a> to update this config map:</p> <pre><code>resource &quot;kubernetes_config_map&quot; &quot;aws_auth&quot; { depends_on = [module.eks.cluster_id] metadata { name = &quot;aws-auth&quot; namespace = &quot;kube-system&quot; } data = THATS_MY_UPDATED_CONFIG } </code></pre> <p>But do not succeed and get the following error:</p> <pre><code>2022-01-07T15:49:55.732+0100 [DEBUG] provider.terraform-provider-kubernetes_v2.7.1_x5: 2022/01/07 15:49:55 [DEBUG] Kubernetes API Response Details: 2022-01-07T15:49:55.732+0100 [DEBUG] provider.terraform-provider-kubernetes_v2.7.1_x5: ---[ RESPONSE ]-------------------------------------- 2022-01-07T15:49:55.732+0100 [DEBUG] provider.terraform-provider-kubernetes_v2.7.1_x5: HTTP/2.0 409 Conflict 2022-01-07T15:49:55.732+0100 [DEBUG] provider.terraform-provider-kubernetes_v2.7.1_x5: Content-Length: 206 2022-01-07T15:49:55.732+0100 [DEBUG] provider.terraform-provider-kubernetes_v2.7.1_x5: Audit-Id: 15.... 2022-01-07T15:49:55.732+0100 [DEBUG] provider.terraform-provider-kubernetes_v2.7.1_x5: Cache-Control: no-cache, private 2022-01-07T15:49:55.732+0100 [DEBUG] provider.terraform-provider-kubernetes_v2.7.1_x5: Content-Type: application/json 2022-01-07T15:49:55.732+0100 [DEBUG] provider.terraform-provider-kubernetes_v2.7.1_x5: Date: Fri, 07 Jan 2022 14:49:55 GMT 2022-01-07T15:49:55.732+0100 [DEBUG] provider.terraform-provider-kubernetes_v2.7.1_x5: X-Kubernetes-Pf-Flowschema-Uid: f43... 2022-01-07T15:49:55.732+0100 [DEBUG] provider.terraform-provider-kubernetes_v2.7.1_x5: X-Kubernetes-Pf-Prioritylevel-Uid: 0054... 2022-01-07T15:49:55.732+0100 [DEBUG] provider.terraform-provider-kubernetes_v2.7.1_x5: 2022-01-07T15:49:55.732+0100 [DEBUG] provider.terraform-provider-kubernetes_v2.7.1_x5: { 2022-01-07T15:49:55.732+0100 [DEBUG] provider.terraform-provider-kubernetes_v2.7.1_x5: &quot;kind&quot;: &quot;Status&quot;, 2022-01-07T15:49:55.732+0100 [DEBUG] provider.terraform-provider-kubernetes_v2.7.1_x5: &quot;apiVersion&quot;: &quot;v1&quot;, 2022-01-07T15:49:55.732+0100 [DEBUG] provider.terraform-provider-kubernetes_v2.7.1_x5: &quot;metadata&quot;: {}, 2022-01-07T15:49:55.732+0100 [DEBUG] provider.terraform-provider-kubernetes_v2.7.1_x5: &quot;status&quot;: &quot;Failure&quot;, 2022-01-07T15:49:55.732+0100 [DEBUG] provider.terraform-provider-kubernetes_v2.7.1_x5: &quot;message&quot;: &quot;configmaps \&quot;aws-auth\&quot; already exists&quot;, 2022-01-07T15:49:55.733+0100 [DEBUG] provider.terraform-provider-kubernetes_v2.7.1_x5: &quot;reason&quot;: &quot;AlreadyExists&quot;, 2022-01-07T15:49:55.733+0100 [DEBUG] provider.terraform-provider-kubernetes_v2.7.1_x5: &quot;details&quot;: { 2022-01-07T15:49:55.733+0100 [DEBUG] provider.terraform-provider-kubernetes_v2.7.1_x5: &quot;name&quot;: &quot;aws-auth&quot;, 2022-01-07T15:49:55.733+0100 [DEBUG] provider.terraform-provider-kubernetes_v2.7.1_x5: &quot;kind&quot;: &quot;configmaps&quot; 2022-01-07T15:49:55.733+0100 [DEBUG] provider.terraform-provider-kubernetes_v2.7.1_x5: }, 2022-01-07T15:49:55.733+0100 [DEBUG] provider.terraform-provider-kubernetes_v2.7.1_x5: &quot;code&quot;: 409 2022-01-07T15:49:55.733+0100 [DEBUG] provider.terraform-provider-kubernetes_v2.7.1_x5: } 2022-01-07T15:49:55.733+0100 [DEBUG] provider.terraform-provider-kubernetes_v2.7.1_x5: 2022-01-07T15:49:55.733+0100 [DEBUG] provider.terraform-provider-kubernetes_v2.7.1_x5: ----------------------------------------------------- 2022-01-07T15:49:55.775+0100 [ERROR] vertex &quot;module.main.module.eks.kubernetes_config_map.aws_auth&quot; error: configmaps &quot;aws-auth&quot; already exists ╷ │ Error: configmaps &quot;aws-auth&quot; already exists │ │ with module.main.module.eks.kubernetes_config_map.aws_auth, │ on ../../modules/eks/eks-iam-map-users.tf line 44, in resource &quot;kubernetes_config_map&quot; &quot;aws_auth&quot;: │ 44: resource &quot;kubernetes_config_map&quot; &quot;aws_auth&quot; { │ ╵ </code></pre> <p>It seems this is a controversial problem and as everyone using EKS and Terraform should have it – I ask myself how to solve this? The <a href="https://github.com/terraform-aws-modules/terraform-aws-eks/issues/852" rel="nofollow noreferrer">related issue</a>, <a href="https://stackoverflow.com/questions/51127339/terraform-kubernetes-provider-with-eks-fails-on-configmap">I</a> is close .... I'm somewhat lost, anyone has an idea?</p> <p>I use the following versions:</p> <pre><code>terraform { required_providers { # https://registry.terraform.io/providers/hashicorp/aws/latest aws = { source = &quot;hashicorp/aws&quot; version = &quot;~&gt; 3.70&quot; } # https://registry.terraform.io/providers/hashicorp/kubernetes/latest kubernetes = { source = &quot;hashicorp/kubernetes&quot; version = &quot;~&gt; 2.7.1&quot; } required_version = &quot;&gt;= 1.1.2&quot; } ... module &quot;eks&quot; { source = &quot;terraform-aws-modules/eks/aws&quot; version = &quot;18.0.3&quot; ... </code></pre>
<p>I use 17.24.0 and have no idea what is new with 18.0.3.</p> <p>In my case, I follow this example: <a href="https://github.com/terraform-aws-modules/terraform-aws-eks/blob/v17.24.0/examples/complete/main.tf" rel="nofollow noreferrer">https://github.com/terraform-aws-modules/terraform-aws-eks/blob/v17.24.0/examples/complete/main.tf</a></p> <p>My main.tf</p> <pre><code>locals { eks_map_roles = [] eks_map_users = [] } data &quot;aws_eks_cluster&quot; &quot;cluster&quot; { name = module.eks.cluster_id } data &quot;aws_eks_cluster_auth&quot; &quot;cluster&quot; { name = module.eks.cluster_id } provider &quot;kubernetes&quot; { host = data.aws_eks_cluster.cluster.endpoint cluster_ca_certificate = base64decode(data.aws_eks_cluster.cluster.certificate_authority[0].data) token = data.aws_eks_cluster_auth.cluster.token } module &quot;eks&quot; { source = &quot;...&quot; ... eks_map_roles = local.eks_map_roles eks_map_users = local.eks_map_users ... } </code></pre> <p>To add another user, you can follow this docs: <a href="https://aws.amazon.com/premiumsupport/knowledge-center/eks-api-server-unauthorized-error/" rel="nofollow noreferrer">https://aws.amazon.com/premiumsupport/knowledge-center/eks-api-server-unauthorized-error/</a></p> <p>I think you should add the role (don't forget to remove the path).</p>
<p>Has anyone tried out nested kubernetes cluster inside kubernetes, I want to emulated sandboxed a small kubernetes cluster inside my running kubernetes cluster and not again use VM's again and again for new cluster. </p> <p>New clusters I want to used for testing and trail of various features of kubernetes, has anyone tried anything on it.</p> <p>I tried various solution like.</p> <ul> <li><a href="https://github.com/marun/nkube" rel="nofollow noreferrer">https://github.com/marun/nkube</a></li> <li><a href="https://kubernetes.io/blog/2017/01/how-we-run-kubernetes-in-kubernetes-kubeception/" rel="nofollow noreferrer">https://kubernetes.io/blog/2017/01/how-we-run-kubernetes-in-kubernetes-kubeception/</a></li> </ul> <p>I also tried <a href="https://github.com/kubernetes-sigs/kubeadm-dind-cluster" rel="nofollow noreferrer">https://github.com/kubernetes-sigs/kubeadm-dind-cluster</a> and this works for me, but it starts the k8s cluster using docker containers, but I wanted this sort of solution to work inside kubernetes, so that it can be scaled across nodes I have.</p> <p>If anyone has tried it or can point to solution people have tried, it can be of great help.</p> <p><strong>Edit 1:</strong></p> <p>I know k8s runs workloads as containers and this was part of my problem, "is it possible to run k8s using containers or pods or using any other k8s constructs".</p> <p>I know, we can create namespace and network policies around it, but that would regulate the system, I wanted people to play with master/api-servers freely, un-regulated like we do in minikube. Wanted to have freedom to screw up master/api-servers, and to clean mess probably just need something like <code>k8s delete cluster c1</code> or anything of that sort. </p> <p>And for creating those clusters in <em>sandbox cluster</em> was just a command operation. Just didn't wanted to spin vm's again and setup cluster, if someone wants to play with it,</p>
<p>I realize this question is way old and the landscape has changed dramatically, but just in case anyone else ends up here in 2022, make sure you look into Kubernetes-in-Docker (KinD) for this kind of situation: <a href="https://kind.sigs.k8s.io/" rel="nofollow noreferrer">https://kind.sigs.k8s.io/</a></p> <p>This allows you to create local K8s clusters which run as local docker containers (e.g. local CP is a container, workers are containers, etc) and is excellent for this kind of experimental development work.</p>
<p>I want to edit my <code>Nginx.conf</code> file present inside Nginx controller pod in AKS, but the edit command is not working using the exec command, is there any way else I could edit my <code>nginx.conf</code>.</p> <p>the command which I tried:</p> <pre><code>kubectl exec -it nginx-nginx-ingress-controller -n nginx -- cat /etc/nginx/nginx.conf </code></pre>
<p>yh, seems this is also working. tried an alternative way:</p> <p><code>Edit/add</code> the properties to change in <code>ingress.yaml</code> and redeploy it. the changes will then reflect in <code>nginx.conf</code></p>
<p>I have an Argo workflow with dynamic fan-out tasks that do some map operation (in a Map-Reduce meaning context). I want to create a reducer that aggregates their results. It's possible to do that when the outputs of each mapper are small and can be put as an output parameter. See <a href="https://stackoverflow.com/questions/60569353/dynamic-fan-in-in-argo-workflows">this SO question-answer</a> for the description of how to do it.</p> <p>But how to aggregate output <strong>artifacts</strong> with Argo without writing custom logic of writing them to some storage in each mapper and read from it in reducer?</p>
<p>Artifacts are more difficult to aggregate than parameters.</p> <p>Parameters are always text and are generally small. This makes it easy for Argo Workflows to aggregate them into a single JSON object which can then be consumed by a &quot;reduce&quot; step.</p> <p>Artifacts, on the other hand, may be any type or size. So Argo Workflows is limited in how much it can help with aggregation.</p> <p>The main relevant feature it provides is declarative repository write/read operations. You can specify, for example, an S3 prefix to write each parameter to. Then, in the reduce step, you can load everything from that prefix and perform your aggregation logic.</p> <p>Argo Workflows provides a <a href="https://github.com/argoproj/argo-workflows/blob/master/examples/map-reduce.yaml" rel="nofollow noreferrer">generic map/reduce example</a>. But besides artifact writing/reading, you pretty much have to do the aggregation logic yourself.</p>
<p>my problem is why ingress doesnt assigne an Address for the services?</p> <p>first of all i create 3 deployments:</p> <pre><code>kubectl create deployment cheddar --image=errm/cheese:cheddar kubectl create deployment stilton --image=errm/cheese:stilton kubectl create deployment wensleydale --image=errm/cheese:wensleydale </code></pre> <p>second of all i expose those 3 deployment:</p> <pre><code>kubectl expose deployment cheddar --port=80 kubectl expose deployment stilton --port=80 kubectl expose deployment wensleydale --port=80 </code></pre> <p>then i apply my ingress.yaml with <code>kubectl apply -f ingress.yaml</code>, the ingress.yaml content is:</p> <pre><code>apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: cheddar spec: ingressClassName: nginx rules: - host: cheddar.127.0.0.1.nip.io http: paths: - path: / pathType: Prefix backend: service: name: cheddar port: number: 80 --- apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: stilton spec: ingressClassName: nginx rules: - host: stilton.127.0.0.1.nip.io http: paths: - path: / pathType: Prefix backend: service: name: stilton port: number: 80 --- apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: wensleydale spec: ingressClassName: nginx rules: - host: wensleydale.127.0.0.1.nip.io http: paths: - path: / pathType: Prefix backend: service: name: wensleydale port: number: 80 --- </code></pre> <p>but when i route this paths, the result would still be <code>404-nginx</code></p> <p>the <code>kubectl get ingress</code> returns:</p> <pre><code>NAME CLASS HOSTS ADDRESS PORTS AGE cheddar nginx cheddar.127.0.0.1.nip.io 80 43s stilton nginx stilton.127.0.0.1.nip.io 80 43s wensleydale nginx wensleydale.127.0.0.1.nip.io 80 43s </code></pre> <p>NOTE1: im using microk8s on ubuntu, my clusterversion is: <code>v1.21.7-3+7700880a5c71e2</code></p> <pre><code>➜ ~ k get no NAME STATUS ROLES AGE VERSION ali Ready &lt;none&gt; 8d v1.21.7-3+7700880a5c71e2 ➜ ~ kubectl version Client Version: version.Info{Major:&quot;1&quot;, Minor:&quot;21+&quot;, GitVersion:&quot;v1.21.7-3+7700880a5c71e2&quot;, GitCommit:&quot;7700880a5c71e25c44491ef5c7d7fb30527d8337&quot;, GitTreeState:&quot;clean&quot;, BuildDate:&quot;2021-11-17T22:07:23Z&quot;, GoVersion:&quot;go1.16.10&quot;, Compiler:&quot;gc&quot;, Platform:&quot;linux/amd64&quot;} Server Version: version.Info{Major:&quot;1&quot;, Minor:&quot;21+&quot;, GitVersion:&quot;v1.21.7-3+7700880a5c71e2&quot;, GitCommit:&quot;7700880a5c71e25c44491ef5c7d7fb30527d8337&quot;, GitTreeState:&quot;clean&quot;, BuildDate:&quot;2021-11-17T22:02:47Z&quot;, GoVersion:&quot;go1.16.10&quot;, Compiler:&quot;gc&quot;, Platform:&quot;linux/amd64&quot;} </code></pre> <p>NOTE2: i've already enaled the ingress extention by this command: <code>microk8s enable ingress</code></p>
<p>If you're using this cluster bare-metal, you'll have to use something like metallb. Kubernetes does not implement network load balancers and therefore will not be able to assign an ip address to your ingress.</p> <p>Since you're using microk8s, you can use <code>microk8s enable metallb</code></p> <p>If you're using aws, gcp, aks, you'll find it in their documentation.</p> <p>For bare-metal see the following : <a href="https://metallb.org/" rel="nofollow noreferrer">https://metallb.org/</a></p>
<p>How do I have to specify the comments like <code>+kubebuilder:printcolumn</code> to add columns to the output of the command <code>kubectl get my-crd.my-group.my-domain.com</code>?</p> <p>I've a CRD (Custom Resource Definition) with the usual <code>struct</code>s for the specs and the status (similar to what's explained in the Kubebuilder tutorial here <a href="https://book.kubebuilder.io/cronjob-tutorial/new-api.html#adding-a-new-api" rel="nofollow noreferrer">https://book.kubebuilder.io/cronjob-tutorial/new-api.html#adding-a-new-api</a>).</p> <p>I've a <strong>Status</strong> <code>struct</code> like this:</p> <pre class="lang-golang prettyprint-override"><code>type ScheduleSetStatus struct { // When was the last time the Schedule Set // was successfully deployed. LastDeployTime string `json:&quot;lastDeployTime&quot;` // metav1.Time // The CronJobs that have been successfully deployed DeployedCronJobs []string `json:&quot;deployedCronJobs&quot;` // The CronJobs that had errors when the deployment // has been attempted. ErroredCronJobs map[string]string `json:&quot;erroredCronJobs&quot;` // TODO `error` JSON serialisable } </code></pre> <p>Which has a few problems:</p> <p><strong>The time field</strong></p> <ul> <li>I've tried that to be of type <code>metav1.Time</code> (handy formatting as they state at <a href="https://book.kubebuilder.io/cronjob-tutorial/api-design.html?highlight=metav1.Time#designing-an-api" rel="nofollow noreferrer">https://book.kubebuilder.io/cronjob-tutorial/api-design.html?highlight=metav1.Time#designing-an-api</a>), but then this comment <code>// +kubebuilder:printcolumn:name=&quot;Last Deploy&quot;,type=&quot;date&quot;,JSONPath=</code>.status.lastDeployTime`` shows as empty in the output of <code>kubectl</code>.</li> <li>So I changed the type to be <code>string</code> (then in the controller doing <code>oess.Status.LastDeployTime = fmt.Sprintf(&quot;%s&quot;, metav1.Time{Time: time.Now().UTC()})</code>), then adding the comment <code>+kubebuilder:printcolumn:name=&quot;Last Deploy&quot;,type=string,JSONPath=</code>.status.lastDeployTime`` but still the field is shown as empty in the output of <code>kubectl</code>.</li> </ul> <p><strong>The slice field <code>[]string</code> and the map field <code>map[string]string</code></strong></p> <ul> <li>How do I configure these? Here there's no mention (when clicking on &quot;Show Detailed Argument Help&quot;): <a href="https://book.kubebuilder.io/reference/markers/crd.html" rel="nofollow noreferrer">https://book.kubebuilder.io/reference/markers/crd.html</a></li> <li>In case these are not &quot;simple types&quot; with formatting issues when using <code>kubectl</code>, does that mean the only option I have is to make them <code>string</code> with some sort of <code>fmt.Sprintf(...)</code>?</li> <li>Any other option?</li> </ul>
<p>The solution was to add the code to update the resource status in the <strong>reconciler method</strong> of the controller - <code>Reconcile(ctx context.Context, req ctrl.Request)</code>, like this:</p> <pre class="lang-golang prettyprint-override"><code> // Update the status for &quot;last deploy time&quot; of a ScheduleSet myStruct.Status.LastDeployTime = metav1.Time{Time: time.Now().UTC()} // https://book.kubebuilder.io/cronjob-tutorial/api-design.html?highlight=metav1.Time#designing-an-api if err := r.Status().Update(ctx, &amp;myStruct); err != nil { log.Error(err, &quot;unable to update status xyz&quot;) return ctrl.Result{}, err } </code></pre> <p>The special Kubebuilder annotation was all right:</p> <pre class="lang-golang prettyprint-override"><code>//+kubebuilder:printcolumn:name=&quot;Last Deploy&quot;,type=&quot;date&quot;,JSONPath=`.status.lastDeployTime` </code></pre> <p>Also, Go slices and Go maps work out of the box with comments like:</p> <pre class="lang-golang prettyprint-override"><code>... DeployedCronJobs []string `json:&quot;deployedCronJobs&quot;` ... ErroredCronJobs map[string]string `json:&quot;erroredCronJobs&quot;` ... //+kubebuilder:printcolumn:name=&quot;Deployed CJs&quot;,type=string,JSONPath=`.status.deployedCronJobs` //+kubebuilder:printcolumn:name=&quot;Errored CJs&quot;,type=string,JSONPath=`.status.erroredCronJobs` </code></pre>
<p>I was wondering if is possible to get resources from <a href="https://kustomize.io/" rel="noreferrer">kustomize</a> in a private GitHub repository, I already tried something like this without success</p> <pre><code>apiVersion: kustomize.config.k8s.io/v1beta1 kind: Kustomization resources: - git@github.com:gituser/kustomize.git/kustomize/main/nginx.yaml - ssh://github.com/gituser/kustomize.git/kustomize/main/nginx.yaml </code></pre> <p>error</p> <pre><code>Error: accumulating resources: accumulation err='accumulating resources from 'ssh://github.com/diego1277/kustomize.git//kustomize/main/nginx.yaml': evalsymlink failure on '/Users/diego/Desktop/estudo/kustomize/see/base/ssh:/github.com/diego1277/kustomize.git/kustomize/main/nginx.yaml' : lstat /Users/diego/Desktop/estudo/kustomize/see/base/ssh:: no such file or directory': evalsymlink failure on '/private/var/folders/qq/mk6t7dpd5435qm78_zsfdjvm0000gp/T/kustomize-056937086/kustomize/main/nginx.yaml' : lstat /private/var/folders/qq/mk6t7dpd5435qm78_zsfdjvm0000gp/T/kustomize-056937086/kustomize: no such file or directory </code></pre>
<p>Your remote resource needs to resolve to a <em>directory</em> that contains a <code>kustomization.yaml</code> file. That is, instead of:</p> <pre><code>apiVersion: kustomize.config.k8s.io/v1beta1 kind: Kustomization resources: - git@github.com:gituser/kustomize.git/kustomize/main/nginx.yaml </code></pre> <p>You need:</p> <pre><code>apiVersion: kustomize.config.k8s.io/v1beta1 kind: Kustomization resources: - git@github.com:gituser/kustomize.git/kustomize/main/ </code></pre> <p>And your <code>kustomize/main</code> directory should contain <code>kustomization.yaml</code>. You can try this out using a public repository, for example:</p> <pre><code>apiVersion: kustomize.config.k8s.io/v1beta1 kind: Kustomization resources: - &quot;git@github.com:kubernetes-sigs/kustomize/examples/helloWorld&quot; </code></pre>
<p>I have created a k8s cluster with kops (1.21.4) on AWS and as per the <a href="https://kops.sigs.k8s.io/addons/#cluster-autoscaler" rel="nofollow noreferrer">docs on autoscaler</a>. I have done the required changes to my cluster but when the cluster starts, the cluster-autoscaler pod is unable to schedule on any node. When I describe the pod, I see the following:</p> <pre><code>Events: Type Reason Age From Message ---- ------ ---- ---- ------- Warning FailedScheduling 4m31s (x92 over 98m) default-scheduler 0/4 nodes are available: 1 Too many pods, 3 node(s) didn't match Pod's node affinity/selector. </code></pre> <p>Looking at the deployment for cluster I see the following <code>podAntiAffinity</code>:</p> <pre><code> affinity: podAntiAffinity: preferredDuringSchedulingIgnoredDuringExecution: - podAffinityTerm: labelSelector: matchExpressions: - key: app operator: In values: - cluster-autoscaler topologyKey: topology.kubernetes.io/zone weight: 100 requiredDuringSchedulingIgnoredDuringExecution: - labelSelector: matchExpressions: - key: app operator: In values: - cluster-autoscaler topologyKey: kubernetes.com/hostname </code></pre> <p>From this I understand that it want to prevent running pod on same node which already has cluster-autoscaler running. But that doesn't seem to justify the error seen in the pod status.</p> <p>Edit: The pod for autoscaler has the following <code>nodeSelectors</code> and <code>tolerations</code>:</p> <pre><code>Node-Selectors: node-role.kubernetes.io/master= Tolerations: node-role.kubernetes.io/master op=Exists node.kubernetes.io/not-ready:NoExecute op=Exists for 300s node.kubernetes.io/unreachable:NoExecute op=Exists for 300s </code></pre> <p>So clearly, it should be able to schedule on master node too.</p> <p>I am not sure what else do I need to do to make the pod up and running.</p>
<p>Posting the answer out of comments.</p> <hr /> <p>There are <code>podAffinity</code> rules in place so first thing to check is if any errors in scheduling are presented. Which is the case:</p> <pre><code>0/4 nodes are available: 1 Too many pods, 3 node(s) didn't match Pod's node affinity/selector. </code></pre> <p>Since there are 1 control plane (on which pod is supposed to be scheduled) and 3 worked nodes, that leads to the error <code>1 Too many pods</code> related to the control plane.</p> <hr /> <p>Since cluster is running in AWS, there's a known limitation about amount of <code>network interfaces</code> and <code>private IP addresses</code> per machine type - <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-eni.html#AvailableIpPerENI" rel="nofollow noreferrer">IP addresses per network interface per instance type</a>.</p> <p><code>t3.small</code> was used which has 3 interfaces and 4 IPs per interface = 12 in total which was not enough.</p> <p>Scaling up to <code>t3.medium</code> resolved the issue.</p> <hr /> <p>Credits to <a href="https://stackoverflow.com/a/64972286/15537201">Jonas's answer</a> about the root cause.</p>
<p>AWS supports <a href="https://docs.aws.amazon.com/eks/latest/userguide/iam-roles-for-service-accounts.html" rel="noreferrer">IAM Roles for Service Accounts (IRSA)</a> that allows cluster operators to map AWS IAM Roles to Kubernetes Service Accounts.</p> <p>To do so, one has to create an <a href="https://eksctl.io/usage/iamserviceaccounts/" rel="noreferrer">iamserviceaccount</a> in an EKS cluster:</p> <pre><code>eksctl create iamserviceaccount \ --name &lt;AUTOSCALER_NAME&gt; \ --namespace kube-system \ --cluster &lt;CLUSTER_NAME&gt; \ --attach-policy-arn &lt;POLICY_ARN&gt; \ --approve \ --override-existing-serviceaccounts </code></pre> <p>The problem is that I don't want to use the above <code>eksctl</code> command because I want to declare my infrastructure using <code>terraform</code>.</p> <p>Does eksctl command do anything other than creating a service account? If it only creates a service account, what is the <code>YAML</code> representation of it?</p>
<p>I am adding my answer here because I stumble upon the same issue, and accepted answer (and other answers above), do not provide full resolution to the issue - no code examples. They are just guidelines which I had to use to research much deeper. There are some issues which is really easy to miss - and without code examples its quite hard to conclude what is happening (especially part related with Conditions/StringEquals while creating IAM role)</p> <p>The whole purpose of creating a service account which is going to be tied with the role - is possibility of creating aws resources from within cluster (most common case is load balancer, or roles for pushing logs to the cloudwatch).</p> <p>So, question is how we can do this, using terraform, instead of using eks commands.</p> <p>What we need to do, is:</p> <ol> <li>create eks oidc (which can be done with terraform)</li> <li>create AWS IAM role (which can be done with terraform), create and use proper policies</li> <li>Create k8s service account (needs to be done with kubectl commands - or with terraform using kubernetes resources</li> <li>Annotate k8s service account with IAM role we created (meaning that we are linking k8s service account with IAM role)</li> </ol> <p>After this setup, our k8s service account will have k8s cluster role and k8s cluster role binding (which will allow that service account to perform actions within the k8s) and, our k8s service account will have IAM role attached to it, which will allow to perform actions outside of the cluster (like creating aws resources)</p> <p>So lets start with it. Assumption bellow is that your eks cluster is already created with terraform, and we are focusing on creating resources areound that eks cluster necessary for working service account.</p> <p><strong>Create eks_oidc</strong></p> <pre><code>### First we need to create tls certificate data &quot;tls_certificate&quot; &quot;eks-cluster-tls-certificate&quot; { url = aws_eks_cluster.eks-cluster.identity[0].oidc[0].issuer } # After that create oidc resource &quot;aws_iam_openid_connect_provider&quot; &quot;eks-cluster-oidc&quot; { client_id_list = [&quot;sts.amazonaws.com&quot;] thumbprint_list = [data.tls_certificate.eks-cluster-tls-certificate.certificates[0].sha1_fingerprint] url = aws_eks_cluster.eks-cluster.identity[0].oidc[0].issuer } </code></pre> <p><strong>Now, lets create AWS IAM role with all necessary policies.</strong></p> <p>Terraform declarative code bellow will:</p> <ul> <li>create ALBIngressControllerIAMPolicy policy</li> <li>create alb-ingress-controller-role role</li> <li>attach ALBIngressControllerIAMPolicyr policy to alb-ingress-controller-role role</li> <li>attach already existing AmazonEKS_CNI_Policy policy to the role</li> </ul> <p>Make a note that i used suffixes as alb ingress controller here, because that is primary use of my role from within the cluster. You can change the name of policy of the role or you can change permission access for the policy as well in dependency of what you are planing to do with it.</p> <pre><code>data &quot;aws_caller_identity&quot; &quot;current&quot; {} locals { account_id = data.aws_caller_identity.current.account_id eks_oidc = replace(replace(aws_eks_cluster.eks-cluster.endpoint, &quot;https://&quot;, &quot;&quot;), &quot;/\\..*$/&quot;, &quot;&quot;) } # Policy which will allow us to create application load balancer from inside of cluster resource &quot;aws_iam_policy&quot; &quot;ALBIngressControllerIAMPolicy&quot; { name = &quot;ALBIngressControllerIAMPolicy&quot; description = &quot;Policy which will be used by role for service - for creating alb from within cluster by issuing declarative kube commands&quot; policy = jsonencode({ Version = &quot;2012-10-17&quot;, Statement = [ { Effect = &quot;Allow&quot;, Action = [ &quot;elasticloadbalancing:ModifyListener&quot;, &quot;wafv2:AssociateWebACL&quot;, &quot;ec2:AuthorizeSecurityGroupIngress&quot;, &quot;ec2:DescribeInstances&quot;, &quot;wafv2:GetWebACLForResource&quot;, &quot;elasticloadbalancing:RegisterTargets&quot;, &quot;iam:ListServerCertificates&quot;, &quot;wafv2:GetWebACL&quot;, &quot;elasticloadbalancing:SetIpAddressType&quot;, &quot;elasticloadbalancing:DeleteLoadBalancer&quot;, &quot;elasticloadbalancing:SetWebAcl&quot;, &quot;ec2:DescribeInternetGateways&quot;, &quot;elasticloadbalancing:DescribeLoadBalancers&quot;, &quot;waf-regional:GetWebACLForResource&quot;, &quot;acm:GetCertificate&quot;, &quot;shield:DescribeSubscription&quot;, &quot;waf-regional:GetWebACL&quot;, &quot;elasticloadbalancing:CreateRule&quot;, &quot;ec2:DescribeAccountAttributes&quot;, &quot;elasticloadbalancing:AddListenerCertificates&quot;, &quot;elasticloadbalancing:ModifyTargetGroupAttributes&quot;, &quot;waf:GetWebACL&quot;, &quot;iam:GetServerCertificate&quot;, &quot;wafv2:DisassociateWebACL&quot;, &quot;shield:GetSubscriptionState&quot;, &quot;ec2:CreateTags&quot;, &quot;elasticloadbalancing:CreateTargetGroup&quot;, &quot;ec2:ModifyNetworkInterfaceAttribute&quot;, &quot;elasticloadbalancing:DeregisterTargets&quot;, &quot;elasticloadbalancing:DescribeLoadBalancerAttributes&quot;, &quot;ec2:RevokeSecurityGroupIngress&quot;, &quot;elasticloadbalancing:DescribeTargetGroupAttributes&quot;, &quot;shield:CreateProtection&quot;, &quot;acm:DescribeCertificate&quot;, &quot;elasticloadbalancing:ModifyRule&quot;, &quot;elasticloadbalancing:AddTags&quot;, &quot;elasticloadbalancing:DescribeRules&quot;, &quot;ec2:DescribeSubnets&quot;, &quot;elasticloadbalancing:ModifyLoadBalancerAttributes&quot;, &quot;waf-regional:AssociateWebACL&quot;, &quot;tag:GetResources&quot;, &quot;ec2:DescribeAddresses&quot;, &quot;ec2:DeleteTags&quot;, &quot;shield:DescribeProtection&quot;, &quot;shield:DeleteProtection&quot;, &quot;elasticloadbalancing:RemoveListenerCertificates&quot;, &quot;tag:TagResources&quot;, &quot;elasticloadbalancing:RemoveTags&quot;, &quot;elasticloadbalancing:CreateListener&quot;, &quot;elasticloadbalancing:DescribeListeners&quot;, &quot;ec2:DescribeNetworkInterfaces&quot;, &quot;ec2:CreateSecurityGroup&quot;, &quot;acm:ListCertificates&quot;, &quot;elasticloadbalancing:DescribeListenerCertificates&quot;, &quot;ec2:ModifyInstanceAttribute&quot;, &quot;elasticloadbalancing:DeleteRule&quot;, &quot;cognito-idp:DescribeUserPoolClient&quot;, &quot;ec2:DescribeInstanceStatus&quot;, &quot;elasticloadbalancing:DescribeSSLPolicies&quot;, &quot;elasticloadbalancing:CreateLoadBalancer&quot;, &quot;waf-regional:DisassociateWebACL&quot;, &quot;elasticloadbalancing:DescribeTags&quot;, &quot;ec2:DescribeTags&quot;, &quot;elasticloadbalancing:*&quot;, &quot;elasticloadbalancing:SetSubnets&quot;, &quot;elasticloadbalancing:DeleteTargetGroup&quot;, &quot;ec2:DescribeSecurityGroups&quot;, &quot;iam:CreateServiceLinkedRole&quot;, &quot;ec2:DescribeVpcs&quot;, &quot;ec2:DeleteSecurityGroup&quot;, &quot;elasticloadbalancing:DescribeTargetHealth&quot;, &quot;elasticloadbalancing:SetSecurityGroups&quot;, &quot;elasticloadbalancing:DescribeTargetGroups&quot;, &quot;shield:ListProtections&quot;, &quot;elasticloadbalancing:ModifyTargetGroup&quot;, &quot;elasticloadbalancing:DeleteListener&quot; ], Resource = &quot;*&quot; } ] }) } # Create IAM role resource &quot;aws_iam_role&quot; &quot;alb-ingress-controller-role&quot; { name = &quot;alb-ingress-controller&quot; assume_role_policy = &lt;&lt;POLICY { &quot;Version&quot;: &quot;2012-10-17&quot;, &quot;Statement&quot;: [ { &quot;Sid&quot;: &quot;&quot;, &quot;Effect&quot;: &quot;Allow&quot;, &quot;Principal&quot;: { &quot;Federated&quot;: &quot;${aws_iam_openid_connect_provider.eks-cluster-oidc.arn}&quot; }, &quot;Action&quot;: &quot;sts:AssumeRoleWithWebIdentity&quot;, &quot;Condition&quot;: { &quot;StringEquals&quot;: { &quot;${replace(aws_iam_openid_connect_provider.eks-cluster-oidc.url, &quot;https://&quot;, &quot;&quot;)}:sub&quot;: &quot;system:serviceaccount:kube-system:alb-ingress-controller&quot;, &quot;${replace(aws_iam_openid_connect_provider.eks-cluster-oidc.url, &quot;https://&quot;, &quot;&quot;)}:aud&quot;: &quot;sts.amazonaws.com&quot; } } } ] } POLICY depends_on = [aws_iam_openid_connect_provider.eks-cluster-oidc] tags = { &quot;ServiceAccountName&quot; = &quot;alb-ingress-controller&quot; &quot;ServiceAccountNameSpace&quot; = &quot;kube-system&quot; } } # Attach policies to IAM role resource &quot;aws_iam_role_policy_attachment&quot; &quot;alb-ingress-controller-role-ALBIngressControllerIAMPolicy&quot; { policy_arn = aws_iam_policy.ALBIngressControllerIAMPolicy.arn role = aws_iam_role.alb-ingress-controller-role.name depends_on = [aws_iam_role.alb-ingress-controller-role] } resource &quot;aws_iam_role_policy_attachment&quot; &quot;alb-ingress-controller-role-AmazonEKS_CNI_Policy&quot; { role = aws_iam_role.alb-ingress-controller-role.name policy_arn = &quot;arn:aws:iam::aws:policy/AmazonEKS_CNI_Policy&quot; depends_on = [aws_iam_role.alb-ingress-controller-role] } </code></pre> <p>After executing terraform above, you have successfully created terraform part of the resources. Now we need to create a k8s service account and bind IAM role with that service account.</p> <p><strong>Creating cluster role, cluster role binding and service account</strong></p> <p>You can use</p> <p><a href="https://raw.githubusercontent.com/kubernetes-sigs/aws-alb-ingress-controller/master/docs/examples/rbac-role.yaml" rel="noreferrer">https://raw.githubusercontent.com/kubernetes-sigs/aws-alb-ingress-controller/master/docs/examples/rbac-role.yaml</a></p> <p>directly (from the master branch), but having in mind that we need to annotate the iam arn, i have tendency to download this file, update it and store it as updated within my kubectl config files.</p> <pre><code>apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: labels: app.kubernetes.io/name: alb-ingress-controller name: alb-ingress-controller rules: - apiGroups: - &quot;&quot; - extensions resources: - configmaps - endpoints - events - ingresses - ingresses/status - services - pods/status verbs: - create - get - list - update - watch - patch - apiGroups: - &quot;&quot; - extensions resources: - nodes - pods - secrets - services - namespaces verbs: - get - list - watch --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: labels: app.kubernetes.io/name: alb-ingress-controller name: alb-ingress-controller roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: alb-ingress-controller subjects: - kind: ServiceAccount name: alb-ingress-controller namespace: kube-system --- apiVersion: v1 kind: ServiceAccount metadata: labels: app.kubernetes.io/name: alb-ingress-controller name: alb-ingress-controller namespace: kube-system annotations: eks.amazonaws.com/role-arn: &lt;ARN OF YOUR ROLE HERE&gt; ... </code></pre> <p>At the bottom of this file, you will notice annotation where you will need to place your ANR role.</p> <p><strong>Double check</strong></p> <p>And that would be it. After that you have a k8s service account which is connected with iam role.</p> <p>Check with:</p> <pre><code>kubectl get sa -n kube-system kubectl describe sa alb-ingress-controller -n kube-system </code></pre> <p>And you should get output similar to this (annotations is the most important part, because it confirms the attachment of iam role):</p> <pre><code>Name: alb-ingress-controller Namespace: kube-system Labels: app.kubernetes.io/managed-by=Helm app.kubernetes.io/name=alb-ingress-controller Annotations: eks.amazonaws.com/role-arn: &lt;YOUR ANR WILL BE HERE&gt; meta.helm.sh/release-name: testrelease meta.helm.sh/release-namespace: default Image pull secrets: &lt;none&gt; Mountable secrets: alb-ingress-controller-token-l4pd8 Tokens: alb-ingress-controller-token-l4pd8 Events: &lt;none&gt; </code></pre> <p>From now on, you can use this service to manage internal k8s resources and external which are allowed by the policies you attached.</p> <p>In my case, as mentioned before, I used it (beside other things) for creation of alb ingress controller and load balancer, hence all of the prefixes with &quot;alb-ingress&quot;</p>
<p>I'm trying to add a Container Insight to my EKS cluster but running into a bit of an issue when deploying. According to my logs, I'm getting the following:</p> <pre><code>[error] [output:cloudwatch_logs:cloudwatch_logs.2] CreateLogGroup API responded with error='AccessDeniedException' [error] [output:cloudwatch_logs:cloudwatch_logs.2] Failed to create log group </code></pre> <p>The strange part about this is the role it seems to be assuming is the same role found within my EC2 worker nodes rather than the role for the service account I have created. I'm creating the service account and can see it within AWS successfully using the following command:</p> <pre><code>eksctl create iamserviceaccount --region ${env:AWS_DEFAULT_REGION} --name cloudwatch-agent --namespace amazon-cloudwatch --cluster ${env:CLUSTER_NAME} --attach-policy-arn arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy --override-existing-serviceaccounts --approve </code></pre> <p>Despite the serviceaccount being created successfully, I continue to get my AccessDeniedException.</p> <p>One thing I found was the logs work fine when I manually add the CloudWatchAgentServerPolicy to my worker nodes, however this is not the implementation I would like and instead would rather have an automative way of adding the service account and not touching the worker nodes directly if possible. The steps I followed can be found at the bottom of <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Container-Insights-prerequisites.html" rel="nofollow noreferrer">this documentation.</a></p> <p>Thanks so much!</p>
<p>For anyone running into this issue: within the quickstart yaml, there is a fluent-bit service account that must be removed from that file and created manually. For me I created it using the following command:</p> <pre><code>eksctl create iamserviceaccount --region ${env:AWS_DEFAULT_REGION} --name fluent-bit --namespace amazon-cloudwatch --cluster ${env:CLUSTER_NAME} --attach-policy-arn arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy --override-existing-serviceaccounts --approve </code></pre> <p>Upon running this command and removing the fluent-bit service account from the yaml, delete and reapply al your amazon-cloudwatch namespace items and it should be working.</p>
<p>My kubernetes application is made of several flavors of nodes, a couple of “schedulers” which send tasks to quite a few more “worker” nodes. In order for this app to work correctly all the nodes must be of exactly the same code version.</p> <p>The deployment is performed using a standard ReplicaSet and when my CICD kicks in it just does a simple rolling update. This causes a problem though since during the rolling update, nodes of different code versions co-exist for a few seconds, so a few tasks during this time get wrong results.</p> <p>Ideally what I would want is that deploying a new version would create a completely new application that only communicates with itself and has time to warm its cache, then on a flick of a switch this new app would become active and start to get new client requests. The old app would remain active for a few more seconds and then shut down.</p> <p>I’m using Istio sidecar for mesh communication.</p> <p>Is there a standard way to do this? How is such a requirement usually handled?</p>
<p>I also had such a situation. Kubernetes alone cannot satisfy your requirement, I was also not able to find any tool that allows to coordinate multiple deployments together (although <a href="https://flagger.app/" rel="nofollow noreferrer">Flagger</a> looks promising).</p> <p>So the only way I found was by using CI/CD: Jenkins in my case. I don't have the code, but the idea is the following:</p> <ol> <li><p>Deploy all application deployments using single Helm chart. Every Helm release name and corresponding Kubernetes labels must be based off of some sequential number, e.g. Jenkins <code>$BUILD_NUMBER</code>. Helm release can be named like <code>example-app-${BUILD_NUMBER}</code> and all deployments must have label <code>version: $BUILD_NUMBER</code> . Important part here is that your <code>Services</code> should not be a part of your Helm chart because they will be handled by Jenkins.</p> </li> <li><p>Start your build with detecting the current version of the app (using bash script or you can store it in <code>ConfigMap</code>).</p> </li> <li><p>Start <code>helm install example-app-{$BUILD_NUMBER}</code> with <code>--atomic</code> flag set. Atomic flag will make sure that the release is properly removed on failure. And don't delete previous version of the app yet.</p> </li> <li><p>Wait for Helm to complete and in case of success run <code>kubectl set selector service/example-app version=$BUILD_NUMBER</code>. That will instantly switch Kubernetes <code>Service</code> from one version to another. If you have multiple services you can issue multiple <code>set selector</code> commands (each command executes immediately).</p> </li> <li><p>Delete previous Helm release and optionally update <code>ConfigMap</code> with new app version.</p> </li> </ol> <p>Depending on your app you may want to run tests on non user facing <code>Services</code> as a part of step 4 (after Helm release succeeds).</p> <p>Another good idea is to have <a href="https://kubernetes.io/docs/concepts/containers/container-lifecycle-hooks/" rel="nofollow noreferrer"><code>preStop</code></a> hooks on your worker pods so that they can finish their jobs before being deleted.</p>
<p>I have just set up a kubernetes cluster on bare metal using kubeadm, Flannel and MetalLB. Next step for me is to install ArgoCD.</p> <p>I installed the ArgoCD yaml from the &quot;Getting Started&quot; page and logged in.</p> <p>When adding my Git repositories ArgoCD gives me very weird error messages: <a href="https://i.stack.imgur.com/xhlUm.png" rel="noreferrer"><img src="https://i.stack.imgur.com/xhlUm.png" alt="enter image description here" /></a> The error message seems to suggest that ArgoCD for some reason is resolving github.com to my public IP address (I am not exposing SSH, therefore connection refused).</p> <p>I can not find any reason why it would do this. When using https:// instead of SSH I get the same result, but on port 443.</p> <p>I have put a dummy pod in the same namespace as ArgoCD and made some DNS queries. These queries resolved correctly.</p> <p>What makes ArgoCD think that github.com resolves to my public IP address?</p> <p>EDIT:</p> <p>I have also checked for network policies in the argocd namespace and found no policy that was restricting egress.</p> <p>I have had this working on clusters in the same network previously and have not changed my router firewall since then.</p>
<p>I solved my problem!</p> <p>My /etc/resolv.conf had two lines that caused trouble:</p> <pre><code>domain &lt;my domain&gt; search &lt;my domain&gt; </code></pre> <p>These lines were put there as a step in the installation of my host machine's OS that I did not realize would affect me in this way. After removing these lines, everything is now working perfectly.</p> <p>Multiple people told me to check resolv.conf, but I didn't realize what these two lines did until now.</p>
<p>It looks like Docker Desktop for Mac is using a 1.22+ version of Kubernetes which introduces a number of breaking changes specifically to the <code>ingress-nginx</code> controller <code>apiVersion</code>. This is causing issues with our local development cluster.</p> <p>There are couple options:</p> <ol> <li>Rolling back the Kubernetes version to something <code>&lt;1.22</code> in the development cluster.</li> <li>Updating <code>ingress-nginx</code> and the development configuration to use <code>&gt;=1.22</code>.</li> </ol> <p>I'm trying to go with route <code>1.</code> and downgrade the version to match our production cluster: <code>v1.20.7</code> primarily because 1.22+ isn't available in Azure yet it looks like. It makes sense to me to have the development and production versions match.</p> <p>That is my question: <strong>How do you change the version of Kuberentes that `docker-desktop uses?</strong></p> <p>If that can't be done, then I guess I'll just have to go with <code>2.</code></p> <hr /> <p>What've tried so far is simply following the <code>kubectl</code> <a href="https://kubernetes.io/docs/tasks/tools/install-kubectl-macos/" rel="nofollow noreferrer">documentation</a>:</p> <pre><code>curl -LO &quot;https://dl.k8s.io/release/v1.20.7/bin/darwin/arm64/kubectl&quot; chmod +x ./kubectl sudo mv ./kubectl /usr/local/bin/kubectl kubectl version --client Client Version: version.Info{Major:&quot;1&quot;, Minor:&quot;23&quot;, GitVersion:&quot;v1.23.0&quot;, GitCommit:&quot;ab69524f795c42094a6630298ff53f3c3ebab7f4&quot;, GitTreeState:&quot;clean&quot;, BuildDate:&quot;2021-12-07T18:08:39Z&quot;, GoVersion:&quot;go1.17.3&quot;, Compiler:&quot;gc&quot;, Platform:&quot;darwin/arm64&quot;} </code></pre> <p>Skeptical it was going to work and sure enough it doesn't.</p> <hr /> <p>Edit:</p> <p>Option <strong>3.</strong>: use something like <code>minikube</code>, <code>mikrok8s</code>, <code>k3d</code>, etc.</p> <p>It is looking like the only way to downgrade change the <code>kubectl</code> version is to downgrade Docker Desktop for Mac.</p>
<p>As best as I could determine, there is not a way to do this. (Please correct me if I'm wrong).</p> <p>The options appear to just be:</p> <ol> <li>Downgrade Docker Desktop for Mac to a version that has the version of Kubernetes that you want. Can find previous versions here: <a href="https://docs.docker.com/desktop/mac/release-notes/" rel="noreferrer">https://docs.docker.com/desktop/mac/release-notes/</a></li> <li>Use something like <code>minikube</code>, <code>mikrok8s</code>, <code>k3d</code>, etc. that gives you better control over the Kubernetes version being used.</li> </ol> <p>I ended up just dong <code>1.</code> as opposed to adding another tool to our development environment, but <code>2.</code> feels like a much better option.</p>
<p>I'd like to edit my secrets. The only way I'm aware of is <code>kubectl edit secret mysecret</code> which gets me yaml blob to edit. However, all secrets are base64 encoded which isn't an easy way to edit them.</p> <p>Can I mount secrets to local volume somehow? Can I extract secrets to my localhost and edit them there? And lastly, can I edit some way to get plaintext keys/values (or just one key) instead of base64 encoded values.</p> <p>P.S. Can I see secret keys easily with kubectl? With <code>edit</code> I see them, but when I'm only interested in keys, not the values.</p>
<p><strong>I would highly recommend on using</strong> <a href="https://github.com/derailed/k9s" rel="nofollow noreferrer">k9s</a> (not only for this purpose, but also as a lightweight k8s CLI management tool).</p> <p>As you can see below (ignore all white placeholders), when your cluster's context is set on terminal you just type <code>k9s</code> and you will hit a nice terminal where you can inspect all cluster resources.</p> <p>Just type <code>&quot;:&quot;</code> and enter the resource name (<em>secrets</em> in this case) which will appear in the middle of screen.</p> <p>Then you can choose a secret with the up and down arrows and type <code>e</code> to edit it (green arrow):</p> <p><a href="https://i.stack.imgur.com/lF4Ci.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lF4Ci.png" alt="enter image description here" /></a></p>
<p>I am trying to migrate a socket io service from GCP (App Engine) to a kubernetes cluster. Everything works fine on the GCP side (we have one instance of the server without replicas). The migration to k8s is going very well, except that when connecting the client socket to the server, it does not receive some information:</p> <ul> <li><p>In transport 'polling': Of course, as there are two pods, this doesn't work properly anymore and the client socket keeps deconnecting / reconnecting in loop.</p> </li> <li><p>In 'websocket' transport: The connection is correctly established, the client can receive data from the server in 'broadcast to all client' mode =&gt; <code>socket.emit('getDeviceList', os.hostname())</code> but, as soon as the server tries to send data only to the concerned client <code>io.of(namespace).to(socket.id).emit('getDeviceList', JSON.stringify(obj))</code>, this one doesn't receive anything...</p> </li> <li><p>Moreover, I modified my service to have only one pod for a test, the polling mode works correctly, but, I find myself in the same case as the websocket mode =&gt; I can't send an information to a precise client...</p> </li> </ul> <p>Of course, the same code on the App Engine side works correctly and the client receives everything correctly.</p> <p>I'm working with:</p> <pre><code>&quot;socket.io&quot;: &quot;^3.1.0&quot;, &quot;socket.io-redis&quot;: &quot;^5.2.0&quot;, &quot;vue&quot;: &quot;^2.5.18&quot;, &quot;vue-socket.io&quot;: &quot;3.0.7&quot;, </code></pre> <p>My server side configuration:</p> <pre><code>var io = require('socket.io')(server, { pingTimeout: 5000, pingInterval : 2000, cors: { origin: true, methods: [&quot;GET&quot;, &quot;POST&quot;], transports: ['websocket', 'polling'], credentials: true }, allowEIO3: true }); io.adapter(redis({ host: redis_host, port: redis_port })) </code></pre> <p>My front side configuration:</p> <pre><code>Vue.use(new VueSocketIO({ debug: true, connection: 'path_to_the_socket_io/namespace, options: { query: `id=..._timestamp`, transports: ['polling'] } })); </code></pre> <p>My ingress side annotation:</p> <pre><code>kubernetes.io/ingress.class: nginx kubernetes.io/ingress.global-static-ip-name: ip-loadbalancer meta.helm.sh/release-name: xxx meta.helm.sh/release-namespace: xxx -release nginx.ingress.kubernetes.io/affinity: cookie nginx.ingress.kubernetes.io/affinity-mode: persistent nginx.ingress.kubernetes.io/force-ssl-redirect: true nginx.ingress.kubernetes.io/proxy-connect-timeout: 10800 nginx.ingress.kubernetes.io/proxy-read-timeout: 10800 nginx.ingress.kubernetes.io/proxy-send-timeout: 10800 nginx.org/websocket-services: app-sockets-cluster-ip-service </code></pre> <p>My question is : why i can get broadcast to all user message and not specific message to my socket ?</p> <p>Can someone try to help me ? :)</p> <p>Thanks a lot !</p>
<p>I found the solution in the day.and share it.</p> <p>In fact, the problem is not due to the kubernetes Cluster but due to the socket io and socket io redis adapter version.</p> <p>I was using <code>socket.io: 3.x.x</code> and using <code>socket.io-redis: 5.x.x</code> In fact, i need to use the <code>socket.io-redis: 6.x.x</code> with this version of socket io :)</p> <p>You can find the compatible version of socket io and redis adapter here: <a href="https://github.com/socketio/socket.io-redis-adapter#compatibility-table" rel="nofollow noreferrer">https://github.com/socketio/socket.io-redis-adapter#compatibility-table</a></p> <p>Thanks a lot.</p>
<p>I am new to the world of Spark and Kubernetes. I built a Spark docker image using the official Spark 3.0.1 bundled with Hadoop 3.2 using the docker-image-tool.sh utility.</p> <p>I have also created another docker image for Jupyter notebook and am trying to run spark on Kubernetes in client mode. I first run my Jupyter notebook as a pod, do a port forward using kubectl and access the notebook UI from my system at localhost:8888 . All seems to be working fine. I am able to run commands successfully from the notebook.</p> <p>Now I am trying to access Azure Data Lake Gen2 from my notebook using <a href="https://hadoop.apache.org/docs/current/hadoop-azure/abfs.html#Default:_Shared_Key" rel="noreferrer">Hadoop ABFS connector</a>. I am setting the Spark context as below.</p> <pre><code>from pyspark import SparkContext, SparkConf from pyspark.sql import SparkSession # Create Spark config for our Kubernetes based cluster manager sparkConf = SparkConf() sparkConf.setMaster(&quot;k8s://https://kubernetes.default.svc.cluster.local:443&quot;) sparkConf.setAppName(&quot;spark&quot;) sparkConf.set(&quot;spark.kubernetes.container.image&quot;, &quot;&lt;&lt;my_repo&gt;&gt;/spark-py:latest&quot;) sparkConf.set(&quot;spark.kubernetes.namespace&quot;, &quot;spark&quot;) sparkConf.set(&quot;spark.executor.instances&quot;, &quot;3&quot;) sparkConf.set(&quot;spark.executor.cores&quot;, &quot;2&quot;) sparkConf.set(&quot;spark.driver.memory&quot;, &quot;512m&quot;) sparkConf.set(&quot;spark.executor.memory&quot;, &quot;512m&quot;) sparkConf.set(&quot;spark.kubernetes.pyspark.pythonVersion&quot;, &quot;3&quot;) sparkConf.set(&quot;spark.kubernetes.authenticate.driver.serviceAccountName&quot;, &quot;spark&quot;) sparkConf.set(&quot;spark.kubernetes.authenticate.serviceAccountName&quot;, &quot;spark&quot;) sparkConf.set(&quot;spark.driver.port&quot;, &quot;29413&quot;) sparkConf.set(&quot;spark.driver.host&quot;, &quot;my-notebook-deployment.spark.svc.cluster.local&quot;) sparkConf.set(&quot;fs.azure.account.auth.type&quot;, &quot;SharedKey&quot;) sparkConf.set(&quot;fs.azure.account.key.&lt;&lt;storage_account_name&gt;&gt;.dfs.core.windows.net&quot;,&quot;&lt;&lt;account_key&gt;&gt;&quot;) spark = SparkSession.builder.config(conf=sparkConf).getOrCreate() </code></pre> <p>And then I am running the below command to read a csv file present in the ADLS location</p> <pre><code>df = spark.read.csv(&quot;abfss://&lt;&lt;container&gt;&gt;@&lt;&lt;storage_account&gt;&gt;.dfs.core.windows.net/&quot;) </code></pre> <p>On runnining it I am getting the error <em><strong>Py4JJavaError: An error occurred while calling o443.csv. : java.lang.RuntimeException: java.lang.ClassNotFoundException: Class org.apache.hadoop.fs.azurebfs.SecureAzureBlobFileSystem not found</strong></em></p> <p>After some research, I found that I would have to explicitly include the hadoop-azure jar for the appropriate classes to be available. I downloaded the jar from <a href="https://repo1.maven.org/maven2/org/apache/hadoop/hadoop-azure/3.2.2/hadoop-azure-3.2.2.jar" rel="noreferrer">here</a> , put it in the /spark-3.0.1-bin-hadoop3.2/jars folder and built the image again.</p> <p><strong>Unfortunately I am still getting this error</strong>. I manually verified that the jar file is indeed present in the docker image and contains the class <code>org.apache.hadoop.fs.azurebfs.SecureAzureBlobFileSystem</code></p> <p>I looked at the entrypoint.sh present at <code>spark-3.0.1-bin-hadoop3.2\kubernetes\dockerfiles\spark</code> folder which is the entry point of our spark docker image. It adds all the packages present in the <code>spark-3.0.1-bin-hadoop3.2\jar\</code> folder in the class path.</p> <pre><code># If HADOOP_HOME is set and SPARK_DIST_CLASSPATH is not set, set it here so Hadoop jars are available to the executor. # It does not set SPARK_DIST_CLASSPATH if already set, to avoid overriding customizations of this value from elsewhere e.g. Docker/K8s. if [ -n &quot;${HADOOP_HOME}&quot; ] &amp;&amp; [ -z &quot;${SPARK_DIST_CLASSPATH}&quot; ]; then export SPARK_DIST_CLASSPATH=&quot;$($HADOOP_HOME/bin/hadoop classpath)&quot; fi if ! [ -z ${HADOOP_CONF_DIR+x} ]; then SPARK_CLASSPATH=&quot;$HADOOP_CONF_DIR:$SPARK_CLASSPATH&quot;; fi </code></pre> <p>According to my understanding spark should be able to find the class in its classpath with any addition setJar configuration.</p> <p>Can someone please guide me how to resolve this? I might be missing something quite basic here.</p>
<p>Applying the solution provided here...</p> <p><a href="https://stackoverflow.com/questions/42978976/how-do-we-specify-maven-dependencies-in-pyspark">How do we specify maven dependencies in pyspark</a></p> <p>We can start a Spark session and include the required Jar from Maven.</p> <pre><code>from pyspark.sql import SparkSession spark = SparkSession.builder.master(&quot;local[*]&quot;)\ .config('spark.jars.packages', 'org.apache.hadoop:hadoop-azure:3.3.1')\ .getOrCreate() </code></pre>
<p>I would like to set the value of <code>terminationMessagePolicy</code> to <code>FallbackToLogsOnError</code> by default for all my pods.</p> <p>Is there any way to do that?</p> <p>I am running Kubernetes 1.21.</p>
<p><code>terminationMessagePolicy</code> is a field in container spec, currently beside set it in your spec there is no cluster level setting that could change the default value (&quot;File&quot;).</p>
<p>I have created a YAML file its only job is: <code>It should immediately redirect to google.com</code></p> <p>but it just doesn't work...</p> <p>my <code>localhost</code> still returns <code>404-nginx</code></p> <p>I'm on docker-desktop and my cluster version is <code>v1.21.5</code></p> <p>here is my <code>redirect.yaml</code></p> <pre><code>apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: my-google annotations: nginx.ingress.kubernetes.io/permanent-redirect: https://www.google.com spec: rules: - http: paths: - path: / pathType: Prefix backend: service: name: doesntmatter port: number: 80 </code></pre> <p>here is my <code>kubectl get ingress</code></p> <pre><code>NAME CLASS HOSTS ADDRESS PORTS AGE cheddar nginx cheddar.127.0.0.1.nip.io localhost 80 31m my-google &lt;none&gt; * 80 26m stilton nginx stilton.127.0.0.1.nip.io localhost 80 31m wensleydale nginx wensleydale.127.0.0.1.nip.io localhost 80 31m </code></pre> <p>NOTE: the other ingress sevices e.g. <code>cheddar.127.0.0.1.nip.io</code> is working perfectly...</p>
<p>I guess you forgot the ingress class name.</p> <pre class="lang-yaml prettyprint-override"><code>spec: ingressClassName: nginx ... </code></pre> <p>Apart from that, you can create an <a href="https://kubernetes.io/docs/concepts/services-networking/service/#externalname" rel="nofollow noreferrer">external service</a>.</p> <pre class="lang-yaml prettyprint-override"><code>--- apiVersion: v1 kind: Service metadata: name: google spec: type: ExternalName externalName: www.google.com ports: - name: https port: 443 protocol: TCP targetPort: 443 --- apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: google labels: name: google annotations: nginx.ingress.kubernetes.io/backend-protocol: HTTPS nginx.ingress.kubernetes.io/upstream-vhost: www.google.com spec: ingressClassName: nginx rules: - http: paths: - path: / pathType: Prefix backend: service: name: google port: name: https </code></pre> <p>Note, that the cert from your ingress controller is not the cert of google. So there can be some issues around that. One setting that may help with those kind of issues is the annotation <code>nginx.ingress.kubernetes.io/upstream-vhost</code> like shown above.</p>
<p>I am trying to run my node application (which successfully runs on my PC with Docker Desktop) through Kubernetes. This is a raspberry pi multi-node ubuntu kubeadm server (everything is latest stable version). I do have successful pods running on this server. I followed <a href="https://kubernetes.io/docs/tasks/configure-pod-container/pull-image-private-registry/#create-a-secret-by-providing-credentials-on-the-command-line" rel="nofollow noreferrer">Kubernetes official guide</a> to login to my private docker repository on Docker hub. I have double checked my credentials and I can use docker without <code>sudo</code> privileges.</p> <p>My exact setup is listed below, please comment if you want me to add any more information!</p> <p>My error code:</p> <blockquote> <p>Failed to pull image &quot;matthewvine/node-tools:rewrite&quot;: rpc error: code = Unknown desc = Error response from daemon: pull access denied for matthewvine/node-tools, repository does not exist or may require 'docker login': denied: requested access to the resource is denied</p> </blockquote> <p>My <code>regcred</code> docker secret:</p> <pre><code>data: .dockerconfigjson: ey...== kind: Secret metadata: creationTimestamp: &quot;2022-01-10T23:34:40Z&quot; name: regcred namespace: default resourceVersion: &quot;1807979&quot; uid: 69... type: kubernetes.io/dockerconfigjson </code></pre> <p>My <code>node-ht</code> deployment:</p> <pre><code>apiVersion: apps/v1 metadata: name: node-ht namespace: node ... spec: replicas: 1 selector: matchLabels: app: node-ht template: metadata: ... spec: containers: - name: node-ht image: matthewvine/node-tools:rewrite ports: - containerPort: 3000 protocol: TCP resources: {} terminationMessagePath: /dev/termination-log terminationMessagePolicy: File imagePullPolicy: Always restartPolicy: Always terminationGracePeriodSeconds: 30 dnsPolicy: ClusterFirst securityContext: {} imagePullSecrets: - name: regcred schedulerName: default-scheduler strategy: type: RollingUpdate rollingUpdate: maxUnavailable: 25% maxSurge: 25% revisionHistoryLimit: 10 progressDeadlineSeconds: 600 </code></pre> <p><strong>My Soluton</strong>: Turns out it was a simple namespace issue. Secrets need to be in the same namespace as the resources trying to use them.</p>
<p>The secret key must be in the same place as the distribution namespace.</p> <p>If you want to connect your docker secret to kubernetes you can use below method.</p> <p><strong>Create a Secret based on existing Docker credentials</strong> (<a href="https://kubernetes.io/docs/tasks/configure-pod-container/pull-image-private-registry/#registry-secret-existing-credentials" rel="nofollow noreferrer">link</a>)</p> <pre><code>kubectl create secret generic regcred \ --from-file=.dockerconfigjson=&lt;path/to/.docker/config.json&gt; \ --type=kubernetes.io/dockerconfigjson </code></pre> <p>I think you already did that. The namespace change should fix your problem</p>
<p>I was looking for a solution but I couldn't find any.</p> <p>I have a bash script which executes something like this:</p> <pre class="lang-sh prettyprint-override"><code>kubectl get services -o=json | \ jq '.items[].metadata.annotations | '\ 'select (.&quot;my-ingress/enabled&quot; == &quot;true&quot;) | '\ '{&quot;my-ingress/path&quot;, &quot;my-ingress/service-name&quot;, &quot;my-ingress/service-port&quot;}' </code></pre> <p>Which means it can take list of the services, filter and take only with annotations <code>my-ingress/enabled == true</code></p> <p>Based on that result it creates dynamically YAML for Ingress and loads it.</p> <p>Everywhere I was looking, Helm is using templates and other fancy approaches but nowhere I could find any information how to ask K8S about some resources and based on that info build YAML.</p> <p>Is this possible at all?</p> <p><strong><em>Note</em></strong>: calling Bash to prepare some kind <code>values.yaml</code> is not an option in my case.</p>
<p>You may use <a href="https://helm.sh/docs/chart_template_guide/functions_and_pipelines/#using-the-lookup-function" rel="nofollow noreferrer">HELM's lookup function</a> to query the cluster</p> <blockquote> <p>The lookup function can be used to look up resources in a running cluster. The synopsis of the lookup function is lookup apiVersion, kind, namespace, name -&gt; resource or resource list.</p> <p>parameter type apiVersion string kind string namespace string name string Both name and namespace are optional and can be passed as an empty string (&quot;&quot;).</p> </blockquote> <pre><code>{{ range $index, $service := (lookup &quot;v1&quot; &quot;Service&quot; &quot;mynamespace&quot; &quot;&quot;).items }} {{/* do something with each service */}} {{ end }} </code></pre> <p><strong>Important note:</strong></p> <blockquote> <p>Keep in mind that Helm is not supposed to contact the Kubernetes API Server during a <code>helm template</code> or a <code>helm install|update|delete|rollback --dry-run</code>, so the lookup function will return an empty list (i.e. dict) in such a case.</p> </blockquote>
<p>I've installed ArgoCD on my kubernetes cluster using</p> <pre><code>kubectl create namespace argocd kubectl apply -n argocd -f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml </code></pre> <p>Now, how to remove it from the cluster totally?</p>
<p>You can delete the entire installation using this - <code>kubectl delete -n argocd -f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml</code></p> <p><a href="https://www.reddit.com/r/kubernetes/comments/kayu97/how_to_uninstall_argocd/gfdlufl/" rel="noreferrer">Reference</a></p>
<p>I would like to set the value of <code>terminationMessagePolicy</code> to <code>FallbackToLogsOnError</code> by default for all my pods.</p> <p>Is there any way to do that?</p> <p>I am running Kubernetes 1.21.</p>
<p>Community wiki answer to summarise the topic.</p> <p>The answer provided by the <a href="https://stackoverflow.com/users/14704799/gohmc">gohm'c</a> is good. It is not possible to change this value from the cluster level. You can find more information about it <a href="https://kubernetes.io/docs/tasks/debug-application-cluster/_print/#customizing-the-termination-message" rel="nofollow noreferrer">in the official documentation</a>:</p> <blockquote> <p>Moreover, users can set the <code>terminationMessagePolicy</code> field of a Container for further customization. This field defaults to &quot;<code>File</code>&quot; which means the termination messages are retrieved only from the termination message file. By setting the <code>terminationMessagePolicy</code> to &quot;<code>FallbackToLogsOnError</code>&quot;, you can tell Kubernetes to use the last chunk of container log output if the termination message file is empty and the container exited with an error. The log output is limited to 2048 bytes or 80 lines, whichever is smaller.</p> </blockquote> <p>See also this page about <a href="https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.21/#podspec-v1-core" rel="nofollow noreferrer">Container v1 core API</a> for 1.21 version. You can find there information about <code>terminationMessagePolicy</code>:</p> <blockquote> <p>Indicate how the termination message should be populated. File will use the contents of terminationMessagePath to populate the container status message on both success and failure. FallbackToLogsOnError will use the last chunk of container log output if the termination message file is empty and the container exited with an error. The log output is limited to 2048 bytes or 80 lines, whichever is smaller. Defaults to File. Cannot be updated.</p> </blockquote> <p>This can be done only from the Container level.</p>
<p>We are using Istio Envoy based Rate limiting (with Kubernetes &amp; Docker) as specified in <a href="https://istio.io/latest/docs/tasks/policy-enforcement/rate-limit/" rel="nofollow noreferrer">this documentation</a>.</p> <p>Although I was able to set it up for local and global rate limiting in the Kubernetes cluster, I am unable to achieve the following:</p> <ol> <li><p>Rate limit a Service only for POST requests, while GET requests should go through unencumbered.</p> </li> <li><p>Rate limit a Service only for a certain time duration (e.g. 9 AM to 5 PM EST) and work normally at other times.</p> </li> </ol> <p>Is the above possible in current Istio functionalities?</p>
<p>I will try to answer both of your questions below.</p> <h4>1. Rate limit a Service only for a specific request method</h4> <p>We can use the <a href="https://www.envoyproxy.io/docs/envoy/v1.14.5/api-v2/api/v2/route/route_components.proto#envoy-api-msg-route-ratelimit-action-headervaluematch" rel="nofollow noreferrer">header_value_match</a> rate limit actions.</p> <p>I created a single <code>rate_limits filter</code> with one <code>action</code> that matches any request with method <strong>GET</strong>:<br /> <strong>NOTE:</strong> For the sake of simplicity, I have only given an important part of the configuration.</p> <p>Envoy rate_limits filter configuration:</p> <pre><code>... value: rate_limits: - actions: - header_value_match: descriptor_value: get headers: - name: :method prefix_match: GET ... </code></pre> <p>Next, I created a <code>ratelimit service configuration</code> that matches descriptors with key <code>header_match</code> and value <code>get</code>. It will provide a limit of 1 request per minute:</p> <pre><code>... descriptors: - key: header_match rate_limit: unit: minute requests_per_unit: 1 value: get ... </code></pre> <p>After applying the above configuration, we can check whether it will be possible to use the <strong>GET</strong> method more than once within 1 minute:</p> <pre><code>$ curl &quot;http://$GATEWAY_URL/productpage&quot; -I -X GET HTTP/1.1 200 OK content-type: text/html; charset=utf-8 content-length: 5179 server: istio-envoy date: Tue, 11 Jan 2022 09:57:33 GMT x-envoy-upstream-service-time: 120 $ curl &quot;http://$GATEWAY_URL/productpage&quot; -I -X GET HTTP/1.1 429 Too Many Requests x-envoy-ratelimited: true date: Tue, 11 Jan 2022 09:57:35 GMT server: istio-envoy content-length: 0 </code></pre> <p>As we can see, after the second request, we received the HTTP <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429" rel="nofollow noreferrer">429 Too Many Requests</a> response status code which indicates that the user has sent too many requests in a given amount of time. It means that everything works as expected.</p> <p>I recommend you to read the <a href="https://www.aboutwayfair.com/tech-innovation/understanding-envoy-rate-limits" rel="nofollow noreferrer">Understanding Envoy Rate Limits</a> article which contains a lot of useful information.</p> <h4>2. Rate limit a Service only for a certain time duration (e.g. 9 AM to 5 PM EST) and work normally at other times.</h4> <p>Unfortunately, I cannot find any suitable option to configure this behavior. I think that <a href="https://kubernetes.io/docs/concepts/workloads/controllers/cron-jobs/" rel="nofollow noreferrer">CronJob</a> can be used as a workaround, which will run periodically on a given schedule and will create/delete the appropriate configuration responsible for rate-limiting. In short, you can use a Bash script that creates/deletes a configuration responsible for rate-limiting and then you can mount that script in a volume to the <code>CronJob</code> Pod. I have already described a similar use of <code>CronJob</code> <a href="https://stackoverflow.com/a/68406717/14801225">here</a> and believe it can help you.</p>
<p>I'm trying to setup a ingress network for my Google GKE, I have tested locally on Minikube and its working as I expect.</p> <p>When I hit the domain with the prefix /test-1 or /test-2 its sending me to the root of the my service /.</p> <pre><code>apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: api-test-domain-ingress annotations: nginx.ingress.kubernetes.io/rewrite-target: /$2 spec: tls: - hosts: - api.test-domain.com secretName: tls-secret rules: - host: api.test-domain.com http: paths: - path: /test-1(/|$)(.*) pathType: Prefix backend: service: name: test-1-port-forwarding port: number: 8080 - path: /test-2(/|$)(.*) pathType: Prefix backend: service: name: test-2-port-forwarding port: number: 8081 </code></pre> <p>The issue is when I put it into my Kubernetes cluster on Google (GKE) then I get this error</p> <blockquote> <p>Translation failed: invalid ingress spec: failed to validate prefix path /test-1(/|$)(.<em>) due to invalid wildcard; failed to validate prefix path /test-2(/|$)(.</em>) due to invalid wildcard</p> </blockquote> <p>I have trying in hours to trying to get it to working and what's going on, whiteout any kind of result, so really hope some one here can explain about what I did wrong and what I shut change to resolved my problem.</p>
<p>GKE Built-in Ingress supports wildcard but with some <a href="https://cloud.google.com/kubernetes-engine/docs/concepts/ingress#multiple_backend_services" rel="nofollow noreferrer">conditions</a>. From the doc:</p> <pre><code>The only supported wildcard character for the path field of an Ingress is the * character. The * character must follow a forward slash (/) and must be the last character in the pattern. For example, /*, /foo/*, and /foo/bar/* are valid patterns, but *, /foo/bar*, and /foo/*/bar are not. </code></pre> <p>If you want to use NGINX you will have to deploy it, GKE doesn't ship with NGINX out of the box. Keep in mind that this is something you will have to maintain and take care of yourself. It's a valid choice to make if the GKE default ingress doesn't support what you need to do (like headers re-write for example) but just be aware of the fact that it's an extra piece of software.</p>
<p>I am trying to use Kubernetes volumes for Nginx, but am facing an issue with it. After volumes are set Nginx is unable to serve the HTML page. Also am tried with PV and PVS this time also got the same error.</p> <p>nginx.yml</p> <pre><code>apiVersion: apps/v1 kind: Deployment metadata: name: nginx-deployment labels: app: nginx spec: replicas: 2 selector: matchLabels: app: nginx template: metadata: labels: app: nginx spec: volumes: - name: nginxhtml # persistentVolumeClaim: # claimName: pvc hostPath: path: /home/amjed/Documents/SPS/k8s/mongo/mnt containers: - name: nginx image: nginx volumeMounts: - name: nginxhtml mountPath: /usr/share/nginx/html ports: - containerPort: 80 --- apiVersion: v1 kind: Service metadata: name: nginx-service spec: selector: app: nginx type: LoadBalancer ports: - protocol: TCP port: 80 targetPort: 80 </code></pre>
<p>First, create folder that you want to mount inside minikube:</p> <pre><code>dobrucki@minikube:~$ minikube ssh Last login: Tue Jan 11 13:54:50 2022 from 192.168.49.1 docker@minikube:~$ ls -l total 4 drwxr-xr-x 2 docker docker 4096 Jan 11 13:56 nginx-mount </code></pre> <p>This folder is what is mapped to <code>/usr/share/nginx/html</code> inside Pods, so files you paste here will be displayed when you connect to your service. Make sure that you have some <code>.html</code> file inside that folder, otherwise you will get 403 error. For me, example <code>index.html</code> is this:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;Hello World&lt;h1&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>You also need to add <code>securityContext</code> <code>fsGroup</code> inside your Deployment manifest, so that <code>/usr/share/nginx/html</code> is owned by nginx user (101 uid).</p> <p>Then, apply Deployment and LoadBalancer resources using this:</p> <pre><code>apiVersion: apps/v1 kind: Deployment metadata: name: nginx-deployment labels: app: nginx spec: replicas: 2 selector: matchLabels: app: nginx template: metadata: labels: app: nginx spec: securityContext: fsGroup: 101 volumes: - name: nginxhtml hostPath: path: /home/docker/nginx-mount containers: - name: nginx image: nginx volumeMounts: - name: nginxhtml mountPath: /usr/share/nginx/html ports: - containerPort: 80 --- apiVersion: v1 kind: Service metadata: name: nginx-service spec: selector: app: nginx type: LoadBalancer ports: - protocol: TCP port: 80 targetPort: 80 </code></pre> <p>After that you can check if the content is served correctly</p> <pre><code>dobrucki@minikube:~$ curl $(minikube service nginx-service --url) &lt;html&gt; &lt;head&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;Hello World&lt;h1&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Let me know if you have more questions.</p>
<p>I’m trying to set some environment variables in k8s deployment and use them within the <code>application.properties</code> in my spring boot application, but it looks like I'm doing something wrong because spring is not reading those variables, although when checking the <code>env vars</code> on the pod, all the vars are set correctly.</p> <p>The error log from the container:</p> <pre><code>org.postgresql.util.PSQLException: Connection to localhost:5432 refused. Check that the hostname and port... </code></pre> <p>Any help will be appreciated.</p> <p><strong>application.properties:</strong></p> <pre><code>spring.datasource.url=jdbc:postgresql://${DB_URL}:${DB_PORT}/${DB_NAME} spring.datasource.username=${DB_USER_NAME} spring.datasource.password=${DB_PASSWORD} </code></pre> <p><strong>DockerFile</strong></p> <pre><code>FROM openjdk:11-jre-slim-buster ARG JAR_FILE=target/*.jar COPY ${JAR_FILE} app.jar ENTRYPOINT [&quot;java&quot;,&quot;-jar&quot;,&quot;/app.jar&quot;] </code></pre> <p><strong>deployment.yaml:</strong></p> <pre><code>apiVersion: apps/v1 kind: Deployment metadata: name: api-deployment labels: app: api spec: replicas: 1 selector: matchLabels: app: api template: metadata: labels: app: api spec: containers: - name: api image: .../api resources: requests: memory: &quot;64Mi&quot; cpu: &quot;250m&quot; limits: memory: &quot;128Mi&quot; cpu: &quot;500m&quot; ports: - containerPort: 80 env: - name: DB_URL value: &quot;posgres&quot; - name: DB_NAME valueFrom: configMapKeyRef: name: postgres-config key: dbName - name: DB_USER_NAME valueFrom: secretKeyRef: name: db-secret key: dbUserName - name: DB_PASSWORD valueFrom: secretKeyRef: name: db-secret key: dbPassword </code></pre>
<p>The DockerFile was wrong. Everything is working fine after changing the DockerFile to this:</p> <pre><code>FROM maven:3.6.3-openjdk-11-slim as builder WORKDIR /app COPY pom.xml . COPY src/ /app/src/ RUN mvn install -DskipTests=true FROM adoptopenjdk/openjdk11:jre-11.0.8_10-alpine COPY --from=builder /app/target/*.jar /app.jar ENTRYPOINT [&quot;java&quot;, &quot;-jar&quot;, &quot;/app.jar&quot;] </code></pre>
<p>I have a problem with minikube when I want to create deployment manifest files, I receive an error when I write this code: <code>minikube kubectl create -f .</code> I got this Error:</p> <p>Error: unknown shorthand flag: 'f' in -f See 'minikube kubectl --help' for usage.</p> <p>but not only this, I try to write another command but again same error happening</p> <p><code>minikube kubectl delete daemonsets,replicasets,services,deployments,pods,rc,pvc --all </code> Error: unknown flag: --all See 'minikube kubectl --help' for usage.</p> <p>please help me. thanks</p>
<p>AFAIK, --all is not a valid flag. Valid flag is --all-namespaces or just -A.</p> <p>However, &quot;kubectl delete&quot; does not take -A as it needs the resource name for deletion.</p> <p>To accomplish what you are trying to do you will have to write a loop to delete the objects 1 by one using</p> <pre><code>kubectl get daemonsets,replicasets,services,deployments,pods,rc,pvc -A --no-headers | while read line; do namespace=$(echo $line | awk '{print $1}') resource=$(echo $line | awk '{print $2}') kubectl delete ${resource} -n ${namespace} done </code></pre> <p><strong>Execution - BE extremely careful with this as it will delete all queried resources in all namespaces including those in kube-system namespace</strong>:</p> <pre><code>controlplane $ kubectl get daemonsets,replicasets,services,deployments,pods,rc,pvc -A --no-headers | while read line; do &gt; namespace=$(echo $line | awk '{print $1}') &gt; resource=$(echo $line | awk '{print $2}') &gt; kubectl delete ${resource} -n ${namespace} &gt; done daemonset.extensions &quot;kube-keepalived-vip&quot; deleted daemonset.extensions &quot;kube-proxy&quot; deleted daemonset.extensions &quot;weave-net&quot; deleted replicaset.extensions &quot;coredns-fb8b8dccf&quot; deleted replicaset.extensions &quot;katacoda-cloud-provider-d5cb9d656&quot; deleted service &quot;kubernetes&quot; deleted service &quot;kube-dns&quot; deleted deployment.extensions &quot;coredns&quot; deleted deployment.extensions &quot;katacoda-cloud-provider&quot; deleted </code></pre>
<p>I am trying to access my microservice &quot;externalforum-api-svc&quot; inside my kubernetes cluster using ocelot gateway. I`ve followed the docs but it does not seem to be working.</p> <p>Can someone please tell me whats wrong with it?</p> <p>I want to deploy the ocelot api gateway as clusterIP and use Ingress to access it from outside of the cluster, but i am facing this issue when trying to reroute from ocelot -&gt; service inside the cluster.</p> <blockquote> <p>## Error warn: Ocelot.Responder.Middleware.ResponderMiddleware[0] requestId: 0HMCO5SFMMOIQ:00000002, previousRequestId: no previous request id, message: Error Code: UnableToFindServiceDiscoveryProviderError Message: Unable to find service discovery provider for type: consul errors found in ResponderMiddleware. Setting error response for request path:/externalForumService, request method: GET</p> </blockquote> <pre><code>{ &quot;Routes&quot;: [ { &quot;UpstreamPathTemplate&quot;: &quot;/externalForumService/GetAll&quot;, &quot;DownstreamPathTemplate&quot;: &quot;/api/externalforum/v1/forum/GetAll&quot;, &quot;DownstreamScheme&quot;: &quot;http&quot;, &quot;ServiceName&quot;: &quot;externalforum-api-svc&quot;, &quot;UpstreamHttpMethod&quot;: [ &quot;Get&quot; ] }, { &quot;UpstreamPathTemplate&quot;: &quot;/externalForumService&quot;, &quot;DownstreamPathTemplate&quot;: &quot;/api/externalforum/v1/forum&quot;, &quot;DownstreamScheme&quot;: &quot;http&quot;, &quot;ServiceName&quot;: &quot;externalforum-api-svc&quot;, &quot;UpstreamHttpMethod&quot;: [ &quot;Get&quot; ] } ], &quot;GlobalConfiguration&quot;: { &quot;ServiceDiscoveryProvider&quot;: { &quot;Namespace&quot;: &quot;propnull&quot;, &quot;Type&quot;: &quot;kube&quot; } } } </code></pre> <h2>Service to map</h2> <pre><code>apiVersion: v1 kind: Service metadata: name: externalforum-api-svc namespace: propnull spec: type: ClusterIP selector: app: externalforum-api ports: - name: http protocol: TCP port: 80 targetPort: 80 </code></pre> <p>I have already ran <code>kubectl create clusterrolebinding permissive-binding --clusterrole=cluster-admin --user=admin --user=kubelet --group=system:serviceaccounts</code></p> <h2>Specifications</h2> <ul> <li>Version: 17.0.0</li> <li>Platform: net core 5.0</li> </ul>
<p>Try to change &quot;type : kube&quot; to &quot;type : KubernetesServiceDiscoveryProvider&quot; in GlobalConfiguration section.</p>
<p>I'm trying to add a custom function In Go template for parsing the time in PodStatus and getting the absolute time for it.</p> <p>Example for the custom function:</p> <pre><code>PodScheduled, _ := time.Parse(time.RFC3339, &quot;2021-12- 23T20:20:36Z&quot;) Ready, _ := time.Parse(time.RFC3339, &quot;2021-12-31T07:36:11Z&quot;) difference := Ready.Sub(PodScheduled) fmt.Printf(&quot;difference = %v\n&quot;, difference) </code></pre> <p>I can use the built-in functions.</p> <p>How I can use a custom function with the kubectl?</p> <p>For example this lib: <a href="https://github.com/Masterminds/sprig" rel="nofollow noreferrer">https://github.com/Masterminds/sprig</a></p> <p>Thanks :)</p>
<p>IIUC you have (at least) 3 options:</p> <ol> <li>Discouraged: Write your own client (instead of <code>kubectl</code>) that provides the functionality;</li> <li>Encouraged: Use the shell to post-process the output from e.g. <code>kubectl get pods --output=json</code>) by piping the result through: <ul> <li>Either your Golang binary that reads from standard input</li> <li>Or better a general-purpose JSON processing tool like <a href="https://stedolan.github.io/jq/" rel="nofollow noreferrer"><code>jq</code></a> that would do this (and much more!)</li> </ul> </li> <li>For completeness, <code>kubectl</code> supports output formatting (<code>--output=jsonpath...</code>); although <a href="https://kubernetes.io/docs/reference/kubectl/jsonpath/" rel="nofollow noreferrer"><code>JSONPath</code></a> may be insufficient for this need;</li> </ol> <p>See jq's documentation for <a href="https://stedolan.github.io/jq/manual/#Dates" rel="nofollow noreferrer">Dates</a></p>
<p>I feel like I am misunderstanding RAM based <code>emptyDir</code> volumes in Kubernetes.</p> <ol> <li><p>Let's suppose my Kubernetes node has a total of 100GB. If I have 4 different emptyDirs that have <code>emptyDir.medium</code> set to &quot;Memory&quot;, by default will they all have 50GBs of memory? In that case what happens when the total amount of memory used in my 4 emptyDirs exceeds 100GB?</p> </li> <li><p>I know in general RAM is fast, but what are some examples for the downsides? From the <a href="https://kubernetes.io/docs/concepts/storage/volumes/" rel="nofollow noreferrer">official documentation</a>, I see the below but I don't quite understand the statement. My understanding is that if a Pod crashes, files on emptyDirs using disk will still be deleted. Will the files be kept upon node reboot if they are stored in disk? Also what do they mean by <code>count against container memory limit</code>?</p> </li> </ol> <pre><code>While tmpfs is very fast, be aware that unlike disks, tmpfs is cleared on node reboot and any files you write count against your container's memory limit </code></pre>
<p><code>...by default will they all have 50GBs of memory?</code></p> <p>Yes. You can exec into the pod and check with <code>df -h</code>. If your cluster has <code>SizeMemoryBackedVolumes</code> feature enabled, you can specify the size.</p> <p><code>...what happens when the total amount of memory used in my 4 emptyDirs exceeds 100GB?</code></p> <p>You won't get that chance because the moment the total amount of memory used by all emptyDir(s) reach 50GB; your pod will be evicted. <strong>It doesn't need a single emptyDir to reach 50GB to evict</strong>.</p> <p><code>...don't quite understand the statement.</code></p> <p>It means you will not get back the data storing on emptyDir.</p> <p><code>count against container memory limit</code></p> <p>It means the amount of memory that you consumed using emptyDir is added to the amount of the memory that your container used and check against the resources.limits.memory.</p>
<p>I would love to list deployments having <code>mongodb</code> environment value along with their phase status. Is there anyway to do so?</p> <p>With this command, I get the deployments name which carries a specific environment value</p> <pre><code>kubectl get deploy -o=custom-columns=&quot;NAME:.metadata.name,SEC:.spec.template.spec.containers[*].env[*].value&quot; | grep mongodb | cut -f 1 -d ' ' </code></pre> <p>Output:</p> <pre><code>app1 app2 app3 app4 </code></pre> <p>Output I want to get:</p> <pre><code>NAME READY UP-TO-DATE AVAILABLE AGE app1 1/1 1 1 125d app2 1/1 1 1 248d app3 1/1 1 1 248d app4 1/1 1 1 248d </code></pre> <p>Or it can be pods as well. I'd appreciate your help.</p> <p>Thank you!</p>
<p>I had a go at a solution using <code>kubectl</code> but was unsuccessful.</p> <p>I suspect (!?) you'll need to use additional tools to parse|process the results to get what you want. Perhaps using <a href="https://stedolan.github.io/jq/" rel="noreferrer"><code>jq</code></a>?</p> <p>For Deployments, you can filter the results based on environment variable names using, e.g.:</p> <pre class="lang-sh prettyprint-override"><code>FILTER=&quot;{.items[*].spec.template.spec.containers[*].env[?(@.name==\&quot;mongodb\&quot;)]}&quot; kubectl get deployments \ --namespace=${NAMESPACE} \ --output=jsonpath=&quot;${FILTER}&quot; </code></pre> <p>But this only returns the filtered path (i.e. <code>items[*].spec.template.spec.containers[*].env</code>).</p> <p>With JSONPath, you ought (!) be able to apply the filter to the item but I this isn't supported (by <code>kubectl</code>'s implementation) i.e.:</p> <pre class="lang-sh prettyprint-override"><code>FILTER=&quot;{.items[?(@.spec.template.spec.containers[?(@.env[?(@.name==\&quot;mongodb\&quot;)])])]}&quot; </code></pre> <p>With <code>jq</code>, I think you'll be able to select the <code>env.name</code>, return the <code>item</code>'s status and get the raw <code>status</code> values that you need. Something like:</p> <pre class="lang-sh prettyprint-override"><code>FILTER=' .items[] |select(.spec.template.spec.containers[].env[].name == &quot;mongodb&quot;) |{&quot;name&quot;:.metadata.name, &quot;ready&quot;:.status.readyReplicas} ' kubectl get deployments \ --output=json \ | jq -r &quot;${FILTER}&quot; </code></pre>
<p>I am creating a new Operator with Kubebuilder to deploy a Kubernetes controller to manage a new CRD Custom Resource Definition.</p> <p>This new CRD (let's say is called <code>MyNewResource</code>), needs to list/create/delete CronJobs.</p> <p>So in the Controller Go code where the <code>Reconcile(...)</code> method is defined I added a new RBAC comment to allow the reconciliation to work on CronJobs (see <a href="https://book.kubebuilder.io/reference/markers/rbac.html" rel="nofollow noreferrer">here</a>):</p> <pre class="lang-golang prettyprint-override"><code>//+kubebuilder:rbac:groups=batch,resources=cronjobs,verbs=get;list;watch;create;update;patch;delete </code></pre> <p>However after building pushing and deploying the Docker/Kubernetes controller (repo <code>myrepo</code>, <code>make manifests</code>, then <code>make install</code>, then <code>make docker-build docker-push</code>, then <code>make deploy</code>), then in the logs I still see:</p> <pre><code>E0111 09:35:18.785523 1 reflector.go:138] pkg/mod/k8s.io/client-go@v0.22.1/tools/cache/reflector.go:167: Failed to watch *v1beta1.CronJob: failed to list *v1beta1.CronJob: cronjobs.batch is forbidden: User &quot;system:serviceaccount:myrepo-system:myrepo-controller-manager&quot; cannot list resource &quot;cronjobs&quot; in API group &quot;batch&quot; at the cluster scope </code></pre> <p>I also see issues about the cache, but they might not be related (not sure):</p> <pre><code>2022-01-11T09:35:57.857Z ERROR controller.mynewresource Could not wait for Cache to sync {&quot;reconciler group&quot;: &quot;mygroup.mydomain.com&quot;, &quot;reconciler kind&quot;: &quot;MyNewResource&quot;, &quot;error&quot;: &quot;failed to wait for mynewresource caches to sync: timed out waiting for cache to be synced&quot;} sigs.k8s.io/controller-runtime/pkg/internal/controller.(*Controller).Start /go/pkg/mod/sigs.k8s.io/controller-runtime@v0.10.0/pkg/internal/controller/controller.go:234 sigs.k8s.io/controller-runtime/pkg/manager.(*controllerManager).startRunnable.func1 /go/pkg/mod/sigs.k8s.io/controller-runtime@v0.10.0/pkg/manager/internal.go:696 2022-01-11T09:35:57.858Z ERROR error received after stop sequence was engaged {&quot;error&quot;: &quot;leader election lost&quot;} 2022-01-11T09:35:57.858Z ERROR setup problem running manager {&quot;error&quot;: &quot;failed to wait for mynewresource caches to sync: timed out waiting for cache to be synced&quot;} </code></pre> <p>How can I allow my new Operator to deal with CronJobs resources?</p> <p>At the moment basically I am not able to create new CronJobs programmatically (Go code) when I provide some YAML for a new instance of my CRD, by invoking:</p> <pre><code>kubectl create -f mynewresource-project/config/samples/ </code></pre>
<p>You need to create new Role or ClusterRole (depending if you want your permissions to be namespaced or cluster-wide) and bind that to your <code>system:serviceaccount:myrepo-system:myrepo-controller-manager</code> user using RoleBinding/ClusterRoleBinding. I will provide examples for cluster-wide configuration.</p> <p>ClusterRole:</p> <pre><code>apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: cronjobs-role rules: - apiGroups: [&quot;&quot;] resources: [&quot;cronjobs&quot;] verbs: [&quot;get&quot;, &quot;watch&quot;, &quot;list&quot;, &quot;create&quot;, &quot;update&quot;, &quot;patch&quot;, &quot;delete&quot;] </code></pre> <p>Then, bind that using ClusterRoleBinding:</p> <pre><code>apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: cronjobs-rolebinding subjects: - kind: User name: system:serviceaccount:myrepo-system:myrepo-controller-manager apiGroup: rbac.authorization.k8s.io roleRef: kind: ClusterRole name: cronjob-role apiGroup: rbac.authorization.k8s.io </code></pre> <p>Judging from your logs you might want to use <code>batch</code> apiGroup but I'll leave more generic example. More about k8s RBAC <a href="https://kubernetes.io/docs/reference/access-authn-authz/rbac/" rel="nofollow noreferrer">here</a>.</p> <p><strong>Kubebuilder</strong></p> <p>With Kubebuilder the ClusterRole and the ClusterRoleBinding YAML code is autogenerated and stored in the <code>config/rbac/</code> directory.</p> <p>To grant the binding on all groups (rather than just <code>batch</code>), you can place the Go comment with an asterisk like this:</p> <pre class="lang-golang prettyprint-override"><code>//+kubebuilder:rbac:groups=*,resources=cronjobs,verbs=get;list;watch;create;update;patch;delete </code></pre> <p>This will change the autogenerated YAML for the <code>ClusterRole</code> to:</p> <pre><code>rules: - apiGroups: - '*' # instead of simply: batch </code></pre> <p>When deploying the updated operator, then the controller should be able to list/create/delete CronJobs.</p> <p>See here for a <a href="https://book.kubebuilder.io/reference/markers/rbac.html" rel="nofollow noreferrer">reference RBAC for Kubebuilder comments</a></p>
<p>Currently I'm facing the issue:</p> <pre><code>ERROR: Job failed (system failure): prepare environment: setting up credentials: secrets is forbidden: User &quot;system:serviceaccount:default:gitlab-runner&quot; cannot create resource &quot;secrets&quot; in API group &quot;&quot; in the namespace &quot;gitlab&quot;` after following the official documentation on how to integrate the GitLab Runner. </code></pre> <p>I'm using the following <code>runner-chart-values.yaml</code>:</p> <pre><code># The GitLab Server URL (with protocol) that want to register the runner against # ref: https://docs.gitlab.com/runner/commands/README.html#gitlab-runner-register # gitlabUrl: http://example.domain/ # The Registration Token for adding new runners to the GitLab Server. This must # be retrieved from your GitLab instance. # ref: https://docs.gitlab.com/ce/ci/runners/README.html # runnerRegistrationToken: &quot;&lt;token&gt;&quot; # For RBAC support: rbac: create: true rules: - apiGroups: [&quot;*&quot;] # Run all containers with the privileged flag enabled # This will allow the docker:dind image to run if you need to run Docker # commands. Please read the docs before turning this on: # ref: https://docs.gitlab.com/runner/executors/kubernetes.html#using-dockerdind runners: privileged: true </code></pre> <p>Any clues what's going on?</p> <p>Many thanks!</p>
<p>For me adding all necessary roles was the only solution that actually helped.</p> <p>Here the corresponding runner-chart-values.yaml file:</p> <pre><code>## GitLab Runner Image gitlabUrl: http://example.domain/ runnerRegistrationToken: &quot;&lt;token&gt;&quot; rbac: create: true rules: - apiGroups: [&quot;&quot;] resources: [&quot;pods&quot;] verbs: [&quot;list&quot;, &quot;get&quot;, &quot;watch&quot;, &quot;create&quot;, &quot;delete&quot;] - apiGroups: [&quot;&quot;] resources: [&quot;pods/exec&quot;] verbs: [&quot;create&quot;] - apiGroups: [&quot;&quot;] resources: [&quot;pods/log&quot;] verbs: [&quot;get&quot;] - apiGroups: [&quot;&quot;] resources: [&quot;pods/attach&quot;] verbs: [&quot;list&quot;, &quot;get&quot;, &quot;create&quot;, &quot;delete&quot;, &quot;update&quot;] - apiGroups: [&quot;&quot;] resources: [&quot;secrets&quot;] verbs: [&quot;list&quot;, &quot;get&quot;, &quot;create&quot;, &quot;delete&quot;, &quot;update&quot;] - apiGroups: [&quot;&quot;] resources: [&quot;configmaps&quot;] verbs: [&quot;list&quot;, &quot;get&quot;, &quot;create&quot;, &quot;delete&quot;, &quot;update&quot;] runners: privileged: true </code></pre>
<p>We have an application deployed on GKE with a total of 10 pods running and serving the application. I am trying to find the metrics using which I can create an alert when my Pod goes down or is there a way to check the status of Pods so that I can set up an alert based on that condition?</p> <p>I explored GCP and looked into their documentation but couldn't find anything. What I could find is one metric below but I don't know what it measures. To me it looks like a number of times Kubernetes thinks a pod has died and it restarts the pod.</p> <pre><code>Metric: kubernetes.io/container/restart_count Resource type: k8s_container </code></pre> <p>Any advice on this is highly appreciated as we can improve our monitoring based on this metric</p> <p><a href="https://i.stack.imgur.com/rbPiw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rbPiw.png" alt="GCP alerting policy creation" /></a></p>
<p>That metric is the same you are right it will the count of POD restart.</p> <blockquote> <p>Number of times the container has restarted. Sampled every 60 seconds. After sampling, data is not visible for up to 120 seconds.</p> </blockquote> <p>Read more at : <a href="https://cloud.google.com/monitoring/api/metrics_kubernetes" rel="nofollow noreferrer">https://cloud.google.com/monitoring/api/metrics_kubernetes</a></p> <p><strong>Or</strong></p> <p>You can use Prometheus to get the metrics and monitor with <strong>Grafana</strong></p> <pre><code>sum(kube_pod_container_status_restarts_total{cluster=&quot;$cluster&quot;,namespace=&quot;$namespace&quot;,pod=~&quot;$service.*&quot;}) </code></pre> <p>This will give the value of the POD restart count.</p> <p><strong>OR</strong></p> <p>You can also use the <strong>BotKube</strong> : <a href="https://www.botkube.io/installation/" rel="nofollow noreferrer">https://www.botkube.io/installation/</a></p> <p>You can set to notify when your readiness liveness fails to slack notification etc..</p> <p><strong>Or</strong></p> <p>You write your own script and run it on Kubernetes to monitor and notify when any POD restart in cluster.</p> <p>Example github : <a href="https://github.com/harsh4870/Slack-Post-On-POD-Ready-State" rel="nofollow noreferrer">https://github.com/harsh4870/Slack-Post-On-POD-Ready-State</a></p> <p>This script notifies in slack when POD becomes ready after deployment, you can change it to monitor the restart count.</p> <p>i would recommend using <strong>Prometheus, Grafana</strong> option, however, <strong>stackdriver</strong> is Good but i am not Google employee.</p>
<p>I get the below error when I try to push the chart to ACR. Can you suggest the steps to be done here?</p> <p>&quot;This command is implicitly deprecated because command group 'acr helm' is deprecated and will be removed in a future release. Use 'helm v3' instead.&quot;</p> <p>I followed this article to create helm chart</p> <p><a href="https://cloudblogs.microsoft.com/opensource/2018/11/27/tutorial-azure-devops-setup-cicd-pipeline-kubernetes-docker-helm/" rel="nofollow noreferrer">https://cloudblogs.microsoft.com/opensource/2018/11/27/tutorial-azure-devops-setup-cicd-pipeline-kubernetes-docker-helm/</a></p> <p>These articles also describe the issue, but I don't understand what needs to be done to fix it. <a href="https://github.com/Azure/azure-cli/issues/14498" rel="nofollow noreferrer">https://github.com/Azure/azure-cli/issues/14498</a> <a href="https://gitanswer.com/azure-cli-az-acr-helm-commands-not-working-python-663770738" rel="nofollow noreferrer">https://gitanswer.com/azure-cli-az-acr-helm-commands-not-working-python-663770738</a> <a href="https://github.com/Azure/azure-cli/issues/14467" rel="nofollow noreferrer">https://github.com/Azure/azure-cli/issues/14467</a></p> <p>Here is the yaml script which throws error</p> <pre><code>- bash: | cd $(projectName) chartPackage=$(ls $(projectName)-$(helmChartVersion).tgz) az acr helm push \ -n $(registryName) \ -u $(registryLogin) \ -p '$(registryPassword)' \ $chartPackage Chart.yaml apiVersion: v1 description: first helm chart create name: helmApp version: v0.3.0 </code></pre>
<p>Azure has deprecated the support managing Helm charts using the Az Cli. So you will need Helm client version <code>3.7.1</code> to push the Helm charts to ACR.</p> <p>To push the Helm charts to ACR, follow the next steps:</p> <ol> <li><p>Enable OCI support</p> <pre><code>export HELM_EXPERIMENTAL_OCI=1 </code></pre> </li> <li><p>Save your chart to a local archive</p> <pre><code>cd chart-dir helm package . </code></pre> </li> <li><p>Authenticate with the registry using <code>helm registry login</code> command</p> <pre><code>helm registry login $ACR_NAME.azurecr.io \ --username $USER_NAME \ --password $PASSWORD </code></pre> </li> <li><p>Push chart to the registry as OCI artifact</p> <pre><code>helm push chart-name-0.1.0.tgz oci://$ACR_NAME.azurecr.io/helm </code></pre> </li> </ol> <p>You can use the above steps in the Azure DevOps pipeline and it will work as expected. For more info on pushing helm charts to ACR, refer to <a href="https://learn.microsoft.com/en-us/azure/container-registry/container-registry-helm-repos" rel="nofollow noreferrer">this doc</a>.</p>
<p>Question is straightforward, but I've not been able to quite figure out which steps a request follows when it reaches kubernetes system.</p> <ol> <li>Who first handle a received request? <code>Ingress Controller</code>, <code>LoadBalancer</code>, <code>ClusterIP</code>...</li> </ol> <p>So, I know there are several ways to make pods externally accessible:</p> <ol> <li>Creating a <code>NodePort</code> service.</li> <li>Creating an <code>LoadBalancer</code> service.</li> <li>Creating an <code>Ingress</code> rule.</li> </ol> <p>Some questions here related with best-practices or mandatory facts?</p> <ol> <li><p><code>Ingress</code> is in front of a <code>ClusterIP Service</code> mandatory?</p> <p>1.1 Could or shouldn't I create an <code>Ingress</code> in front of a <code>NodePort</code> or a <code>LoadBalancer</code> service?</p> </li> <li><p><code>Ingress Controllers</code> are <code>LoadBalancer Services</code>? I mean, <code>traefik</code> or other <code>Ingress Controllers</code> are all of them deployed as <code>LoadBalancer</code> services?</p> </li> </ol> <p>Misunderstanding arises from several texts I've found over there:</p> <ol> <li><a href="http://www.sandtable.com/wp-content/uploads/2016/12/New_infra-750x487.jpg" rel="nofollow noreferrer">image here</a>: Seems <code>LoadBalancer</code> is placed first of <code>Ingress Controllers</code>.</li> <li><a href="https://refactorizando.com/wp-content/uploads/2021/08/Ingress-Kubernetes-1-1024x527.png" rel="nofollow noreferrer">image here</a>: Seems <code>Ingress</code> is in front of a <code>LoadBalancer</code>.</li> </ol> <p>Above questions arises from an attempt of expose externally a <code>mongodb</code> replicatset.</p> <ol> <li>I've created a <code>LoadBalancer</code> for each node. Is this correct?</li> <li>I'd like to create a domain using my <code>Ingress Controller</code> for those <code>LoadBalancer</code>. Can this be possible?</li> <li>Is there point to create an Ingress in front of a headless service?</li> </ol>
<blockquote> <p>Ingress is in front of a ClusterIP Service mandatory?</p> </blockquote> <p>If you want the service accessible externally, then you will need an externally accessible service. This can be a LoadBalancer service or an Ingress. A ClusterIP service is not accessible outside the cluster.</p> <blockquote> <p>Could or shouldn't I create an Ingress in front of a NodePort or a LoadBalancer service?</p> </blockquote> <p>You <em>can</em> create an Ingress in front of a NodePort or LoadBalancer, but there's no point in creating an Ingress in front of a LoadBalancer unless you want two different endpoints for accessing the same service (the LoadBalancer will get one IP and the Ingress Controller's own LoadBalancer will get another IP). However, using an Ingress will allow you to have additional functionality, such as SSL Certificates, which the standard LoadBalancer service resource does not (normally) provide</p> <blockquote> <p>Ingress Controllers are LoadBalancer Services? I mean, traefik or other Ingress Controllers are all of them deployed as LoadBalancer services?</p> </blockquote> <p>Correct. An Ingress controller opens an endpoint for traffic into the cluster, and then uses the ingress resources you create in the cluster to determine how and where to route the traffic.</p> <p>The endpoint is a publicly accessible endpoint (unless you configure it to be an internal loadbalancer, in which case only machines within your corporate network will be able to access it).</p> <p>The controller will normally update the Ingress resource in your cluster so you will see the IP of the loadbalancer belonging to the ingress</p>
<p>I have attached AWS ACM provided SSL certificate to NLB. NLB will forward request to nginx ingress. Nginx is giving me the following error. <code>The plain HTTP request was sent to HTTPS port</code>. I have set the following annotation in nginx ingress.</p> <ul> <li>nginx.ingress.kubernetes.io/force-ssl-redirect: false</li> <li>nginx.ingress.kubernetes.io/ssl-redirect: false</li> </ul> <p>I have set following annotation in nginx ingress service which is running behind NLB.</p> <ul> <li>service.beta.kubernetes.io/aws-load-balancer-backend-protocol: http</li> <li>service.beta.kubernetes.io/aws-load-balancer-ssl-cert: &quot;certificate</li> <li>arn&quot; service.beta.kubernetes.io/aws-load-balancer-ssl-ports: https</li> <li>service.beta.kubernetes.io/aws-load-balancer-type: nlb</li> </ul>
<p>For this error :</p> <blockquote> <p>The plain HTTP request was sent to HTTPS port</p> </blockquote> <p>Change your port configuration in <strong>Nginx</strong> service like, your <strong>target port</strong> in <em>HTTPS</em> section should be <strong>http</strong> instead of <strong>https</strong></p> <pre><code>ports: - name: https **targetPort: http** </code></pre> <p>Here the annotation for reference</p> <pre><code>service.beta.kubernetes.io/aws-load-balancer-backend-protocol: tcp service.beta.kubernetes.io/aws-load-balancer-connection-idle-timeout: &quot;60&quot; service.beta.kubernetes.io/aws-load-balancer-cross-zone-load-balancing-enabled: &quot;true&quot; service.beta.kubernetes.io/aws-load-balancer-ssl-cert: arn:aws:acm:ap-southeast-1:xxxxxxx:certificate/8991ftt8-69e0-4e7d-1164-yy0aae19da90v service.beta.kubernetes.io/aws-load-balancer-type: nlb </code></pre>
<p>I have been trying to figure out how to consume a ConfigMap created using a ConfigMap generator via Kustomize.</p> <p>When created using Kustomize generators, the configMaps are named with a special suffix. See here:</p> <p><a href="https://kubernetes.io/docs/tasks/configure-pod-container/configure-pod-configmap/#create-a-configmap-from-generator" rel="nofollow noreferrer">https://kubernetes.io/docs/tasks/configure-pod-container/configure-pod-configmap/#create-a-configmap-from-generator</a></p> <p>Question is how can this be referenced?</p>
<p>You don't reference it yourself. Kustomize recognizes where the configMap is used in the other resources (like a Deployment) and changes those references to use the name+hash.</p> <p>The reason for this is so that if you change the configMap, Kustomize generates a new hash and updates the Deployment, causing a rolling restart of the Pods.</p> <p>If you don't want this behavior, you can add the following to your <code>kustomization.yaml</code> file:</p> <pre><code>generatorOptions: disableNameSuffixHash: true </code></pre>
<p>Here is the issue: We have several microk8s cluster running on different networks; yet each have access to our storage network where our NAS are.</p> <p>within Kubernetes, we create disks with an nfs-provisionner (nfs-externalsubdir). Some disks were created with the IP of the NAS server specified. Once we had to change the IP, we discovered that the disk was bound to the IP, and changing the IP meant creating a new storage resource within.</p> <p>To avoid this, we would like to be able to set a DNS record on the Kubernetes cluster level so we could create storage resources with the nfs provisionner based on a name an not an IP, and we could alter the DNS record when needed (when we upgrade or migrate our external NAS appliances, for instance) for instance, I'd like to tell every microk8s environnements that:</p> <p>192.168.1.4 my-nas.mydomain.local</p> <p>... like I would within the /etc/hosts file.</p> <p>Is there a proper way to achieve this? I tried to follow the advices on this link: <a href="https://stackoverflow.com/questions/37166822/is-there-a-way-to-add-arbitrary-records-to-kube-dns">Is there a way to add arbitrary records to kube-dns?</a> (the answer upvoted 15 time, the cluster-wise section), restarted a deployment, but it didn't work</p> <p>I cannot use the hostAliases feature since it isn't provided on every chart we are using, that's why I'm looking for a more global solution.</p> <p>Best Regards,</p>
<p><code>...we could create storage resources with the nfs provisionner based on a name an not an IP, and we could alter the DNS record when needed...</code></p> <p>For this you can try headless service without touching coreDNS:</p> <pre><code>apiVersion: v1 kind: Service metadata: name: my-nas namespace: kube-system # &lt;-- you can place it somewhere else labels: app: my-nas spec: ports: - protocol: TCP port: &lt;nas port&gt; --- apiVersion: v1 kind: Endpoints metadata: name: my-nas subsets: - addresses: - ip: 192.168.1.4 ports: - port: &lt;nas port&gt; </code></pre> <p>Use it as: <code>my-nas.kube-system.svc.cluster.local</code></p>
<p>I'd like to do all k8s installation, configuration, and maintenance using Helm v3 (v3.7.2).</p> <p>Thus I have setup yaml templates for:</p> <ul> <li>deployment</li> <li>configmap</li> <li>service</li> <li>ingress</li> </ul> <p>Yet I can't find any information in the Helm v3 docs on setting up an HPA (<em>HorizontalPodAutoscaler</em>). Can this be done using an hpa.yaml that pulls from values.yaml?</p>
<p>Yes. Example, try <code>helm create nginx</code> will create a template project call &quot;nginx&quot;, and inside the &quot;nginx&quot; directory you will find a templates/hpa.yaml example. Inside the values.yaml -&gt; autoscaling is what control the HPA resources:</p> <pre><code>autoscaling: enabled: false # &lt;-- change to true to create HPA minReplicas: 1 maxReplicas: 100 targetCPUUtilizationPercentage: 80 # targetMemoryUtilizationPercentage: 80 </code></pre>
<p>In some cases after a node reboot the Kubernetes cluster managed by MicroK8S cannot start pods.</p> <p>With a describe of the pod failing to be ready I could see that the pod was stuck in a &quot;Pulling image&quot; state during several minutes without any other event, as following:</p> <pre><code>Events: Type Reason Age From Message ---- ------ ---- ---- ------- Normal Scheduled 50s default-scheduler Successfully assigned default/my-service-abc to my-desktop Normal Pulling 8m kubelet Pulling image &quot;127.0.0.1:32000/some-service&quot; </code></pre> <p>Pulling from the node with <code>docker pull 127.0.0.1:32000/some-service</code> works perfectly, so it doesn't seem a problem with Docker.</p> <p>I have upgraded Docker just in case.</p> <p>I seem to run the latest version of microk8s.</p>
<p>Running a <code>sudo microk8s inspect</code> gives no error/warning, everything seemed to work perfectly.</p> <p>As a Docker pull did work locally, it's really the Kubelet app which is communicating with Docker that seemed stuck.</p> <p>Even with a <code>sudo service docker stop &amp;&amp; sudo service docker start</code> it did not work.</p> <p>Even a rollout did not suffice to get out of the Pulling state after the reboot of docker.</p> <p>Worst of all, a reboot of the server did not change anything (the pod that were up were still working, but all the other pods (70%) were down and in ContainerCreating state.</p> <p>Checking the status <code>systemctl status snap.microk8s.daemon-kubelet</code> did not report any error.</p> <p>The only thing that worked seemed to do this:</p> <p><code>sudo systemctl reboot snap.microk8s.daemon-kubelet</code></p> <p>However, it also rebooted the whole node, so that's something to do in a last case scenario (same as the node reboot).</p>
<p>K8s network policies allow specifying CIDRs, but I'd like to specify DNS name.</p> <p>On a high level I'd see it working the following way:</p> <ul> <li>There's a whitelist of allowed hosts</li> <li>k8s intercepts IP resolution requests and checks whether host is whitelisted</li> <li>if yes, resolved IPs are temporarily added to network policy thus allowing for egress traffic</li> </ul> <p>Is there any way to achieve this functionality?</p>
<p>vpc-cni does not implement k8s network policies. You need to replace vpc-cni with one of the EKS compatible CNI of your choice <a href="https://docs.aws.amazon.com/eks/latest/userguide/alternate-cni-plugins.html" rel="nofollow noreferrer">here</a> that support using FQDN in the policy. Note upgrade may be required (eg. Calico Enterprise) to have this feature.</p>
<p>In Kubernetes <code>CustomResourceDefinitions</code> (CRDs), we can specify <code>additionalPrinterColumns</code>, which (for example) are used for <code>kubectl get</code> with a CRD. The value for a column is usually extracted from the status of a CRD using a <code>jsonPath</code>. From the <a href="https://kubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definitions/#type" rel="nofollow noreferrer">Kubernetes docs</a>, we can also see that timestamps are rendered in a user friendly way (e.g., <em>5m</em> or <em>2h</em>, representing the duration from this timestamp to now):</p> <pre class="lang-yaml prettyprint-override"><code>additionalPrinterColumns: - name: Duration type: date jsonPath: .status.completitionTimestamp </code></pre> <p>The Kubernetes <em>Job</em> resource is an example for a resource, which does not only show since when it exists, but also <a href="https://kubernetes.io/docs/tasks/job/automated-tasks-with-cron-jobs/" rel="nofollow noreferrer">for long it was running</a>:</p> <pre><code>NAME COMPLETIONS DURATION AGE hello-4111706356 0/1 0s hello-4111706356 0/1 0s 0s hello-4111706356 1/1 5s 5s </code></pre> <p>I'm looking for building something similar for my CRD, that is: Showing the duration between two timestamps in the same way. More specific, I would like to get the duration between two status fields such as <code>.status.startTimestamp</code> and <code>.status.completitionTimestamp</code> evaluated and formatted by Kubernetes.</p> <p>As exactly the same thing is done in the <em>Job</em> resource, I'm wondering if this is somehow possible or if this is special behavior built into <code>kubectl</code>?</p>
<p>I will answer on your question partially so you have some understanding and ideas on what/how/where.</p> <hr /> <p><strong>kubectl get</strong></p> <p>When <code>kubectl get jobs</code> is executed, <code>kubernetes API server</code> decides which fields to provide in response:</p> <blockquote> <p>The <code>kubectl</code> tool relies on server-side output formatting. Your cluster's API server decides which columns are shown by the <code>kubectl get</code> command</p> </blockquote> <p>See <a href="https://kubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definitions/#additional-printer-columns" rel="nofollow noreferrer">here</a>.</p> <p><code>Duration</code> field for <code>jobs</code> is also calculated on the server's side. This happens because <code>job</code> is a well-known resource for kubernetes server and it's built into the code &quot;How to print the response&quot;. See <a href="https://github.com/kubernetes/kubernetes/blob/d1a5513cb044ad805007cbea6327bdfb1cc73aab/pkg/printers/internalversion/printers.go#L1031-L1046" rel="nofollow noreferrer">JobDuration - printer</a>.</p> <p>This also can be checked by running regular command:</p> <pre><code>kubectl get job job-name --v=8 </code></pre> <p>And then using <a href="https://kubernetes.io/docs/reference/kubectl/overview/#server-side-columns" rel="nofollow noreferrer"><code>server-print</code></a> flag set to <code>false</code> (default is <code>true</code> for human-readable reasons):</p> <pre><code>kubectl get job job-name --v=8 --server-print=false </code></pre> <p>With last command only general information will be returned and <code>name</code> and <code>age</code> will be shown in output.</p> <hr /> <p><strong>What can be done</strong></p> <p>Let's start with <a href="https://kubernetes.io/docs/concepts/extend-kubernetes/api-extension/custom-resources/#custom-controllers" rel="nofollow noreferrer">CRDs and controllers</a>:</p> <blockquote> <p>On their own, custom resources let you store and retrieve structured data. When you combine a custom resource with a custom controller, custom resources provide a true declarative API.</p> <p>The Kubernetes declarative API enforces a separation of responsibilities. You declare the desired state of your resource. The Kubernetes controller keeps the current state of Kubernetes objects in sync with your declared desired state. This is in contrast to an imperative API, where you instruct a server what to do.</p> </blockquote> <p>Moving forward to <a href="https://kubernetes.io/docs/reference/command-line-tools-reference/feature-gates/#feature-gates" rel="nofollow noreferrer"><code>feature gates</code></a>. We're interested in <code>CustomResourceSubresources</code>:</p> <blockquote> <p>Enable <code>/status</code> and <code>/scale</code> subresources on resources created from <code>CustomResourceDefinition</code>.</p> </blockquote> <p>This <code>feature gate</code> is enabled by default starting from kubernetes <code>1.16</code>.</p> <p>Therefore custom field like <code>duration-execution</code> could be created within CRD <code>subresource</code>'s status and custom controller could update the value of the given field whenever the value is changed using <code>watch update funtion</code>.</p> <p><strong>Part 2</strong></p> <p>There's a <a href="https://kubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definitions/#controlling-pruning" rel="nofollow noreferrer"><code>controller prunning</code></a> that should be taken into consideration:</p> <blockquote> <p>By default, all unspecified fields for a custom resource, across all versions, are pruned. It is possible though to opt-out of that for specific sub-trees of fields by adding <code>x-kubernetes-preserve-unknown-fields: true</code> in the <a href="https://kubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definitions/#specifying-a-structural-schema" rel="nofollow noreferrer">structural OpenAPI v3 validation schema</a>.</p> </blockquote> <p>Here's a very similar <a href="https://stackoverflow.com/a/66766843/15537201">answer</a> about custom field and <code>additionalPrinterColumns</code>.</p>
<p>I am attempting to setup a multi-node k8s cluster as per this <a href="https://techviewleo.com/deploy-kubernetes-cluster-on-debian-using-k0s/" rel="nofollow noreferrer">kOS Setup Link</a>, but I face the error below when I try to join one of the nodes to the master node:</p> <pre><code> k0s token create --role=worker WARN[2022-01-12 13:55:31] no config file given, using defaults Error: failed to read cluster ca certificate from /var/lib/k0s/pki/ca.crt: open /var/lib/k0s/pki/ca.crt: no such file or directory. check if the control plane is initialized on this node </code></pre> <p>I verified from the control node that this file does, exist however:</p> <pre><code>cd /var/lib/k0s/pki ls </code></pre> <p>I am new to k8s setup from scratch, and a bit unsure which configuration item I need to fix (and where between master and worker nodes?). My research shows that <em><strong>A token is required when joining a new worker node to the Kubernetes cluster -- This token is generated from the control node</strong></em>. It also says that <em><strong>When you bootstrap a cluster with kubeadm, a token is generated which expires after 24 hours</strong></em></p> <p>When I try to check for the existence of a token on master node I get:</p> <pre><code> kubeadm tokens list -bash: kubeadm: command not found </code></pre> <p>I am unsure however if this is correct ( Is k0s <em><strong>even</strong></em> bootstrapped with <code>kubeadm</code>??).</p> <p>However using k0s CLI syntax I can see that they are no tokens on the master:</p> <pre><code>k0s token list No k0s join tokens found </code></pre> <p>My question:</p> <ol> <li>What do I need to do for the file that is reporting as missing.</li> <li>Is this error (possibly) related to the issue of token above and if so do I first need to regenerate the token at the master node end.</li> <li>I have encountered multiple fixes at this <a href="https://github.com/kubernetes/kubernetes/issues/53889" rel="nofollow noreferrer">Github Issue</a> but I am not sure if any of them applies to my issue. Last thing I need is to break the current setup before I have even finished the cluster setup.</li> </ol> <p>Environment Master node : Debian 10 Buster Worker node : Debian 10 Buster</p>
<p>I've got the same error as you when I tried to run <code>k0s token create --role=worker</code> on the <strong>worker</strong> node.</p> <p>You need to run <a href="https://techviewleo.com/deploy-kubernetes-cluster-on-debian-using-k0s/" rel="nofollow noreferrer">this command on the <strong>master</strong> node</a>:</p> <blockquote> <p>Next, you need to <strong>create a join token</strong> that the worker node will use to join the cluster. This token is generated from the control node.</p> </blockquote> <p>First you need to run <code>k0s token create --role=worker</code> on the <strong>master</strong> node to get a token and later <a href="https://techviewleo.com/deploy-kubernetes-cluster-on-debian-using-k0s/" rel="nofollow noreferrer">use this token on the <strong>worker</strong> node</a>:</p> <blockquote> <p>On the worker node, issue the command below.</p> <pre><code>k0s worker &lt;login-token&gt; </code></pre> </blockquote> <p>So:</p> <ul> <li>generate a token on the <strong>master</strong> using <code>k0s token create --role=worker</code></li> <li>use this token on the <strong>worker</strong> using <code>k0s worker &lt;login-token&gt; </code></li> </ul> <p>In my case I also needed to add <code>sudo</code> before both commands, so they looked like <code>sudo k0s token create --role=worker</code> and <code>sudo k0s worker &lt;login-token&gt; </code></p> <p>You wrote:</p> <blockquote> <p>I am unsure however if this is correct ( Is k0s <em><strong>even</strong></em> bootstrapped with kubeadm ?? ).</p> </blockquote> <p>No, they are two different and independent solutions.</p>
<p>Our system runs on GKE in a VPC-native network. We've recently upgraded from v1.9 to v1.21, and when we transferred the configuration, I've noticed the spec.template.spec.affinity.nodeAffinity in out kube-dns deployment is deleted and ignored. I tried manually adding this with &quot;kubectl apply -f kube-dns-deployment.yaml&quot;</p> <p>I get &quot;deployment.apps/kube-dns configured&quot;, but after a few seconds the kube-dns reverts to a configuration without this affinity.</p> <p>This is the relevant code in the yaml:</p> <pre><code>apiVersion: apps/v1 kind: Deployment metadata: labels: addonmanager.kubernetes.io/mode: Reconcile k8s-app: kube-dns kubernetes.io/cluster-service: &quot;true&quot; name: kube-dns namespace: kube-system spec: progressDeadlineSeconds: 600 replicas: 2 revisionHistoryLimit: 10 selector: matchLabels: k8s-app: kube-dns strategy: rollingUpdate: maxSurge: 10% maxUnavailable: 0 type: RollingUpdate template: metadata: annotations: components.gke.io/component-name: kubedns prometheus.io/port: &quot;10054&quot; prometheus.io/scrape: &quot;true&quot; scheduler.alpha.kubernetes.io/critical-pod: &quot;&quot; seccomp.security.alpha.kubernetes.io/pod: runtime/default creationTimestamp: null labels: k8s-app: kube-dns spec: affinity: nodeAffinity: preferredDuringSchedulingIgnoredDuringExecution: - preference: matchExpressions: - key: cloud.google.com/gke-nodepool operator: In values: - pool-1 weight: 20 - preference: matchExpressions: - key: cloud.google.com/gke-nodepool operator: In values: - pool-3 - training-pool weight: 1 requiredDuringSchedulingIgnoredDuringExecution: nodeSelectorTerms: - matchExpressions: - key: cloud.google.com/gke-nodepool operator: In values: - pool-1 - pool-3 - training-pool podAntiAffinity: preferredDuringSchedulingIgnoredDuringExecution: - podAffinityTerm: labelSelector: matchExpressions: - key: k8s-app operator: In values: - kube-dns topologyKey: kubernetes.io/hostname weight: 100 requiredDuringSchedulingIgnoredDuringExecution: - labelSelector: matchExpressions: - key: k8s-app operator: In values: - kube-dns topologyKey: cloud.google.com/hostname containers: .... dnsPolicy: Default nodeSelector: kubernetes.io/os: linux </code></pre> <p>This is what I get when I run <em>$ kubectl get deployment kube-dns -n kube-system -o yaml</em>:</p> <pre><code>apiVersion: apps/v1 kind: Deployment metadata: annotations: .... labels: addonmanager.kubernetes.io/mode: Reconcile k8s-app: kube-dns kubernetes.io/cluster-service: &quot;true&quot; name: kube-dns namespace: kube-system resourceVersion: &quot;16650828&quot; uid: .... spec: progressDeadlineSeconds: 600 replicas: 2 revisionHistoryLimit: 10 selector: matchLabels: k8s-app: kube-dns strategy: rollingUpdate: maxSurge: 10% maxUnavailable: 0 type: RollingUpdate template: metadata: annotations: components.gke.io/component-name: kubedns prometheus.io/port: &quot;10054&quot; prometheus.io/scrape: &quot;true&quot; scheduler.alpha.kubernetes.io/critical-pod: &quot;&quot; seccomp.security.alpha.kubernetes.io/pod: runtime/default creationTimestamp: null labels: k8s-app: kube-dns spec: affinity: podAntiAffinity: preferredDuringSchedulingIgnoredDuringExecution: - podAffinityTerm: labelSelector: matchExpressions: - key: k8s-app operator: In values: - kube-dns topologyKey: kubernetes.io/hostname weight: 100 containers: ... dnsPolicy: Default nodeSelector: kubernetes.io/os: linux priorityClassName: system-cluster-critical restartPolicy: Always schedulerName: default-scheduler securityContext: fsGroup: 65534 supplementalGroups: - 65534 serviceAccount: kube-dns serviceAccountName: kube-dns terminationGracePeriodSeconds: 30 tolerations: - key: CriticalAddonsOnly operator: Exists - key: components.gke.io/gke-managed-components operator: Exists volumes: - configMap: defaultMode: 420 name: kube-dns optional: true name: kube-dns-config status: ... </code></pre> <p>As you can see, GKE just REMOVES the NodeAffinity part, as well as one part of the podAffinity.</p>
<p><a href="https://cloud.google.com/kubernetes-engine/docs/how-to/kube-dns" rel="nofollow noreferrer">kube-dns</a> is a service discovery mechanism within GKE, and the default DNS provider used by the clusters. It is managed by Google and that is why the changes are not holding, and most probably that part of the code was removed in the new version.</p> <p>If you need to apply a custom configuration, you can do that following the guide <a href="https://cloud.google.com/kubernetes-engine/docs/how-to/custom-kube-dns" rel="nofollow noreferrer">Setting up a custom kube-dns Deployment</a>.</p>
<p>I installed kubectl and tried enable shell autocompletion for zsh. When I'm using <code>kubectl</code> autocompletion works fine. Howewer when I'm trying use autocompletion with alias <code>k</code> then shell return me</p> <pre><code>k g...(eval):1: command not found: __start_kubectl  8:45 (eval):1: command not found: __start_kubectl (eval):1: command not found: __start_kubectl </code></pre> <p>In my <code>.zshrc</code> file I have:</p> <pre><code>source &lt;(kubectl completion zsh) alias k=kubectl compdef __start_kubectl k </code></pre>
<p>add the following to the beginning of your ~/.zshrc file:</p> <pre><code>autoload -Uz compinit compinit </code></pre> <p>then restart your terminal.</p>
<p>I'm trying to run/set up ingress in Minikube. But it is not happening. Here are the steps Environment:</p> <ul> <li>Windows 10 professional</li> <li>minikube version: v1.24.0</li> </ul> <br> <p><strong>Ingress enabled:</strong></p> <p>| ingress | minikube | enabled ✅ | unknown (third-party) | <br> | ingress-dns | minikube | enabled ✅ | unknown (third-party) |</p> <br> <p><strong>Create Deployment</strong></p> <pre><code> $ kubectl get deployment NAME READY UP-TO-DATE AVAILABLE AGE deployment.apps/web 1/1 1 1 9s </code></pre> <p><strong>Expose service</strong></p> <pre><code>kubectl expose deployment web --type=NodePort --port=8080 $ kubectl get svc NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE kubernetes ClusterIP 10.96.0.1 &lt;none&gt; 443/TCP 38h web NodePort 10.103.21.35 &lt;none&gt; 8080:30945/TCP 3m22s </code></pre> <p><strong>Start Service</strong></p> <pre><code>minikube service web Browser url: http://127.0.0.1:59188/ Browser content: Hello, world! Version: 1.0.0 Hostname: web-79d88c97d6-c79mp </code></pre> <p><strong>Create ingress:</strong></p> <pre><code>$ kubectl apply -f https://k8s.io/examples/service/networking/example-ingress.yaml ingress.networking.k8s.io/example-ingress unchanged $ kubectl get ingress NAME CLASS HOSTS ADDRESS PORTS AGE example-ingress nginx hello-world.info localhost 80 14h </code></pre> <p><strong>Add map hosts:</strong></p> <pre><code>&gt; in /etc/hosts &gt; 127.0.0.1 hello-world.info and in windows/system32/etc/hosts &gt; 127.0.0.1 hello-world.info </code></pre> <p><strong>Run curl command: (from a new git bash I executing the following command)</strong></p> <pre><code>$ curl hello-world.info % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 0 0 0 0 0 0 0 0 --:--:-- 0:00:02 --:--:-- 0 curl: (7) Failed to connect to hello-world.info port 80: Connection refused </code></pre> <p>In browser:</p> <pre><code> URL: http://hello-world.info/ Browser content: This site can't be reached hello-world.info refused to connect. </code></pre> <p><em><strong>not sure why I'm getting failure. Request help here.</strong></em></p>
<p>I believe there's 2 issues at play here after testing various scenarios.</p> <ol> <li>An issue with the current latest minikube, v1.24.0, which messes with the minikube ingress addon and makes the address for the ingress be localhost instead of being the same as the <code>minikube ip</code></li> <li>An issue with the docker driver which prevents the <code>minikube ip</code> from being accessible through curl and the browser.</li> </ol> <p>To resolve both of these issues I downgraded minikube to the previous version, v1.23.2, and then used the HyperV driver, after which the examples and tutorials on the Kubernetes site began to work as intended.</p> <hr /> <p>Below are the full steps I took:</p> <p>Delete any previous instances of minikube that was spun up using v1.24.0 with the same version prior to downgrading just to be safe</p> <pre><code>minikube delete </code></pre> <p>Download and replace the minikube executable with <a href="https://github.com/kubernetes/minikube/releases/tag/v1.23.2" rel="nofollow noreferrer">v1.23.2</a></p> <p>Check that you replaced the executable correctly</p> <pre><code>minikube version </code></pre> <p>Turn on HyperV in <em>Turn Windows features on or off</em></p> <p>Restart the computer</p> <p>Create a new minikube instance, but this time with HyperV</p> <pre><code>minikube start --driver=hyperv </code></pre> <p>Enable the ingress addon in minikube</p> <pre><code>minikube addons enable ingress </code></pre> <p>Deploy all the deployment, service and ingress to this new instance.</p> <p>Wait a minute or so until an address is assigned to the ingress. Once it's there, update the hosts file and route the domain to the address.</p> <p>Now check both the address and the domain via curl and/or the browser to see if the issue's resolved.</p>
<p>I want do some device initiation by using Daemonset(K8s resource).</p> <p>Actually the deivce has been formated(inside container) and mounted(inside container) successfully to a container path <code>/hostmnt/lvpmem/</code> which is mapped of <code>/mnt/</code> which is a host path.</p> <p><code>mountpoint</code> works fine in container</p> <pre><code>[root@driver-hm4ll /] #mountpoint /hostmnt/lvpmem/ /hostmnt/lvpmem/ is a mountpoint </code></pre> <p>but <code>mountpoint</code> works wrong in host env</p> <pre><code>[root@host ~]# mountpoint /mnt/lvpmem/ /mnt/lvpmem/ is not a mountpoint </code></pre> <p>Also the data I write in container under <code>/hostmnt/lvpmem/</code> can't been seen under <code>/mnt/lvpmem/</code> in host env.</p> <p>How can I mount the device so that both host and container can see it ?<br /> Also, if container is destroyed does the mount relation also be destroyed ? I have no idea about umounting the device in host env if mount relation can't be seen.<br /> Some opensource project use <code>nsenter</code> in container to run such format/mount command does it help ?</p>
<ul> <li>add /mnt as a volume to pod on directory /hostmnt. So that whatever being written under /hostmnt directory (insisde the container) will be seen on host under directory /mnt .</li> </ul> <pre><code>Example of a pod with hostpath : apiVersion: v1 kind: Pod metadata: name: test-pd spec: containers: - image: k8s.gcr.io/test-webserver name: test-container volumeMounts: - mountPath: /hostmnt name: test-volume volumes: - name: test-volume hostPath: # directory location on host path: /mnt # this field is optional type: Directory </code></pre>
<p>We have a setup where we want to run 3 replicas of our Image. Each replica will be run in independent node and corresponding pods inside it. So to summarize we will have 3 nodes in 3 separate JVMs and 3 corresponding pods. Please provide following details,</p> <ol> <li>Can we fix POD IP and hostName always?</li> <li>Can the Node IP and hostname be same as machine IP and hostname?</li> <li>Can the same Machine IP and hostname be made POD IP and hostname?</li> </ol>
<p><code>Can we fix POD IP and hostName always?</code></p> <p>There is a <code>hostname</code> field for Pod that you can use. Using static IP for Pod is possible if the CNI plugin that you used support it. For example, Calico does <a href="https://projectcalico.docs.tigera.io/networking/use-specific-ip" rel="nofollow noreferrer">support</a> this use case. You need to check your CNI manual.</p> <p><code>Can the Node IP and hostname be same as machine IP and hostname?</code></p> <p>Yes.</p> <p><code>Can the same Machine IP and hostname be made POD IP and hostname?</code></p> <p>Pod name is up to you to set, but Pod IP is always in the range of Pod CIDR which is not applicable to machine IP.</p>
<p>When I read the k8s source code, I found that both <strong>dockerService</strong> located in <code>pkg/kubelet/dockershim/docker_service.go</code> and <strong>DockerServer</strong> located in <code>pkg/kubelet/dockershim/remote/docker_server.go</code> seem to implement the interface of the <code>CRI shim server</code>.</p> <p>But I don't understand the difference between the two, why do I need to distinguish between the two?</p> <blockquote> <p>k8s version is tag 1.23.1</p> </blockquote>
<ul> <li>DockerServer simply creates <strong>dockershim grpc server</strong></li> </ul> <pre><code>// DockerServer is the grpc server of dockershim. type DockerServer struct { // endpoint is the endpoint to serve on. endpoint string // service is the docker service which implements runtime and image services. service DockerService // server is the grpc server. server *grpc.Server } ... // Start starts the dockershim grpc server. func (s *DockerServer) Start() error { glog.V(2).Infof(&quot;Start dockershim grpc server&quot;) l, err := util.CreateListener(s.endpoint) if err != nil { return fmt.Errorf(&quot;failed to listen on %q: %v&quot;, s.endpoint, err) } // Create the grpc server and register runtime and image services. s.server = grpc.NewServer() runtimeapi.RegisterRuntimeServiceServer(s.server, s.service) runtimeapi.RegisterImageServiceServer(s.server, s.service) go func() { // Use interrupt handler to make sure the server to be stopped properly. h := interrupt.New(nil, s.Stop) err := h.Run(func() error { return s.server.Serve(l) }) if err != nil { glog.Errorf(&quot;Failed to serve connections: %v&quot;, err) } }() return nil } </code></pre> <ul> <li>DockerService is the interface <strong>implement CRI remote service server</strong></li> </ul> <pre><code>// DockerService is the interface implement CRI remote service server. type DockerService interface { runtimeapi.RuntimeServiceServer runtimeapi.ImageServiceServer } // **dockerService uses dockershim service to implement DockerService**. </code></pre> <hr /> <p>BTW, are you sure you will use in the future? From the latest (5 days ago) news: <a href="https://kubernetes.io/blog/2022/01/07/kubernetes-is-moving-on-from-dockershim/" rel="nofollow noreferrer">Kubernetes is Moving on From Dockershim: Commitments and Next Steps</a>:</p> <ul> <li><strong>Kubernetes is removing dockershim in the upcoming v1.24 release.</strong></li> <li><strong>If you use Docker Engine as a container runtime for your Kubernetes cluster, get ready to migrate in 1.24</strong></li> <li><strong>Full removal is targeted in Kubernetes 1.24, in April 2022.</strong></li> <li><strong>We'll support Kubernetes version 1.23, which includes dockershim, for another year in the Kubernetes project.</strong></li> </ul>
<p>I'm deploying an <code>AKS</code> k8s cluster with terraform.</p> <p>The cluster has rbac enabled with azure active directory.</p> <p>The cluster creation goes fine and after that terraform tries to perfom some taks on the cluster like creating <code>k8s-roles</code> <code>storage classes</code>...., and fails there with an <code>Unauthorized</code> error message, like this :</p> <pre><code>module.k8s_cluster.module.infra.kubernetes_storage_class.managed-premium-retain: Creating... module.k8s_cluster.module.infra.kubernetes_cluster_role.containerlogs: Creating... module.k8s_cluster.module.infra.kubernetes_namespace.add_pod_identity: Creating... module.k8s_cluster.module.infra.kubernetes_storage_class.managed-standard-retain: Creating... module.k8s_cluster.module.infra.kubernetes_storage_class.managed-premium-delete: Creating... module.k8s_cluster.module.appgw.kubernetes_namespace.agic[0]: Creating... module.k8s_cluster.module.infra.kubernetes_storage_class.managed-standard-delete: Creating... Error: Unauthorized on .terraform/modules/k8s_cluster/modules/infra/k8s-roles.tf line 1, in resource &quot;kubernetes_cluster_role&quot; &quot;containerlogs&quot;: 1: resource &quot;kubernetes_cluster_role&quot; &quot;containerlogs&quot; { Error: Unauthorized on .terraform/modules/k8s_cluster/modules/infra/k8s-storages-classes.tf line 1, in resource &quot;kubernetes_storage_class&quot; &quot;managed-standard-retain&quot;: 1: resource &quot;kubernetes_storage_class&quot; &quot;managed-standard-retain&quot; { Error: Unauthorized on .terraform/modules/k8s_cluster/modules/infra/k8s-storages-classes.tf line 14, in resource &quot;kubernetes_storage_class&quot; &quot;managed-standard-delete&quot;: 14: resource &quot;kubernetes_storage_class&quot; &quot;managed-standard-delete&quot; { Error: Unauthorized on .terraform/modules/k8s_cluster/modules/infra/k8s-storages-classes.tf line 27, in resource &quot;kubernetes_storage_class&quot; &quot;managed-premium-retain&quot;: 27: resource &quot;kubernetes_storage_class&quot; &quot;managed-premium-retain&quot; { Error: Unauthorized on .terraform/modules/k8s_cluster/modules/infra/k8s-storages-classes.tf line 40, in resource &quot;kubernetes_storage_class&quot; &quot;managed-premium-delete&quot;: 40: resource &quot;kubernetes_storage_class&quot; &quot;managed-premium-delete&quot; { Error: Unauthorized on .terraform/modules/k8s_cluster/modules/infra/r-aad-pod-identity.tf line 5, in resource &quot;kubernetes_namespace&quot; &quot;add_pod_identity&quot;: 5: resource &quot;kubernetes_namespace&quot; &quot;add_pod_identity&quot; { Error: Unauthorized on .terraform/modules/k8s_cluster/modules/tools/agic/helm-agic.tf line 1, in resource &quot;kubernetes_namespace&quot; &quot;agic&quot;: 1: resource &quot;kubernetes_namespace&quot; &quot;agic&quot; { </code></pre> <p>As you can see these are not <code>azure</code> errors, but <code>kubernetes</code></p> <p>It seems like I don't have rights to perform the above resources creation task on the newly created cluster. What and where to do in order to grant my user account permissions for these terraform task?</p>
<p>An answer could be to change kubernetes provider configuration from</p> <pre class="lang-hcl prettyprint-override"><code>provider &quot;kubernetes&quot; { load_config_file = &quot;false&quot; host = azurerm_kubernetes_cluster.main.kube_config.0.host username = azurerm_kubernetes_cluster.main.kube_config.0.username password = azurerm_kubernetes_cluster.main.kube_config.0.password client_certificate = &quot;${base64decode(azurerm_kubernetes_cluster.main.kube_config.0.client_certificate)}&quot; client_key = &quot;${base64decode(azurerm_kubernetes_cluster.main.kube_config.0.client_key)}&quot; cluster_ca_certificate = &quot;${base64decode(azurerm_kubernetes_cluster.main.kube_config.0.cluster_ca_certificate)}&quot; } </code></pre> <p>to</p> <pre class="lang-hcl prettyprint-override"><code>provider &quot;kubernetes&quot; { load_config_file = &quot;false&quot; host = azurerm_kubernetes_cluster.main.kube_admin_config.0.host username = azurerm_kubernetes_cluster.main.kube_admin_config.0.username password = azurerm_kubernetes_cluster.main.kube_admin_config.0.password client_certificate = &quot;${base64decode(azurerm_kubernetes_cluster.main.kube_admin_config.0.client_certificate)}&quot; client_key = &quot;${base64decode(azurerm_kubernetes_cluster.main.kube_admin_config.0.client_key)}&quot; cluster_ca_certificate = &quot;${base64decode(azurerm_kubernetes_cluster.main.kube_admin_config.0.cluster_ca_certificate)}&quot; } </code></pre> <p>Note that if you disable the <code>local account</code> usage on your cluster this solution doesn't work.</p>
<p>I'm on a windows machine in a powershell prompt. I don't have the Linux commands like <code>grep</code>, <code>awk</code>.</p> <p>I have a couple of jobs that I want to delete</p> <p><a href="https://i.stack.imgur.com/80yY2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/80yY2.png" alt="enter image description here" /></a></p> <p>I'm not finding the correct syntax for deleting them such as</p> <pre><code>kubectl delete job mailmigrationjob-id699* </code></pre> <p>or</p> <pre><code>kubectl delete job where name like mailmigrationjob-id699 </code></pre>
<p>Try:</p> <pre><code>$Pattern=&quot;mailmigrationjob-id699&quot;; &amp; kubectl get job | % {&quot;$_&quot; -Split &quot; &quot;} | Select-String -Pattern $Pattern | %{ &amp; kubectl delete job $_ } </code></pre> <p>Taken from: <a href="https://gist.github.com/IAmStoxe/37f84f0898e10e1a5da23793aada3e30" rel="nofollow noreferrer">Delete all kubernetes pods by regex pattern with PowerShell</a></p>
<p>I'm trying to get logs from mysql container. I have to set the variable :</p> <blockquote> <p>&quot;SET GLOBAL general_log= 1&quot;</p> </blockquote> <p>I'm trying to set the variable by using kubernetes poststart but it's not working . Here is my config :</p> <pre><code>apiVersion: apps/v1 kind: StatefulSet metadata: name: mysql spec: selector: matchLabels: app: mysql serviceName: mysql replicas: 1 template: metadata: labels: app: mysql spec: containers: - image: mysql:5.7 name: mysql env: - name: MYSQL_ROOT_PASSWORD valueFrom: secretKeyRef: name: mysql-secret key: password lifecycle: postStart: exec: command: [&quot;/bin/bash&quot;, &quot;-c&quot;,&quot;/etc/init.d/mysql start&quot;, &quot;mysql -p${MYSQL_ROOT_PASSWORD} &lt;&lt;&lt; 'SET GLOBAL general_log= 1;'&quot; ] ports: - containerPort: 3306 name: mysql volumeMounts: - name: mysql-persistent-storage mountPath: /var/lib/mysql #The path used to mount the hostPath share inside the pod. - name: log-mysql image: alpine args: [/bin/sh, -c, &quot;tail -n+1 -f /tmp/logs/mysql-0.log&quot;] volumeMounts: - name: mysql-persistent-storage mountPath: /tmp/logs volumes: - name: mysql-persistent-storage persistentVolumeClaim: claimName: mysql-pvclaim --- apiVersion: v1 kind: Service metadata: name: mysql spec: ports: - port: 3306 selector: app: mysql </code></pre> <p>I don't have any error when I apply this config but the value of the general_log variable stay OFF and doesn't turn ON.</p> <p>PS: when I connect to my pod and manually type</p> <blockquote> <p>mysql -p${MYSQL_ROOT_PASSWORD} &lt;&lt;&lt; 'SET GLOBAL general_log= 1;'</p> </blockquote> <p>the value of the variable turn ON. I don't understand why it's not working using Poststart.</p> <p>Can I have some help ? Thanks</p>
<p>The command is excuted too early, right after the container is created and before mysqld is ready to accept commands.</p> <p>You can use a different method to achieve your goal:</p> <ul> <li>proivde a container command and use &quot;--general-log=1&quot;</li> <li>create a custom custom.cnf file with the settings and volume mount it to /etc/mysql/conf.d</li> </ul>
<p>I'm trying to monitor my app using helm prometheus <a href="https://github.com/prometheus-community/helm-charts" rel="nofollow noreferrer">https://github.com/prometheus-community/helm-charts</a>. I've installed this helm chart successfully.</p> <pre><code>prometheus-kube-prometheus-operator-5d8dcd5988-bw222 1/1 Running 0 11h prometheus-kube-state-metrics-5d45f64d67-97vxt 1/1 Running 0 11h prometheus-prometheus-kube-prometheus-prometheus-0 2/2 Running 0 11h prometheus-prometheus-node-exporter-gl4cz 1/1 Running 0 11h prometheus-prometheus-node-exporter-mxrsm 1/1 Running 0 11h prometheus-prometheus-node-exporter-twvdb 1/1 Running 0 11h </code></pre> <p>App Service and Deployment created in the same namespace, by these yml configs:</p> <pre><code>apiVersion: apps/v1 kind: Deployment metadata: name: appservice namespace: monitoring labels: app: appservice annotations: prometheus.io/scrape: 'true' prometheus.io/path: '/actuator/prometheus' spec: replicas: 1 selector: matchLabels: app: appservice template: metadata: labels: app: appservice ... </code></pre> <pre><code>apiVersion: v1 kind: Service metadata: name: appservice namespace: monitoring annotations: prometheus.io/scrape: 'true' prometheus.io/path: '/actuator/prometheus' spec: selector: app: appservice type: ClusterIP ports: - name: web protocol: TCP port: 8080 targetPort: 8080 - name: jvm-debug protocol: TCP port: 5005 targetPort: 5005 </code></pre> <p>And after app was deployed, I had created ServiceMonitor:</p> <pre><code>apiVersion: monitoring.coreos.com/v1 kind: ServiceMonitor metadata: name: appservice-servicemonitor namespace: monitoring labels: app: appservice release: prometheus-repo spec: selector: matchLabels: app: appservice # target app service namespaceSelector: matchNames: - monitoring endpoints: - port: web path: '/actuator/prometheus' interval: 15s </code></pre> <p>I expect that after adding this ServiceMonitor, my prometheus instance create new target``` like &quot;http://appservice:8080/actuator/prometheus&quot;, but it is not, new endpoints doesn't appears in prometheus UI.</p> <p>I tried to change helm values by adding additionalServiceMonitors</p> <pre><code>namespaceOverride: &quot;monitoring&quot; nodeExporter: enabled: true prometheus: enabled: true prometheusSpec: serviceMonitorSelectorNilUsesHelmValues: false serviceMonitorSelector: matchLabels: release: prometheus-repo additionalServiceMonitors: namespaceSelector: any: true replicas: 1 shards: 1 storageSpec: ... securityContext: ... nodeSelector: assignment: monitoring nodeSelector: assignment: monitoring prometheusOperator: nodeSelector: assignment: monitoring admissionWebhooks: patch: securityContext: ... securityContext: ... global: alertmanagerSpec: nodeSelector: assignment: monitoring </code></pre> <p>But it didn't help. It is really hard to say what is going wrong, no error logs, all configs applies successfully.</p>
<p>I found <a href="https://github.com/prometheus-operator/prometheus-operator/blob/main/Documentation/troubleshooting.md#troubleshooting-servicemonitor-changes" rel="nofollow noreferrer">this guide</a> very helpful.</p> <p>Please keep in mind that depending on the prometheus stack you are using labels and names can have different default values (for me, using kube-prometheus-stack, for example the secret name was prometheus-kube-prometheus-stack-prometheus instead of prometheus-k8s).</p> <p>Essential quotes:</p> <p><a href="https://i.stack.imgur.com/ArWwd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ArWwd.png" alt="ServiceMonitor references" /></a></p> <h2>Has my ServiceMonitor been picked up by Prometheus?</h2> <p>ServiceMonitor objects and the namespace where they belong are selected by the serviceMonitorSelector and serviceMonitorNamespaceSelectorof a Prometheus object. The name of a ServiceMonitor is encoded in the Prometheus configuration, so you can simply grep whether it is present there. The configuration generated by the Prometheus Operator is stored in a Kubernetes Secret, named after the Prometheus object name prefixed with prometheus- and is located in the same namespace as the Prometheus object. For example for a Prometheus object called k8s one can find out if the ServiceMonitor named my-service-monitor has been picked up with:</p> <pre><code>kubectl -n monitoring get secret prometheus-k8s -ojson | jq -r '.data[&quot;prometheus.yaml.gz&quot;]' | base64 -d | gunzip | grep &quot;my-service-monitor </code></pre>
<p>This is my configMap. I'm trying to specify [mysqld] config, but when I use this file alone with</p> <pre><code>helm upgrade -i eramba bitnami/mariadb --set auth.rootPassword=eramba,auth.database=erambadb,initdbScriptsConfigMap=eramba,volumePermissions.enabled=true,primary.persistence.existingClaim=eramba-storage --namespace eramba-1 --set mariadb.volumePermissions.enabled=true </code></pre> <p>I don't see the specified configurations in my db pod; however, I do see the c2.8.1.sql file applied tho.</p> <pre><code>apiVersion: v1 kind: ConfigMap metadata: name: eramba namespace: eramba-1 data: my.cnf: |- [mysqld] max_connections = 2000 sql_mode=&quot;&quot; max_allowed_packet=&quot;128000000&quot; innodb_lock_wait_timeout=&quot;200&quot; c2.8.1.sql: | CREATE DATABASE IF NOT EXISTS erambadb; #create user 'erambauser'@'eramba-mariadb' identified by 'erambapassword'; #grant all on erambadb.* to 'erambauser'@'eramba-mariadb'; #flush privileges; USE erambadb; # # SQL Export # Created by Querious (201067) # Created: 22 October 2019 at 17:39:48 CEST # Encoding: Unicode (UTF-8) # SET @PREVIOUS_FOREIGN_KEY_CHECKS = @@FOREIGN_KEY_CHECKS; SET FOREIGN_KEY_CHECKS = 0; ..... </code></pre>
<p>If you look at <a href="https://github.com/bitnami/charts/blob/master/bitnami/mariadb/values.yaml" rel="nofollow noreferrer">values.yaml</a> file for MariaDB helm chart, you can see 3 types of ConfigMap:</p> <ul> <li>initdbScriptsConfigMap - to supply Init scripts to be run at first boot of DB instance</li> <li>primary.existingConfigmap - to control MariaDB Primary instance configuration</li> <li>secondary.existingConfigmap - to control MariaDB Secondary instance configuration</li> </ul> <p>Thus, each of them is intended for the specific purpose and it is not a good idea to mix these settings in one ConfigMap.</p> <p>I recommend you to create new ConfigMap eramba2 for custom <code>my.cnf</code> with all necessary values (not only new) as below.</p> <pre><code> apiVersion: v1 kind: ConfigMap metadata: name: eramba2 namespace: eramba-1 data: my.cnf: |- [mysqld] skip-name-resolve explicit_defaults_for_timestamp max_connections = 2000 sql_mode=&quot;&quot; innodb_lock_wait_timeout=&quot;200&quot; basedir=/opt/bitnami/mariadb plugin_dir=/opt/bitnami/mariadb/plugin port=3306 socket=/opt/bitnami/mariadb/tmp/mysql.sock tmpdir=/opt/bitnami/mariadb/tmp max_allowed_packet=128000000 bind-address=:: pid-file=/opt/bitnami/mariadb/tmp/mysqld.pid log-error=/opt/bitnami/mariadb/logs/mysqld.log character-set-server=UTF8 collation-server=utf8_general_ci [client] port=3306 socket=/opt/bitnami/mariadb/tmp/mysql.sock default-character-set=UTF8 plugin_dir=/opt/bitnami/mariadb/plugin [manager] port=3306 socket=/opt/bitnami/mariadb/tmp/mysql.sock pid-file=/opt/bitnami/mariadb/tmp/mysqld.pid </code></pre> <p>Create eramba2 ConfigMap:</p> <pre><code>kubectl create -f eramba2.yaml </code></pre> <p>And then create MariaDB with helm using new ConfigMap eramba2:</p> <pre><code>helm upgrade -i eramba bitnami/mariadb --set auth.rootPassword=eramba,auth.database=erambadb,initdbScriptsConfigMap=eramba,volumePermissions.enabled=true,primary.persistence.existingClaim=eramba-storage,mariadb.volumePermissions.enabled=true,primary.existingConfigmap=eramba2 --namespace eramba-1 </code></pre> <p>Connect to pod:</p> <pre><code>kubectl exec -it eramba-mariadb-0 -- /bin/bash </code></pre> <p>Check my.cnf file:</p> <pre><code>cat /opt/bitnami/mariadb/conf/my.cnf </code></pre>
<p>! StartHost failed, but will try again: creating host: create: precreate: This computer doesn't have VT-X/AMD-v enabled. Enabling it in the BIOS is mandatory</p> <p>I am getting this issue when I am executing the [minikube start --driver=virtualbox] command in my windows machine. I have already enable the VT-X/AMD-v in my machine.</p>
<p>minikube start --no-vtx-check</p> <p>This command create the kubertenes cluster with out any error.</p>
<p>I'm attempting to read the contents of a Kubernetes Secret using <code>kube-rs</code>. The secret contains a key named &quot;apiKey&quot;.</p> <p>I seem to be able to pull the secret from the kube-apiserver (debug logging shows the correct contents of the secret) but I can't get to the value itself as it's returned as a <code>ByteString</code>.</p> <p>I can't find a way to convert the <code>ByteString</code> to a <code>String</code>.</p> <p>Could anyone kindly shed some light on this? My code is below, including my failed attempts and the related error messages.</p> <pre><code>use kube::{Client, api::{Api, ResourceExt, ListParams, PostParams}}; use k8s_openapi::api::core::v1::Secret; use bytes::Bytes; use std::collections::BTreeMap; use k8s_openapi::ByteString; async fn get_credentials_from_secret(secret_namespace: &amp;String, secret_name: &amp;String) -&gt; Result&lt;String, kube::Error&gt; { let client = Client::try_default().await?; let secrets: Api&lt;Secret&gt; = Api::namespaced(client, secret_namespace); let secret: Secret = secrets.get(secret_name).await?; let secret_data: BTreeMap&lt;String, ByteString&gt; = secret.data.unwrap(); let api_key = &amp;secret_data[&quot;apiKey&quot;]; println!(&quot;{:?}&quot;, api_key); // This prints 'ByteString([97, 112, 105, 107, 101, 121])' // let api_key_string: String = api_key.into(); // the trait `From&lt;&amp;ByteString&gt;` is not implemented for `std::string::String` // let api_key_slice = api_key.as_slice(); // method not found in `&amp;ByteString // let api_key_string: String = api_key.serialize(); // method not found in `&amp;ByteString` // let api_key_string = String::from(api_key); // the trait `From&lt;&amp;ByteString&gt;` is not implemented for `std::string::String` Ok(&quot;Secret data here ideally!&quot;.to_string()) } </code></pre>
<p>I faced the same issue. I saw that it had some serialization traits at <a href="https://docs.rs/k8s-openapi/0.13.1/src/k8s_openapi/lib.rs.html#482-506" rel="nofollow noreferrer">https://docs.rs/k8s-openapi/0.13.1/src/k8s_openapi/lib.rs.html#482-506</a>, so I resorted to using the <code>serde_json</code> crate which worked just fine.</p> <pre><code>use k8s_openapi::ByteString; ... let some_byte_str = ByteString(&quot;foobar&quot;.as_bytes().to_vec()); serde_json::to_string(&amp;some_byte_str).unwrap(); </code></pre>
<p>I have deployment my kubernetes cluster v1.23.1 with kubeadm and configured it with the keycloak identity provider for authentication.</p> <p>API server configuration for keycloak IDP</p> <pre><code>... - --oidc-issuer-url=https://kubemaster:8443/auth/realms/local - --oidc-client-id=gatekeeper - --oidc-username-claim=name - --oidc-groups-claim=groups - --oidc-ca-file=/etc/kubernetes/ssl/kubemaster.crt ... </code></pre> <p>I am running oauth2-proxy in another pod which authenticates with keycloak idp and provides the tokens (id_token). Here is my oauth2-proxy deployment with the service to expose it.</p> <pre><code>--- kind: Deployment apiVersion: apps/v1 metadata: labels: k8s-app: oauth2-proxy name: oauth2-proxy namespace: kubernetes-dashboard spec: replicas: 1 revisionHistoryLimit: 10 selector: matchLabels: k8s-app: oauth2-proxy template: metadata: labels: k8s-app: oauth2-proxy spec: containers: - name: oauth2-proxy image: quay.io/oauth2-proxy/oauth2-proxy:latest imagePullPolicy: Always ports: - containerPort: 4180 protocol: TCP args: - --provider=oidc - --email-domain=* - --http-address=0.0.0.0:4180 env: - name: OAUTH2_PROXY_OIDC_ISSUER_URL value: https://192.168.122.54:8443/auth/realms/local - name: OAUTH2_PROXY_REDIRECT_URL value: https://kubernetes-dashboard.localdev.me:8081/oauth2/callback - name: OAUTH2_PROXY_CLIENT_ID value: gatekeeper - name: OAUTH2_PROXY_CLIENT_SECRET value: jZzvJ0wCDDwltV3tAf0SXSbVoKXM1RqV - name: OAUTH2_PROXY_COOKIE_SECRET value: kgKUT3IMmESA81VWXvRpYIYwMSo1xndwIogUks6IS00= - name: OAUTH2_PROXY_UPSTREAM value: https://kubernetes-dashboard - name: OAUTH2_PROXY_SSL_INSECURE_SKIP_VERIFY value: &quot;true&quot; - name: OAUTH2_PROXY_COOKIE_DOMAIN value: .localdev.me - name: OAUTH2_PROXY_INSECURE_OIDC_ALLOW_UNVERIFIED_EMAIL value: &quot;true&quot; - name: OAUTH2_PROXY_PASS_AUTHORIZATION_HEADER value: &quot;true&quot; - name: OAUTH2_PROXY_SSL_UPSTREAM_INSECURE_SKIP_VERIFY value: &quot;true&quot; - name: OAUTH2_PROXY_OIDC_EMAIL_CLAIM value: email - name: OAUTH2_PROXY_GROUPS_CLAIM value: groups - name: OAUTH2_PROXY_ALLOWED_GROUPS value: developers --- kind: Service apiVersion: v1 metadata: labels: k8s-app: oauth2-proxy name: oauth2-proxy namespace: kubernetes-dashboard spec: #type: NodePort ports: - port: 4180 targetPort: 4180 name: http selector: k8s-app: oauth2-proxy </code></pre> <p>I have nginx ingress deployed in front to route the request to oauth2-proxy as shown below.</p> <pre><code>--- apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: oauth-proxy namespace: kubernetes-dashboard annotations: nginx.ingress.kubernetes.io/rewrite-target: / spec: ingressClassName: nginx rules: - host: kubernetes-dashboard.localdev.me http: paths: - path: / pathType: Prefix backend: service: name: oauth2-proxy port: number: 4180 tls: - hosts: - kubernetes-dashboard.localdev.me secretName: kubernetes-dashboard-ingress-tls </code></pre> <p>I am using port forward from localhost to ingress resource on port 443.</p> <pre><code>kubectl port-forward --namespace=ingress-nginx service/ingress-nginx-controller 8081:443 </code></pre> <p>The issue currently i am facing is i am able to launch the url - <a href="https://kubernetes-dashboard.localdev.me:8081/" rel="nofollow noreferrer">https://kubernetes-dashboard.localdev.me:8081/</a> which routes to oauth2 proxy page from there i am able to launch the keycloak realm login page which i can authenticate. But once the keycloak authentication is successfully done i am not able to load the upstream which is kubernetes-dashboard service with the id_token. Instead i am getting a 404 not found for <a href="https://kubernetes-dashboard.localdev.me:8081/" rel="nofollow noreferrer">https://kubernetes-dashboard.localdev.me:8081/</a></p> <p>oauth2-proxy Log details</p> <pre><code>[2022/01/04 19:06:24] [oauthproxy.go:866] No valid authentication in request. Initiating login. 192.168.1.169:33826 - 48490760d6e0fc519e13d3158878112a - - [2022/01/04 19:06:24] kubernetes-dashboard.localdev.me:8081 GET - &quot;/&quot; HTTP/1.1 &quot;Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:95.0) Gecko/20100101 Firefox/95.0&quot; 403 8033 0.000 [2022/01/04 19:06:25] [oauthproxy.go:866] No valid authentication in request. Initiating login. 192.168.1.169:33826 - a87fbdc228026d99e6fc9f29d9ffc6df - - [2022/01/04 19:06:25] kubernetes-dashboard.localdev.me:8081 GET - &quot;/favicon.ico&quot; HTTP/1.1 &quot;Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:95.0) Gecko/20100101 Firefox/95.0&quot; 403 8044 0.000 192.168.1.169:33826 - 3c052e49f9f77e89c561f3d0bef47fed - - [2022/01/04 19:06:43] kubernetes-dashboard.localdev.me:8081 GET - &quot;/oauth2/start?rd=%2F&quot; HTTP/1.1 &quot;Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:95.0) Gecko/20100101 Firefox/95.0&quot; 302 356 0.000 192.168.1.169:33826 - a16b9b1b22ec03e58b9b930caa325f5b - alice@stack.com [2022/01/04 19:06:55] [AuthSuccess] Authenticated via OAuth2: Session{email:alice@stack.com user:52ed0190-4d9c-4749-90f4-37e5896bdc42 PreferredUsername:alice token:true id_token:true created:2022-01-04 19:06:55.77587057 +0000 UTC m=+290.895007232 expires:2022-01-04 19:11:55.775499536 +0000 UTC m=+590.894636200 refresh_token:true groups:[developers]} 192.168.1.169:33826 - a16b9b1b22ec03e58b9b930caa325f5b - - [2022/01/04 19:06:55] kubernetes-dashboard.localdev.me:8081 GET - &quot;/oauth2/callback?state=HBDoNuX3mudlwQrjdEkxYP9yjgHn5_mqOXk8T-G21dg%3A%2F&amp;session_state=e928739a-c94d-49ba-80a9-a1f83a936bf1&amp;code=9a592559-236c-4896-86b4-ba8f657821e6.e928739a-c94d-49ba-80a9-a1f83a936bf1.b7b62a18-269b-480a-b5bd-ad3c16f94394&quot; HTTP/1.1 &quot;Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:95.0) Gecko/20100101 Firefox/95.0&quot; 302 24 0.030 192.168.1.169:33826 - 9288833c2f8e82f2ad94c6260bcf68c7 - alice@stack.com [2022/01/04 19:06:55] kubernetes-dashboard.localdev.me:8081 GET - &quot;/&quot; HTTP/1.1 &quot;Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:95.0) Gecko/20100101 Firefox/95.0&quot; 404 19 0.000 </code></pre> <p>Ingress controller logs</p> <pre><code>127.0.0.1 - - [04/Jan/2022:19:02:26 +0000] &quot;GET / HTTP/2.0&quot; 404 19 &quot;-&quot; &quot;Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:95.0) Gecko/20100101 Firefox/95.0&quot; 2842 0.001 [kubernetes-dashboard-oauth2-proxy-4180] [] 192.168.1.177:4180 19 0.000 404 d19c25394498799f5024567ddd1fafcd 127.0.0.1 - - [04/Jan/2022:19:06:24 +0000] &quot;GET / HTTP/2.0&quot; 403 8033 &quot;-&quot; &quot;Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:95.0) Gecko/20100101 Firefox/95.0&quot; 297 0.001 [kubernetes-dashboard-oauth2-proxy-4180] [] 192.168.1.177:4180 8060 0.000 403 48490760d6e0fc519e13d3158878112a 127.0.0.1 - - [04/Jan/2022:19:06:25 +0000] &quot;GET /favicon.ico HTTP/2.0&quot; 403 8044 &quot;https://kubernetes-dashboard.localdev.me:8081/&quot; &quot;Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:95.0) Gecko/20100101 Firefox/95.0&quot; 102 0.003 [kubernetes-dashboard-oauth2-proxy-4180] [] 192.168.1.177:4180 8071 0.004 403 a87fbdc228026d99e6fc9f29d9ffc6df 127.0.0.1 - - [04/Jan/2022:19:06:43 +0000] &quot;GET /oauth2/start?rd=%2F HTTP/2.0&quot; 302 356 &quot;https://kubernetes-dashboard.localdev.me:8081/&quot; &quot;Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:95.0) Gecko/20100101 Firefox/95.0&quot; 32 0.001 [kubernetes-dashboard-oauth2-proxy-4180] [] 192.168.1.177:4180 356 0.000 302 3c052e49f9f77e89c561f3d0bef47fed 127.0.0.1 - - [04/Jan/2022:19:06:55 +0000] &quot;GET /oauth2/callback?state=HBDoNuX3mudlwQrjdEkxYP9yjgHn5_mqOXk8T-G21dg%3A%2F&amp;session_state=e928739a-c94d-49ba-80a9-a1f83a936bf1&amp;code=9a592559-236c-4896-86b4-ba8f657821e6.e928739a-c94d-49ba-80a9-a1f83a936bf1.b7b62a18-269b-480a-b5bd-ad3c16f94394 HTTP/2.0&quot; 302 24 &quot;-&quot; &quot;Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:95.0) Gecko/20100101 Firefox/95.0&quot; 351 0.031 [kubernetes-dashboard-oauth2-proxy-4180] [] 192.168.1.177:4180 24 0.028 302 a16b9b1b22ec03e58b9b930caa325f5b 127.0.0.1 - - [04/Jan/2022:19:06:55 +0000] &quot;GET / HTTP/2.0&quot; 404 19 &quot;-&quot; &quot;Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:95.0) Gecko/20100101 Firefox/95.0&quot; 2827 0.001 [kubernetes-dashboard-oauth2-proxy-4180] [] 192.168.1.177:4180 19 0.004 404 9288833c2f8e82f2ad94c6260bcf68c7 </code></pre> <p>Please suggest on how i can route the authenticated session with id_token to kubernetes dashboard service for loading the dashboard.</p>
<p>I was finally able to resolve my issue with some updates to my yaml definition files.</p> <p>Assuming you have a kubernetes cluster installed v1.23.1 with kubeadm on Ubuntu 20.04 and setup networking with flannel networking --pod-network-cidr=10.244.0.0/16. Also you have the keycloak oidc service setup (image - quay.io/keycloak/keycloak:16.1.0). Here are the updated yml definition files which helped me to resolve this issue.</p> <p>Ingress controller applied -</p> <pre><code>kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-v1.1.0/deploy/static/provider/cloud/deploy.yaml </code></pre> <p>kubernetes dashboard applied -</p> <pre><code>kubectl apply -f https://raw.githubusercontent.com/kubernetes/dashboard/v2.4.0/aio/deploy/recommended.yaml </code></pre> <p>oauth2-proxy.yml</p> <pre><code>apiVersion: apps/v1 kind: Deployment metadata: labels: k8s-app: oauth2-proxy name: oauth2-proxy namespace: kubernetes-dashboard spec: replicas: 1 selector: matchLabels: k8s-app: oauth2-proxy template: metadata: labels: k8s-app: oauth2-proxy spec: containers: - args: - --provider=oidc - --email-domain=* - --http-address=0.0.0.0:4180 env: - name: OAUTH2_PROXY_OIDC_ISSUER_URL value: https://kubemaster:8443/auth/realms/local - name: OAUTH2_PROXY_REDIRECT_URL value: https://&lt;FQDN&gt;/oauth2/callback - name: OAUTH2_PROXY_CLIENT_ID value: gatekeeper - name: OAUTH2_PROXY_CLIENT_SECRET value: jZzvJ0wCDDwltV3tAf0SXSbVoKXM1RqV - name: OAUTH2_PROXY_COOKIE_SECRET value: kgKUT3IMmESA81VWXvRpYIYwMSo1xndwIogUks6IS00= - name: OAUTH2_PROXY_UPSTREAM value: https://kubernetes-dashboard - name: OAUTH2_PROXY_SSL_INSECURE_SKIP_VERIFY value: &quot;true&quot; - name: OAUTH2_PROXY_INSECURE_OIDC_ALLOW_UNVERIFIED_EMAIL value: &quot;true&quot; - name: OAUTH2_PROXY_PASS_AUTHORIZATION_HEADER value: &quot;true&quot; - name: OAUTH2_PROXY_SSL_UPSTREAM_INSECURE_SKIP_VERIFY value: &quot;true&quot; - name: OAUTH2_PROXY_OIDC_EMAIL_CLAIM value: email - name: OAUTH2_PROXY_GROUPS_CLAIM value: groups - name: OAUTH2_PROXY_ALLOWED_GROUPS value: developers - name: OAUTH2_PROXY_SKIP_PROVIDER_BUTTON value: &quot;true&quot; - name: OAUTH2_PROXY_SET_AUTHORIZATION_HEADER value: &quot;true&quot; image: quay.io/oauth2-proxy/oauth2-proxy:latest imagePullPolicy: Always name: oauth2-proxy ports: - containerPort: 4180 protocol: TCP </code></pre> <p>dashboard-ingress.yml</p> <pre><code>apiVersion: networking.k8s.io/v1 kind: Ingress metadata: annotations: nginx.ingress.kubernetes.io/auth-url: &quot;https://$host/oauth2/auth&quot; nginx.ingress.kubernetes.io/auth-signin: &quot;https://$host/oauth2/start?rd=$escaped_request_uri&quot; nginx.ingress.kubernetes.io/backend-protocol: &quot;HTTPS&quot; nginx.ingress.kubernetes.io/auth-response-headers: &quot;authorization&quot; name: external-auth-oauth2 namespace: kubernetes-dashboard spec: ingressClassName: nginx rules: - host: __INGRESS_HOST__ http: paths: - path: / pathType: Prefix backend: service: name: kubernetes-dashboard port: number: 443 --- apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: oauth2-proxy namespace: kubernetes-dashboard spec: ingressClassName: nginx rules: - host: __INGRESS_HOST__ http: paths: - path: /oauth2 pathType: Prefix backend: service: name: oauth2-proxy port: number: 4180 tls: - hosts: - __INGRESS_HOST__ secretName: __INGRESS_SECRET__ </code></pre> <p>The issue with keycloak oidc provider its unable to set the Authroization header for which we need to manaully add the set authorization header in the oauth2-proxy defintion and also this header need to be appended in the response from the ingress to the upstream kubernetes dashboard by setting annotation - nginx.ingress.kubernetes.io/auth-response-headers: &quot;authorization&quot;</p> <p>Also adding a reference for kubernetes dashboard authentication using github oauth2 which i was following to resolve this issue.</p> <pre><code>https://kubernetes.github.io/ingress-nginx/examples/auth/oauth-external-auth/#example-oauth2-proxy-kubernetes-dashboard </code></pre>
<p>I'm trying to use pod's lifecycle event. Problem is that command from <code>preStop</code> doesn't run at all. Is there any way to monitor if it was started? Log of the container is empty. </p> <pre><code> lifecycle: preStop: exec: command: [ "/bin/sh", "-c", "/clean.sh" ] </code></pre>
<p>I was looking for something, so I added some logging that help to see the logs of the script in the pod's stdout/stderr logs.</p> <p>so for me, this approach help me</p> <ul> <li>To write logs to the centralized logging system (help me to check logs in datadog)</li> <li>Verify the script is executed properly</li> </ul> <pre><code> lifecycle: preStop: exec: command: [&quot;/bin/sh&quot;, &quot;-c&quot;, &quot;/clean.sh &gt; /proc/1/fd/1&quot;] </code></pre> <p>and was able to verify the logs</p> <pre><code>kubectl get pods kubectl logs -f my_stohook_pod </code></pre> <p><code>/proc/PID/fd/1</code> will help us to redirect script logs stdout/stderr of the container main process.</p>
<p>I am looking for a way to do something like that</p> <pre><code>kubectl get pods -l app=foo | kubectl delete </code></pre> <p>I think this would be a great way to deal with multiple ressources at once, but I cannot find a reasonably easy way to do this.</p>
<p>You may use command substitution:</p> <pre><code>Kubectl delete $(kubectl get pod -l app=foo -o name) </code></pre>
<p>I have Kubernetes cluster set up and managed by AKS, and I have access to it with the python client.</p> <p>Thing is that when I'm trying to send patch scale request, I'm getting an error.</p> <p>I've found information about scaling namespaced deployments from python client in the GitHub docs, but it was not clear what is the body needed in order to make the request work:</p> <pre><code># Enter a context with an instance of the API kubernetes.client with kubernetes.client.ApiClient(configuration) as api_client: # Create an instance of the API class api_instance = kubernetes.client.AppsV1Api(api_client) name = 'name_example' # str | name of the Scale namespace = 'namespace_example' # str | object name and auth scope, such as for teams and projects body = None # object | pretty = 'pretty_example' # str | If 'true', then the output is pretty printed. (optional) dry_run = 'dry_run_example' # str | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed (optional) field_manager = 'field_manager_example' # str | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). (optional) force = True # bool | Force is going to \&quot;force\&quot; Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. (optional) try: api_response = api_instance.patch_namespaced_deployment_scale(name, namespace, body, pretty=pretty, dry_run=dry_run, field_manager=field_manager, force=force) pprint(api_response) except ApiException as e: print(&quot;Exception when calling AppsV1Api-&gt;patch_namespaced_deployment_scale: %s\n&quot; % e) </code></pre> <p>So when running the code I'm getting <code>Reason: Unprocessable Entity</code></p> <p>Does anyone have any idea in what format should the body be? For example if I want to scale the deployment to 2 replicas how can it be done?</p>
<p>The <code>body</code> argument to the <code>patch_namespaced_deployment_scale</code> can be a <a href="http://jsonpatch.com/" rel="noreferrer">JSONPatch</a> document, as @RakeshGupta shows in the comment, but it can also be a partial resource manifest. For example, this works:</p> <pre><code>&gt;&gt;&gt; api_response = api_instance.patch_namespaced_deployment_scale( ... name, namespace, ... [{'op': 'replace', 'path': '/spec/replicas', 'value': 2}]) </code></pre> <p>(Note that the <code>value</code> needs to be an integer, not a string as in the comment.)</p> <p>But this also works:</p> <pre><code>&gt;&gt;&gt; api_response = api_instance.patch_namespaced_deployment_scale( ... name, namespace, ... {'spec': {'replicas': 2}}) </code></pre>
<p>Background: Have approx 50 nodes &quot;behind&quot; a namespace. Meaning that a given Pod in this namespace can land on any of those 50 nodes.</p> <p>The task is to test if an outbound firewall rule (in a FW outside the cluster) has been implemented correctly. Therefore I would like to test a command <strong>on each potential node</strong> in the namespace which will tell me if I can reach my target from the given node. (using <code>curl</code> for such test but that is besides the point for my question)</p> <p>I can create a small containerized app which will exit 0 on success. Then next step would be execute this on each potential node and harvest the result. How to do that?</p> <p>(I don't have access to the nodes directly, only indirectly via Kubernetes/OpenShift. I only have access to the namespace-level, not the cluster-level.)</p>
<p>The underlying node firewall settings is NOT control by K8s network policies. To test network connectivity in a namespace you only need to run 1 pod in that namespace. To test firewall settings of the node you typically ssh into the node and execute command to test - while this is possible with K8s but that would require the pod to run with root privileged; which not applicable to you as you only has access to a single namespace.</p>
<p>I was following a guide to connect a database to kubernetes: <a href="https://itnext.io/basic-postgres-database-in-kubernetes-23c7834d91ef" rel="nofollow noreferrer">https://itnext.io/basic-postgres-database-in-kubernetes-23c7834d91ef</a></p> <p>after installing Kubernetes (minikube) on Windows 10 64 bit: <a href="https://minikube.sigs.k8s.io/docs/start/" rel="nofollow noreferrer">https://minikube.sigs.k8s.io/docs/start/</a></p> <p>I am encountering an issue with 'base64' where the DB is trying to connect and store the password. As PowerShell doesn't recognise it. I was wondering if anyone has any ideas how I could either fix this and still use windows or an alternative means that would enable me to continue with the rest of the guide?</p> <p>Error Code:</p> <pre><code>base64 : The term 'base64' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:131 + ... postgresql -o jsonpath=&quot;{.data.postgresql-password}&quot; | base64 --decod ... + ~~~~~~ + CategoryInfo : ObjectNotFound: (base64:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException export : The term 'export' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + export POSTGRES_PASSWORD=$(kubectl get secret --namespace default pos ... + ~~~~~~ + CategoryInfo : ObjectNotFound: (export:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException </code></pre> <p><a href="https://i.stack.imgur.com/veiUJ.png" rel="nofollow noreferrer">Windows Powershell Error message</a></p>
<p>The <code>base64</code> cli found in Mac OS and some *nix distros is not available on Windows.</p> <p>You <em>could</em> write a small function named <code>base64</code> that mimics the behavior of the <code>base64</code> unix tool though:</p> <pre><code>function base64 { # enumerate all pipeline input $input |ForEach-Object { if($MyInvocation.UnboundArguments -contains '--decode'){ # caller supplied `--decode`, so decode $bytes = [convert]::FromBase64String($_) [System.Text.Encoding]::ASCII.GetString($bytes) } else { # default mode, encode ascii text as base64 $bytes = [System.Text.Encoding]::ASCII.GetBytes($_) [convert]::ToBase64String($bytes) } } } </code></pre> <p>This should work as a drop-in replacement for conversion between ASCII/UTF7 text and base64:</p> <pre><code>PS ~&gt; 'Hello, World!' |base64 --encode SGVsbG8sIFdvcmxkIQ== PS ~&gt; 'Hello, World!' |base64 --encode |base64 --decode Hello, World! </code></pre> <hr /> <p>To use with your existing scripts, simple dot-source a script with the function definition in your shell before executing the others:</p> <pre><code>PS ~&gt; . .\path\to\base64.ps1 </code></pre> <p>The above will work from a script as well. If you have a multi-line paste-aware shell (Windows' default Console Host with PSReadLine should be okay), you can also just paste the function definition directly into the prompt :)</p>
<p>I'm new with Prometheus and I have simple flask app in Kubernetes cluster also I have Prometheus-Monitoring-Grafana services in cluster too in namespace calles <code>prometheus-monitoring</code>. But the problem is when I create ServiceMonitor via .yaml file to connect my app to monitor with Prometheus I see that targets is not added but in config i see that job was added. But status in Prometheus - Service Discovery is Dropped.</p> <p>A have no idea why my service is not connect to serviceMonitor</p> <p><code>serviceMonitor/default/monitoring-webapp/0 (0 / 2 active targets)</code></p> <p><code>app.py</code></p> <pre><code>app = Flask(__name__) metrics = PrometheusMetrics(app) @app.route('/api') def index(): return 'ok' </code></pre> <p><code>deployment.yaml</code></p> <pre><code>apiVersion: apps/v1 kind: Deployment metadata: name: webapp-deployment labels: app: webapp spec: replicas: 1 selector: matchLabels: app: webapp template: metadata: labels: app: webapp spec: containers: - name: webapp image: dmitriy83/flask_one:latest imagePullPolicy: Always resources: requests: memory: &quot;64Mi&quot; cpu: &quot;250m&quot; limits: memory: &quot;128Mi&quot; cpu: &quot;500m&quot; ports: - containerPort: 5000 env: - name: flask_url value: http://flasktwo-service:5003 imagePullSecrets: - name: dockersecret --- apiVersion: v1 kind: Service metadata: name: webapp-service spec: selector: app: webapp ports: - name: service protocol: TCP port: 5000 targetPort: 5000 --- apiVersion: monitoring.coreos.com/v1 kind: ServiceMonitor metadata: name: monitoring-webapp labels: release: prometheus-monitoring app: webapp spec: endpoints: - path: /metrics port: service targetPort: 5000 namespaceSelector: matchNames: - default selector: matchLabels: app: webapp </code></pre>
<p>Finally i figured it out. The issue was port name. Please find workable solution below</p> <p><code>deployment.yaml</code></p> <pre><code>apiVersion: apps/v1 kind: Deployment metadata: name: webapp labels: component: backend instance: app name: containers-my-app namespace: default spec: selector: matchLabels: component: backend instance: app name: containers-my-app template: metadata: labels: component: backend instance: app name: containers-my-app spec: containers: - name: app image: dmitriy83/flask_one:latest imagePullPolicy: IfNotPresent ports: - containerPort: 5000 name: webapp imagePullSecrets: - name: myregistrykey </code></pre> <p><code>service.yaml</code></p> <pre><code>apiVersion: v1 kind: Service metadata: name: webapp labels: component: backend instance: app name: containers-my-app namespace: default spec: type: ClusterIP ports: - name: http port: 5000 protocol: TCP targetPort: webapp # one of the major thing w/o it you could not have active targets in Prometheus selector: component: backend instance: app name: containers-my-app </code></pre> <p>finally <code>monitor.yaml</code></p> <pre><code>apiVersion: monitoring.coreos.com/v1 kind: ServiceMonitor metadata: name: webapp-super labels: component: backend instance: app name: containers-my-app release: kube-prometheus-stack # You need to verify what is your realease name pf prometheus namespace: prometheus-monitoring # choose in what name space your prometheus is spec: namespaceSelector: matchNames: - default selector: matchLabels: component: backend instance: app name: containers-my-app endpoints: - port: http # http - is a port name which was put in service.yaml </code></pre>
<p>I have a .pfx file that a Java container needs to use.</p> <p>I have created a tls secret using the command</p> <p><code>kubectl create secret tls secret-pfx-key --dry-run=client --cert tls.crt --key tls.key -o yaml</code></p> <pre><code>apiVersion: v1 kind: Secret type: kubernetes.io/tls metadata: name : secret-pfx-key namespace: default data: #cat tls.crt | base64 tls.crt: base64-gibberish.... #cat tls.key | base64 tls.key: base64-gibberish.... </code></pre> <p>However, now I cannot understand how to use it. When I add the secret as volume in the pod I can see the two files that are created. But I need the combination of the two in one .pfx file.</p> <p>Am I missing something? Thanks.</p> <p>Note: I have read the related stackoverflow questions but could not understand how to use it.</p>
<p>You can <a href="https://www.sslshopper.com/ssl-converter.html" rel="nofollow noreferrer">convert</a> to pfx first, then <code>kubectl create secret generic mypfx --from-file=pfx-cert=&lt;converted pfx file&gt;</code></p> <p>Mount the secret as a volume in your pod:</p> <pre><code>apiVersion: v1 kind: Pod metadata: name: test-mypfx spec: restartPolicy: OnFailure volumes: - name: pfx-volume secret: secretName: mypfx containers: - name: busybox image: busybox command: [&quot;ash&quot;,&quot;-c&quot;,&quot;cat /path/in/the/container/pfx-cert; sleep 5&quot;] volumeMounts: - name: pfx-volume mountPath: /path/in/the/container </code></pre> <p>The above example dump the cert, wait for 5s and exit.</p>
<pre><code>$ helm version version.BuildInfo{Version:&quot;v3.3.0&quot;, GitCommit:&quot;8a4aeec08d67a7b84472007529e8097ec3742105&quot;, GitTreeState:&quot;dirty&quot;, GoVersion:&quot;go1.14.6&quot;} </code></pre> <p>So I have my template:</p> <pre class="lang-yaml prettyprint-override"><code> minAvailable: {{ mul .Values.autoscaling.minReplicas 0.75 }} </code></pre> <p>values.yaml:</p> <pre class="lang-yaml prettyprint-override"><code>autoscaling: minReplicas: 3 </code></pre> <p>I would have expected a rendered output of <code>2.25</code>, but I get 0 (<code>3 * 0</code> because <code>0.75</code> gets floored...)</p> <p>I've tried things like</p> <pre class="lang-yaml prettyprint-override"><code> minAvailable: {{ mul (float .Values.autoscaling.minReplicas) 0.75 }} </code></pre> <p>Ultimately I'm going to <code>floor</code> the value to get back to an int...</p> <pre class="lang-yaml prettyprint-override"><code> minAvailable: {{ floor ( mul .Values.autoscaling.minReplicas 0.75 ) }} </code></pre> <p>But I just don't understand why I can't seem to do simple float arithmetic</p> <hr /> <p>Other things I've tried</p> <pre class="lang-yaml prettyprint-override"><code> minAvailable: {{ float64 .Values.autoscaling.minReplicas }} </code></pre> <pre class="lang-yaml prettyprint-override"><code> minAvailable: {{ float64 .Values.autoscaling.minReplicas | toString }} </code></pre> <p>nothing produces a float number....</p> <p>I've even tried doing this in values.yaml</p> <pre><code>autoscaling: minReplicas: 3.0 </code></pre>
<p>Helm and its templates support the default Go <a href="https://pkg.go.dev/text/template?utm_source=godoc#hdr-Functions" rel="noreferrer">text/template</a> functions and the function provided by the <a href="https://masterminds.github.io/sprig/" rel="noreferrer">Sprig</a> extension. Since Sprig version <a href="https://github.com/Masterminds/sprig/releases/tag/v3.2.0" rel="noreferrer">3.2</a> it also supports <a href="https://masterminds.github.io/sprig/mathf.html" rel="noreferrer">Float Math Functions</a> like <code>addf</code>, <code>subf</code>, <code>mulf</code>, <code>divf</code>, etc. In your case you would just need:</p> <pre><code> minAvailable: {{ mulf .Values.autoscaling.minReplicas 0.75 }} </code></pre>