The easiest way to setup CICD with GitHub workflows and terraform for GCP
Without wasting much time let's get into what steps we need to take to create a CICD pipeline and deploy simple nodeJs applications docker containers on GCP cloud run using terraform and GitHub workflow
The following are some prerequisites needed before moving forward
- Terraform CLI installed on your Local Machine
- gcloud CLI on Local Machine
- A project created on GCP such as
4. Authenticate gcloud CLI and the earlier created Project is selected after authentication (command: gcloud auth login )
Then we need to create a Cloud Run service and a Google Artifact Registry Repository
- Cloud Run Service is used to run docker containers and
- Artifact Registry holds the docker images
To create these services we will use Terraform
Following is the code for terraform which will create those services.
As you can see we are creating an initial cloud-run app with a sample “hello-app” image provided by Google. Also an Artifact registry repository with the name “docker-artifact registry” will be created.
After terraform apply command finishes it will show the service URL as follows
On visiting the URL this will be the output of the hello-app image container
With this, we have created the required services needed to implement CICD
Following code shows the CICD pipeline code
The above workflow file is set up so that it will execute when the code is pushed to the main branch
Before that, we need to add some GitHub action secrets inside the GitHub repository settings, following are these secret variables
1. PROJECT_ID: this you can find on the GCP console project listing page
2. SERVICE_NAME: this is what we created earlier with terraform i.e test-app
3. SERVICE_ACCOUNT_KEY: This is JSON that we need to download from the GCP IAM service account section i.e.
To create and download the service account key click on the service account email then go to the KEYS section and create one
The credential JSON file will look like the following, which we need to copy and add to GitHub secrets for SERVICE_ACCOUNT_KEY
GitHub action secrets should look like this.
Now final remaining thing is to push our code to the “main” branch and check if the CICD pipeline works or not
This is what our GitHub actions tab will show if the pipeline successfully runs
Then we need to check whether our service is deployed on not.
The following image shows that our new image has been deployed.
And when click on the service URL it will show our new app's response.
Final Thoughts
- Make sure that the service account has needed permissions to push images to the artifact registry and deploy on the cloud run
- You can add more variables than those are mentioned here to GitHub secrets and use them in the workflow
- GCP project can also be created using Terraform but here our focus is only on creating an Artifact registry and cloud run service
You can check out the complete code which includes a simple nodeJS app here