Google Cloud Builds - Commit to GitHub repository

· Read in about 2 min · (232 words) ·

Setting up a cloud builder task to commit back to a Github repository using Deploy keys.

Intro

  • Sometimes it is useful to be able perform write operations in github repositories (or access a private repository etc.)
  • This requires setting up an account with permissions
  • An alternative would be setting up a cloud builder with SSH key which will be authorized to access the repository
  • Cloud builder task below generates an RSA key which will be part of the task and can be allowed to access repository

    • Be aware that each key can be authorized to access a single repository only
  • Dockerfile

    FROM gcr.io/cloud-builders/git
    
    CMD [ '/bin/sh', '-c' ]
    
    COPY known_hosts /root/.ssh/known_hosts
    RUN ssh-keygen -t rsa -N "" -f ~/.ssh/id_rsa
    RUN cat ~/.ssh/id_rsa.pub
    
    ENTRYPOINT ["git"]
  • known_hosts (collocated with Dockerfile)

    github.com,192.30.253.113 ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAq2A7hRGmdnm9tUDbO9IDSwBK6TbQa+PXYPCPy6rbTrTtw7PHkccKrpp0yVhp5HdEIcKr6pLlVDBfOLX9QUsyCOV0wzfjIJNlGEYsdlLJizHhbn2mUjvSAHQqZETYP81eFzLQNnPHt4EVVUh7VfDESU84KezmD5QlWpXLmvU31/yMf+Se8xhHTvKSCZIFImWwoG6mbUoWf9nzpIoaSjB+weqqUUmpaaasXVal72J+UX2B+2RPW3RcT0eOzQgqlJL3RKrTJvdsjE3JEAvGq3lGHSZXy28G3skua2SmVi/w4yCE6gbODqnTWlg7+wC604ydGXA8VJiS5ap43JXiUFFAaQ==
  • cloudbuild.yaml

    steps:
    - name: 'gcr.io/cloud-builders/docker'
    args: ['build', '--tag=gcr.io/$PROJECT_ID/github', '.']
    
    images:
    - 'gcr.io/$PROJECT_ID/github:latest'
  • Once you build your cloud builder check the log and look for the generated public key:

    Step 5/6 : RUN cat ~/.ssh/id_rsa.pub
    ---> Running in 32c7423c4915
    ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC/XRz6pyjViympvwmj7Y2QWSO+ZeahAn3xlsJlmnY+3mODKXieHKnI6Zyt26MCrLpgZ30LhQ1m2WcVZJHGkmot+mYt70Lr1spD9AJ3RCaVOuphBsOhyKzRh9Qq6qtEBBiA+TnRYlRTxE51879/9WJXCbM6Bb27bUYRPRMWAAxeY+pF2zUjk5A/mgfHE/+OfHVeWkKlPjNIV+keZ8TlLvH51ntuTdwrC7rq3TFGkrkXJQ6tqNnlqaFORpJ6KiDkgCryqCByadZnJOsEbA1bFt9q2mpXVnyL6YjV8MuVf8XY+yYjs7xZCRtAMPZXtEcqv+S1JjTlDIOKX4BCeD/M4Ok3 root@cf525f31d11f
  • Take the line starting with ssh-rsa to clipboard and add it to your Github repository:

Github Deploy Keys setup

  • Be careful though - the secrets are now stored as a part of GCP project where the cloudbuilder task image is saved so if somebody gets access to your project or docker image she will get access to your Github repository

Links