Skip to content

Instantly share code, notes, and snippets.

@x-yuri
Last active February 12, 2024 17:48
Show Gist options
  • Save x-yuri/19f292b2d77a9718c281a887e647b200 to your computer and use it in GitHub Desktop.
Save x-yuri/19f292b2d77a9718c281a887e647b200 to your computer and use it in GitHub Desktop.
Reusing GCP credentials

Reusing GCP credentials

gcloud and ADC credentials are interchangeable and can be copied.

Gemfile:

source "https://rubygems.org"
gem 'google-cloud-storage'

a.rb:

require 'google/cloud/storage'
storage = Google::Cloud::Storage.new(
    project_id: 'PROJECT_ID',
)
storage.buckets.all do |bucket|
    puts bucket.name
end

cp-adc.sh:

set -eu
docker run -v "$PWD:/app" -w /app google/cloud-sdk:457.0.0-alpine sh -euc '
    cp application_default_credentials.json ~/.config/gcloud
    gcloud auth application-default print-access-token
    apk add ruby ruby-dev ruby-bundler
    bundle
    bundle exec ruby a.rb
'

cp-gcloud.sh:

set -eu
docker run -v "$PWD:/app" -w /app google/cloud-sdk:457.0.0-alpine sh -euc '
    cp credentials.db ~/.config/gcloud
    gcloud config set account EMAIL
    gcloud config set project PROJECT_ID
    gcloud auth print-access-token
    gcloud compute instances list
'

gcloud2adc.sh:

set -eu
docker run --rm -itv "$PWD:/app" -w /app alpine:3.19 sh -euc '
    apk add sqlite jq
    sqlite3 credentials.db "select value from credentials" \
        | jq "{client_id, client_secret, refresh_token, type}" \
            > application_default_credentials2.json
'

adc2gcloud.sh:

set -eu
docker run --rm -itv "$PWD:/app" -w /app alpine:3.19 sh -euc "
    apk add sqlite
    # rm credentials2.db
    sqlite3 credentials2.db \"CREATE TABLE credentials (account_id TEXT PRIMARY KEY, value BLOB)\"
    sqlite3 credentials2.db \"INSERT INTO credentials (account_id, value) VALUES ('EMAIL', CAST(readfile('application_default_credentials.json') AS TEXT))\"
    # sqlite3 credentials2.db \"INSERT INTO credentials (account_id, value) VALUES ('EMAIL', '\`cat application_default_credentials.json\`')\"
"
// replace PROJECT_ID, EMAIL
// copy credentials.db and application_default_credentials.json
$ sh cp-adc.sh
$ sh cp-gcloud.sh
$ sh gcloud2adc.sh
$ sh adc2gcloud.sh
// running cp-{adc,gcloud}.sh with *2* files also works
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment