Run hooks before and after deploying

This quickstart shows you how to run a deploy hook—an arbitrary program to run before or after you deploy using Cloud Deploy.

In this quickstart, you'll do the following:

  1. Create one GKE cluster or one Cloud Run service.

    You can use an GKE Enterprise cluster for this too, but this quickstart uses GKE and Cloud Run only.

  2. Create a Skaffold configuration and either a Kubernetes manifest or a Cloud Run service definition.

    The Skaffold configuration file is where you configure the deploy hooks to run. You identify a container to run before deploying, and a container to run after deploying.

  3. Define your Cloud Deploy delivery pipeline and deployment target.

    In the delivery pipeline configuration, you'll reference the deploy hooks that were defined in skaffold.yaml, to run those hooks.

    This pipeline includes only one stage and uses only one target.

  4. Create a release, which automatically deploys to the target.

    One of the hooks is run before the application is deployed, and the other is run after.

  5. View the results of the pre- and post-deploy hooks in the Cloud Build logs, using the Cloud Deploy Rollout details page in Google Cloud console.

Before you begin

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Make sure that billing is enabled for your Google Cloud project.

  4. Enable the Cloud Deploy, Cloud Build, GKE, Cloud Run, and Cloud Storage APIs.

    Enable the APIs

  5. Install the Google Cloud CLI.
  6. To initialize the gcloud CLI, run the following command:

    gcloud init
  7. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  8. Make sure that billing is enabled for your Google Cloud project.

  9. Enable the Cloud Deploy, Cloud Build, GKE, Cloud Run, and Cloud Storage APIs.

    Enable the APIs

  10. Install the Google Cloud CLI.
  11. To initialize the gcloud CLI, run the following command:

    gcloud init
  12. If you already have the CLI installed, make sure you're running the latest version:

    gcloud components update
    

  13. Make sure the default Compute Engine service account has sufficient permissions.

    The service account might already have the necessary permissions. These steps are included for projects that disable automatic role grants for default service accounts.

    1. First add the clouddeploy.jobRunner role:

      gcloud projects add-iam-policy-binding PROJECT_ID \
          --member=serviceAccount:$(gcloud projects describe PROJECT_ID \
          --format="value(projectNumber)")-compute@developer.gserviceaccount.com \
          --role="roles/clouddeploy.jobRunner"
      

    2. Add the developer role for your specific runtime.
      • For GKE:

        gcloud projects add-iam-policy-binding PROJECT_ID \
            --member=serviceAccount:$(gcloud projects describe PROJECT_ID \
            --format="value(projectNumber)")-compute@developer.gserviceaccount.com \
            --role="roles/container.developer"
        

      • For Cloud Run:

        gcloud projects add-iam-policy-binding PROJECT_ID \
            --member=serviceAccount:$(gcloud projects describe PROJECT_ID \
            --format="value(projectNumber)")-compute@developer.gserviceaccount.com \
            --role="roles/run.developer"
        

    3. Add the iam.serviceAccountUser role, which includes the actAspermission to deploy to the runtime:

      gcloud iam service-accounts add-iam-policy-binding $(gcloud projects describe PROJECT_ID \
          --format="value(projectNumber)")-compute@developer.gserviceaccount.com \
          --member=serviceAccount:$(gcloud projects describe PROJECT_ID \
          --format="value(projectNumber)")-compute@developer.gserviceaccount.com \
          --role="roles/iam.serviceAccountUser" \
          --project=PROJECT_ID
      

Create your runtime environment

If you're deploying to Cloud Run, you can skip this command.

For GKE, create one cluster: deploy-hooks-cluster, with default settings. The cluster's Kubernetes API endpoint must be network-reachable from the public internet. GKE clusters are externally accessible by default.

gcloud container clusters create-auto deploy-hooks-cluster \
                 --project=PROJECT_ID \
                 --region=us-central1

Prepare your Skaffold configuration and application manifest

Cloud Deploy uses Skaffold to provide the details for what to deploy and how to deploy it to your target.

