Gitlab - 4.4.2 Writing gitlab pipeline
Now that you know the basic commands and the overall flow needed to run a GitLab CI pipeline, this lesson walks through actually writing a .gitlab-ci.yml for the Node.js application from the previous session. The recommended approach is to create the file locally, push it to a feature branch, run it, and then merge to master. The pipeline will need two jobs: a build job that installs every required dependency, and a deploy job that runs the application.
Build and deploy jobs
The build job must first install NPM on the runner, because the default GitLab environment does not ship with Node. We add the script block to install NPM (the Node Package Manager) and then run npm install at the project root, which reads package.json and pulls every declared dependency into node_modules. The deploy job is responsible for running node index.js. As in the previous lesson, this job must also install Node beforehand, because the GitLab environment is shared and each job starts from a clean slate.
You might wonder why we don't merge both installation steps into the build job. The answer becomes clearer in a moment, once we look at how GitLab schedules jobs. For now, we keep two distinct jobs, commit and push everything except the node_modules folder (which we deliberately exclude since the pipeline will rebuild it):
build_job:
script:
- apt-get install npm
- npm install
deploy_job:
script:
- apt-get install npm
- node index.js
When we push and watch the pipeline run, we discover an important default behavior: GitLab does not care about the order in which jobs are declared in the YAML file. It tries to execute every job in parallel. As a result, the deploy job starts before the build job has finished installing the dependencies, and the pipeline fails because the prerequisites from the build step are not yet in place. To enforce a build-then-deploy order, we need to explicitly group the jobs into stages, which we will explore in the next lesson.