Using multiline strings in GitLab YML file

Sometimes your script is too long and it doesn't fit on one line:

script:
  - docker run --name build-container --tag gitlab:demo --workdir /project --build-arg SOME_VAR=123 custom-image .

It would be nice to be able to split this on multiple lines, just like you can do on the shell or in a script file:

> docker run \
	--name build-container \
    --tag gitlab:demo \
    --workdir /project \
    --build-arg SOME_VAR=123 \
    custom-image .

In a .gitlab-ci.yml file you can use multiline YML strings:

script:
	- > 
        docker run 
        --name build-container 
        --tag gitlab:demo 
        --workdir /project 
        --build-arg SOME_VAR=123 
        custom-image .

So, how does this work?

  1. You need to start the script with - >; this indicates a YML block element;
  2. Split your script on several lines and make sure they all have the exact same indentation
  3. At runtime, all the text will be combined into one line (skipping newlines)

Do you want to keep the newlines? Then start the YML block with - | instead of - >.

If you want to learn more, I found https://yaml-multiline.info/ to be a great resource!