How to give annotations by using run command in kubernetes to a pod - kubernetes

I attempted but there is an error..i also see See 'kubectl run --help' for usage.
but i can't fix it..
kubectl run pod pod4 --image=aamirpinger/helloworld:latest --port=80 --annotaions=createdBy="Muhammad Shahbaz" --restart=Never
Error: unknown flag: --annotaions

kubectl run supports specifying annotations via the --annotations flag that can be specified multiple times to apply multiple annotations.
For example:
$ kubectl run --image myimage --annotations="foo=bar" --annotations="another=one" mypod
results in the following:
$ kubectl get pod mypod -o yaml
apiVersion: v1
kind: Pod
metadata:
annotations:
foo: bar
another: one
[...]

kubectl run doesn't have an option to set annotations.
Unless you're running a one-off debugging pod, it's usually better practice to write out the full (Deployment) YAML file, commit to source control, and install it using kubectl apply -f. That will let you specify any Kubernetes object property you need to.

As David Maze mentioned ,there is no --annotations flag for kubectl run command.It is better to write deployment yaml file compared to running using kubectl run command.
However you can add annotations to kubernetes resources using Kubectl annotate command.All Kubernetes objects support the ability to store additional data with the object as annotations.
Hope this helps.

Related

Kubernetes NetworkPolicy - Is there a way to identify which NetworkPolicies are applied to Pods

We have 3-4 different NetworkPolicy in our Namespace and they are applied based on Pod Selector. Want to know is there any way from Pod side to know which NetworkPolicy is applied on it?
If POD selector used you can use the simple way
kubectl get pod -l \
$( \
kubectl get netpolicies <netpolicy-name> \
-o jsonpath="{.spec.podSelector.matchLabels}"| \
jq -r 'to_entries|map("\(.key)=\(.value)")[]' \
)
This will get the policy selector and use it as input and list the pods
Any way from Pod side
There is no POD side you can check, however I read somewhere kubectl describe pod-name could show Network Policies I tested not showing at least in minikube
So you can use the above command or describe the networkpolicy itself to get POD selector and get an idea.
kubectl describe networkpolicies <name of policy>
The output of kubectl get network policy should display the pod-selector.
After that you can use kubectl get pod -l key=value to list the pods affected.
you can automate this using a bash script/function.
I would also recommend checking "kubectl np-viewer" which is a kubectl plugin, can be found here. This plugin has what you are asking for out of box.
kubectl np-viewer -p pod-name prints network policies rules affecting a specific pod in the current namespace

Cluster name within the Pod [duplicate]

