Automating Google Cloud with GitHub Actions using gcloud CLI
In today's DevOps landscape, automating tasks and deployments is essential for efficiency and reliability. One powerful way to achieve this is by leveraging GitHub Actions to connect with Google Cloud Platform (GCP) using the gcloud CLI. In this post, I'll walk you through setting up a GitHub Action workflow to use the gcloud CLI, allowing you to perform various tasks in GCP directly from your GitHub repository.
Prerequisites
Google Cloud Account: You need access to GCP and sufficient permissions to perform actions, such as deploying applications or managing resources.
GitHub Repository: Ensure you have a repository where you want to set up the workflow.
gcloud CLI: Familiarity with the
gcloudCLI is helpful, but not required, as we'll cover the basic commands needed.
Step 1: Set Up a Service Account in GCP
First, create a service account in your Google Cloud project with the necessary permissions:
Navigate to the IAM & Admin section in the Google Cloud Console.
Select Service Accounts and create a new service account.
Assign the necessary roles for the actions you wish to automate. For example, you might need roles such as
roles/storage.adminfor Cloud Storage tasks orroles/compute.adminfor Compute Engine tasks.Generate a JSON key for the service account and download it. You'll use this key to authenticate in your GitHub Actions workflow.
Step 2: Store Service Account Credentials in GitHub Secrets
Go to your GitHub repository.
Navigate to Settings > Secrets and variables > Actions.
Click on New repository secret.
Add a new secret with the name
GCP_SERVICE_ACCOUNT_KEY.Copy the content of the JSON key file and paste it as the secret value.
Step 3: Create Your GitHub Action Workflow
Create a GitHub Actions workflow file in your repository. Here’s an example configuration:
name: GCP Deployment
on:
push:
branches:
- main
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v3
- id: 'auth'
uses: 'google-github-actions/auth@v2'
with:
credentials_json: '${{ secrets.GCP_SERVICE_ACCOUNT_KEY }}'
- name: 'Set up Cloud SDK'
uses: 'google-github-actions/setup-gcloud@v2'
- name: 'Use gcloud CLI'
run: 'gcloud info'
Explanation
- The
authaction sets Application Default Credentials, then thesetup-gcloudaction references these credentials to configure gcloud credentials. Thesetup-gcloudaction installs the Cloud SDK (gcloud).
Step 4: Test and Validate
Commit and push your changes to your GitHub repository. Navigate to the Actions tab to see the workflow run and validate the output. Make sure that all steps are completed successfully and that the desired actions are performed in your GCP environment.