Gerenciar recursos do Service Usage com o Terraform

Neste documento, descrevemos como provisionar recursos do Service Usage, como substituições de cotas, usando o Terraform.

Para gerenciar substituições de cota do consumidor, use o esquema google_service_usage_consumer_quota_override para especificar recursos no arquivo de configuração do Terraform e execute os comandos do Terraform para aplicar a mudança.

Antes de começar

Consulte o modelo de cota de serviço, que descreve a terminologia usada neste tutorial.

Configure o Terraform e as credenciais:

  1. Instale o Terraform.

  2. Instale o SDK do Google Cloud.

  3. Crie as credenciais padrão do aplicativo:

    gcloud auth application-default login
    

Criar substituições de cota do consumidor

  1. Crie o arquivo de configuração:

    1. Navegue até o diretório de trabalho.

    2. Copie e cole o conteúdo abaixo em um novo arquivo chamado main.tf.

    resource "google_service_usage_consumer_quota_override" "regional_override" {
      provider       = google-beta
      dimensions = {
        region = "us-central1"
      }
      project        = PROJECT_ID
      service        = "libraryagent.googleapis.com"
      metric         = "libraryagent.googleapis.com%2Fread_requests_regional"
      limit          = "%2Fmin%2Fproject%2Fregion"
      override_value = "8"
      force          = true
    }
    
    resource "google_service_usage_consumer_quota_override" "cd_override" {
      provider       = google-beta
      dimensions = {
        author = "larry"
      }
      project        = PROJECT_ID
      service        = "libraryagent.googleapis.com"
      metric         = "libraryagent.googleapis.com%2Fborrows"
      limit          = "%2Fauthor%2Fproject"
      override_value = "8"
      force          = true
    }
    

    O conteúdo colocado no arquivo main.tf contém as informações de configuração de duas substituições de consumidor: "regional_override" e "cd_override". Consulte a Referência de argumentos sobre as explicações de cada campo.

  2. Inicialize o diretório de trabalho.

    terraform init -upgrade
    
  3. Aplique a configuração do Terraform.

    terraform apply
    

    O Terraform inspeciona o estado atual e o compara com as informações no arquivo de configuração. Depois que a comparação for concluída, o Terraform vai mostrar uma lista de mudanças e oferecer opções para prosseguir ou cancelar a aplicação das mudanças.

    GoSM: Setting up security policy for terraform binary.
    GoSM: Setting up security policy for terraform binary.
    google_service_usage_consumer_quota_override.cd_override: Refreshing state... [id=projects/loas-linweic/services/libraryagent.googleapis.com/consumerQuotaMetrics/libraryagent.googleapis.com%2Fborrows/limits/%2Fauthor%2Fproject/consumerOverrides/Cg1RdW90YU92ZXJyaWRlGg8KBmF1dGhvchIFbGFycnk=]
    
    An execution plan has been generated and is shown below.
    Resource actions are indicated with the following symbols:
      + create
    
    Terraform will perform the following actions:
    
      # google_service_usage_consumer_quota_override.cd_override will be created
      + resource "google_service_usage_consumer_quota_override" "cd_override" {
          + dimensions     = {
              + "author" = "larry"
            }
          + force          = true
          + id             = (known after apply)
          + limit          = "%2Fauthor%2Fproject"
          + metric         = "libraryagent.googleapis.com%2Fborrows"
          + name           = (known after apply)
          + override_value = "8"
          + project        = "loas-linweic"
          + service        = "libraryagent.googleapis.com"
        }
    
      # google_service_usage_consumer_quota_override.regional_override will be created
      + resource "google_service_usage_consumer_quota_override" "regional_override" {
          + dimensions     = {
              + "region" = "us-central1"
            }
          + force          = true
          + id             = (known after apply)
          + limit          = "%2Fmin%2Fproject%2Fregion"
          + metric         = "libraryagent.googleapis.com%2Fread_requests_regional"
          + name           = (known after apply)
          + override_value = "8"
          + project        = "loas-linweic"
          + service        = "libraryagent.googleapis.com"
        }
    
    Plan: 2 to add, 0 to change, 0 to destroy.
    
    Do you want to perform these actions?
      Terraform will perform the actions described above.
      Only 'yes' will be accepted to approve.
    
      Enter a value:
    
    

    Digite yes:

    Enter a value: yes
    
    google_service_usage_consumer_quota_override.regional_override: Creating...
    google_service_usage_consumer_quota_override.cd_override: Creating...
    google_service_usage_consumer_quota_override.cd_override: Still creating... [10s elapsed]
    google_service_usage_consumer_quota_override.regional_override: Still creating... [10s elapsed]
    google_service_usage_consumer_quota_override.cd_override: Creation complete after 12s [id=projects/loas-linweic/services/libraryagent.googleapis.com/consumerQuotaMetrics/libraryagent.googleapis.com%2Fborrows/limits/%2Fauthor%2Fproject/consumerOverrides/Cg1RdW90YU92ZXJyaWRlGg8KBmF1dGhvchIFbGFycnk=]
    google_service_usage_consumer_quota_override.regional_override: Creation complete after 12s [id=projects/loas-linweic/services/libraryagent.googleapis.com/consumerQuotaMetrics/libraryagent.googleapis.com%2Fread_requests_regional/limits/%2Fmin%2Fproject%2Fregion/consumerOverrides/Cg1RdW90YU92ZXJyaWRlGhUKBnJlZ2lvbhILdXMtY2VudHJhbDE=]
    
    Apply complete! Resources: 2 added, 0 changed, 0 destroyed.
    

Modificar substituições de cota do consumidor

  1. Para modificar uma substituição, edite o arquivo main.tf e mude o valor de um campo override_value.
  2. Aplique a configuração do Terraform.

    terraform apply
    

Excluir substituições de cota do consumidor

  1. Para excluir uma modificação de cota do consumidor, remova o bloco de recursos correspondente do arquivo main.tf. É possível remover várias substituições. Para remover todas as substituições, verifique se o arquivo main.tf está vazio.

  2. Aplique a configuração do Terraform.

    terraform apply
    

    Por exemplo, para excluir a substituição regional que você provisionou anteriormente. Exclua o bloco que se refere ao recurso:

    resource "google_service_usage_consumer_quota_override" "regional_override" {
      ...
    }
    

    A saída após terraform apply é a seguinte:

    GoSM: Setting up security policy for terraform binary.
    GoSM: Setting up security policy for terraform binary.
    google_service_usage_consumer_quota_override.regional_override: Refreshing state... [id=projects/loas-linweic/services/libraryagent.googleapis.com/consumerQuotaMetrics/libraryagent.googleapis.com%2Fread_requests_regional/limits/%2Fmin%2Fproject%2Fregion/consumerOverrides/Cg1RdW90YU92ZXJyaWRlGhUKBnJlZ2lvbhILdXMtY2VudHJhbDE=]
    google_service_usage_consumer_quota_override.cd_override: Refreshing state... [id=projects/loas-linweic/services/libraryagent.googleapis.com/consumerQuotaMetrics/libraryagent.googleapis.com%2Fborrows/limits/%2Fauthor%2Fproject/consumerOverrides/Cg1RdW90YU92ZXJyaWRlGg8KBmF1dGhvchIFbGFycnk=]
    
    An execution plan has been generated and is shown below.
    Resource actions are indicated with the following symbols:
      - destroy
    
    Terraform will perform the following actions:
    
      # google_service_usage_consumer_quota_override.regional_override will be destroyed
      - resource "google_service_usage_consumer_quota_override" "regional_override" {
          - dimensions     = {
              - "region" = "us-central1"
            } -> null
          - force          = true -> null
          - id             = "projects/loas-linweic/services/libraryagent.googleapis.com/consumerQuotaMetrics/libraryagent.googleapis.com%2Fread_requests_regional/limits/%2Fmin%2Fproject%2Fregion/consumerOverrides/Cg1RdW90YU92ZXJyaWRlGhUKBnJlZ2lvbhILdXMtY2VudHJhbDE=" -> null
          - limit          = "%2Fmin%2Fproject%2Fregion" -> null
          - metric         = "libraryagent.googleapis.com%2Fread_requests_regional" -> null
          - name           = "Cg1RdW90YU92ZXJyaWRlGhUKBnJlZ2lvbhILdXMtY2VudHJhbDE=" -> null
          - override_value = "8" -> null
          - project        = "loas-linweic" -> null
          - service        = "libraryagent.googleapis.com" -> null
        }
    
    Plan: 0 to add, 0 to change, 1 to destroy.
    
    Do you want to perform these actions?
      Terraform will perform the actions described above.
      Only 'yes' will be accepted to approve.
    
      Enter a value:
    

    Digite yes para continuar:

    Enter a value: yes
    
    google_service_usage_consumer_quota_override.regional_override: Destroying... [id=projects/loas-linweic/services/libraryagent.googleapis.com/consumerQuotaMetrics/libraryagent.googleapis.com%2Fread_requests_regional/limits/%2Fmin%2Fproject%2Fregion/consumerOverrides/Cg1RdW90YU92ZXJyaWRlGhUKBnJlZ2lvbhILdXMtY2VudHJhbDE=]
    google_service_usage_consumer_quota_override.regional_override: Still destroying... [id=projects/loas-linweic/services/librarya...JyaWRlGhUKBnJlZ2lvbhILdXMtY2VudHJhbDE=, 10s elapsed]
    google_service_usage_consumer_quota_override.regional_override: Destruction complete after 11s
    
    Apply complete! Resources: 0 added, 0 changed, 1 destroyed.
    

Arquivos de estado

Observe que há dois arquivos gerados no seu diretório de trabalho: terraform.tfstate e terraform.tfstate.backup. O primeiro arquivo registra o estado atual da infraestrutura depois que você executa o terraform apply mais recente. O segundo arquivo registra o estado anterior ao terraform apply mais recente. Para mais informações sobre o estado do Terraform, consulte a documentação oficial.