In this quickstart, you create a skaffold.yaml file, which identifies the manifest to be used to deploy the sample app, and also identifies the containers to run before and after deployment (the deploy hooks).

  1. Open a terminal window.

  2. Create a new directory and navigate into it.

    GKE

    mkdir deploy-hooks-gke-quickstart
    cd deploy-hooks-gke-quickstart
    

    Cloud Run

    mkdir deploy-hooks-run-quickstart
    cd deploy-hooks-run-quickstart
    
  3. Create a file named skaffold.yaml with the following contents:

    GKE

    apiVersion: skaffold/v4beta7
    kind: Config
    manifests:
      rawYaml:
      - k8s-pod.yaml
    deploy:
      kubectl: {}
    customActions:
    - name: predeploy-action
      containers:
      - name: predeploy-echo
        image: ubuntu
        command: ["/bin/sh"]
        args: ["-c", 'echo "this is a predeploy action"' ]
    - name: postdeploy-action
      containers:
      - name: postdeploy-echo
        image: ubuntu
        command: ["/bin/sh"]
        args: ["-c", 'echo "this is a postdeploy action"' ]
    

    Cloud Run

    apiVersion: skaffold/v4beta7
    kind: Config
    manifests:
      rawYaml:
      - service.yaml
    deploy:
      cloudrun: {}
    customActions:
    - name: predeploy-action
      containers:
      - name: predeploy-echo
        image: ubuntu
        command: ["/bin/sh"]
        args: ["-c", 'echo "this is a predeploy action"' ]
    - name: postdeploy-action
      containers:
      - name: postdeploy-echo
        image: ubuntu
        command: ["/bin/sh"]
        args: ["-c", 'echo "this is a postdeploy action"' ]
    

    This file includes the customActions: stanza. This defines the containers to run before and after deploying—the hooks.

    See the skaffold.yaml reference for more information about this configuration file.

  4. Create the definition for your application—a service definition for Cloud Run or a Kubernetes manifest for GKE.

    GKE

    Create a file named k8s-pod.yaml, with the following contents:

    apiVersion: v1
    kind: Pod
    metadata:
      name: my-hooks-pod
    spec:
      containers:
      - name: nginx
        image: my-app-image
    

    This file is a simple Kubernetes manifest, which is applied to the cluster to deploy the application.

    Cloud Run

    Create a file named service.yaml, with the following contents:

    apiVersion: serving.knative.dev/v1
    kind: Service
    metadata:
      name: my-hooks-run-service
    spec:
      template:
        spec:
          containers:
          - image: my-app-image
    

    This file is a simple Cloud Run service definition, which is used at deploy time to create your Cloud Run service.

Create your delivery pipeline and target

You can define your pipeline and target in one file or in separate files. In this quickstart, you create a single file.

  1. Create your delivery pipeline and target definition:

    GKE

    In the deploy-hooks-gke-quickstart directory, create a new file: clouddeploy.yaml, with the following contents:

    apiVersion: deploy.cloud.google.com/v1
    kind: DeliveryPipeline
    metadata:
      name: deploy-hooks-demo-app-gke-1
    description: main application pipeline
    serialPipeline:
      stages:
      - targetId: hooks-staging
        profiles: []
        strategy:
          standard:
            predeploy:
              actions: ["predeploy-action"]
            postdeploy:
              actions: ["postdeploy-action"]
    ---
    
    apiVersion: deploy.cloud.google.com/v1
    kind: Target
    metadata:
      name: hooks-staging
    description: hooks staging cluster
    gke:
      cluster: projects/PROJECT_ID/locations/us-central1/clusters/deploy-hooks-cluster
    

    Cloud Run

    In the deploy-hooks-run-quickstart directory, create a new file: clouddeploy.yaml, with the following contents:

    apiVersion: deploy.cloud.google.com/v1
    kind: DeliveryPipeline
    metadata:
      name: deploy-hooks-demo-app-run-1
    description: main application pipeline
    serialPipeline:
      stages:
      - targetId: hooks-staging
        profiles: []
        strategy:
          standard:
            predeploy:
              actions: ["predeploy-action"]
            postdeploy:
              actions: ["postdeploy-action"]
    ---
    
    apiVersion: deploy.cloud.google.com/v1
    kind: Target
    metadata:
      name: hooks-staging
    description: staging Run service
    run:
      location: projects/PROJECT_ID/locations/us-central1
    
  2. Register your pipeline and targets with the Cloud Deploy service:

    gcloud deploy apply --file=clouddeploy.yaml --region=us-central1 --project=PROJECT_ID
    

    You now have a delivery pipeline, with one target, ready to deploy your application and run your pre-deploy and post-deploy jobs.

  3. Confirm your pipeline and targets:

    In the Google Cloud console, navigate to the Cloud Deploy Delivery pipelines page to view of list of your available delivery pipelines.

    Open the Delivery pipelines page

    The delivery pipeline you just created is shown, with one target listed in the Targets column.

    delivery pipeline page in Google Cloud console, showing your pipeline

