google-cloud-buildcloudbuild.yaml

Changing directories in Cloud Build 'cd' no found


I'm using cloud build to clone a repository. I can confirm the repository clones successfully to the cloud build /workspace volume.

steps:
  - id: 'Clone repository'
    name: 'gcr.io/cloud-builders/git'
    args: ['clone', $_REPO_URL]
    volumes:
    - name: 'ssh'
      path: /root/.ssh

I then run the next step to confirm

  - id: 'List'
    name: 'alpine'
    args: ['ls']

and it shows me the repository is in the current directory. But when I try and cd into the directory the cd command doesn't work and throws an error:

ERROR: build step 3 "alpine" failed: starting step container failed: Error response from daemon: OCI runtime create failed: container_linux.go:380: starting container process caused: exec: "cd <repo-name>": executable file not found in $PATH: unknown

My ultimate goal is to cd into the repository and run some git commands. I use alpine later on because the git builder image doesn't allow me to use cd either.

substitutions:
  _REPO_NAME: 'test-repo'
  _REPO_URL: 'git@bitbucket.org:example/test-repo.git'
  _BRANCH_NAME: 'feature/something'

steps:
  - id: 'Clone repository'
    name: 'gcr.io/cloud-builders/git'
    args: ['clone', $_REPO_URL]
    volumes:
    - name: 'ssh'
      path: /root/.ssh

  - id: 'Check Diff'
    name: 'alpine'
    args: ['cd $_REPO_NAME', '&&', 'git checkout $_BRANCH_NAME', '&&', 'git diff main --name-only']

Solution

  • You can use bash to run any commands you would like. Here is one example I use for one of my projects:

    - name: 'gcr.io/cloud-builders/git'
      id: Clone env repository
      entrypoint: /bin/sh
      args:
      - '-c'
      - |
        git clone git@github.com:xyz/abc.git && \
        cd gitops-env-repo/ && \
        git checkout dev