Search code examples
gogitlabgitlab-cigitlab-ci-runner

How to make a linux executable file using gitlab (go env)?


I am trying to make a Linux executable file of my Go project. I have the following configuration in my .config-ci.yml in my gitlab project.

demo_job_1:
    tags:
        - cpf
        - cpf-test
        - testing
        - unit-testing
    script:
        - go run test/main.go
        - GOOS=linux GOARCH=amd64 go build
        - go env
        - cd test
        - ./test
        - echo Successfully run and Built

After running this pipeline, I still get the GOOS=windows when I check in env file. How can I build my project so that the output after building is of Linux executable file. Right now, I am getting .exe file which runs on Windows only.

You can see the project details in the following gitlab:

https://gitlab.com/smilekison/test

This is the error that is shown by Pipeline Job:

$ go run test/main.go
Hello world
$ GOOS=linux GOARCH=amd64 go build

GOOS=linux : The term 'GOOS=linux' is not recognized as the name of a cmdlet, function, script file, or operable 
program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At C:\WINDOWS\TEMP\build_script487326907\script.ps1:207 char:1
+ GOOS=linux GOARCH=amd64 go build
+ ~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (GOOS=linux:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

Solution

  • First to address your actual error: it seems you are on a windows based runner. That means you have to use windows CMD commands. It does not know ENV, etc.

    You can do go env -w GOOS="linux" instead. Same with GOARCH. Then just run go build ..

    You can also use a variables section to overwrite go env with environment variables:

    variables:
      GOOS: "linux"
      GOARCH: "amd64"
    

    It goes at the top of the gitlab file somewhere.


    Here my typical build pipeline for Go projects using docker containers:

    build_App:
      image: golang:1.15.3
      stage: build
      allow_failure: false
      tags:
        - unix
      script:
        - go mod download
        - mkdir $CI_PROJECT_DIR/release
        - cd cmd/app
        - GOOS=linux GOARCH=amd64 go build -o $CI_PROJECT_DIR/release/app .
      artifacts:
        paths:
          - $CI_PROJECT_DIR/release
    
    

    And test pipeline

    go_test:
      image: golang:1.15.3
      stage: verify
      allow_failure: false
      tags:
        - unix
      script:
        - go mod download
        - go test -race -cover ./...
    

    This is based on a runner that uses docker images to build in.