Deployment replacement in Kubernetes encounters error

I've developed a NodeJS script to deploy review apps to Kubernetes for my GitLab repository, using the Kubernetes NodeJS client.

Including abbreviated definitions of Kubernetes resources for thoroughness:

const k8s = require('@kubernetes/client-node');

const logger = require('../logger');

const {
  CI_COMMIT_REF_NAME,
  CI_ENVIRONMENT_SLUG,
  CI_ENVIRONMENT_URL,
  CI_REGISTRY_IMAGE,
  KUBE_NAMESPACE,
} = process.env;

const { hostname } = new URL(CI_ENVIRONMENT_URL);

const mysqlDeployment = {
  apiVersion: 'apps/v1',
  kind: 'Deployment',
  metadata: {
    name: `${CI_ENVIRONMENT_SLUG}-mysql`, 
    labels: {
      app: CI_ENVIRONMENT_SLUG,
      tier: 'mysql',
    },
  },
  spec: {...}
};

// More resource definitions...

Using functions to deploy these resources to Kubernetes:

async function noConflict(resource, create, patch) {
  const { kind } = resource;
  const { name } = resource.metadata;
  try {
    // Create or patch resource based on conflict
  } catch (err) {
    // Handle error if resource exists
  }
}

async function deploy() {
  // Set up Kubernetes clients and deploy resources
}

await deploy();

Encountering issues when replacing running resources:

{ detailed HTTP request body with errors }

Tried modifying noConflict for current version retrieval, but faced another error.

{ detailed HTTP request body with immutable field errors }

Seeking solutions for updating existing resources smoothly. Database continuity is secondary.

Update:

Refactored code based on feedback, incorporating read operations for respective resources.

Updated code snippet...

Current implementation doesn't update the review environment effectively.

Update:

Addressed suggestions by further switching to patch calls instead of replace for updates.

Updated code snippet...

However, encountered an "Unsupported Media Type" error upon implementing this change.

Answer №1

It seems like there may be some confusion in how you are utilizing the replace command.

The correct way to use it is to replace a resource either by filename or stdin.

When replacing an existing resource, ensure that you provide the complete resource spec in JSON or YAML format. You can obtain this information by running:

$ kubectl get TYPE NAME -o yaml

If you attempt to replace without retrieving the yaml from Kubernetes, you will miss out on the necessary resourceVersion. This is likely the reason for the error message you received:

Service "review-fix-kubern-8a4yh2-mysql" is invalid: metadata.resourceVersion: Invalid value: "": must be specified for an update

If you are only replacing certain parts of the Deployment, consider using patch or apply instead.

Answer №2

Dealing with a similar issue today, I was trying to replicate the functionality of the kubectl apply -f command using the node client. Fortunately, I came across a TypeScript snippet here. Hopefully, it will be beneficial for you too.

In my JavaScript implementation, I used:

const kubernetesConfig = new k8s.KubeConfig()
kubernetesConfig.loadFromFile("kube-config.yaml")
this.k8sClient = k8s.KubernetesObjectApi.makeApiClient(kubernetesConfig)

and developed an apply function:

 async apply(spec) {
  try {
    // Attempt to retrieve the resource, if it does not exist, an error will be thrown and handled in the catch block.
    await this.k8sClient.read(spec)
    // Resource exists, proceed with patching it
    await this.k8sClient.patch(spec)
  } catch (e) {
    // Resource not found, create it instead
    await this.k8sClient.create(spec)
  }
},

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting: WordPress post not uploading to custom PHP file - Issue causing ERROR 500

Our website is built using WordPress, and I was tasked with adding a function to our newsletter subscription that sends an email to a specific address based on the selected value in the form. Everything was working perfectly on my local host, but when I tr ...

Develop a cross-platform application using webpack for both web browsers and Node.js

I'm currently developing my first module, and the code is almost identical for both browser and node.js versions. The only variance lies in the use of XmlHttpRequest for the browser and the http module for node.js. Here's a sample code snippet t ...

The strict-origin-when-cross-origin policy is enforced when submitting a POST request through a form to a specific route

Currently, I am diving into the world of Node.js, express, and MongoDB by reading Greg Lims's book. However, I've hit a roadblock when trying to utilize a form to submit data to a route that should then output the body.title of the form in the co ...

Guide to showcasing user input using a Javascript function