As stated in the title, is it possible to find out a K8s cluster name from the API? I looked around the API and could not find it.
kubectl config current-context does the trick (it outputs little bit more, like project name, region, etc., but it should give you the answer you need).
Unfortunately a cluster doesn't know its own name, or anything else that would uniquely identify it (K8s issue #44954). I wanted to know for helm issue #2055.
Update:
A common workaround is to create a ConfigMap containing the cluster name and read that when required (#2055 comment 1244537799).
apiVersion: v1
kind: ConfigMap
metadata:
name: cluster-info
namespace: kube-system
data:
cluster-name: foo
There is no way to get the name via K8s API. But here is a one-liner in case the name you have in your .kube/config file is enough for you (if you download it from your cloud provider the names should match):
kubectl config view --minify -o jsonpath='{.clusters[].name}'
Note 1: The --minify is key here so it will output the name of your current context only. There are other similar answers posted here but without the "minify" you will be listing other contexts in your config that might confuse you.
Note 2: The name in your .kube/config might not reflect the name in your cloud provider, if the file was autogenerated by the cloud provider the names should match, if you configured it manually you could have typed any name just for local config.
Note 3: Do not rely on kubectl config current-context this returns just the name of the context, not the name of the cluster.
I dont believe there is a k8s cluster name. This command could provide some nice informations
kubectl cluster-info
The question is not really well described. However, if this question is related to Google Container Engine then as coreypobrien mentioned the name of cluster is stored in custom metadata of nodes. From inside a node, run the following command and the output will be name of cluster:
curl http://metadata/computeMetadata/v1/instance/attributes/cluster-name -H "Metadata-Flavor: Google"
If you specify your use case, I might be able to extend my answer to cover it.
The kubernetes API doesn't know much about the GKE cluster name, but you can easily get the cluster name from the Google metatdata server like this
kubectl run curl --rm --restart=Never -it --image=appropriate/curl -- -H "Metadata-Flavor: Google" http://metadata.google.internal/computeMetadata/v1/instance/attributes/cluster-name
It is the same as getting the current config, but the below command gives clear output:
kubectl config view
This command will Check all possible clusters, as you know .KUBECONFIG may have multiple contexts
kubectl config view -o jsonpath='{"Cluster name\tServer\n"}{range .clusters[*]}{.name}{"\t"}{.cluster.server}{"\n"}{end}'
And you will get output like
Cluster name Server
kubernetes https://localhost:6443
at-least for kubespray clusters, the following works for me
kubectl config current-context | cut -d '#' -f2
For clusters that were installed using kubeadm, the configuration stored in the kubeadm-config configmap has the cluster name used when installing the cluster.
$ kubectl -n kube-system get configmap kubeadm-config -o yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: kubeadm-config
namespace: kube-system
data:
ClusterConfiguration: |
clusterName: NAME_OF_CLUSTER
For clusters that are using CoreDNS for their DNS, the "cluster name" from kubeadm is also used as the domain suffix.
$ kubectl -n kube-system get configmap coredns -o yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: coredns
namespace: kube-system
data:
Corefile: |
.:53 {
kubernetes NAME_OF_CLUSTER.local in-addr.arpa ip6.arpa {
Well this returns precisely one thing, a cluster name
K8s:
kubectl config view -o jsonpath='{.clusters[].name}{"\n"}'
Openshift:
oc config view -o jsonpath='{.clusters[].name}{"\n"}'
$ kubectl config get-clusters --> get you the list of existing clusters
Using python k8s client. But this won't work with incluster_kubeconfig.
from kubernetes import config
cluster_context = config.kube_config.list_kube_config_contexts()
print (cluster_context)
([{'context': {'cluster': 'k01.test.use1.aws.platform.gov', 'user': 'k01-test'}, 'name': 'k01.test.use1.aws.platform.gov'}], {'context': {'cluster': 'k01.test.use1.aws.platform.gov', 'user': 'k01-test'}, 'name': 'k01.test.use1.aws.platform.gov'})
cluster_name = cluster_context[1]['context']['cluster']
print (cluster_name)
k01.test.use1.aws.platform.gov
Using kubectl command:
$ kubectl config get-clusters
NAME
kubernetes
kubectl config get-clusters
kubectl config get-contexts
There is a great tool called kubectx https://github.com/ahmetb/kubectx.
kubectx - lists all previously added clusters and highlights the currently used one. This is only one word to type instead of kubectl config current-context.
kubectx <cluster> - switches to a chosen cluster.
Moreover this tool comes also with kubens which does exactly the same for namespaces:
kubens - lists all namespaces and shows the current one,
kubens <namespace> - switches to a chosen namespace.

Is there an imperative command to create daemonsets in kubernetes?

I was wondering if there is an easier way to create daemonsets in k8s other than yaml files.
For eg, for pods we have kubectl run --generator=run-pod/v1 command. I was wondering if there is something similar for DS.
Thanks in advance.
There is no such quick kubectl create type command for creating daemonsets. But you can do it in some other way.
One way to do this is:
$ kubectl create deploy nginx --image=nginx --dry-run=client -o yaml | \
sed '/null\|{}\|replicas/d;/status/,$d;s/Deployment/DaemonSet/g' > nginx-ds.yaml
$ kubectl apply -f nginx-ds.yaml
If you don't want to save the yaml data to any file, here's how you can do this:
$ kubectl create deploy nginx --image=nginx --dry-run=client -o yaml | \
sed '/null\|{}\|replicas/d;/status/,$d;s/Deployment/DaemonSet/g' | \
kubectl apply -f -
You have your daemonset now.
What we are doing here is: at first we're creating a deployment yaml and then replacing kind: Deployment with kind: DaemonSet and remove replicas: 1 from the deployment yaml.
Thats's how we get yaml for daemonset.
You can access Kubernetes Documentation for DaemonSets. You could use the link and get examples of DaemonSet yaml files. However there is no way you could create a Daemonset by imperative way. You could create a deployment specification and change the deployment specification to DaemonSet specification. You need to change the kind to Daemonset, remove strategy, replicas and status fields. That would do.

k3s cleanup of HelmChart?

I have followed instructions from this blog post to set up a k3s cluster on a couple of raspberry pi 4:
I'm now trying to get my hands dirty with traefik as front, but I'm having issues with the way it has been deployed as a 'HelmChart' I think.
From the k3s docs
It is also possible to deploy Helm charts. k3s supports a CRD
controller for installing charts. A YAML file specification can look
as following (example taken from
/var/lib/rancher/k3s/server/manifests/traefik.yaml):
So I have been starting up my k3s with the --no-deploy traefik option to manually add it with settings. So I therefore manually apply a yaml like this:
apiVersion: helm.cattle.io/v1
kind: HelmChart
metadata:
name: traefik
namespace: kube-system
spec:
chart: https://%{KUBERNETES_API}%/static/charts/traefik-1.64.0.tgz
set:
rbac.enabled: "true"
ssl.enabled: "true"
kubernetes.ingressEndpoint.useDefaultPublishedService: "true"
dashboard:
enabled: true
domain: "traefik.k3s1.local"
But when trying to iterate over settings to get it working as I want, I'm having trouble tearing it down. If I try kubectl delete -f on this yaml it just hangs indefinitely. And I can't seem to find a clean way to delete all the resources manually either.
I've been resorting now to just reinstall my entire cluster over and over because I can't seem to cleanup properly.
Is there a way to delete all the resources created by a chart like this without the helm cli (which I don't even have)?
Are you sure that kubectl delete -f is hanging?
I had the same issue as you and it seemed like kubectl delete -f was hanging, but it was really just taking a long time.
As far as I can tell, when you issue the kubectl delete -f a pod in the kube-system namespace with a name of helm-delete-* should spin up and try to delete the resources deployed via helm. You can get the full name of that container by running kubectl -n kube-system get pods, find the one with kube-delete-<name of yaml>-<id>. Then use the pod name to look at the logs using kubectl -n kube-system logs kube-delete-<name of yaml>-<id>.
An example of what I did was:
kubectl delete -f jenkins.yaml # seems to hang
kubectl -n kube-system get pods # look at pods in kube-system namespace
kubectl -n kube-system logs helm-delete-jenkins-wkjct # look at the delete logs
I see two options here:
Use the --now flag to delete your yaml file with minimal delay.
Use --grace-period=0 --force flags to force delete the resource.
There are other options but you'll need Helm CLI for them.
Please let me know if that helped.

Why kubectl run create deplyment sometimes

Can I know why kubectl run sometimes create deployment and sometimes pod.
You can see 1st one creates pod and 2nd one creates deployment. only diff is --restart=Never
// 1
chams#master:~/yml$ kubectl run ng --image=ngnix --command --restart=Never --dry-run -o yaml
apiVersion: v1
kind: Pod
..
status: {}
//2
chams#master:~/yml$ kubectl run ng --image=ngnix --command --dry-run -o yaml
kubectl run --generator=deployment/apps.v1 is DEPRECATED and will be removed in a future version. Use kubectl run --generator=run-pod/v1 or kubectl create instead.
apiVersion: apps/v1
kind: Deployment
metadata:
creationTimestamp: null
labels:
run: ng
name: ng
..
status: {}
The flags are intentionally meant to create different kind of objects. I am copying from the help of kubectl run:
--restart='Always': The restart policy for this Pod. Legal values [Always,
OnFailure, Never]. If set to 'Always' a deployment is created, if set to
'OnFailure' a job is created, if set to 'Never', a regular pod is created. For
the latter two --replicas must be 1. Default 'Always', for CronJobs `Never`.
Never acts like a cronjob which is scheduled immediately.
Always creates a deployment and the deployment monitors the pod and restarts in case of failure.
By default kubectl run command creates a Deployment.
Using kubectl run command you can create and run a particular image, possibly replicated.
Creates a deployment or job to manage the created containers.
The difference in your case is seen in command (1st one) including restart policy argument.
If value of restart policy is set to 'Never', a regular pod is created. For the latter two --replicas must be 1. Default 'Always', for CronJobs Never.
Try to use command:
$ kubectl run --generator=run-pod/v1 ng --image=ngnix --command --dry-run -o yaml
instead of
$ kubectl run ng --image=ngnix --command --dry-run -o yaml
to avoid statement
"kubectl run --generator=deployment/apps.v1 is DEPRECATED and will be removed in a future version. Use kubectl run --generator=run-pod/v1 or kubectl create instead."
More information you can find here:docker-kubectl, kubectl-run.