Search code examples
bashyamlgcloudgithub-actions

GitHub -> GCP, use gcloud commands inside shell script


I have a workflow in GitHub that will execute a shell script, and inside this script I need to use gsutil

In my workflow yml-file I have the following steps:

name: Dummy Script
on:
  workflow_dispatch:

jobs:
  build:
    runs-on: ubuntu-latest
    environment: alfa    
    env:
      _PROJECT_ID: my-project
    steps:
    - uses: actions/checkout@v2
    - name: Set up Cloud SDK for ${{env._PROJECT_ID}}
      uses: google-github-actions/setup-gcloud@master
      with:
        project_id: ${{env._PROJECT_ID}}
        service_account_key: ${{ secrets.SA_ALFA }}
        export_default_credentials: true
    - run: gcloud projects list
    - name: Run script.sh
      run: |
        path="${GITHUB_WORKSPACE}/script.sh"
        chmod +x $path
        sudo $path 
      shell: bash

And the script looks like:

#!/bin/bash
apt-get update -y
gcloud projects list

The 2nd step in yml (run: gcloud projects list) works as expected, listing the projects SA_USER have access to.

But when running the script in step 3, I get the following output:

WARNING: Could not open the configuration file: [/root/.config/gcloud/configurations/config_default].
ERROR: (gcloud.projects.list) You do not currently have an active account selected.
Please run:

  $ gcloud auth login

to obtain new credentials.

If you have already logged in with a different account:

    $ gcloud config set account ACCOUNT

to select an already authenticated account to use.
Error: Process completed with exit code 1.

So my question is: How can I run a shell script file and pass on the authentication I have for my service account so I can run gcloud commands from a script file?

Due to reasons, it's a requirement that the script file should be able to run locally on developers computers, and from GitHub.


Solution

  • The problem seemed to be that the environment variables were not inherited when running with sudo. There are many ways to work around this, but I was able to confirm that it would run with sudo -E. Of course, if you don't need to run with sudo, you should remove it, but I guess it's necessary.

    enter image description here

    (The reproduction code was easy for me to reproduce it. Thanks)