I need assistance to show the user input via the submit button. Users will enter tool types and the first five inputs will be displayed in list items (li). Once the limit of 5 tools is reached, a message 'Thanks for your suggestions' should appea ...

Fastify endpoint failing to respond to designated URL

Within my code, there is a router setup: fastify.get('/:link', (req, reply) => { req.params.url = req.host+req.url; reply.view("template.ejs",req.params); }); I am trying to capture URLs and process them in the template. All URLs are ...

Enhancing parent component props in React-router-dom: A guide to updating them

Here is the structure of my App component: const App = (props) => ( <BrowserRouter> <PageTheme {...some props I'd like to change on route change}> <Switch> <Route exact path="/example"> <E ...

The one-click button is functional on larger screens, while on mobile devices, only a double click will register

I am facing an issue in angular where a button works perfectly fine with one click on larger screens, such as Macbook. However, on iPhone, it requires a double click to function properly (it works fine on Android too). The alert triggers with a single cl ...

"During the testing phase, the req.body object is found

I'm currently performing unit testing on my express application using Mocha and Chai. However, when I attempt to use req.body in the test file to parse the object, I only receive undefined in the testing results. In my server (app.js), I have alread ...

Guide to accessing and updating data in various tabs within a Google spreadsheet

I have two tabs named TAB A and TAB B. My goal is to iterate through TAB A and extract a set of values that I can then paste into TAB B. However, I encountered an error message saying, "Cannot read property 1, etc" function getValuesFromModal(form) { ...

I encountered a 404 (Not Found) error when attempting to access http://localhost:3000/. Interestingly, I intended to make a

const express = require('express') const app = express() const port = 3000 app.post('/', (req, res) => { res.send('Hello World!') }) // app.post('/post', (req, res) => { // res.send('Hello World!&apo ...

Transferring information from Vue Component to Vuex storage

I am currently working with a Laravel API route that looks like this: Route::get('c/maintenances/{contractor_user_id}', 'Maintenance\Api\ApiContractorMaintenanceController@index'); The contractor_user_id parameter is dynamic ...

Prevent the need to go through the keycloak callback process each time the page is

I have integrated keycloak as an identity provider into my React application. I successfully added the keycloak react dependency via npm. Below are the versions of the keycloak react npm modules on which my application depends : "@react-keycloak/web ...

After reloading the data tables, analyze the information and dynamically highlight any rows in red that remain unchanged

I have a table that is refreshed every 5 minutes using ajax.reload(). One of the rows in this table is labeled as CIP. My goal is to highlight the CIP row on each refresh where the value remains unchanged from the previous value (value received in the la ...

Prevent the risk of revealing your LinkedIn API key within HTML code

For my website, I am looking to incorporate the Sign In With LinkedIn feature for user logins. The initial example snippet provided in the LinkedIn API docs is as follows: <script type="text/javascript" src="//platform.linkedin.com/in.js"> api_k ...

What is the best way to incorporate autoplay video within the viewport?

My objective is for the video to automatically start playing when it enters the viewport, even if the play button is not clicked. It should also pause automatically when it leaves the viewport, without the need to click the pause button. <script src=& ...

Learn the process of setting up a connection between Express JS and the NotionAPI using both POST and

As someone who is new to backend development, I am currently working on integrating a simple Notion form into a Typescript website. To guide me through the process, I found a helpful tutorial at . The tutorial demonstrates how to send data from localhost:3 ...

What could be the reason why the initial console.log is failing to print?

Apologies for the oversight. The !== was a mistake that slipped past me before posting. Thank you for your understanding. I am a beginner in Javascript. I have written this function with winston: function setlogger(log_level = "warn", logfile, scree ...

The address :::3000 is already in use by NestJS

While attempting to deploy my NestJs server on a C-Panel hosting, I have encountered an issue. Despite properly installing all node_modules and ensuring every project file is in place, the server fails to start and continuously displays the following error ...

How can you modify the starting point of data in jQuery flot?

Currently using Flot to create a graph displaying clicks per minute within the first 60 minutes of short URLs generated at . The graph currently displays data from minute 0 to minute 59. My query is about adjusting the data to start at 1 and end at 59, wh ...

How to Change a Property in a Child DTO Class in NestJS with Node.js

I am working with enums for status: export enum Status { Active = "Active", Inactive = "Inactive", } Additionally, I have a UserStatus enum: export enum UserStatus { Active = Status.Active, }; There is also a common dto that inc ...