Automate Google Cloud CLI with Bash Scripts for CI/CD Pipelines

Automate Google Cloud CLI with Bash Scripts

Learn how to automate Google Cloud CLI tasks using Bash scripts in your CI/CD pipelines. Includes CLI examples, GitHub Actions integration, and optimization tips.

Table of Contents

Introduction

In today’s fast-paced software development landscape, automation is key to achieving efficient and reliable Continuous Integration and Continuous Deployment (CI/CD) pipelines. Google Cloud Platform (GCP) offers a suite of tools that can be seamlessly integrated with Bash scripts to automate various tasks, from provisioning resources to deploying applications.


Why Automate with Bash Scripts?

Bash scripts provide a lightweight and flexible approach to automation. They are particularly useful for:

  • Provisioning Infrastructure: Automate the creation and management of GCP resources.
  • Deployment: Streamline the process of deploying applications to services like Google Kubernetes Engine (GKE) or Cloud Run.
  • Monitoring and Maintenance: Set up automated checks and maintenance tasks.
  • Cost Management: Implement scripts to monitor and control cloud expenditures.

By integrating these scripts into CI/CD pipelines, teams can ensure consistent and repeatable deployments, reduce human error, and accelerate development cycles.


Setting Up Google Cloud CLI

Before diving into automation, ensure the following prerequisites are in place:

RequirementCommand / Link
Install gcloud CLIGoogle Cloud SDK Installation Guide
Authenticate CLIgcloud auth login
Set default projectgcloud config set project [PROJECT_ID]
Enable required APIsgcloud services enable compute.googleapis.com (and others as needed)

Sample Bash Script for GCP Automation

Let’s break down a sample Bash script that automates the following:

  • Sets up configuration ⚙️ 
  • Creates a GCE (Google Compute Engine) instance
  • Deploys an app to it
  • Outputs deployment details

📄 deploy.sh

				
					#!/bin/bash

# Set variables
PROJECT_ID="your-project-id"
ZONE="us-central1-a"
INSTANCE_NAME="ci-cd-instance"
MACHINE_TYPE="e2-medium"
IMAGE_FAMILY="debian-11"
IMAGE_PROJECT="debian-cloud"

# Authenticate
gcloud auth activate-service-account --key-file=$GOOGLE_APPLICATION_CREDENTIALS
gcloud config set project $PROJECT_ID

# Create VM instance
gcloud compute instances create $INSTANCE_NAME \
  --zone=$ZONE \
  --machine-type=$MACHINE_TYPE \
  --image-family=$IMAGE_FAMILY \
  --image-project=$IMAGE_PROJECT

# Deploy application (example: copy files and start server)
gcloud compute scp ./app/* $INSTANCE_NAME:/home/debian/ --zone=$ZONE
gcloud compute ssh $INSTANCE_NAME --zone=$ZONE --command="sudo systemctl restart my-app"

# Output instance IP
EXTERNAL_IP=$(gcloud compute instances describe $INSTANCE_NAME --zone=$ZONE --format='get(networkInterfaces[0].accessConfigs[0].natIP)')
echo "App deployed at http://$EXTERNAL_IP"
				
			

Integrating with CI/CD Platforms

Bash scripts and gcloud commands can be seamlessly embedded in popular CI/CD platforms. Here’s an example for GitHub Actions.

🧬 GitHub Actions Workflow (.github/workflows/deploy.yml)

				
					name: Deploy to GCP

on:
  push:
    branches:
      - main

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      
      - name: Setup gcloud CLI
        uses: google-github-actions/setup-gcloud@v1
        with:
          project_id: ${{ secrets.GCP_PROJECT_ID }}
          service_account_key: ${{ secrets.GCP_SA_KEY }}
          export_default_credentials: true

      - name: Run deployment script
        run: |
          chmod +x ./deploy.sh
          ./deploy.sh
				
			

📊 Common gcloud CLI Commands (Cheat Sheet)

TaskCommand Example
Set projectgcloud config set project [PROJECT_ID]
Create VMgcloud compute instances create
Deploy to App Enginegcloud app deploy
Enable a service/APIgcloud services enable [API_NAME]
View VM external IPgcloud compute instances describe
Authenticate with service accountgcloud auth activate-service-account

🧠 Tips for Effective Bash Scripting in CI/CD

  1. Use Functions: Structure scripts with reusable functions for readability and maintenance.

  2. Logging & Error Handling: Use set -e and trap for robust error handling.

  3. Use Environment Variables: Store secrets securely using CI/CD platform’s secret store.

  4. Use JSON/YAML Output: Many gcloud commands support structured output for scripting.

📁 Directory Structure Example

				
					project-root/
│
├── deploy.sh
├── app/
│   ├── index.js
│   └── Dockerfile
└── .github/
    └── workflows/
        └── deploy.yml
				
			

📌 Final Thoughts

Automating Google Cloud CLI tasks with Bash scripts is not only practical but essential for modern DevOps teams. When integrated into CI/CD pipelines, it accelerates deployments, reduces human error, and ensures consistent environments across development and production.

By leveraging simple, modular Bash scripts and integrating them with tools like GitHub Actions, you can turn complex cloud workflows into repeatable, reliable automation that saves time and scales with your team.

Did you find this article helpful? Your feedback is invaluable to us! Feel free to share this post with those who may benefit, and let us know your thoughts in the comments section below.


Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *