Connecting [Cloud Build triggers](https://docs.cloud.google.com/build/docs/triggers.md.txt) with
Infrastructure Manager lets you automate infrastructure deployments directly
from your Git repositories. In this workflow, pull requests generate a
[deployment preview](https://docs.cloud.google.com/infrastructure-manager/docs/preview-deployment.md.txt), and
merged commits automatically
[create](https://docs.cloud.google.com/infrastructure-manager/docs/deploy-resources.md.txt) or
[update the deployment](https://docs.cloud.google.com/infrastructure-manager/docs/update-deployment.md.txt).

## Before you begin

1. Enable the required APIs in your project:

   - [Infra Manager API](https://docs.cloud.google.com/infrastructure-manager/docs/enable-service.md.txt) (`config.googleapis.com`)
   - Cloud Build API (`cloudbuild.googleapis.com`)
   - Secret Manager API (`secretmanager.googleapis.com`)
   - Identity and Access Management (IAM) API (`iam.googleapis.com`)
   - Cloud Storage API (`storage.googleapis.com`)

   Enable these APIs using the `gcloud` CLI:

   ```bash
   gcloud services enable \
       config.googleapis.com \
       cloudbuild.googleapis.com \
       secretmanager.googleapis.com \
       iam.googleapis.com \
       storage.googleapis.com
   ```
2. Ensure you have a service account with the required roles. For details, see
   [Configure the service account](https://docs.cloud.google.com/infrastructure-manager/docs/configure-service-account.md.txt).

3. Identify the existing Git repository that has the Terraform configuration.
   When you set up the automation described in this document,
   Infra Manager uses this Terraform configuration to update resources.

4. Recommended: Set up
   [branch protection](https://docs.cloud.google.com/docs/terraform/resource-management/managing-infrastructure-as-code.md.txt#enforcing_cloud_build_execution_success_before_merging_branches)
   for your Git repository.

### Required roles

To automate deployments, your user account, the deploying service account, and
the Cloud Build service agent each require specific IAM roles.

#### Your user account roles


To get the permissions that
you need to create deployments,

ask your administrator to grant you the
following IAM roles:

- [Cloud Infrastructure Manager Admin](https://docs.cloud.google.com/iam/docs/roles-permissions/config.md.txt#config.admin) (`roles/config.admin`) on your project
- [Service Account User](https://docs.cloud.google.com/iam/docs/roles-permissions/iam.md.txt#iam.serviceAccountUser) (`roles/iam.serviceAccountUser`) on the service account used to deploy the `im_cloudbuild_workspace` module


For details about configuring the service account, see
[Configure the service account](https://docs.cloud.google.com/infrastructure-manager/docs/configure-service-account.md.txt).

#### Deploying service account roles


To ensure that the service account that you specify in the
`--service-account` flag has the necessary
permissions to deploy the `im_cloudbuild_workspace`
module,

ask your administrator to grant the
following IAM roles to the service account that you specify in the
`--service-account` flag on your project:

**Important:** You must grant these roles to the service account that you specify in the `--service-account` flag, *not* to your user account. Failure to grant the roles to the correct principal might result in permission errors.

- [Cloud Infrastructure Manager Agent](https://docs.cloud.google.com/iam/docs/roles-permissions/config.md.txt#config.agent) (`roles/config.agent`)
- [Cloud Build Connection Admin](https://docs.cloud.google.com/iam/docs/roles-permissions/cloudbuild.md.txt#cloudbuild.connectionAdmin) (`roles/cloudbuild.connectionAdmin`)
- [Cloud Build Editor](https://docs.cloud.google.com/iam/docs/roles-permissions/cloudbuild.md.txt#cloudbuild.builds.editor) (`roles/cloudbuild.builds.editor`)
- [Secret Manager Admin](https://docs.cloud.google.com/iam/docs/roles-permissions/secretmanager.md.txt#secretmanager.admin) (`roles/secretmanager.admin`)
- Create the Cloud Build and Infra Manager service accounts (if you don't specify existing `cloudbuild_sa` and `infra_manager_sa` values in the `im_cloudbuild_workspace` module): [Service Account Admin](https://docs.cloud.google.com/iam/docs/roles-permissions/iam.md.txt#iam.serviceAccountAdmin) (`roles/iam.serviceAccountAdmin`)
- Grant project-level roles to the created service accounts (if you don't specify existing `cloudbuild_sa` and `infra_manager_sa` values in the `im_cloudbuild_workspace` module): [Project IAM Admin](https://docs.cloud.google.com/iam/docs/roles-permissions/resourcemanager.md.txt#resourcemanager.projectIamAdmin) (`roles/resourcemanager.projectIamAdmin`)


For details about specifying existing service accounts with the `cloudbuild_sa`
and `infra_manager_sa` variables, see the
[`im_cloudbuild_workspace` module `README`](https://github.com/terraform-google-modules/terraform-google-bootstrap/tree/master/modules/im_cloudbuild_workspace).

#### Cloud Build service agent roles


To ensure that the Cloud Build service agent
(`service-PROJECT_NUMBER@gcp-sa-cloudbuild.iam.gserviceaccount.com`) has the necessary
permissions to access the GitHub personal access token secret,

ask your administrator to grant the
[Secret Manager Secret Accessor](https://docs.cloud.google.com/iam/docs/roles-permissions/secretmanager.md.txt#secretmanager.secretAccessor) (`roles/secretmanager.secretAccessor`) IAM role to the Cloud Build service agent
(`service-PROJECT_NUMBER@gcp-sa-cloudbuild.iam.gserviceaccount.com`) on the Secret Manager secret that stores the
GitHub token.


**Important:** You must grant this role to the Cloud Build service agent (`service-PROJECT_NUMBER@gcp-sa-cloudbuild.iam.gserviceaccount.com`), *not* to your user account. Failure to grant the role to the correct principal might result in permission errors. For more information about granting roles, see [Manage access to projects, folders, and organizations](https://docs.cloud.google.com/iam/docs/granting-changing-revoking-access.md.txt).

<br />


Your administrator might also be able to give the Cloud Build service agent
(`service-PROJECT_NUMBER@gcp-sa-cloudbuild.iam.gserviceaccount.com`)
the required permissions through [custom
roles](https://docs.cloud.google.com/iam/docs/creating-custom-roles) or other [predefined
roles](https://docs.cloud.google.com/iam/docs/roles-overview#predefined).

In the preceding email address, `PROJECT_NUMBER` is the
project number of your project. In the `im_cloudbuild_workspace` module
configuration
([`github.tf` file](https://github.com/terraform-google-modules/terraform-google-bootstrap/blob/master/modules/im_cloudbuild_workspace/github.tf)),
the module grants `roles/secretmanager.secretAccessor` on the secret when the
deploying service account has `roles/secretmanager.admin`. If you use an
existing secret and manage its allow policy separately, grant
`roles/secretmanager.secretAccessor` on that secret to the Cloud Build
service agent.

## Automate the deployment of Google Cloud resources

> [!CAUTION]
> **Caution:** Infra Manager doesn't perform data migration or ensure service continuity. For example, if a revision deletes or replaces a database, it's your responsibility to manage data migration. Creating a revision can cause unrecoverable data loss. Reapplying the previous revision doesn't restore the data.

The following steps describe the setup required to automate the preview and
deployment of a Terraform configuration stored in a Git repository. A deployment
of a Terraform configuration can be a revision to an existing deployment.
Revisions might delete or replace provisioned Google Cloud resources.

When the setup is complete, a pull request in the Git repository causes
Infra Manager to create a preview of the deployment. When a pull
request is merged, Infra Manager automatically deploys the Terraform
configuration.

The `im_cloudbuild_workspace` module creates several resources, including:

- A Cloud Build repository connection.
- A Cloud Build trigger that is invoked when a pull request is created. This trigger causes Infra Manager to create a preview deployment using the Terraform configuration in the repository.
- A Cloud Build trigger that is invoked when a pull request is merged with the Git repository. This trigger causes Infra Manager to create or update the deployment using the Terraform configuration in the repository.

For more information about modifying the `im_cloudbuild_workspace` module's
behavior, see the
[`im_cloudbuild_workspace` module `README`](https://github.com/terraform-google-modules/terraform-google-bootstrap/tree/master/modules/im_cloudbuild_workspace).

To automate Terraform configuration deployments when the repository is
updated:

1. Install the [Cloud Build GitHub App](https://github.com/apps/google-cloud-build) on your GitHub account or in an organization you own.
2. [Create a classic GitHub personal access token](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens#creating-a-personal-access-token-classic).

   Cloud Build requires a classic GitHub personal access token;
   fine-grained personal access tokens aren't supported.

   Make sure to set your token to have no expiration date and select the
   following permissions when prompted in GitHub: `repo` and `read:user`. If
   your app is installed in an organization, make sure to also select the
   `read:org` permission.

   After you generate your personal access token, save your generated token in
   a secure place. You use the generated token in the following steps.

   > [!NOTE]
   > **Note:** If you have an authentication token stored in a secret from a previously created connection, you can use that same secret for the new connection.

3. Copy the `im_cloudbuild_workspace` module into the `main.tf` file within
   your Git repository:

   ```terraform
   module "im-workspace" {
    source = "terraform-google-modules/bootstrap/google//modules/im_cloudbuild_workspace"
    version = "~> 7.0"

    project_id = "PROJECT_ID"
    deployment_id = "DEPLOYMENT_ID"
    im_deployment_repo_uri = "GIT_REPO"
    im_deployment_ref = "REF"

    github_app_installation_id = "GIT_APP_ID"
    github_personal_access_token = "TOKEN"
   }
   ```

   Replace the following:
   - `PROJECT_ID`: the project ID where Infra Manager runs.
   - `DEPLOYMENT_ID`: the deployment identifier that you specify. See [Deployment ID](https://docs.cloud.google.com/infrastructure-manager/docs/deployments-revisions.md.txt#deployment-name) for details about constraints on the deployment identifier.
   - `GIT_REPO`: the URI of the Git repository.
   - `REF`: the Git reference of the configuration. The reference is optional. If you don't specify the reference, the Git repository's default configured branch is used.
   - `GIT_APP_ID`: the installation ID of the Cloud Build GitHub App used for pull and push request triggers.
   - `TOKEN`: a personal access token for a GitHub repository. If you provide a token, the module creates a secret in Secret Manager.
4. Create a deployment (or update your existing deployment) with the
   `im_cloudbuild_workspace` module:

   - If your Terraform configuration is in a public Git repository, deploy it by using the `gcloud infra-manager deployments apply` command with the `--git-source-repo` flag.
   - If your Terraform configuration is in a private Git repository, a
     Cloud Build connection to the repository must exist before you can
     use the `--git-source-repo` flag. Complete one of the following tasks:

     - [Connect your GitHub host and repository to Cloud Build](https://docs.cloud.google.com/build/docs/automating-builds/github/connect-repo-github.md.txt?generation=2nd-gen), and then run `gcloud infra-manager deployments apply --git-source-repo`.
     - Deploy the `im_cloudbuild_workspace` configuration from a local directory (`--local-source` flag) or a Cloud Storage bucket (`--gcs-source` flag) to create the connection first. For details, see [Deploy infrastructure using Infrastructure Manager](https://docs.cloud.google.com/infrastructure-manager/docs/deploy-resources.md.txt).

   ```bash
   gcloud infra-manager deployments apply \
       projects/PROJECT_ID/locations/LOCATION/deployments/DEPLOYMENT_ID \
       --service-account projects/SERVICE_ACCOUNT_PROJECT_ID/serviceAccounts/SERVICE_ACCOUNT \
       --git-source-repo=GIT_REPO \
       --git-source-directory=DIRECTORY \
       --git-source-ref=REF
   ```

   Replace the following:
   - `PROJECT_ID`: the project ID where Infra Manager runs.
   - `LOCATION`: the location where Infra Manager runs. See [Infra Manager locations](https://docs.cloud.google.com/infrastructure-manager/docs/locations.md.txt) for the list of locations.
   - `DEPLOYMENT_ID`: the deployment identifier that you specify. See [Deployment ID](https://docs.cloud.google.com/infrastructure-manager/docs/deployments-revisions.md.txt#deployment-name) for details about constraints on the deployment identifier.
   - `SERVICE_ACCOUNT_PROJECT_ID`: the project ID of the service account. It's common for this to be the same project where Infra Manager runs.
   - `SERVICE_ACCOUNT`: the email address of the service account that you use to call Infra Manager.
   - `GIT_REPO`: the URI of the Git repository.
   - `DIRECTORY`: the directory that has the Terraform configuration.
   - `REF`: the Git reference of the configuration. The reference is optional. If you don't specify the reference, the Git repository's default configured branch is used.
5. To confirm that your Git repository is connected correctly with
   Infra Manager,
   [create a pull request on your repository](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request).

   To see the results of the validation of the Terraform configuration,
   [view the pull request in GitHub](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/reviewing-changes-in-pull-requests/commenting-on-a-pull-request#discovering-and-navigating-conversations).

Now that this automation is set up, the Cloud Build triggers cause the
following:

- When a pull request is made to the repository, Infra Manager creates a preview deployment using the Terraform configuration stored in the Git repository.
- When a pull request is merged into the repository, Infra Manager updates the deployment using the Terraform configuration stored in the Git repository.

## What's next

- Use Cloud Build to [view build results for your build triggers](https://docs.cloud.google.com/build/docs/view-build-results-triggers.md.txt).
- [View resources deployed](https://docs.cloud.google.com/infrastructure-manager/docs/view-resources.md.txt) with Infra Manager.
- Monitor your Google Cloud resources with [Infrastructure Manager audit logging](https://docs.cloud.google.com/infrastructure-manager/docs/audit-logging.md.txt).