Google Professional Cloud Developerの模擬試験メモ

[模擬試験](https://docs.google.com/forms/d/e/1FAIpQLSc_67KaPnNwQrLZ7kuhw-aubz7gMAwY6DQwRJYcW0qlG-iajA/viewform?hl=ja)

# 受けてみた

1回目

正解数: 31
誤答数: 8

# 参考ドキュメント

## 1
https://cloud.google.com/kubernetes-engine/docs/concepts/service

- The idea of a Service is to group a set of Pod endpoints into a single resource
- a stable cluster IP address that clients inside the cluster can use to contact Pods in the Service
- A client sends a request to the stable IP address, and the request is routed to one of the Pods in the Service
- For a Pod to be a member of the Service, the Pod must have all of the labels specified in the selector

```yaml
apiVersion: v1
kind: Service
metadata:
  name: my-cip-service
spec:
  selector:
    app: metrics
    department: sales
  type: ClusterIP
  ports:
  - protocol: TCP
    port: 80
    targetPort: 8080
```

- cluster ip
- node port
- load balancer
- external name
- headless
    - A headless Service is a type of Kubernetes Service that does not allocate a cluster IP address
    - Instead, a headless Service uses DNS to expose the IP addresses of the Pods that are associated with the Service
    - Headless Services are a useful tool for accessing Services that are not located within the Kubernetes cluster itself, as the control plane does not create EndpointSlice objects


## 2

- https://cloud.google.com/kubernetes-engine/docs/how-to/workload-identity
    - Kubernetes ServiceAccount を参照する IAM 許可ポリシーを作成します
- https://kubernetes.io/docs/concepts/configuration/secret/
    - Secrets are similar to ConfigMaps but are specifically intended to hold confidential data
    - Kubernetes Secrets are, by default, stored unencrypted in the API server's underlying data store
    - one way to do that is to have Kubernetes make the value of that Secret be available as a file inside the filesystem of one or more of the Pod's containers
    - add an environment variable for each Secret key that you want to use to the `env[].valueFrom.secretKeyRef` field
- https://cloud.google.com/secret-manager/docs/overview

## 3

Istio とはオープンソースのサービスメッシュ・プラットフォームで、マイクロサービスが相互にデータを共有する方法を制御する手段を提供します

- https://istio.io/latest/docs/tasks/security/authorization/authz-http/
    - set up access control using Istio authorization
    - allow-nothing policy that rejects all requests to the workload
    -  productpage-viewer policy to allow access with GET method to the productpage workload
- https://kubernetes.io/docs/concepts/services-networking/network-policies/
    - NetworkPolicies apply to a connection with a pod on one or both ends, and are not relevant to other connections
    - Other pods that are allowed
    - Namespaces that are allowed
    - IP blocks
- https://istio.io/latest/docs/tasks/security/authentication/mtls-migration/
    - Istio automatically configures workload sidecars to use mutual TLS when calling other workloads

```yaml
kubectl apply -n foo -f - <<EOF
apiVersion: security.istio.io/v1beta1
kind: PeerAuthentication
metadata:
  name: default
spec:
  mtls:
    mode: STRICT
EOF
```

## 4

2と一緒

## 5

- https://cloud.google.com/kubernetes-engine/docs/how-to/vertical-pod-autoscaling
    - The Vertical Pod Autoscaler automatically analyzes your containers and provides suggested resource requests

```yaml
apiVersion: autoscaling.k8s.io/v1
kind: VerticalPodAutoscaler
metadata:
  name: my-rec-vpa
spec:
  targetRef:
    apiVersion: "apps/v1"
    kind:       Deployment
    name:       my-rec-deployment
  updatePolicy:
    updateMode: "Off"  # "Auto" とかも
```

- https://cloud.google.com/kubernetes-engine/docs/concepts/verticalpodautoscaler
    - If you create a VerticalPodAutoscaler object with an updateMode of Auto, the VerticalPodAutoscaler evicts a Pod if it needs to change the Pod's resource requests
    - To avoid cluster update disruptions, we recommend that you keep the number of VerticalPodAutoscaler objects per cluster under 1,000
    - Vertical Pod autoscaling works best with long-running homogenous workloads

## 6

略

## 7
- https://cloud.google.com/endpoints/docs/openapi/quotas-configure
    - x-google-management.metrics: A named metric that counts requests to your API
    - x-google-management.quota.limits: Represents a single enforceable limit on a named metric
    - x-google-quota.metricCosts: The metricCosts maps methods to metrics
- https://cloud.google.com/endpoints/docs/openapi/monitoring-your-api
    - At the top are graphs for some of the metrics, so you can spot any spikes and drops right away
    - When you are ready to drill down further, scroll below the graphs for a table with metrics for individual methods in your API
    - When you spot an issue in the metrics, go to the Logs Explorer page in the Google Cloud console to see logs of the requests and responses for your API
    - Because Endpoints uses the API key to identify the project that the calling application is associated with, the API key must have been created in the API consumer's Google Cloud project
    - You can use Monitoring to set up alerting on latency, traffic, and errors

## 8

- https://cloud.google.com/storage/docs/bucket-lock
    - The feature also lets you lock the bucket's retention policy, permanently preventing the policy from being reduced or removed
    - retention policy
        - objects in the bucket can only be deleted or replaced once their age is greater than the retention period
    - lock
        - cannot remove it or reduce the retention period it has
        - cannot delete a bucket with a locked policy unless every object in the bucket has met the retention period
        - Locking a bucket's retention policy is irreversible
    - Bucket retention policies and Object Versioning are mutually exclusive
- https://cloud.google.com/storage/docs/lifecycle
    -  rules which apply to current and future objects in the bucket


## 9

8と同じ

## 10

- https://cloud.google.com/serverless-options
    - run: abstracts away all infrastructure management by automatically scaling up and down from zero almost instantaneously
    - function: to connect with Google Cloud or third-party cloud services via triggers to streamline challenging orchestration problems
- https://cloud.google.com/appengine/docs/the-appengine-environments
    - standard
        - when need rapid scaling
        - run for free or at very low cost
        - application can scale to 0
        - sudden and extreme spikes of traffic
    - flexible
        - run within Docker containers on Compute Engine
        - receive consistent traffic, experience regular traffic fluctuations
        - source code written in other programming languages
        - Compute Engine network

## 11

- https://cloud.google.com/container-registry/docs/get-image-vulnerabilities#viewing_vulnerabilities_and_other_occurrences
    - Container Scanning API
    - Artifact Analysis
- https://cloud.google.com/container-registry/docs/container-analysis
    - gcr deprecated
    - you can use Binary Authorization to create deployment policies that only allow deployments for compliant images from trusted registries

## 12

- https://cloud.google.com/cloud-build/docs/speeding-up-builds
    - Kaniko キャッシュは、Cloud Build の機能の 1 つであり、コンテナビルドのアーティファクトをキャッシュに保存します
    - `--cache-from` 引数を追加すると、キャッシュされたイメージを指定できます
    - 以前のビルドの結果を Google Cloud Storage バケットにコピーし、その結果から計算を行い、新しい結果をコピーしてバケットに戻すことができます。ビルドに時間がかかるときに、生成されるファイル数が少なく、Google Cloud Storage とのコピーに時間がかからない場合は、この方法を使用します
    - アップロード時間を最適化するには、`.gcloudignore` ファイルを使用して、ビルドに不要なファイルを除外します

```yaml
steps:
- name: gcr.io/cloud-builders/gsutil
  args: ['cp', 'gs://mybucket/results.zip', 'previous_results.zip']
# operations that use previous_results.zip and produce new_results.zip
- name: gcr.io/cloud-builders/gsutil
  args: ['cp', 'new_results.zip', 'gs://mybucket/results.zip']
```

- https://cloud.google.com/build/docs/optimize-builds/increase-vcpu-for-builds
    - 高い性能の vCPU マシンを選択するとビルド速度は速くなりますが、Cloud Build はオンデマンドで標準以外のマシンのみを起動するため、ビルドの立ち上がり時間が長くなる可能性があります

```yaml
steps:
- name: 'gcr.io/cloud-builders/docker'
  args: ['build', '-t', 'gcr.io/my-project/image1', '.']
options:
  machineType: 'N1_HIGHCPU_8'
```

## 13

- https://cloud.google.com/run/docs/logging#container-logs
    - ログの出力先が次のいずれかであれば、Cloud Logging によってログが自動的に取得されます
        - stdout
        - stderr
        - /var/log
        - /dev/log
        - sdk
    - 単純なテキスト文字列を送信することも、シリアル化された JSON（構造化データ）の 1 行を送信することもできます
        - 解析された後、jsonPayload に配置されます
        - 単純なテキスト メッセージは textPayload に配置されます
    1. https://cloud.google.com/logging/docs/reference/libraries

## 14

- https://cloud.google.com/knative/
    - Knative は、元々 Google が 50 社を超える企業の協力を得て作成したもので、Kubernetes でサーバーレス アプリケーションをビルドし、実行するのに不可欠なコンポーネント セットを提供します
    - Knative には、ゼロへのスケーリング、自動スケーリング、クラスタ内ビルド、Kubernetes 上のクラウド ネイティブ アプリケーション用のイベント フレームワークなどの機能があります
    - Knative はそこがオンプレミスでも、クラウドでも、あるいはサードパーティのデータセンターでも、実際に成功している Kubernetes ベースのフレームワークに共通するベスト プラクティスを実体化します
    - Knative Serving defines a set of objects as Kubernetes Custom Resource Definitions
    - Knative Eventing is a collection of APIs that enable you to use an event-driven architecture with your applications
- https://cloud.google.com/blog/products/containers-kubernetes/when-to-use-google-kubernetes-engine-vs-cloud-run-for-containers

## 15

- https://cloud.google.com/functions/docs/securing/function-identity#per-function_identity
    - The service account a function uses as its identity is also known as its runtime service account
    - Cloud Functions (1st gen) uses the App Engine default service account, PROJECT_ID@appspot.gserviceaccount.com
    - Cloud Functions (2nd gen) uses the default compute service account, PROJECT_NUMBER-compute@developer.gserviceaccount.com
    - If your target service requires that you present an OpenID Connect ID token or an Oauth 2.0 access token, you might be able to use the Compute Metadata Server to fetch these tokens rather than setting up a full OAuth client
- https://cloud.google.com/storage/docs/access-control/iam-roles
- https://cloud.google.com/iam/docs/using-iam-securely#least_privilege
    - Basic roles include thousands of permissions across all Google Cloud services
    - In production environments, do not grant basic roles unless there is no alternative
    - Instead, grant the most limited predefined roles or custom roles that meet your needs. 
- https://cloud.google.com/iam/docs/understanding-service-accounts#granting_minimum_permissions_to_service_accounts
    - You should choose a more secure [alternative](https://cloud.google.com/docs/authentication#auth-decision-tree) to service account keys whenever possible
    - User-managed service accounts: Service accounts that you create and manage
    - Default service accounts: User-managed service accounts that are created automatically when you enable certain Google Cloud services
    - Service agents: Service accounts that are created and managed by Google Cloud, and that allow services to access resources on your behalf
    - Unused service accounts create an unnecessary security risk, so we recommend disabling unused service accounts, then deleting the service accounts when you are sure that you no longer need them
    - Service account insights tell you which service accounts in your project have not authenticated in the past 90 days
    - Activity Analyzer lets you check when a service account or key was last used

## 16

- https://cloud.google.com/iam/docs/understanding-roles
    - In production environments, do not grant basic roles unless there is no alternative
    - Predefined roles give granular access to specific Google Cloud resources and are created and maintained by Google
- https://cloud.google.com/sql/docs/mysql/connect-instance-kubernetes#set_up_a_service_account
    - app on Google Kubernetes Engine (GKE) connected to a MySQL
    - Create and configure a Google Cloud service account to be used by GKE so that it has the Cloud SQL Client role with permissions to connect to Cloud SQL
    - Create a Kubernetes service account configured to have access to Cloud SQL by binding it to the Google Cloud service account using Workload Identity
    - Run the kubectl create secret generic command as follows to create Kubernetes secrets for the database, user, and user password to be used by the sample app

## 17

- https://cloud.google.com/compute/docs/private-google-access/private-google-access
    - VM instances that only have internal IP addresses (no external IP addresses) can use Private Google Access
    - They can reach the external IP addresses of Google APIs and services
- https://cloud.google.com/vpc/docs/shared-vpc
    -  Shared VPC allows an organization to connect resources from multiple projects to a common Virtual Private Cloud (VPC) network so that they can communicate with each other securely and efficiently by using internal IP addresses from that network
    -  if they are in different folders the admin must have Shared VPC Admin rights to both folders

![example](https://cloud.google.com/static/vpc/images/shared-vpc/shared-vpc-example-concepts.png)

- https://cloud.google.com/vpc/docs/vpc-peering
    - Google Cloud VPC Network Peering connects two Virtual Private Cloud (VPC) networks so that resources in each network can communicate with each other
    - Peered VPC networks can be in the same project, different projects of the same organization, or different projects of different organizations
    - VPC Network Peering works with Compute Engine, GKE, and App Engine flexible environment
    - VPC Network Peering does not provide connectivity between `net-b` and `net-c` (`b - a - c`)
    - Peered VPC networks remain administratively separate
    - VPC Network Peering doesn't exchange VPC firewall rules or firewall policies
- https://cloud.google.com/interconnect/docs/how-to/carrier-peering
    - Carrier Peering enables you to access Google applications, such as Google Workspace, by using a service provider to obtain enterprise-grade network services that connect your infrastructure to Google
    - the organization can work with a service provider so that their traffic travels on a dedicated link from their systems to Google
    - Partner Interconnect is the recommended way to connect to Google through a service provider

## 18

https://cloud.google.com/profiler/docs/

Cloud Profiler is a statistical, low-overhead profiler that continuously gathers CPU usage and memory-allocation information from your production applications

## 19

- https://cloud.google.com/memorystore/docs/redis/redis-overview#connecting
    - use any standard Redis client on the following environments to connect to your Memorystore for Redis instance
        - App Engine flexible environment
        - App Engine standard environment
        - Compute Engine VM instances
        - Cloud Functions
        - Cloud Run
        - Google Kubernetes Engine clusters
    - Some serverless environments require a Serverless VPC Access connector as a prerequisite for connectivity with Memorystore for Redis
    - Memorystore for Redis currently supports RDB snapshots and exporting data
    - Memorystore for Redis does not support AOF persistence
    - Most parameters are preconfigured for Memorystore for Redis instances, and you cannot change them
- https://cloud.google.com/memorystore/docs/redis/connect-redis-instance-cloud-run
    - To connect to your Redis instance, your Cloud Run service needs access to the Redis instance's authorized VPC network
    - you need either Direct VPC egress or a Serverless VPC Access connector

`Direct VPC egress`
```bash
gcloud run deploy \
--image gcr.io/PROJECT_ID/visit-count \
--platform managed \
--allow-unauthenticated \
--region REGION \
--network NETWORK \
--subnet SUBNET \
--set-env-vars REDISHOST=REDIS_IP,REDISPORT=REDIS_PORT
```

`Serverless VPC Access`
```bash
gcloud run deploy \
--image gcr.io/PROJECT_ID/visit-count \
--platform managed \
--allow-unauthenticated \
--region REGION \
--vpc-connector CONNECTOR_NAME \
--set-env-vars REDISHOST=REDIS_IP,REDISPORT=REDIS_PORT
```

- https://cloud.google.com/vpc/docs/configure-serverless-vpc-access#creating_a_connector
    - Creating or deleting a connector requires Deployment Manager functionality
    - Each connector requires its own dedicated, `PRIVATE`-purpose subnet with a `/28` primary IPv4 address range
    - `gcloud run deploy SERVICE --image IMAGE_URL --vpc-connector CONNECTOR_NAME`

## 20

- https://kubernetes.io/docs/concepts/storage/persistent-volumes/#access-modes
    - A PersistentVolume (PV) is a piece of storage in the cluster that has been provisioned by an administrator or dynamically provisioned using Storage Classes
        - It is a resource in the cluster just like a node is a cluster resource
    - A PersistentVolumeClaim (PVC) is a request for storage by a use
    - `ReadWriteOnce`: the volume can be mounted as read-write by a single node
    - `ReadOnlyMany`
    - `ReadWriteMany`
    - `ReadWriteOncePod`: the volume can be mounted as read-write by a single Pod
- https://cloud.google.com/filestore/docs/accessing-fileshares
    - The Filestore CSI driver is the primary way for you to use Filestore instances with Google Kubernetes Engine
- https://cloud.google.com/storage/docs/gcs-fuse
    - a FUSE adapter that lets you mount and access Cloud Storage buckets as local file systems, so applications can read and write objects in your bucket using standard file system semantics
    - Cloud Storage FUSE works by translating object storage names into a file and directory system, interpreting the slash character ("/") in object names as a directory separator so that objects with the same common prefix are treated as files in the same directory

## 21

- https://cloud.google.com/run/docs/logging#correlate-logs
    - In the Logs Explorer, logs correlated by the same trace are viewable in "parent-child" format
    - To correlate container logs with request logs without using a client library, you can use a structured JSON log line that contains a `logging.googleapis.com/trace` field with the trace identifier extracted from the `X-Cloud-Trace-Context` header as shown in the above sample for structured logging
- https://cloud.google.com/logging/docs/structured-logging
    - When the log payload is formatted as a JSON object and that object is stored in the jsonPayload field, the log entry is called a structured log
    - Call the `entries.write` API method and supply a fully formatted `LogEntry`
    - Use a Cloud Logging client library which writes structured logs
    - Use the `gcloud logging write` command
    - Use the BindPlane service
    - Use an agent to write logs:
        - Some Google Cloud services contain an integrated logging agent that sends the data written to `stdout` or `stderr` as logs to Cloud Logging

## 22

https://cloud.google.com/pubsub/docs/subscriber#push-subscription

- Pull subscription
    - Large volume of messages (GBs per second)
    - Efficiency and throughput of message processing is critical
    - Environments where a public HTTPS endpoint with a non-self-signed SSL certificate is not feasible to set up
    - Any device on the internet that has authorized credentials is able to call the Pub/Sub API
    - Multiple subscribers can make pull calls to the same "shared" subscription
    - Each subscriber receives a subset of messages
    - The subscriber client controls the rate of delivery
- Push subscription
    - Multiple topics that must be processed by the same webhook
    - App Engine Standard and Cloud Functions subscribers
    - Environments where Google Cloud dependencies (such as credentials and the client library) are not feasible to set up
    - An HTTPS server with non-self-signed certificate accessible on the public web
    - The receiving endpoint might be decoupled from the Pub/Sub subscription, so that messages from multiple subscriptions are sent to a single endpoint
    - Push endpoints can be load balancers
    - The Pub/Sub server automatically implements flow control

## 23

- https://cloud.google.com/appengine/docs/flexible
    - App Engine flexible environment instances are Compute Engine virtual machines, which means that you can take advantage of custom libraries, use SSH for debugging, and deploy your own Docker containers
    - Instances are health-checked, healed as necessary, and co-located with other services within the project
- https://cloud.google.com/run/docs/overview/what-is-cloud-run
    - Cloud Run is built to rapidly scale out to handle all incoming requests or to handle increased CPU utilization outside requests if CPU allocation is set to `always on`
    - You can route incoming traffic to the latest revision, roll back to a previous revision, or split traffic to multiple revisions at the same time, to perform a gradual rollout

## 24

- https://developers.google.com/identity/protocols/oauth2?#4.-send-the-access-token-to-an-api
    - Then your client application requests an access token from the Google Authorization Server, extracts a token from the response, and sends the token to the Google API that you want to access
- https://cloud.google.com/run/docs/container-contract#metadata-server
    - Cloud Run instances expose a metadata server that you can use to retrieve details about your containers, such as the project ID, region, instance ID or service accounts
    - You can also use the metadata server to generate tokens for the service identity
- https://cloud.google.com/run/docs/securing/service-identity
    - When managing a revision or job, you use Cloud Run deployer account to make requests to the Cloud Run Admin API
    - When the Cloud Run code you wrote interacts with Cloud Client Libraries, or calls another Cloud Run service for service-to-service communication, you use Cloud Run service identity to make requests from Cloud Run to Google Cloud APIs or other Cloud Run services

## 25

1. https://developers.google.com/identity/protocols/OAuth2

## 26

1. https://cloud.google.com/load-balancing/docs/ssl-certificates/google-managed-certs

## 27

1. https://cloud.google.com/dataflow/docs/concepts/streaming-pipelines#windows

## 28

1. https://cloud.google.com/solutions/migrating-postgresql-to-gcp

## 29

1. https://cloud.google.com/build/docs/configuring-builds/configure-build-step-order
    1. https://cloud.google.com/build/docs/configuring-builds/create-basic-configuration

## 30

1. https://cloud.google.com/kubernetes-engine/docs/how-to/cluster-autoscaler
    1. https://cloud.google.com/kubernetes-engine/docs/concepts/cluster-autoscaler
    1. https://cloud.google.com/kubernetes-engine/docs/how-to/scaling-apps

## 31

1. https://cloud.google.com/run/docs/error-reporting

## 32

1. https://cloud.google.com/bigtable/docs/schema-design#types_of_row_keys
    1. https://cloud.google.com/bigtable/docs/schema-design-time-series#ensure_that_your_row_key_avoids_hotspotting

## 33

1. https://cloud.google.com/dataflow/docs/tutorials/dataflow-stream-to-bigquery
    1. https://cloud.google.com/architecture/reference-patterns/overview#general_analytics

## 34

1. https://cloud.google.com/run/docs/rollouts-rollbacks-traffic-migration#split-traffic

## 35

1. https://cloud.google.com/appengine/docs/standard/python/splitting-traffic

## 36

1. https://cloud.google.com/run/docs/triggering/pubsub-push
    1. https://cloud.google.com/pubsub/docs/admin

## 37
略

## 38

1. https://www.restapitutorial.com/httpstatuscodes.html