### Example Snapshot List Output Source: https://cloud.google.com/architecture/performing-pitr-postgresql-database-compute-engine_hl=id Provides an example of the output format when listing snapshots, detailing the name, size, source disk, and status of each snapshot. ```text NAME DISK_SIZE_GB SRC_DISK STATUS instance-pg-pitr-data-1578339767 200 us-central1-f/disks/instance-pg-pitr-data READY instance-pg-pitr-wal-1578339767 100 us-central1-f/disks/instance-pg-pitr-wal READY ``` -------------------------------- ### Install Apache and Utilities Source: https://cloud.google.com/architecture/cold-recoverable-apps-persistent-disk-snapshots_hl=pt-br Installs the Apache web server, moreutils (for extended Unix utilities), and cloud-init on the system. Apache will serve the website content, while cloud-init is useful for initializing cloud instances. ```bash sudo apt-get update && sudo apt-get -y install apache2 moreutils cloud-init ``` -------------------------------- ### Example HTML Output Source: https://cloud.google.com/architecture/cold-recoverable-apps-persistent-disk-snapshots_hl=pt-br This is an example of the HTML output received when accessing the website through the load balancer. It shows a simple webpage structure. ```html HA / DR example

Welcome to a Compute Engine website with warm failover to Cloud Storage!

``` -------------------------------- ### Migrating to Google Cloud: Getting Started Source: https://cloud.google.com/architecture/landing-zones_hl=zh-cn Guidance on assessing existing workloads for migration readiness. ```text Migrate to Google Cloud: Get started ``` -------------------------------- ### Ensuring Deterministic Software Installation with Startup Scripts Source: https://cloud.google.com/architecture/enterprise-app-oracle-database-compute-engine_hl=es Explains how to ensure consistent software installations on VMs created from instance templates. Startup scripts should explicitly specify software versions to avoid inconsistencies. This example shows how to specify the Apache HTTP server version. ```bash # Example startup script snippet to install a specific Apache version # apt-get update && apt-get install -y apache2=2.4.53 ``` -------------------------------- ### Create Application Startup Script Source: https://cloud.google.com/architecture/cold-recoverable-apps-persistent-disk-snapshots_hl=pt-br This bash script, `app-startup.sh`, is designed to run on new VM instances. It installs `jq`, retrieves an OAuth token, fetches instance metadata (zone, project, name), finds the latest disk snapshot, and creates a new persistent disk from that snapshot, attaching it to the VM. ```bash sudo mkdir /opt/cloud-init-scripts sudo tee -a /opt/cloud-init-scripts/app-startup.sh >/dev/null <<'EOF' #!/bin/bash # Install jq and get an access token for API requests apt-get install -y jq OAUTH_TOKEN=$(curl "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token" \ -H "Metadata-Flavor: Google" --silent | jq -r '.access_token') # Make a request against the metadata server to determine the project name, # instance name, and what zone it's running in ZONE_INFO=$(curl http://metadata.google.internal/computeMetadata/v1/instance/zone \ -H "Metadata-Flavor: Google" --silent) PROJECT_NAME=$(curl http://metadata.google.internal/computeMetadata/v1/instance/zone \ -H "Metadata-Flavor: Google" --silent | awk -v FS="/" '{print $2}') ZONE_NAME=$(curl http://metadata.google.internal/computeMetadata/v1/instance/zone \ -H "Metadata-Flavor: Google" --silent | sed 's:.*/::') INSTANCE_NAME=$(curl http://metadata.google.internal/computeMetadata/v1/instance/name \ -H "Metadata-Flavor: Google" --silent) # Get the latest snapshot of the app disk LATEST_SNAPSHOT=$(curl -X GET -H "Authorization: Bearer $OAUTH_TOKEN" \ https://compute.googleapis.com/compute/v1/projects/$PROJECT_NAME/global/snapshots \ --silent | jq -s '.[].items[] | select(.name | contains("disk-$NAME")) | .name' \ | sort -r | head -n 1 | tr -d '"') # Create a persistent disk using the latest persistent disk snapshot curl -X POST -H "Authorization: Bearer $OAUTH_TOKEN" -H "Content-Type: application/json; charset=utf-8" \ https://compute.googleapis.com/compute/v1/$ZONE_INFO/disks \ --data '{"name":"'$LATEST_SNAPSHOT'-restored","sizeGb":"10","type":"zones/'$ZONE_NAME'/diskTypes/pd-ssd","sourceSnapshot":"https://www.googleapis.com/compute/v1/projects/'$PROJECT_NAME'/global/snapshots/'$LATEST_SNAPSHOT'"}' EOF ``` -------------------------------- ### Example VPC Variables Source: https://cloud.google.com/architecture/deploy-fault-tolerant-active-directory-environment_hl=es-419 Provides an example of how to set the variables for VPC name, region, and subnet CIDR ranges. ```powershell $VpcName = "ad" $Region = "us-central1" $SubnetRangeDomainControllers = "10.0.0.0/28" $SubnetRangeResources = "10.0.1.0/24" ``` -------------------------------- ### Basic HTML Web Page Output Source: https://cloud.google.com/architecture/cold-recoverable-apps-persistent-disk-snapshots_hl=pt-br This is an example of the HTML output expected from the web server, confirming successful Apache configuration and content loading from the persistent disk. ```html HA / DR example

Welcome to a test web server with persistent disk snapshots!

