2020-09-30

Implement CI in Gitlab

In this example we would create a gitlab CI Pipeline to compile and run application and check whether the output of that program is as expected. First let's create a source code that we want to test, for example main.go:

package main
import "fmt"
func main() {
    fmt.Println("Hello foo")
}

Then we must create the .gitlab-ci.yml file that show the steps of how to build and what kind of test we want to run, for example:

default:
  image: golang
  before_script:
    - apt install -y grep
    - go version
    - which go
    - go build main.go

test1:
  script:
    - ./main | grep 'Kiswono Prayogo'

In the example above, we would use latest version of golang docker image and run 4 steps to build the golang binary from our main.go code. Then we define next step (in this case just 1 step on test1) to be running the output binary and check whether it contains string 'Kiswono Prayogo'.

We could check the output in Gitlab CI/CD > Pipelines side menu:


It would show something like this:


We could click the failure reason/step:


As we can see on the the lines above, the step that are failed are in the last step, after we fix the code in main.go to give the output 'Kiswono Prayogo', the test1 phase should passed normally:



What if we want to test a service/webserver? What we need to do is install curl and start the service, for example this is the server we want to test (server.go):

package main
import "net/http"
import "fmt"
func hello(w http.ResponseWriter, req *http.Request) {
    fmt.Fprintf(w, "hello test\n")
}
func main() {
    http.HandleFunc("/", hello)
    http.ListenAndServe(":8090", nil)
}

Then we create the CI script to install curl and start the server using ampersand (&) to make it run in background (so it won't hold up until timeout, you might need to add sleep 1 if the server have slow startup, eg. Java).

default:
  image: golang
  before_script:
    - apt install -y grep curl
    - go build -o server1 server.go

coba2:
  script:
    - ./server1 & 
    - curl --silent http://localhost:8090 | grep 'hello test'

For more steps, examples, and information about CI/CD on Gitlab, you can visit the documentation. Personally I don't like the built-in on CI pipeline the git hosting service, since it always re-pull the docker image (which is slow, will took around >1 minutes just to deploy), I usually make my own CI program that triggered by webhook to pull then deploy when there's certain string on the commit message (this took less than 20s if not counting running the automated test).