Se você seguiu as etapas desta página até agora, o conteúdo a seguir está no arquivo terraform.tfstate, com o cd_override à esquerda na nossa infraestrutura.

  {
    "version": 4,
    "terraform_version": "0.12.31",
    "serial": 49,
    "lineage": "9dfbb2cc-7014-10ec-b8e1-ec9f36ea1acc",
    "outputs": {},
    "resources": [
      {
        "mode": "managed",
        "type": "google_service_usage_consumer_quota_override",
        "name": "cd_override",
        "provider": "provider.google-beta",
        "instances": [
          {
            "schema_version": 0,
            "attributes": {
              "dimensions": {
                "author": "larry"
              },
              "force": true,
              "id": "projects/loas-linweic/services/libraryagent.googleapis.com/consumerQuotaMetrics/libraryagent.googleapis.com%2Fborrows/limits/%2Fauthor%2Fproject/consumerOverrides/Cg1RdW90YU92ZXJyaWRlGg8KBmF1dGhvchIFbGFycnk=",
              "limit": "%2Fauthor%2Fproject",
              "metric": "libraryagent.googleapis.com%2Fborrows",
              "name": "Cg1RdW90YU92ZXJyaWRlGg8KBmF1dGhvchIFbGFycnk=",
              "override_value": "8",
              "project": "loas-linweic",
              "service": "libraryagent.googleapis.com",
              "timeouts": null
            },
            "private": "eyJlMmJmYjczMC1lY2FhLTExZTYtOGY4OC0zNDM2M2JjN2M0YzAiOnsiY3JlYXRlIjoyNDAwMDAwMDAwMDAsImRlbGV0ZSI6MjQwMDAwMDAwMDAwLCJ1cGRhdGUiOjI0MDAwMDAwMDAwMH19"
          }
        ]
      }
    ]
  }

No arquivo terraform.tfstate.backup, ele contém as duas substituições antes do deprovisionamento.

  {
    "version": 4,
    "terraform_version": "0.12.31",
    "serial": 47,
    "lineage": "9dfbb2cc-7014-10ec-b8e1-ec9f36ea1acc",
    "outputs": {},
    "resources": [
      {
        "mode": "managed",
        "type": "google_service_usage_consumer_quota_override",
        "name": "cd_override",
        "provider": "provider.google-beta",
        "instances": [
          {
            "schema_version": 0,
            "attributes": {
              "dimensions": {
                "author": "larry"
              },
              "force": true,
              "id": "projects/loas-linweic/services/libraryagent.googleapis.com/consumerQuotaMetrics/libraryagent.googleapis.com%2Fborrows/limits/%2Fauthor%2Fproject/consumerOverrides/Cg1RdW90YU92ZXJyaWRlGg8KBmF1dGhvchIFbGFycnk=",
              "limit": "%2Fauthor%2Fproject",
              "metric": "libraryagent.googleapis.com%2Fborrows",
              "name": "Cg1RdW90YU92ZXJyaWRlGg8KBmF1dGhvchIFbGFycnk=",
              "override_value": "8",
              "project": "loas-linweic",
              "service": "libraryagent.googleapis.com",
              "timeouts": null
            },
            "private": "eyJlMmJmYjczMC1lY2FhLTExZTYtOGY4OC0zNDM2M2JjN2M0YzAiOnsiY3JlYXRlIjoyNDAwMDAwMDAwMDAsImRlbGV0ZSI6MjQwMDAwMDAwMDAwLCJ1cGRhdGUiOjI0MDAwMDAwMDAwMH19"
          }
        ]
      },
      {
        "mode": "managed",
        "type": "google_service_usage_consumer_quota_override",
        "name": "regional_override",
        "provider": "provider.google-beta",
        "instances": [
          {
            "schema_version": 0,
            "attributes": {
              "dimensions": {
                "region": "us-central1"
              },
              "force": true,
              "id": "projects/loas-linweic/services/libraryagent.googleapis.com/consumerQuotaMetrics/libraryagent.googleapis.com%2Fread_requests_regional/limits/%2Fmin%2Fproject%2Fregion/consumerOverrides/Cg1RdW90YU92ZXJyaWRlGhUKBnJlZ2lvbhILdXMtY2VudHJhbDE=",
              "limit": "%2Fmin%2Fproject%2Fregion",
              "metric": "libraryagent.googleapis.com%2Fread_requests_regional",
              "name": "Cg1RdW90YU92ZXJyaWRlGhUKBnJlZ2lvbhILdXMtY2VudHJhbDE=",
              "override_value": "8",
              "project": "loas-linweic",
              "service": "libraryagent.googleapis.com",
              "timeouts": null
            },
            "private": "eyJlMmJmYjczMC1lY2FhLTExZTYtOGY4OC0zNDM2M2JjN2M0YzAiOnsiY3JlYXRlIjoyNDAwMDAwMDAwMDAsImRlbGV0ZSI6MjQwMDAwMDAwMDAwLCJ1cGRhdGUiOjI0MDAwMDAwMDAwMH19"
          }
        ]
      }
    ]
  }