``` -------------------------------- ### Example JSONL for LLM Fine-tuning Source: https://cloud.google.com/architecture/ai-ml/generative-ai-knowledge-base_hl=es-419 This is an example of a line in a JSON Lines (JSONL) file used for fine-tuning a Large Language Model (LLM). Each line contains an input question and its corresponding output answer, structured for training. ```json {"input_text": "CONTEXT: With over 21 million residents, Beijing is the world's most populous national capital city and is China's second largest city after Shanghai. QUESTION: How many people live in Beijing?, "output_text": "21 million people"} ``` -------------------------------- ### Install Chrome Remote Desktop and Desktop Environment (Bash) Source: https://cloud.google.com/architecture/chrome-desktop-remote-on-compute-engine_hl=de This script updates package lists, installs Chrome Remote Desktop if not present, and optionally installs Google Chrome. It requires `wget` and `tasksel` for package management and desktop environment installation. ```bash #!/bin/bash EXTRA_PACKAGES="less bzip2 zip unzip tasksel wget" apt-get update if ! command -v chrome-remote-desktop &> /dev/null then if [[ ! -e /etc/apt/sources.list.d/chrome-remote-desktop.list ]] then echo "deb [arch=amd64] https://dl.google.com/linux/chrome-remote-desktop/deb stable main" \ | tee -a /etc/apt/sources.list.d/chrome-remote-desktop.list fi apt-get update DEBIAN_FRONTEND=noninteractive \ apt-get install --assume-yes chrome-remote-desktop fi # Placeholder for desktop environment installation # install_desktop_env # Example for installing Google Chrome if needed # [[ "$INSTALL_CHROME" = "yes" ]] && ! command -v google-chrome-stable &> /dev/null && \ # wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb -O /tmp/google-chrome-stable_current_amd64.deb && \ # apt-get install -y /tmp/google-chrome-stable_current_amd64.deb echo "Chrome remote desktop installation completed" ``` -------------------------------- ### Download and Install RIOT Migration Tool Source: https://cloud.google.com/architecture/partners/riot-live-migration-redis-enterprise-cloud/deployment_hl=fr Downloads the RIOT migration tool from GitHub, installs unzip, and then unzips the downloaded file to the VM's file system. ```bash sudo apt-get install unzip wget https://github.com/redis-developer/riot/releases/download/v2.19.0/riot-redis-2.19.0.zip unzip riot-redis-2.19.0.zip ``` -------------------------------- ### Terraform Apply Output Example Source: https://cloud.google.com/architecture/application-development/three-tier-web-app_hl=es-419 This is an example of the output you might see after a successful `terraform apply` command. It includes the frontend endpoint URL for accessing the deployed application and the name of the Cloud SQL instance. ```bash endpoint = "https://three-tier-app-fe-pn4ngg7gnq-uc.a.run.app" sqlservername = "three-tier-app-db-75c2" ``` -------------------------------- ### Automate Chrome Remote Desktop Installation Source: https://cloud.google.com/architecture/chrome-desktop-remote-on-compute-engine_hl=de A bash script designed to automate the installation of Chrome Remote Desktop and a chosen desktop environment on Debian-based systems. It includes functions for package installation, downloading files, and checking package status, with configurable environment variables for customization. ```shell #!/bin/bash -x # # Startup script to install Chrome remote desktop and a desktop environment. # # See environmental variables at then end of the script for configuration # function install_desktop_env { PACKAGES="desktop-base xscreensaver dbus-x11" if [[ "$INSTALL_XFCE" != "yes" && "$INSTALL_CINNAMON" != "yes" ]] ; then # neither XFCE nor cinnamon specified; install both INSTALL_XFCE=yes INSTALL_CINNAMON=yes fi if [[ "$INSTALL_XFCE" = "yes" ]] ; then PACKAGES="$PACKAGES xfce4" echo "exec xfce4-session" > /etc/chrome-remote-desktop-session [[ "$INSTALL_FULL_DESKTOP" = "yes" ]] && \ PACKAGES="$PACKAGES task-xfce-desktop" fi if [[ "$INSTALL_CINNAMON" = "yes" ]] ; then PACKAGES="$PACKAGES cinnamon-core" echo "exec cinnamon-session-cinnamon2d" > /etc/chrome-remote-desktop-session [[ "$INSTALL_FULL_DESKTOP" = "yes" ]] && \ PACKAGES="$PACKAGES task-cinnamon-desktop" fi DEBIAN_FRONTEND=noninteractive \ apt-get install --assume-yes $PACKAGES $EXTRA_PACKAGES systemctl disable lightdm.service } function download_and_install { # args URL FILENAME if [[ -e "$2" ]] ; then echo "cannot download $1 to $2 - file exists" return 1; fi curl -L -o "$2" "$1" && \ apt-get install --assume-yes --fix-broken "$2" && \ rm "$2" } function is_installed { # args PACKAGE_NAME dpkg-query --list "$1" | grep -q "^ii" 2>/dev/null return $? } # Configure the following environmental variables as required: INSTALL_XFCE=yes INSTALL_CINNAMON=yes INSTALL_CHROME=yes INSTALL_FULL_DESKTOP=yes ``` -------------------------------- ### Install and Configure Chrome Remote Desktop Host (PowerShell) Source: https://cloud.google.com/architecture/chrome-desktop-remote-windows-compute-engine_hl=de This PowerShell script automates the installation of the Chrome Remote Desktop host. It retrieves essential metadata like the command, PIN, and name, validates the PIN, downloads and installs the MSI package, and then starts the host service with the provided arguments. It also handles the installation of the Chrome browser. ```powershell $crdCommand = Get-Metadata('crd-command') $crdPin = Get-Metadata('crd--pin') $crdName = Get-Metadata('crd-name') if ($crdPin -isNot [Int32] -or $crdPin -gt 999999 -or $crdPin -lt 0) { throw "Metadata \"crd-pin\"=\"$crdPin\" is not a 6 digit number. Skipping Chrome Remote Desktop service installation." } # Prefix $crdPin with zeros if required. $crdPin = $crdPin.ToString("000000"); # Extract the authentication code and redirect URL arguments from the # remote dekstop startup command line. # $crdCommandArgs = $crdCommand.Split(' ') $codeArg = $crdCommandArgs | Select-String -Pattern '--code="[^"]+"' $redirectArg = $crdCommandArgs | Select-String -Pattern '--redirect-url="[^"]+"' if (-not $codeArg) { throw 'Cannot get --code= parameter from crd-command. Skipping Chrome Remote Desktop service installation.' } if (-not $redirectArg) { throw 'Cannot get --redirect-url= parameter from crd-command. Skipping Chrome Remote Desktop service installation.' } Write-Host 'Downloading Chrome Remote Desktop.' $installer = "$env:TEMP\chromeremotedesktophost.msi" $uri = 'https://dl.google.com/edgedl/chrome-remote-desktop/chromeremotedesktophost.msi' (New-Object Net.WebClient).DownloadFile($uri,"$installer") Write-Host 'Installing Chrome Remote Desktop.' & msiexec.exe /I $installer /qn /quiet | Out-Default Remove-Item $installer Write-Host 'Starting Chrome Remote Desktop service.' & "${env:ProgramFiles(x86)}\Google\Chrome Remote Desktop\CurrentVersion\remoting_start_host.exe" ` $codeArg $redirectArg --name=\"$crdName\" -pin=\"$crdPin\" | Out-Default Write-Host 'Downloading Chrome.' $installer = "$env:TEMP\chrome_installer.exe" $uri = 'https://dl.google.com/chrome/install/latest/chrome_installer.exe' (New-Object Net.WebClient).DownloadFile($uri,"$installer") Write-Host 'Installing Chrome.' & $installer /silent /install | Out-Default Remove-Item $installer ``` -------------------------------- ### Startup Script for Web App Deployment Source: https://cloud.google.com/architecture/framework/reliability/product-guides/load-balancing This startup script automates the process of updating packages, installing dependencies, cloning a web application repository, setting up a virtual environment, installing required packages, and finally launching the web application using gunicorn. It's designed to run when a VM instance starts. ```shell apt-get update apt-get -y install git python3-pip python3-venv git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git python3 -m venv venv ./venv/bin/pip3 install -Ur ./python-docs-samples/compute/managed-instances/demo/requirements.txt ./venv/bin/pip3 install gunicorn ./venv/bin/gunicorn --bind 0.0.0.0:80 app:app --daemon --chdir ./python-docs-samples/compute/managed-instances/demo ``` -------------------------------- ### Execute Configuration Script Source: https://cloud.google.com/architecture/cold-recoverable-apps-persistent-disk-snapshots_hl=pt-br This command executes the `configure-vm.sh` script, which presumably performs the necessary setup for the virtual machine. ```bash ./configure-vm.sh ``` -------------------------------- ### Download and Install RIOT Source: https://cloud.google.com/architecture/riot-live-migration-redis-enterprise-cloud/deployment_hl=it Downloads the RIOT tool (riot-redis-2.19.0.zip) from GitHub and extracts it. This process requires unzip and wget utilities. ```bash sudo apt-get install unzip wget https://github.com/redis-developer/riot/releases/download/v2.19.0/riot-redis-2.19.0.zip unzip riot-redis-2.19.0.zip ``` -------------------------------- ### Instalar pacote completo de aplicativos Xfce (Opcional) Source: https://cloud.google.com/architecture/chrome-desktop-remote-on-compute-engine_hl=pt-br Instala um conjunto mais abrangente de aplicativos de desktop Xfce. Este é um passo opcional para uma experiência de desktop mais completa. ```bash sudo apt install --assume-yes task-xfce-desktop ``` -------------------------------- ### Install R and Essentials in Vertex AI Workbench Source: https://cloud.google.com/architecture/data-science-with-r-on-gcp-eda This snippet installs R and essential packages using conda within a Vertex AI Workbench terminal. It ensures the correct version of R is available for data analysis tasks. The commands activate a new conda environment and then install the R essentials. ```bash conda create -n r conda activate r conda install -c r r-essentials r-base=4.3.2 ``` -------------------------------- ### Deploying terraform-example-Foundation from GitHub Source: https://cloud.google.com/architecture/security-foundations/summary_hl=fr This section details the steps for deploying the terraform-example-Foundation from GitHub. It covers creating a foundational pipeline, configuring organization-level resources, setting up environments, establishing networking, and creating an infrastructure pipeline. ```bash terraform-example-Foundation provides different sets of instructions for different CI/CD automation tools. Follow the README instructions for each stage to deploy terraform-example-Foundation from GitHub: * The `0-bootstrap` stage to create a foundational pipeline. If you are using a self-service billing account, you must request additional project quota before proceeding to the next stage. * The `1-org` stage to configure organization-level resources. * The `2-environments` stage to create environments. * The `3-networks-dual-svpc` `or` `3-networks-hub-and-spoke` stage to create networking resources in your preferred topology. * The `4-projects` stage to create an infrastructure pipeline. * Also, the `5-app-infra` stage for an example of using the infrastructure pipeline. ``` -------------------------------- ### Configure and Start Chrome Remote Desktop Service on Linux Source: https://cloud.google.com/architecture/chrome-desktop-remote-on-compute-engine_hl=zh-tw Configures and starts the Chrome Remote Desktop service on the Linux VM. This involves downloading the Chrome Remote Desktop package, installing it, and running the setup command. Requires root privileges. ```bash wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb sudo dpkg -i google-chrome-stable_current_amd64.deb sudo apt install -f cd /opt sudo git clone https://github.com/rustdesk/rustdesk-server cd rustdesk-server sudo ./setup.sh ``` -------------------------------- ### Install and Load R Packages for BigQuery Analysis Source: https://cloud.google.com/architecture/data-science-with-r-on-gcp-eda This R code checks for and installs necessary packages like 'dplyr', 'ggplot2', and 'bigrquery' if they are not already present. It then loads these packages into the current R session, making them available for use in data manipulation, visualization, and BigQuery interaction. ```r # List the necessary packages needed_packages <- c("dplyr", "ggplot2", "bigrquery") # Check if packages are installed installed_packages <- .packages(all.available = TRUE) missing_packages <- needed_packages[!(needed_packages %in% installed_packages)] # If any packages are missing, install them if (length(missing_packages) > 0) { install.packages(missing_packages) } # Load the required packages lapply(needed_packages, library, character.only = TRUE) ``` -------------------------------- ### Install JDK and RIOT on VM Source: https://cloud.google.com/architecture/partners/riot-live-migration-redis-enterprise-cloud/deployment_hl=ja Installs the default Java Development Kit (JDK) and downloads/unzipsthe RIOT migration tool on the Compute Engine VM. Requires `unzip` package. ```bash sudo apt install default-jre -y sudo apt-get install unzip wget https://github.com/redis-developer/riot/releases/download/v2.19.0/riot-redis-2.19.0.zip unzip riot-redis-2.19.0.zip ``` -------------------------------- ### Instalar pacote completo de aplicativos Cinnamon (Opcional) Source: https://cloud.google.com/architecture/chrome-desktop-remote-on-compute-engine_hl=pt-br Instala um conjunto completo de aplicativos de desktop Linux juntamente com o ambiente de desktop Cinnamon. Este é um passo opcional. ```bash sudo apt install --assume-yes task-cinnamon-desktop ``` -------------------------------- ### PowerShell Script for Chrome Remote Desktop Setup Source: https://cloud.google.com/architecture/chrome-desktop-remote-windows-compute-engine_hl=zh-cn This PowerShell script automates the installation and configuration of Chrome Remote Desktop on a Windows VM. It retrieves necessary parameters like the command, PIN, and name from instance metadata, downloads and installs the Chrome Remote Desktop host and Chrome browser, and then starts the host service. ```powershell cat << "EOF" > crd-sysprep-script.ps1 <# .SYNOPSIS GCESysprep specialize script for unattended Chrome Remote Desktop installation. #> $ErrorActionPreference = 'stop' function Get-Metadata([String]$metadataName) { try { $value = (Invoke-RestMethod ` -Headers @{'Metadata-Flavor' = 'Google'} ` -Uri "http://metadata.google.internal/computeMetadata/v1/instance/attributes/$metadataName") } catch { # Report but ignore REST errors. Write-Host $_ } if ($value -eq $null -or $value.Length -eq 0) { throw "Metadata value for \"$metadataName\" not specified. Skipping Chrome Remote Desktop service installation." } return $value } # Get config from metadata # $crdCommand = Get-Metadata('crd-command') $crdPin = Get-Metadata('crd-pin') $crdName = Get-Metadata('crd-name') if ($crdPin -isNot [Int32] -or $crdPin -gt 999999 -or $crdPin -lt 0) { throw "Metadata \"crd-pin\"=\"$crdPin\" is not a 6 digit number. Skipping Chrome Remote Desktop service installation." } # Prefix $crdPin with zeros if required. $crdPin = $crdPin.ToString("000000"); # Extract the authentication code and redirect URL arguments from the # remote dekstop startup command line. # $crdCommandArgs = $crdCommand.Split(' ') $codeArg = $crdCommandArgs | Select-String -Pattern '--code="[^"]+"' $redirectArg = $crdCommandArgs | Select-String -Pattern '--redirect-url="[^"]+"' if (-not $codeArg) { throw 'Cannot get --code= parameter from crd-command. Skipping Chrome Remote Desktop service installation.' } if (-not $redirectArg) { throw 'Cannot get --redirect-url= parameter from crd-command. Skipping Chrome Remote Desktop service installation.' } Write-Host 'Downloading Chrome Remote Desktop.' $installer = "$env:TEMP\chromeremotedesktophost.msi" $uri = 'https://dl.google.com/edgedl/chrome-remote-desktop/chromeremotedesktophost.msi' (New-Object Net.WebClient).DownloadFile($uri,"$installer") Write-Host 'Installing Chrome Remote Desktop.' & msiexec.exe /I $installer /qn /quiet | Out-Default Remove-Item $installer Write-Host 'Starting Chrome Remote Desktop service.' & "${env:ProgramFiles(x86)}\Google\Chrome Remote Desktop\CurrentVersion\remoting_start_host.exe" ` $codeArg $redirectArg --name=\"$crdName\" -pin=\"$crdPin\" | Out-Default Write-Host 'Downloading Chrome.' $installer = "$env:TEMP\chrome_installer.exe" $uri = 'https://dl.google.com/chrome/install/latest/chrome_installer.exe' (New-Object Net.WebClient).DownloadFile($uri,"$installer") Write-Host 'Installing Chrome.' & $installer /silent /install | Out-Default Remove-Item $installer EOF ``` -------------------------------- ### Install RIOT on Compute Engine VM Source: https://cloud.google.com/architecture/partners/riot-live-migration-redis-enterprise-cloud/deployment_hl=de Installs the Java Development Kit (JDK) and downloads/installs the RIOT migration tool on the Compute Engine VM via SSH. It then verifies the installation by checking the RIOT version. ```bash PROJECT_ID=$(gcloud info --format='value(config.project)') gcloud compute ssh redis-oss-riot-vm --project $PROJECT_ID --zone us-central1-a sudo apt install default-jre -y sudo apt-get install unzip wget https://github.com/redis-developer/riot/releases/download/v2.19.0/riot-redis-2.19.0.zip unzip riot-redis-2.19.0.zip ./riot-redis-2.19.0/bin/riot-redis -V ``` -------------------------------- ### Start Live RIOT Migration Source: https://cloud.google.com/architecture/riot-live-migration-redis-enterprise-cloud/deployment_hl=it Initiates a live data migration from the Redis OSS instance to Redis Enterprise Cloud. This command requires the source and destination connection details, including credentials and mode. ```bash ./riot-redis-2.19.0/bin/riot-redis -u redis://localhost:6379 replicate \ -u redis://ENDPOINT_IP:ENDPOINT_PORT \ -a REDIS_ENTERPRISE_DB_PASSWORD \ --mode live ``` -------------------------------- ### Launch GCDS Installer Source: https://cloud.google.com/architecture/identity/federating-gcp-with-active-directory-synchronizing-user-accounts This command executes the downloaded Google Cloud Directory Sync (GCDS) installer for Windows. It launches the installation wizard to begin the setup process. ```powershell .\dirsync-win64.exe ``` -------------------------------- ### Configurar cloud-init para script de inicialização Source: https://cloud.google.com/architecture/cold-recoverable-apps-persistent-disk-snapshots_hl=pt-br Este snippet cria um arquivo de configuração cloud-init para executar um script de inicialização bash quando uma VM é inicializada pela primeira vez. O script especificado é `/opt/cloud-init-scripts/app-startup.sh`. ```bash tee -a cloud-init.yaml >/dev/null <<'EOF' #cloud-config runcmd: - [ bash, /opt/cloud-init-scripts/app-startup.sh ] EOF ``` -------------------------------- ### Simulating Hardware Architectures with QEMU Source: https://cloud.google.com/architecture/connected-devices/best-practices-provisioning-configuring-bare-metal_hl=zh-cn Employ tools like QEMU to simulate different hardware architectures, enabling the customization and testing of OS or firmware images on architectures (e.g., ARM) different from your CI/CD environment's native architecture (e.g., x86_64). ```bash # Example: Running an ARM64 OS image using QEMU on an x86_64 host # This assumes you have an ARM64 disk image (e.g., arm64.qcow2) qemu-system-aarch64 \ -M virt \ -cpu cortex-a57 \ -smp 2 \ -m 1024 \ -kernel /path/to/your/arm64/kernel \ -drive file=/path/to/your/arm64.qcow2,format=qcow2,id=hd0 \ -device virtio-blk-pci,drive=hd0 \ -netdev user,id=net0 \ -device virtio-net-pci,netdev=net0 \ -nographic # You can also use QEMU for user-mode emulation to run individual binaries compiled for a different architecture. # Example: QEMU user-mode execution # qemu-aarch64 ./my_arm64_binary ``` -------------------------------- ### Create Cloud Storage Bucket Source: https://cloud.google.com/architecture/performing-pitr-postgresql-database-compute-engine_hl=id Creates a Cloud Storage bucket to archive WAL files from a PostgreSQL database. This command requires the gsutil tool to be installed and authenticated. ```bash gcloud storage buckets create gs://${ARCHIVE_BUCKET} ``` -------------------------------- ### Make Script Executable and Run Source: https://cloud.google.com/architecture/cold-recoverable-apps-persistent-disk-snapshots_hl=fr Instructions on how to make a shell script executable and then run it. ```APIDOC ## Make the configuration script executable and run it ### Description This section provides the commands to grant execute permissions to a shell script named `configure-vm.sh` and then execute it. This is typically done after creating or modifying a script. ### Method Shell Commands ### Endpoint N/A ### Parameters None ### Request Example ```bash chmod +x configure-vm.sh ./configure-vm.sh ``` ### Response N/A ``` -------------------------------- ### Install and Configure Chrome Remote Desktop Host (PowerShell) Source: https://cloud.google.com/architecture/chrome-desktop-remote-windows-compute-engine_hl=fr This PowerShell script installs the Chrome Remote Desktop host service. It downloads the MSI installer, installs it silently, and then starts the service using provided command-line arguments for authentication and redirection. It also handles the download and silent installation of the Chrome browser. ```powershell $crdCommandArgs = $crdCommand.Split(' ') $codeArg = $crdCommandArgs | Select-String -Pattern '--code="[^"]+"' $redirectArg = $crdCommandArgs | Select-String -Pattern '--redirect-url="[^"]+"' if (-not $codeArg) { throw 'Cannot get --code= parameter from crd-command. Skipping Chrome Remote Desktop service installation.' } if (-not $redirectArg) { throw 'Cannot get --redirect-url= parameter from crd-command. Skipping Chrome Remote Desktop service installation.' } Write-Host 'Downloading Chrome Remote Desktop.' $installer = "$env:TEMP\chromeremotedesktophost.msi" $uri = 'https://dl.google.com/edgedl/chrome-remote-desktop/chromeremotedesktophost.msi' (New-Object Net.WebClient).DownloadFile($uri,"$installer") Write-Host 'Installing Chrome Remote Desktop.' & msiexec.exe /I $installer /qn /quiet | Out-Default Remove-Item $installer Write-Host 'Starting Chrome Remote Desktop service.' & "${env:ProgramFiles(x86)}\Google\Chrome Remote Desktop\CurrentVersion\remoting_start_host.exe" ` $codeArg $redirectArg --name="$crdName" -pin="$crdPin" | Out-Default Write-Host 'Downloading Chrome.' $installer = "$env:TEMP\chrome_installer.exe" $uri = 'https://dl.google.com/chrome/install/latest/chrome_installer.exe' (New-Object Net.WebClient).DownloadFile($uri,"$installer") Write-Host 'Installing Chrome.' & $installer /silent /install | Out-Default Remove-Item $installer ``` -------------------------------- ### 프로비저닝 및 구성 도구 사용 Source: https://cloud.google.com/architecture/best-practices-provisioning-configuring-bare-metal_hl=ko 기기 프로비저닝 및 구성 중에 필요한 로직이 구현되지 않도록 조정 및 구현에 필요한 기본 요소를 제공하는 도구를 사용할 수 있습니다. 예를 들어, 로컬 호스트에 대해 실행되는 Ansible, Puppet 또는 Chef와 같은 구성 관리 도구 또는 스크립팅과 함께 cloud-init 및 해당 NoCloud 데이터 소스를 사용할 수 있습니다. ```bash ansible --help puppet --help chef --help cloud-init --help ``` -------------------------------- ### Criar Snapshot Manual de Disco (gcloud) Source: https://cloud.google.com/architecture/cold-recoverable-apps-persistent-disk-snapshots_hl=pt-br Cria um snapshot manual de um disco permanente. Este comando é usado para iniciar o processo ou para garantir que um snapshot exista antes que a programação automática comece a operar. ```bash gcloud compute disks snapshot disk-$NAME_SUFFIX \ --zone=$ZONE1 \ --snapshot-names=disk-$NAME_SUFFIX-$(date "+%Y%m%d%H%M%S") ``` -------------------------------- ### Install and verify RIOT on Compute Engine VM Source: https://cloud.google.com/architecture/partners/riot-live-migration-redis-enterprise-cloud/deployment_hl=ko Installs the Java Development Kit (JDK) and downloads/installs the RIOT migration tool on the Compute Engine VM. It also includes a command to verify the RIOT installation. ```bash PROJECT_ID=$(gcloud info --format='value(config.project)') gcloud compute ssh redis-oss-riot-vm --project $PROJECT_ID --zone us-central1-a ``` ```bash sudo apt install default-jre -y ``` ```bash sudo apt-get install unzip wget https://github.com/redis-developer/riot/releases/download/v2.19.0/riot-redis-2.19.0.zip unzip riot-redis-2.19.0.zip ``` ```bash ./riot-redis-2.19.0/bin/riot-redis -V ``` -------------------------------- ### Add Chrome Remote Desktop Repository and Install Source: https://cloud.google.com/architecture/chrome-desktop-remote-on-compute-engine_hl=de Adds the Chrome Remote Desktop repository to the apt package list and installs the chrome-remote-desktop package. It uses 'curl' to download the signing key and 'apt-get' for package management. The DEBIAN_FRONTEND=noninteractive parameter prevents interactive prompts during installation. ```bash curl https://dl.google.com/linux/linux_signing_key.pub \ | sudo gpg --dearmor -o /etc/apt/trusted.gpg.d/chrome-remote-desktop.gpg echo "deb [arch=amd64] https://dl.google.com/linux/chrome-remote-desktop/deb stable main" \ | sudo tee /etc/apt/sources.list.d/chrome-remote-desktop.list sudo apt-get update sudo DEBIAN_FRONTEND=noninteractive \ apt-get install --assume-yes chrome-remote-desktop ``` -------------------------------- ### Criar imagem de VM personalizada Source: https://cloud.google.com/architecture/cold-recoverable-apps-persistent-disk-snapshots_hl=pt-br Este comando cria uma imagem de VM personalizada a partir de um disco de origem, capturando a configuração do SO e do aplicativo para implantação em novas VMs. ```bash gcloud compute images create image-$NAME_SUFFIX \ --source-disk=vm-base-$NAME_SUFFIX \ --source-disk-zone=$ZONE1 \ --storage-location=$REGION ``` -------------------------------- ### Configurar cloud-init con fuente de datos NoCloud (Bash) Source: https://cloud.google.com/architecture/connected-devices/best-practices-provisioning-configuring-bare-metal_hl=es-419 Este ejemplo ilustra los pasos para configurar una fuente de datos cloud-init NoCloud en un dispositivo inicial, utilizando un sistema de archivos y la red para la entrega de datos a otros dispositivos. Se detallan las condiciones para descartar el propósito especial del dispositivo inicial. ```bash 1. Proporciona los datos de la fuente de datos de NoCloud al dispositivo inicial a través de un sistema de archivos. 2. Espera a que el dispositivo inicial complete su propio aprovisionamiento y configuración con su propósito especial, que incluye la entrega de datos de la fuente de datos NoCloud a otros dispositivos a través de la red. * ¿Existen otros dispositivos en el entorno que entreguen los datos de la fuente de datos de NoCloud a través de la red? * ¿Existen suficientes nodos en el clúster? * ¿Se completó la primera copia de seguridad? * ¿Está listo el sitio de recuperación ante desastres? 3. Aprovisiona y configura otros dispositivos que descarguen los datos de la fuente de datos NoCloud a través de la red desde el dispositivo de origen. Algunos dispositivos deben poder entregar los datos de la fuente de datos NoCloud a través de la red. 4. Los procesos de aprovisionamiento y configuración del dispositivo de origen se reanudan porque se cumplen las condiciones para descartar el propósito especial del dispositivo de origen: existen otros dispositivos en la flota que entregan los datos de la fuente de datos de NoCloud a través de la red. 5. Los procesos de aprovisionamiento y configuración del dispositivo de origen descartan el propósito especial, lo que hace que el dispositivo inicial no se pueda distinguir de otros dispositivos del mismo arquetipo. ``` -------------------------------- ### Install JDK and RIOT on Compute Engine VM Source: https://cloud.google.com/architecture/partners/riot-live-migration-redis-enterprise-cloud/deployment_hl=es-419 These commands are executed after SSHing into the Compute Engine VM. They first install the default Java Development Kit (JDK) required by RIOT, then download and unzip the RIOT migration tool from a GitHub release URL. ```bash sudo apt install default-jre -y ``` ```bash sudo apt-get install unzip wget https://github.com/redis-developer/riot/releases/download/v2.19.0/riot-redis-2.19.0.zip unzip riot-redis-2.19.0.zip ``` -------------------------------- ### Create Cloud Storage bucket and upload CSV data using gsutil in R Source: https://cloud.google.com/architecture/data-science-with-r-on-gcp-eda This R code snippet demonstrates how to interact with Google Cloud Storage using gsutil commands. It includes creating a new bucket, copying local CSV files to the bucket, and listing the contents of the bucket. Ensure you have gsutil installed and configured, and replace BUCKET_NAME with your actual bucket name. ```R gcs_url <- paste0("gs://", BUCKET_NAME, "/") command <- paste("gsutil mb", gcs_url) system(command) gcs_data_dir <- paste0("gs://", BUCKET_NAME, "/data") command <- paste("gsutil cp data/*_data.csv", gcs_data_dir) system(command) command <- paste("gsutil ls -l", gcs_data_dir) system(command, intern = TRUE) ``` -------------------------------- ### Bootstrap Foundation Pipeline with Terraform Source: https://cloud.google.com/architecture/blueprints/security-foundations/deployment-methodology This snippet details the initial setup for bootstrapping a Google Cloud organization and configuring a CI/CD pipeline for subsequent blueprint deployments. It involves cloning a Terraform example, configuring a bootstrap folder, and utilizing Cloud Build for pipeline automation. ```Shell git clone https://github.com/GoogleCloudPlatform/terraform-example-foundation.git cd terraform-example-foundation/ ./0-bootstrap/README.md ``` -------------------------------- ### Deploying terraform-example-foundation from GitHub Source: https://cloud.google.com/architecture/security-foundations/summary_hl=zh-tw This snippet outlines the phased deployment process for the terraform-example-foundation using Terraform from GitHub. It details the steps for creating the foundation pipeline, organization-level resources, environments, networks, and projects. ```bash # Phase 0: bootstrap # Phase 1: org # Phase 2: environments # Phase 3: networks-dual-svpc or networks-hub-and-spoke # Phase 4: projects # (Optional) Phase 5: app-infra ``` -------------------------------- ### List Available Snapshots Source: https://cloud.google.com/architecture/performing-pitr-postgresql-database-compute-engine_hl=id Lists all available snapshots in Google Cloud Compute Engine, showing their names, disk sizes, source disks, and readiness status. ```bash gcloud compute snapshots list ``` -------------------------------- ### Terraform Example Repository for Enterprise Foundation Source: https://cloud.google.com/architecture/security-foundations_hl=es This snippet refers to an example Terraform repository available on GitHub, containing deployable Terraform resources for the Enterprise Foundation Blueprint. It serves as a practical implementation guide. ```Terraform Terraform repository on GitHub containing deployable resources. ``` -------------------------------- ### Deploy Terraform Foundation Example Source: https://cloud.google.com/architecture/security-foundations/using-example-terraform_hl=id This snippet refers to the 'terraform-example-foundation' GitHub repository, which contains deployable Terraform assets for setting up an enterprise foundation on Google Cloud. It's intended for users who want to deploy all recommendations as a starting point or review existing Google Cloud environments against best practices. ```shell git clone https://github.com/GoogleCloudPlatform/terraform-example-foundation.git cd terraform-example-foundation terraform init terraform apply ``` -------------------------------- ### Exemplo de Status da VM Source: https://cloud.google.com/architecture/cold-recoverable-apps-persistent-disk-snapshots_hl=pt-br Exemplo de saída do comando `list-instances`, mostrando o status `RUNNING` e `HEALTHY` para a VM. ```text NAME ZONE STATUS HEALTH_STATE ACTION instance-vm-app us-central1-f RUNNING HEALTHY NONE ``` -------------------------------- ### Instalar Cinnamon e componentes básicos (Debian/Ubuntu) Source: https://cloud.google.com/architecture/chrome-desktop-remote-on-compute-engine_hl=pt-br Instala o ambiente de desktop Cinnamon e os componentes essenciais. Este comando garante que os pacotes básicos do Cinnamon sejam instalados. ```bash sudo DEBIAN_FRONTEND=noninteractive apt install --assume-yes cinnamon-core desktop-base dbus-x11 ``` -------------------------------- ### Parar VM antes de criar imagem Source: https://cloud.google.com/architecture/cold-recoverable-apps-persistent-disk-snapshots_hl=pt-br Para criar uma imagem de VM personalizada, primeiro você precisa parar a VM de base. Este comando interrompe a VM especificada. ```bash gcloud compute instances stop vm-base-$NAME_SUFFIX --zone=$ZONE1 ``` -------------------------------- ### VM Startup Failure Message Example Source: https://cloud.google.com/architecture/chrome-desktop-remote-windows-compute-engine_hl=zh-tw An example of a log message indicating a failure to start the Chrome Remote Desktop service, possibly due to an expired OAuth token. ```text sysprep-specialize-script-ps1: ... Failed to read 'C:\\ProgramData\\Google\\Chrome Remote Desktop\\host_unprivileged.json'.: The system cannot find the path specified. (0x3) ``` -------------------------------- ### 使用 QEMU 模擬硬體架構 Source: https://cloud.google.com/architecture/best-practices-provisioning-configuring-bare-metal_hl=zh-tw 使用 QEMU 等工具模擬不同的硬體架構,以便在 CI/CD 環境中建構映像檔。這對於確保映像檔與目標裝置相容性非常重要。 ```Shell qemu-system-aarch64 -M virt -cpu cortex-a53 -nographic -initrd initrd.img -kernel vmlinuz -append "root=/dev/vda console=ttyAMA0" ``` -------------------------------- ### Installieren der KDE Plasma-Desktop-Umgebung Source: https://cloud.google.com/architecture/chrome-desktop-remote-on-compute-engine_hl=de Installiert die vollständige KDE Plasma-Desktop-Umgebung auf der VM-Instanz. Der Parameter DEBIAN_FRONTEND=noninteractive unterdrückt die Tastaturkonfigurationsaufforderung. ```bash sudo DEBIAN_FRONTEND=noninteractive \ apt install --assume-yes task-kde-desktop ``` -------------------------------- ### VM Initialization Failure Example Source: https://cloud.google.com/architecture/chrome-desktop-remote-windows-compute-engine_hl=pt-br This log message indicates a failure in starting the Chrome Remote Desktop host, often due to an invalid or expired OAuth token. This can be resolved by reconfiguring the instance or starting over. ```text sysprep-specialize-script-ps1: Couldn't start host: OAuth error. ``` -------------------------------- ### Clone and Setup Online Boutique Source: https://cloud.google.com/architecture/migrating-containers-multi-cluster-gke Clones the Online Boutique microservices demo repository from GitHub and sets a working directory variable for subsequent commands. ```shell cd ~ git clone --branch release/v0.4.1 \ https://github.com/GoogleCloudPlatform/microservices-demo.git cd microservices-demo/release && export WORKDIR=`pwd` ``` -------------------------------- ### Cloud Build Configuration Example Source: https://cloud.google.com/architecture/architecture-for-mlops-using-tfx-kubeflow-pipelines-and-cloud-build_hl=pt-br An example of a `cloudbuild.yaml` file that defines the steps executed by Cloud Build for a CI/CD pipeline. This includes copying source code, running tests, building Docker images, uploading to Artifact Registry, and compiling pipeline definitions. ```yaml steps: - name: 'gcr.io/cloud-builders/git' args: ['clone', 'https://github.com/GoogleCloudPlatform/mlops-on-gcp.git', '/workspace'] - name: 'python:3.9' entrypoint: 'python' args: ['-m', 'pytest'] - name: 'gcr.io/cloud-builders/docker' args: ['build', '-t', 'us-central1-docker.pkg.dev/PROJECT_ID/my-repo/my-image:$COMMIT_SHA', '.'] - name: 'gcr.io/cloud-builders/docker' args: ['push', 'us-central1-docker.pkg.dev/PROJECT_ID/my-repo/my-image:$COMMIT_SHA'] # Add steps for updating component.yaml, compiling pipeline.json, and uploading to Artifact Registry ``` -------------------------------- ### Get Timeseries Data using Cloud Monitoring API (HTTP GET) Source: https://cloud.google.com/architecture/monitoring-metric-export_hl=es Demonstrates how to make an HTTP GET request to the Cloud Monitoring API to retrieve timeseries data. It includes essential parameters such as start and end times, alignment period, aligner, reducer, filter, and group-by fields. This method is useful for aggregating and analyzing metric data over specific time intervals. ```HTTP https://monitoring.googleapis.com/v3/projects/sage-facet-201016/timeSeries? interval.startTime=START_TIME_VALUE& interval.endTime=END_TIME_VALUE& aggregation.alignmentPeriod=ALIGNMENT_VALUE& aggregation.perSeriesAligner=ALIGNER_VALUE& aggregation.crossSeriesReducer=REDUCER_VALUE& filter=FILTER_VALUE& aggregation.groupByFields=GROUP_BY_VALUE ``` ```HTTP https://monitoring.googleapis.com/v3/projects/sage-facet-201016/timeSeries? interval.startTime=2019-02-19T20%3A00%3A01.593641Z& interval.endTime=2019-02-19T21%3A00%3A00.829121Z& aggregation.alignmentPeriod=3600s& aggregation.perSeriesAligner=ALIGN_SUM& aggregation.crossSeriesReducer=REDUCE_SUM& filter=metric.type%3D%22kubernetes.io%2Fnode_daemon%2Fmemory%2Fused_bytes%22+& aggregation.groupByFields=metric.labels.key ``` -------------------------------- ### Install JDK and RIOT on Compute Engine VM Source: https://cloud.google.com/architecture/partners/riot-live-migration-redis-enterprise-cloud/deployment Installs the default Java Development Kit (JDK) and downloads and installs the RIOT migration tool (v2.19.0) on the Compute Engine VM. It also includes a command to verify the RIOT installation. ```bash sudo apt install default-jre -y ``` ```bash sudo apt-get install unzip wget https://github.com/redis-developer/riot/releases/download/v2.19.0/riot-redis-2.19.0.zip unzip riot-redis-2.19.0.zip ``` ```bash ./riot-redis-2.19.0/bin/riot-redis -V ```