~~stoggle_buttons~~ ====== links ====== * [[https://learnk8s.io/]] * [[https://www.katacoda.com/courses/kubernetes]] * calico, istio * [[https://github.com/ahmetb/kubectx|kubectx]] cambiar entre distintos kubectl, como venvs ====== lo bueno es esto ====== User-defined movidas de kubernetes: * [[https://kubernetes.io/docs/tasks/administer-cluster/configure-upgrade-etcd/]] ====== helm ====== * Sistema de plantillas ====== Notación (sintaxis parecida a Python) ====== * ''<>'' indica tipo ''object'' genérico (puede saberse pero no se concreta a propósito de este resumen) * ''def'' indica valores por defecto * Los booleanos se escriben ''option:False'' para decir que es el valor por defecto * ''nombre: tipo. Comentario [:{subcampos: tipo. Comentario}]'' * Un tipo antes de unas llaves afecta a todas las variables de dentro salvo que se sobreescriban.''a:Resource:str{b, c, d:int}'' significa: ''a es Resource, b y c son str, d es int'' * Si el tipo está incluido en el nombre, se marca con **: ''lastProbe*Time*'' es tipo ''Time'', y ''*ContainerStatus*es'' es tipo ''ContainerStatus list'' * Describir tipos que tienen los mismos campos: ''%%[limits:<>.Maximum amount, requests:<>.Minimum amount] :<>{cpu, memory, hugepages}%%'' * Enumeraciones con (): ''%%state: str("start", "run", "stop", "fail")%%'' ====== Container ====== ===== Container v1 core ===== - args: str list - command: str list - env: EnvVar list:str{name, value} - image: str - imagePullPolicy: str ("Always" def if image~=":latest", "Never", def "IfNotPresent") - lifecycle: Lifecycle:{postStart: Handler, preStop: Handler} - livenessProbe: Probe:<>{exec, failureThreshold, httpGet, initialDelaySeconds, periodSeconds}, sucessThreshold, tcpSocket, timeoutSeconds} - name: str - ports: ContainerPort list:<>{containerPort, hostIP, hostPort, name, protocol} - readinessProbe: Probe - resources: ResourceRequirements{[limits:<>.Maximum amount, requests:<>.Minimum amount] :<>{cpu, memory, hugepages}} - *securityContext*: :<>{allowPrivilegeEscalation, capabilities, privileged, procMount, readOnlyFilesystem, runAsGroup, runAsNonRoot, runAsUser, seLinuxOptions, windowsOptions} - startupProbe: Probe - stdin: False. Allocate a buffer for stdin? - stdinOnce: False. Close stdin once it has been opened? - terminationMessagePath: str - terminationMessagePolicy: str - tty: False. Allocate tty? Requires stdin: True - *volumeDevice*s: : str{devicePath, name} - volumeMount: VolumeMount list: str{mountPath, mountPropagation, name, readOnly:False, subPath, subPathExpr} - workingDir: str ===== ContainerStates v1 core ===== - containerID: "docker://" - image: str - imageID: str - lastState: ContainerState:<>{running:{startedAt}, terminated:{containerID,exitCode,finishedAt, message,reason,signal,startedAt},waiting:{message,reason}, name:str, ready:bool, restartCount: int, started:bool, state:ContainerState} ====== Pod v1 core ====== - [apiVersion, kind]: str - metadata: ObjectMetadata - spec: PodSpec - status: PodStatus ===== PodSpec v1 core ===== - activeDeadlineSeconds: int. Seconds active before pod is marked as failed - affinity: Affinity - automountServiceAcountToken: bool - *container*s - dnsConfig: <> - dnsPolicy: str - enableServiceLinks: true. Docker links(?) - *ephemeralContainer*s - *hostAlias*es: {hostnames: str list, ip: str} - hostIPC: False - hostNetwork: False - hostPID: False - hostname: str - imagePullSecrets: LocalObjectReference <> - init*Container*s - nodeName: str - nodeSelector: <> - overhead: <>. Autopopulated - readinessGates: PodReadinessGate list - restartPolicy: str(def "Always", "OnFailure", "Never") - runtimeClassName: str - schedulerName: str - securityContext: PodSecurityContext - serviceAccountName: str - shareProcessNamespace: bool - subdomain: str - terminationGracePeriodSeconds: int. Seconds the pod needs to terminate gracefully, may be decreased in delete rqeuests. def 30 - *toleration*s - *topologySpreadConstraint*s - *volume*s: <>{awsElasticBlockStore, azureDisk, azureFile, cephfs, cinder, configMap, csi, downwardAPI, emptyDir, fc, flexVolume, flocker, gcePersistentDisk, gitRepo, glusterfs, hostPath, iscsi, name, nfs, persistentVolumeClaim, photonPersistentDisk, portworxVolume, projected, quobyte, rbd, scaleIO, secret, storageos, vsphereVolume} ===== PodStatus v1 core ===== - conditions: PodCondition list - *containerStatus*es - ephemeral*ContainerStatus*es - hostIP: str - init*ContainerStatus*es - message: str - nominatedNodeName: str - phase: str - podIP: str - podIPs: PodIP list - qosClass: str - reason: str - start*Time* ====== Deployment v1 apps ====== - [apiVersion, kind]: str - metadata: ObjectMetadata - spec: DeploymentSpec - status: DeploymentStatus ===== DeploymentSpec v1 app ===== - minReadySeconds: int. How many seconds should a pod be running (no containers crashing) for it to be considered available? def 0 - paused: bool - progressDeadlineSeconds: The maximum time in seconds for a deployment to make progress before it is considered to be failed. def 600 - replicas: int. Number of desired pods. def 1 - revisionHistoryLimit: int. Number of old ReplicaSets to retain to allow rollback. def 10 - selector: LabelSelector{matchExpressions: LabelSelectorRequirement list, matchLabels:<>} - strategy: DeploymentStrategy: {rollingUpdate: RollingUpdateDeployment: { maxSurge:<>. Maximum number of pods that can be scheduled above the desired number of pods, can be absolute number or a percentage of desired pods (number is rounded up). def 25% maxUnavailable:<>. Maximum number of pods that hat can be unavailable during the update, can be absolute number or a percentage of desired pods (number is rounded down). }, type: str("Recreate", def "RollingUpdate") } - template: PodTemplateSpec: {metadata: ObjectMetadata, spec: PodSpec} ===== DeploymentStatus v1 apps ===== - availableReplicas: int. Total number of available pods (ready for at least minReadySeconds) - collisionCount: int. Count of hash collisions for the Deployment - conditions: DeploymentCondition list: { lastTransition*Time*. Last time the condition transitioned from one status to another, lastUpdate*Time* Last time this condition was updated, [message,reason,status,type] :str} - observedGeneration: int - readyReplicas: int - replicas: int - unavailableReplicas: int - updatedReplicas: int ====== Job v1 batch ====== - [apiVersion, kind]: str - metadata: ObjectMetadata - spec: JobSpec - status: JobStatus ===== JobSpec v1 batch ===== - activeDeadlineSeconds: int. Seconds relative to the startTime that the job may be active before the system tries to terminate it - backoffLimit: int. Number of retries before marking this job failed. def 6 - completions: int. Desired number of successfully finished pods the job should be run with - parallelism: int. Maximum desired number of pods the job should run at any given time - selector: LabelSelector. A label query over pods (should match the pod count), usually autocompleted - template: PodTemplateSpec - ttlSecondsAfterFinished: int ===== JobStatus v1 batch ===== - active: int. Number of actively running pods - completion*Time* - conditions JobCondition list. Latest available observations of an object current state: { lastProbe*Time*, lastTransition*Time*, [message,reason,status,type]: str } - failed: int. Number of pods which reached phase Failed. - start*Time* - suceeded: int. Number of pods which reached phase Suceeded. ====== StatefulSet v1 apps ====== - [apiVersion, kind]: str - metadata: ObjectMetadata - spec: StatefulSetSpec - status: StatefulSetStatus ===== StatefulSetSpec v1 apps ===== - podManagementPolicy: str(def "OrderedReady". pods are created in increasing order, controller waits until each pod is ready. When scaling down, the pods are removed in the opposite order, "Parallel") - replicas: int. Desired number of replicas. def 1 - revisionHistoryLimit: int. Maximum number of revisions maintained in revision history. def 10 - selector: LabelSelector - serviceName: str. Name of the service that governs this StatefulSet. This service must exist before the StatefulSet, and is responsible for the network identity of the set - template: PodTemplateSpec - updateStrategy: StatefulSetUpdateStrategy {rollingUpdate: RollingUpdateStatefulSetStrategy{ partition:int. Indicates the ordinal at which the StatefulSet should be partitioned. def 0}, type: str(def "RollingUpdate")} - volumeClaimTemplates: PersistentVolumeClaim list: {[apiVersion, kind]: str, metadata:ObjectMetadata, spec: PersistentVolumeClaimSpec, status: PersistentVolumeClaimStatus} ===== StatefulSetStatus v1 apps ===== ====== CronJob v1beta1 batch ====== - apiVersion: str - kind: str - metadata: ObjectMetaData - spec: CronJobSpec - status: CronJobStatus ===== CronJobSpec v1beta1 batch ===== - concurrencyPolicy: str(def "Allow": allows CronJobs to run concurrently, "Forbid": forbids concurrent runs skipping next run if previous run hasn't finished yet, "Replace": cancels currently running job and replaces it with a new one) - failedJobsHistoryLimit: int. Number of failed finished jobs to retain. def 1 - jobTemplate: JobTemplateSpec {metadata: ObjectMeta, spec: JobSpec} - schedule:str. The schedule in Cron format - startingDeadlineSeconds: int. Optional deadline in seconds for starting the job if it misses scheduled time for any reason. Missed jobs executions will be counted as failed ones. - successfulJobsHistoryLimit:int. Number of successful finished jobs to retain. def 3 - suspend: false. This flag tells the controller to suspend subsequent executions, it does not apply to already started executions. ====== LabelSelector v1 meta ====== - matchExpressions: LabelSelectorRequirement list. The requirements are ANDed { key: str operator: str("In", "NotIn", "Exists", "DoesNotExist") } - matchLabels <>. matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of matchExpressions, whose key field is "key", the operator is "In", and the values array contains only "value". The requirements are ANDed. - values str list. If the operator is In or NotIn, the values array must be non-empty. If the operator is Exists or DoesNotExist, the values array must be empty. ====== Secrets en variables de entorno ====== * [[https://kubernetes.io/docs/concepts/configuration/secret/]] Crear el Secret apiVersion: v1 kind: Secret metadata: name: mysecret type: Opaque data: USER_NAME: YWRtaW4= PASSWORD: MWYyZDFlMmU2N2Rm Referenciar el Secret apiVersion: v1 kind: Pod metadata: name: secret-test-pod spec: containers: - name: test-container image: k8s.gcr.io/busybox command: [ "/bin/sh", "-c", "env" ] envFrom: - secretRef: name: mysecret restartPolicy: Never Las variables de entorno tienen ya la información necesaria ====== Regularidades ====== * Todos los objetos tienen ''spec'', que es el estado deseado que tenga el objeto, y ''status'' que es el estado actual. * Los campos TemplateSpec son siempre ''TemplateSpecABC: {metadata: ObjectMetadata, spec: ABCSpec}'' ===== Conditions ===== * ''JobCondition, DeploymentCondition''