Gemini CLI in GCP Cloud Shell with Google login 小記
今天要來實作 在 GCP Cloud Shell - 採取 Google 登入方式使用 Gemini CLI
上一篇文章 Gemini CLI 安裝小記有提到, Gemini CLI 授權方式有 3 種, 而一般使用者大多會使用 Google 登入的方式
另提到 Jimmy Liao 於 Build with AI 2025 簡報有提到, 如何於 GCP Cloud Shell 內安裝 gemini cli (授權採用 Vetex AI 方式) 遇到 問題的時候如何解 ( npm config set prefix )
這邊推一下 使用 GCP Cloud Shell 來進行相關開發或是詢問
之前文章 (https://sakananote2.blogspot.com/2024/10/gcp-cloud-shell-editor-c.html ) 有提到
Cloud Shell 每月有 60 小時可以使用, 4 vCPU / 16 G MEM
有快速的 IDE 環境可以使用, 能連上網路都可以用
但如果你在 GCP Cloud Shell 使用 Google login 方式授權, 因為在請求授權的時候, 不會自動帶出瀏覽器來進行 Google 驗證, 就會發現 驗證的圈圈就會一直轉 @@
這個時候即時看到 Lee Shih Yuan (FourDollars) 的文章
Conquering Google Login for Gemini CLI on Headless Servers (https://medium.com/@fourdollars/conquering-google-login-for-gemini-cli-on-headless-servers-3e9d2649790f )
真是太感謝 FourDollars 的文章
以下的實作是基於 FourDollars 的文章
建立 url-logger.sh 檔案, 內容如下
#!/bin/bash
# This script will log the URL that Gemini CLI tries to open.
# The authentication URL will be written to this file.
URL_FILE="$HOME/gemini_auth_url.txt"
# Ensure the file exists.
touch "$URL_FILE"
# Append the URL and a timestamp to the file.
echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> "$URL_FILE"
# Optional: Print to console as well for immediate visibility.
echo "URL would be opened: $1"
這個檔案我是放在自己的家目錄 ~ , 因為 /usr/local/bin 在 GCP CloudShell 針對一般使用者沒有寫入權限, 但是我不想 sudo 來進行, 因為這個授權方式應該是一次性的
給予執行權限
$ chmod +x ~/url-logger.sh
修改 Shell 設定檔
在 ~/.bashrc 加入 BROWSER 變數
export BROWSER=~/url-logger.sh
重新讀取 Shell 設定檔
$source ~/.bashrc
接下來在 GCP 開啟 2 個 cloudshell 視窗
在 cloudshell 視窗 1 執行 gemini 指令 - 如果你是使用 Google 登入驗證, 他會去使用 BROWSER 要進行驗證 - 這個時候其實會等待驗證連線, 所以不能關閉
在 cloudshell 視窗 2 觀察驗證的 URL - $ cat "$HOME/gemini_auth_url.txt"
在 本機將 取得的 URL 在瀏覽器貼上, 這個時候會要求選取你的 Google 帳號, 然後因為他的連線URL 是 localhost:xxxx 會顯示無法連上這個網站, 將 URL 複製起來
在 cloudshell 視窗 2 使用 $curl "剛剛複製的 URL" - 進行驗證
這個時候就會發現 gemini 已經可以開始使用
再次感謝 Jimmy Liao 與 Lee Shih Yuan (FourDollars) 的文章 讓我可以在 GCP Cloud Shell 方便的使用 Gemini CLI
又跨出一步
~ enjoy it
References