Create a release

A release is the central Cloud Deploy resource representing the changes being deployed. The delivery pipeline defines the lifecycle of that release. See Cloud Deploy service architecture for details about that lifecycle.

GKE

Run the following command from the deploy-hooks-gke-quickstart directory to create a release resource that represents the container image to deploy:

 gcloud deploy releases create test-release-001 \
   --project=PROJECT_ID \
   --region=us-central1 \
   --delivery-pipeline=deploy-hooks-demo-app-gke-1 \
   --images=my-app-image=gcr.io/google-containers/nginx@sha256:f49a843c290594dcf4d193535d1f4ba8af7d56cea2cf79d1e9554f077f1e7aaa

Cloud Run

Run the following command from the deploy-hooks-run-quickstart directory to create a release resource that represents the container image to deploy:

 gcloud deploy releases create test-release-001 \
   --project=PROJECT_ID \
   --region=us-central1 \
   --delivery-pipeline=deploy-hooks-demo-app-run-1 \
   --images=my-app-image=us-docker.pkg.dev/cloudrun/container/hello@sha256:4a856b6f1c3ce723a456ddc2adfbb794cbfba93f727e2d96fcf6540bd0d6fff4

As with all releases (unless they include --disable-initial-rollout), Cloud Deploy automatically creates a rollout resource too. The application is automatically deployed into the one target configured for this delivery pipeline.

Also, the pre-deploy job runs before the application is deployed, and the post-deploy job runs after.

View the results in Google Cloud console

After a few minutes, your release is deployed into your target runtime.

The pre- and post-deploy hooks that we configured (for example purposes) print strings to the Cloud Build logs. We can view those logs to confirm that the hooks worked as expected.

  1. In the Google Cloud console, navigate to the Cloud Deploy Delivery pipelines page to view your delivery pipeline ("deploy-hooks-demo-app-gke-1" or "deploy-hooks-demo-app-run-1").

    Open the Delivery pipelines page

  2. Click the name of your delivery pipeline ("deploy-hooks-demo-app-gke-1" or "deploy-hooks-demo-app-run-1").

    The pipeline visualization shows the app's deployment status. Because there's only one stage in the pipeline, the visualization shows only one node.

    Delivery pipeline visualization showing success

    And your release is listed on the Releases tab under Delivery pipeline details.

  3. Click the Rollouts tab, under Delivery pipeline details.

  4. Click the rollout name to view the rollout details.

    rollouts in Google Cloud console

    Predeploy and Postdeploy are listed as jobs.

  5. Click Predeploy

    The job run log is displayed.

  6. Scroll down in the list of log entries to find predeploy-echo, and click it.

    Log for the Predeploy job

    Notice the textPayload. That string is what was configured in the predeploy-action in your Skaffold configuration.

  7. Click the Postdeploy job, and find the postdeploy-echo log entry.

    Log for the Postdeploy job

Clean up

To avoid incurring charges to your Google Cloud account for the resources used on this page, follow these steps.

  1. Delete the GKE cluster or Cloud Run service:

    GKE

    gcloud container clusters delete deploy-hooks-cluster --region=us-central1 --project=PROJECT_ID
    

    Cloud Run

    gcloud run services delete my-hooks-run-service --region=us-central1 --project=PROJECT_ID
    
  2. Delete the delivery pipeline, target, release, and rollout:

    gcloud deploy delete --file=clouddeploy.yaml --force --region=us-central1 --project=PROJECT_ID
    
  3. Delete the Cloud Storage buckets that Cloud Deploy created.

    One ends with _clouddeploy, and the other is [region].deploy-artifacts.[project].appspot.com.

    Open the Cloud Storage browser page

That's it, you completed this quickstart!

What's next