if you want to remove an article from website contact us from top.

    what is the declarative way to initialize and update kubernetes objects?

    Mohammed

    Guys, does anyone know the answer?

    get what is the declarative way to initialize and update kubernetes objects? from screen.

    Declarative Management of Kubernetes Objects Using Configuration Files

    Kubernetes objects can be created, updated, and deleted by storing multiple object configuration files in a directory and using kubectl apply to recursively create and update those objects as needed. This method retains writes made to live objects without merging the changes back into the object configuration files. kubectl diff also gives you a preview of what changes apply will make. Before you begin Install kubectl. You need to have a Kubernetes cluster, and the kubectl command-line tool must be configured to communicate with your cluster.

    Declarative Management of Kubernetes Objects Using Configuration Files

    Kubernetes objects can be created, updated, and deleted by storing multiple object configuration files in a directory and using kubectl apply to recursively create and update those objects as needed. This method retains writes made to live objects without merging the changes back into the object configuration files. kubectl diff also gives you a preview of what changes apply will make.

    Before you begin

    Install kubectl.

    You need to have a Kubernetes cluster, and the kubectl command-line tool must be configured to communicate with your cluster. It is recommended to run this tutorial on a cluster with at least two nodes that are not acting as control plane hosts. If you do not already have a cluster, you can create one by using minikube or you can use one of these Kubernetes playgrounds:

    Killercoda

    Play with Kubernetes

    To check the version, enter kubectl version.

    Trade-offs

    The kubectl tool supports three kinds of object management:

    Imperative commands

    Imperative object configuration

    Declarative object configuration

    See Kubernetes Object Management for a discussion of the advantages and disadvantage of each kind of object management.

    Overview

    Declarative object configuration requires a firm understanding of the Kubernetes object definitions and configuration. Read and complete the following documents if you have not already:

    Managing Kubernetes Objects Using Imperative Commands

    Imperative Management of Kubernetes Objects Using Configuration Files

    Following are definitions for terms used in this document:

    object configuration file / configuration file: A file that defines the configuration for a Kubernetes object. This topic shows how to pass configuration files to kubectl apply. Configuration files are typically stored in source control, such as Git.

    live object configuration / live configuration: The live configuration values of an object, as observed by the Kubernetes cluster. These are kept in the Kubernetes cluster storage, typically etcd.

    declarative configuration writer / declarative writer: A person or software component that makes updates to a live object. The live writers referred to in this topic make changes to object configuration files and run kubectl apply to write the changes.

    How to create objects

    Use kubectl apply to create all objects, except those that already exist, defined by configuration files in a specified directory:

    kubectl apply -f /

    This sets the kubectl.kubernetes.io/last-applied-configuration: '{...}' annotation on each object. The annotation contains the contents of the object configuration file that was used to create the object.

    Note: Add the -R flag to recursively process directories.

    Here's an example of an object configuration file:

    application/simple_deployment.yaml

    apiVersion: apps/v1 kind: Deployment metadata:

    name: nginx-deployment

    spec: selector: matchLabels: app: nginx minReadySeconds: 5 template: metadata: labels: app: nginx spec: containers: - name: nginx image: nginx:1.14.2 ports: - containerPort: 80

    Run kubectl diff to print the object that will be created:

    kubectl diff -f https://k8s.io/examples/application/simple_deployment.yaml

    Note:

    diff uses server-side dry-run, which needs to be enabled on kube-apiserver.

    Since diff performs a server-side apply request in dry-run mode, it requires granting PATCH, CREATE, and UPDATE permissions. See Dry-Run Authorization for details.

    Create the object using kubectl apply:

    kubectl apply -f https://k8s.io/examples/application/simple_deployment.yaml

    Print the live configuration using kubectl get:

    kubectl get -f https://k8s.io/examples/application/simple_deployment.yaml -o yaml

    The output shows that the kubectl.kubernetes.io/last-applied-configuration annotation was written to the live configuration, and it matches the configuration file:

    kind: Deployment metadata: annotations: # ...

    # This is the json representation of simple_deployment.yaml

    # It was written by kubectl apply when the object was created

    kubectl.kubernetes.io/last-applied-configuration: |

    {"apiVersion":"apps/v1","kind":"Deployment",

    "metadata":{"annotations":{},"name":"nginx-deployment","namespace":"default"},

    "spec":{"minReadySeconds":5,"selector":{"matchLabels":{"app":nginx}},"template":{"metadata":{"labels":{"app":"nginx"}},

    "spec":{"containers":[{"image":"nginx:1.14.2","name":"nginx",

    "ports":[{"containerPort":80}]}]}}}}

    # ... spec: # ... minReadySeconds: 5 selector: matchLabels: # ... app: nginx template: metadata: # ... labels: app: nginx spec: containers:

    - image: nginx:1.14.2

    # ... name: nginx ports: - containerPort: 80 # ... # ... # ... # ...

    How to update objects

    You can also use kubectl apply to update all objects defined in a directory, even if those objects already exist. This approach accomplishes the following:

    Sets fields that appear in the configuration file in the live configuration.

    स्रोत : kubernetes.io

    Imperative vs. declarative Kubernetes commands: What's the difference?

    Imperative and declarative Kubernetes commands are the two different ways to configure the state of your clustered environment. Here we compare declarative versus imperative commands and show you ...

    Coffee Talk: Java, News, Stories and Opinions

    BLOG

    Imperative vs. declarative Kubernetes commands: What's the difference?

    Bob Reselman 09 May 2022

    Declarative and imperative configuration commands

    One of the interesting features of the Kubernetes container orchestration technology is that it’s state-based.

    Under Kubernetes, once you define how the various resources within a cluster of virtual or physical machines are supposed to be configured, Kubernetes ensures that configuration is always in force.

    Under Kubernetes is etcd, a database that keeps track of the state of the given Kubernetes cluster. If you declare a pod deployment of three replicas, Kubernetes guarantees that three pods are always running. If you declare a namespace with the name coolspace, Kubernetes ensures that the namespace is always there.

    Ensuring state is one of the reasons that Kubernetes is a compelling technology.

    Imperative and declarative compared

    There are two ways you can configure a resource under Kubernetes: imperatively or declaratively.

    Imperative configuration means that to describe the configuration of the resource, you execute a command from a terminal’s command prompt. Of course, the terminal’s machine must have permission to access the Kubernetes cluster of interest.

    Apache and Docker Tutorials

    Master the fundamentals of Apache, Docker and Kubernetes.

    Quickly install Apache on Windows

    Run the httpd Docker from the command line

    Learn how to Dockerize Apache server websites

    A simple docker-compose Apache example

    Learn to setup an Apache reverse proxy

    How do you compare Apache vs Tomcat?

    Why you should Choose Apache as your HTTP web server

    Fix the ‘ServerRoot Must be a Valid Directory’ error

    Declarative configuration means that you create a file that describes the configuration for the particular resource and then apply the content of the file to the Kubernetes cluster. To apply the configuration, you use the command kubectl apply at the command prompt as you would for an imperative command, but that’s where the similarity ends.

    Let’s look at some examples of imperative and declarative configuration for commonly used Kubernetes resources: pods, deployments, namespaces and services.

    Imperative K8s pod configuration

    The first example we’ll look at is creating a pod. To create a pod imperatively, execute the kubectl run command set in a terminal window:

    kubectl run nicepod --image=nginx

    Execute the command set kubectl get pods, and you’ll see the following result which indicates the pod has been created and is running.

    NAME      READY   STATUS    RESTARTS   AGE

    nicepod   1/1     Running   0          26s

    To create a pod declaratively, you create a manifest file, either in JSON or YAML. Once the file is created, execute the command set kubectl apply -f from the command prompt.

    The following example is a manifest file in YAML, named nicepod.yaml, that creates a pod with the name nicepod.

    apiVersion: v1 kind: Pod metadata: name: nicepod labels: App: dev spec: containers: - name: web image: nginx ports: - name: web containerPort: 80 protocol: TCP

    Kubernetes resource creation

    To create the source, run the following command in a terminal window:

    kubectl apply -f nicepod.yaml

    The command above essentially says, “Apply this declaration defined in the file nicepod.yaml to create the resource within the Kubernetes cluster.”

    Once the YAML file is applied, the resource is created. To verify all is as intended, execute the command kubectl get pods. You’ll see the following output:

    NAME      READY   STATUS    RESTARTS   AGE

    nicepod   1/1     Running   0          50s

    As you can see, both imperative and declarative configuration produce the same outcome.

    Configuring Kubernetes deployments

    Let’s do an imperative configuration of a Kubernetes deployment.

    A deployment is a Kubernetes resource that is a collection of one or many pods. A deployment is guaranteed to always be running. Creation of a Kubernetes deployment requires execution of two imperative commands. The first command, shown below, creates the deployment named cooldeploy which is a collection of pods that run the Nginx web server:

    kubectl create deploy cooldeploy --image nginx

    The second imperative command scales the deployment up to three replicas of the pod:

    kubectl scale --replicas=3 deployment/cooldeploy

    Thus, deployment using the command kubectl get deployment cooldeploy generates the following output:

    NAME         READY   UP-TO-DATE   AVAILABLE   AGE

    cooldeploy   3/3     3            3           85s

    To create the same deployment declaratively, construct a manifest file in YAML named mydeployment.yaml as follows:

    apiVersion: apps/v1 kind: Deployment metadata: name: cooldeploy labels: app: nginx spec: replicas: 3 selector: matchLabels: app: nginx template: metadata: labels: app: nginx spec: containers: - name: nginx image: nginx:1.14.2 ports: - containerPort: 80

    Next, run the command kubectl apply -f mydeployment.yaml to apply the resource definition to the Kubernetes cluster. Then, run the command kubectl get deployment cooldeploy, and you get output similar to the following:

    स्रोत : www.theserverside.com

    Imperative vs. Declarative — a Kubernetes Tutorial

    There are two basic ways to deploy to Kubernetes: imperatively, with the many kubectl commands, or declaratively, by writing manifests and using kubectl apply. The former is good for learning and…

    Imperative vs. Declarative — a Kubernetes Tutorial

    There are two basic ways to deploy to Kubernetes: imperatively, with the many kubectl commands, or declaratively, by writing manifests and using kubectl apply. The former is good for learning and interactive experimentation (analogous to a programming language’s REPL); the latter is good for reproducible deployments, i.e., for production — though you may still use some kubectl commands for debugging in production.

    The Data Science team at PayScale was an early adopter of Kubernetes. I first wrote this tutorial to onboard fellow team members and help spread the use of Kubernetes to the rest of the company. We’re hoping it will help others too.

    Photo by Matthew T Rader on Unsplash

    Prerequisites

    This tutorial assumes you have access to a cluster. Nowadays, you can easily run a single-node cluster on your machine, or create a multi-node cluster in your favorite cloud. Make sure kubectl is installed on your machine and properly configured. The following command should succeed:

    kubectl cluster-info

    You should also have enough permissions in your default namespace (which may be different than thedefault namespace). The edit role should be enough. If you created a cluster for this tutorial, you’re likely an admin, so you're good to go. Otherwise, somebody may have prepared the ground for you. If you don’t understand this paragraph, just keep going :)

    Optional: If you decide to build and push a custom container image (see below), rather than pull a public one, we assume you and the cluster have access to a container image registry. Again, somebody may have prepared the ground for you. GKE works well with GCR, AKS works well with ACR, etc. Otherwise, DockerHub and Quay are popular options, but if you don’t make your image public, you may need to configure the default service account in your namespace with an image pull secret.

    Optional: Build and Push

    Whether we deploy imperatively or declaratively, we need a container image. You can skip this part and use an existing image if you’re in a hurry, e.g., nginx, but some of the steps in this tutorial are tailored for the application we’ll build in this section. Also, if you want to learn how to containerize an application, read on.

    For the purpose of this tutorial, we’ll start with a simple web app’s source code. Here’s a sample Node.js app based on an example from the Node.js documentation (feel free to write an equivalent in your favorite programming language). In an empty folder, copy the code below to a file named app.js:

    // app.js

    const http = require('http');

    const os = require('os');

    const ip = '0.0.0.0';

    const port = 3000;

    const hostname = os.hostname();

    const whoami = process.env['WHOAMI'] || 'Anonymous';

    const server = http.createServer((req, res) => {

    res.statusCode = 200;

    res.setHeader('Content-Type', 'text/plain');

    res.end(`Hi, I’m ${whoami}, from ${hostname}.\n`);

    });

    server.listen(port, ip, () => {

    console.log(`Server running at http://${ip}:${port}/`);

    });

    We made a few changes to the base example:

    Important! Serve on 0.0.0.0 rather than 127.0.0.1. The latter is for loopback only and this app will listen to incoming requests on a Cluster IP (captured by 0.0.0.0).

    We also changed the “Hello World” message to include two variables: the hostname, which will be an indicator of which replica is responding, and the WHOAMI environment variable, to be set at deploy time, defaulting to “Anonymous”.

    If you’ve installed Node.js, you can test the app locally:

    node app.js # then open http://localhost:3000

    Note: if you’re rolling your own, don’t bother with TLS termination or authentication, because those can be handled at the cluster’s edge by, e.g., Ambassador, and even between apps within the cluster in a service mesh like Istio, if you decide to go zero-trust.

    Let’s package this app as a Docker image. Copy the code below to a file named Dockerfile:

    # Dockerfile FROM node:8 COPY app.js .

    ENTRYPOINT [“node”, “app.js”]

    In the same folder, run:

    docker build -t myrepo:mytag .

    Depending on your container image registry, replace myrepo with something like gcr.io/project-name/image-name on GCR, or user-name/image-name on DockerHub (the default registry). Replace mytag with anything but latest. If you’re taking this tutorial with a group of people, make sure you use different tags. Don’t forget the final dot, making the current folder the build context.

    Finally, push the image to your repository (from which Kubernetes will pull):

    docker push myrepo:mytag

    Imperative Configuration

    Imperative Configuration Run

    The shortest way to deploy to Kubernetes is to use the kubectl run command. Replace myapp with something unique if you’re taking this tutorial with other people and sharing a namespace; replace myrepo:mytag with what you picked in the previous step (or just use nginx):

    kubectl run myapp --image myrepo:mytag --replicas 2

    The command may look familiar if you’ve ever used docker run to start a container locally, but the similarity stops here. Here’s what happens under the hood (also illustrated in the diagram below):

    स्रोत : medium.com

    Do you want to see answer or more ?
    Mohammed 7 day ago
    4

    Guys, does anyone know the answer?

    Click For Answer