{"id":18962903,"url":"https://github.com/mafrosis/step-ca-on-gce","last_synced_at":"2026-02-09T11:07:25.441Z","repository":{"id":138921195,"uuid":"276986919","full_name":"mafrosis/step-ca-on-gce","owner":"mafrosis","description":"Smallstep Certificate Authority on Google Compute Engine","archived":false,"fork":false,"pushed_at":"2021-06-17T21:04:53.000Z","size":76,"stargazers_count":3,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-06-02T06:16:46.573Z","etag":null,"topics":["certificate-authority","gce","gcp","smallstep"],"latest_commit_sha":null,"homepage":"","language":"HCL","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/mafrosis.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2020-07-03T21:03:09.000Z","updated_at":"2023-02-19T11:13:56.000Z","dependencies_parsed_at":"2023-03-30T16:05:08.231Z","dependency_job_id":null,"html_url":"https://github.com/mafrosis/step-ca-on-gce","commit_stats":null,"previous_names":[],"tags_count":1,"template":false,"template_full_name":null,"purl":"pkg:github/mafrosis/step-ca-on-gce","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mafrosis%2Fstep-ca-on-gce","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mafrosis%2Fstep-ca-on-gce/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mafrosis%2Fstep-ca-on-gce/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mafrosis%2Fstep-ca-on-gce/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mafrosis","download_url":"https://codeload.github.com/mafrosis/step-ca-on-gce/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mafrosis%2Fstep-ca-on-gce/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":268370180,"owners_count":24239766,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-08-02T02:00:12.353Z","response_time":74,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["certificate-authority","gce","gcp","smallstep"],"created_at":"2024-11-08T14:17:05.680Z","updated_at":"2026-02-09T11:07:25.388Z","avatar_url":"https://github.com/mafrosis.png","language":"HCL","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Smallstep CA on GCE\n\n## Problem Statement\n\nI run [Home Assistant](https://www.home-assistant.io) in my home network, and wanted to expose that\nto the internet in order to integrate with a Google Home smart speaker. A sensible choice is to\nrequire mTLS client authentication on all inbound conections, but that is hard without\n[sound PKI](https://smallstep.com/blog/everything-pki/).\n\nThis is where the [Smallstep CA](https://github.com/smallstep/certificates) comes in.\n\n```\n┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ \n  step-ca project                                                        │\n│                                                                         \n           ┌────────────────────┐                                        │\n│          │ Cloud Run          │                                         \n           │    ┌───────────┐   │                                        │\n│          │    │           │   │              ┌──────────────────────┐   \n        ┌──┼───▶│   NGINX   │───┼──────┐       │ VPC subnet           │  │\n│       │  │    │           │   │      │       │                      │   \n        │  │    └───────────┘   │      │       │  ┌────────────────┐  │  │\n│       │  │          │         │    request   │  │                │  │   \n        │  └──────────┼─────────┘    TLS cert  │  │  Smallstep CA  │  │  │\n│       │             │                └───────┼─▶│    (GCE VM)    │  │   \n        │          proxied                     │  │                │  │  │\n│       │          request                     │  └────────────────┘  │   \n        │         with added                   │                      │  │\n│       │            mTLS                      └──────────────────────┘   \n        │             │                                                  │\n└ ─ ─ ─ ┼ ─ ─ ─ ─ ─ ─ ┼ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ \n        │             │                                                   \n      HTTPS           │       ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─                       \n        │             │         Home network       │                      \n        │             │       │                                           \n┌─ ── ── ── ── ─┐     │            ┌───────────┐   │                      \n│   External          │       │    │   Home    │                          \n Service without│     └───────────▶│ Assistant │   │                      \n│    CA cert    │             │    │           │                          \n└ ── ── ── ── ──                   └───────────┘   │                      \n                              │                                           \n                               ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘                      \n```\n\nIn this diagram, the \"external service\" cannot talk to Home Assistant as it doesn't support mTLS\nconnections. \n\nThe solution is to run a reverse-proxy which adds the mTLS certificate and forwards the request\nonto Home Assistant. Cloud Run is used as that cheaply provides a HTTPS endpoint on the web to which\nthe external service can connect.\n\n\n## Basic Setup\n\nRefer to [Smallstep's instructions](https://smallstep.com/docs/step-ca/installation) along with the\nbelow, as the following will not be up-to-date forever.\n\n\n### Install Smallstep CLI\n\nThe [CLI](https://github/smallstep/cli) is required to setup and interact with the CA from the shell:\n\n    curl -o /tmp/step.tgz -L https://github.com/smallstep/cli/releases/download/v0.15.14/step_linux_0.15.14_amd64.tar.gz\n    tar xzf /tmp/step.tgz --strip-components=1 -C /tmp\n    mv /tmp/bin/step /usr/local/bin\n\n### Install Smallstep CA\n\nInstall the actual [CA](https://github/smallstep/certificates):\n\n    curl -o /tmp/step-ca.tgz -L https://github.com/smallstep/certificates/releases/download/v0.15.11/step-certificates_linux_0.15.11_amd64.tar.gz\n    tar xzf /tmp/step-ca.tgz --strip-components=1 -C /tmp\n    mv /tmp/bin/step-ca /usr/local/bin\n\n\n### Configure and run Step CA\n\nExample `step-ca` configuration, adding a JWT provisioner called `admin`, and SSH cert support. This\nis copy-pasteable and will create files in `/tmp/step` for you to poke around:\n\n```\n\u003e export STEPPATH=/tmp/step \u0026\u0026 mkdir -p $STEPPATH\n\u003e step ca init --name=\"mafro.dev CA\" --provisioner=admin --dns=certs.mafro.dev --address=':443' --ssh\n✔ What do you want your password to be? [leave empty and we'll generate one]:\n✔ Password: ...\n\nGenerating root certificate...\nall done!\n\nGenerating intermediate certificate...\n\nGenerating user and host SSH certificate signing keys...\nall done!\n\n✔ Root certificate: /tmp/step/certs/root_ca.crt\n✔ Root private key: /tmp/step/secrets/root_ca_key\n✔ Root fingerprint: c7641ce4f91993dc3f00000000000000000000000f829c626d20fa02d89600e0\n✔ Intermediate certificate: /tmp/step/certs/intermediate_ca.crt\n✔ Intermediate private key: /tmp/step/secrets/intermediate_ca_key\n✔ SSH user root certificate: /tmp/step/certs/ssh_user_ca_key.pub\n✔ SSH user root private key: /tmp/step/secrets/ssh_user_ca_key\n✔ SSH host root certificate: /tmp/step/certs/ssh_host_ca_key.pub\n✔ SSH host root private key: /tmp/step/secrets/ssh_host_ca_key\n✔ Database folder: /tmp/step/db\n✔ Templates folder: /tmp/step/templates\n✔ Default configuration: /tmp/step/config/defaults.json\n✔ Certificate Authority configuration: /tmp/step/config/ca.json\n```\n\n\n## Setup GCP\n\nThere are a few requirements and manual steps required to make this work. Follow each section below\nto ensure you get a working result.\n\n\n### Prerequisites\n\n * A GCP Project\n * A DNS zone defined on your project\n * A service account for this project for running terraform. Save the key file somewhere safe.\n * Terraform v0.12.x in your `$PATH`\n\nSet your GCP project ID into an environment variable, so it can be easily used in the below commands\nand in the `Makefile`:\n\n    export PROJECT_ID=step-ca-a3dd5f\n\n\n### GCP Project and DNS zone\n\nSet the GCP project ID, and DNS zone in a file named `terraform.auto.tfvars`, in this format:\n\n    project_id = \"${PROJECT_ID}\"\n    dns_zone   = \"ca\"\n\n\n### Use Google Cloud KMS to create and host the CA keys\n\nA beta feature in Smallstep allows us to use private keys generated and hosted by Cloud KMS. This\nchanges the security posture considerably, since there is no raw access to the private keys, only\nIAM-managed access to _use_ the keys for encryption/signing.\n\nBased on the [documentation here](https://github.com/smallstep/certificates/blob/master/docs/kms.md),\nrun the following:\n\n```\n$ step-cloudkms-init -credentials-file=$GOOGLE_APPLICATION_CREDENTIALS \\\n    -location=australia-southeast1 \\\n    -project=${PROJECT_ID} \\\n    -ring=keyring-name \\\n    -ssh\nCreating PKI ...\n✔ Root Key: projects/a3dd5f/locations/global/keyRings/keyring-name/cryptoKeys/root/cryptoKeyVersions/1\n✔ Root Certificate: root_ca.crt\n✔ Intermediate Key: projects/a3dd5f/locations/global/keyRings/keyring-name/cryptoKeys/intermediate/cryptoKeyVersions/1\n✔ Intermediate Certificate: intermediate_ca.crt\n\nCreating SSH Keys ...\n✔ SSH User Public Key: ssh_user_ca_key.pub\n✔ SSH User Private Key: projects/a3dd5f/locations/global/keyRings/keyring-name/cryptoKeys/ssh-user-key/cryptoKeyVersions/1\n✔ SSH Host Public Key: ssh_host_ca_key.pub\n✔ SSH Host Private Key: projects/a3dd5f/locations/global/keyRings/keyring-name/cryptoKeys/ssh-host-key/cryptoKeyVersions/1\n```\n\nEdit `ca.json`, mapping in the Cloud KMS references according to this mapping:\n\n|Config key | KMS reference |\n|-|-|\n|`key`| Intermediate Key |\n|`hostKey`| SSH Host Private Key |\n|`userKey`| SSH User Private Key |\n\n**NB:** The GCP project ID is now hardcoded in `ca.json`, so if you delete and recreate your project,\nyou will need to update the configuration.\n\n\n### Webmaster privilege for Terraform service account\n\nThe [DNS mapping configuration](https://cloud.google.com/run/docs/mapping-custom-domains) for Cloud\nRun is not like normal DNS zones and records. The account which creates the mapping must be an\n`Owner` of the domain (or subdomain) in [Google's webmaster central](https://www.google.com/webmasters/verification/details).\n\nAdd the service account which runs the terraform as an owner of your custom domain, before running\nthe terraform.\n\n\n### Push a working docker image\n\nCloud Run will not start if the docker image is unavailable in GCR. Solve for that ahead of running\nterraform with:\n\n    docker build -t asia.gcr.io/${PROJECT_ID}/step-ca .\n    docker push asia.gcr.io/${PROJECT_ID}/step-ca\n\n\n### Run the terraform\n\nFinally, run the terraform:\n\n    cd infra\n    make init\n    terraform apply\n\n\n### Cloud Run service account\n\nThe terraform code creates a service account specific to Cloud Run in [`infra/cloudrun.tf`](./infra/cloudrun.tf#L17).\n\nThis service account has permission to read the KMS keys necessary to start `step-ca`.\n\nA key for this service account needs to be included in the docker image for the time being. See this\nline in the [`Dockerfile`](./Dockerfile#L20). This is all chicken-and-egg and rather hacky, because\nI expect it will not be needed long term - the container should be able to authenticate to Google's\nAPI automatically.\n\nThis final -hack-step means downloading a key for this service account, and building a new docker\nimage with the key baked in :/\n\n\nSSO for SSH\n-----------\n\nThis section is essentially short-form instructions derived from\n[smallstep.com/blog/diy-single-sign-on-for-ssh](https://smallstep.com/blog/diy-single-sign-on-for-ssh/).\n\nSmallstep CA can issue certs for use with SSH. By configuring Google oAuth as the identity provider,\nGoogle does the authentication for us, and `step-ca` issues the cert.\n\n\n```\n┌──────────┐            ┌──────────┐           ┌─ ── ── ── ── ─┐\n│          │            │          │\n│  Client  │────SSH────▶│  Server  │           │    Google     │\n│  (macOS) │            │  (locke) │               oAuth app\n│          │            │          │           │               │\n└──────────┘            └──────────┘\n      │                                        └─ ── ── ── ── ─┘\n      │                                                ▲\n      │                 ┌──────────┐                   │\n    request             │          │                   │\n      cert─────────────▶│    CA    │────authenticate───┘\n                        │ (ringil) │\n                        │          │\n                        └──────────┘\n```\n\nNote: The naming convention here is to SSH from the _client_ into the _host_ server.\n\n\n#### Setup the Google oAuth app\n\n 1. Configure oAuth consent at https://console.developers.google.com/apis/credentials/consent\n 2. Create an oAuth app at https://console.cloud.google.com/apis/credentials\n   a. Click `Create credentials`, choosing `OAuth client ID`\n   b. Select `Desktop app` as application type\n   c. Retain your client ID and client secret\n\n\n#### Configure the CA to support this OIDC app\n\nNext, we must configure the CA with a new OIDC provisioner (named \"Google\") using above secrets. The\n`--domain` parameter is your Google SSO domain name.\n\n```\n\u003e step ca provisioner add Google --type=OIDC --ssh \\\n    --client-id \"$OIDC_CLIENT_ID\" \\\n    --client-secret \"$OIDC_CLIENT_SECRET\" \\\n    --configuration-endpoint 'https://accounts.google.com/.well-known/openid-configuration' \\\n    --domain mafro.net\nSuccess! Your `step-ca` config has been updated. To pick up the new configuration SIGHUP (kill -1 \u003cpid\u003e) or restart the step-ca\n process.\n```\n\n\n#### Create trust relationship between host server and our CA\n\nNext our CA needs to trust an identity document provided by the host system. In the blog post,\nthe host is an AWS EC2 instance which provides its instance identity to the CA server, and is trusted\nvia the Amazon signature of the AWS account ID (see [script here](https://gist.github.com/tashian/fde43668cbf6e3227fb13ef51db650b8)).\n\nOn the host server, install the [Smallstep CLI tools](#install-smallstep-cli). Next, bootstrap the\n`step` client as usual:\n\n```\n\u003e FINGERPRINT=$(step certificate fingerprint root_ca.crt)\n\u003e step ca bootstrap --ca-url https://ringil --fingerprint $FINGERPRINT\nThe root certificate has been saved in $HOME/.step/certs/root_ca.crt.\nYour configuration has been saved in $HOME/.step/config/defaults.json.\n```\n\nGenerate a certificate and configure `sshd` to use it. Run the following as root, so it's possible\nto write `/etc/ssh`.\n\nIn the following example, the host server is named `locke`. The steps are:\n\n1. Generate a token with the `admin` provisioner\n2. Inspect the token for your amusement\n\n```\n\u003e TOKEN=$(step ca token $(hostname) --ssh --host --provisioner admin)\n✔ Provisioner: admin (JWK) [kid: ydABxIT07b0000000000000000000000nGYFRfEGmNA]\n✔ Please enter the password to decrypt the provisioner key:\n\u003e echo $TOKEN | step crypto jwt inspect --insecure\n{\n  \"header\": {\n    \"alg\": \"ES256\",\n    \"kid\": \"ydABxIT07bl-G9jSxfCB45pxNylrKitsnGYFRfEGmNA\",\n    \"typ\": \"JWT\"\n  },\n  \"payload\": {\n    \"aud\": \"https://ringil:8443/1.0/ssh/sign\",\n    \"exp\": 1618046362,\n    \"iat\": 1618046062,\n    \"iss\": \"admin\",\n    \"jti\": \"776b2fce13c90b675f0a1f55712eee80f2504f5f6d4723e0a4fd80e5d35fde40\",\n    \"nbf\": 1618046062,\n    \"sha\": \"b07c800d7bf36422bd7da01fc2db11efebaafdd5b83092ff82136e75a6d033f9\",\n    \"step\": {\n      \"ssh\": {\n        \"certType\": \"host\",\n        \"keyID\": \"locke\",\n        \"principals\": [],\n        \"validAfter\": \"\",\n        \"validBefore\": \"\"\n      }\n    },\n    \"sub\": \"locke\"\n  },\n  \"signature\": \"E-b6SIaN9atMMo-ICdnoUCjQWMLYuJxkVuB5dBDGjxtzKpPyC-ydnLH5qYV9TTss7MgA2tciMNi9ka-PJ0LNqg\"\n}\n\u003e step ssh certificate $(hostname) /etc/ssh/ssh_host_ecdsa_key.pub --host --sign --provisioner admin --principal $(hostname) --token $TOKEN\n✔ CA: https://ringil:8443\n✔ Would you like to overwrite /etc/ssh/ssh_host_ecdsa_key-cert.pub [y/n]: y\n✔ Certificate: /etc/ssh/ssh_host_ecdsa_key-cert.pub\n\u003e step ssh config --host --set Certificate=ssh_host_ecdsa_key-cert.pub --set Key=ssh_host_ecdsa_key\n✔ /etc/ssh/sshd_config\n✔ /etc/ssh/ca.pub\n\u003e systemctl restart sshd\n```\n\n### Setup the client to use SSH via OIDC\n\nThe following steps are run on the _client_ system, which is connecting to the host configured above.\n\n```\n\u003e FINGERPRINT=$(step certificate fingerprint root_ca.crt)\n\u003e step ca bootstrap --ca-url https://ringil --fingerprint $FINGERPRINT\nThe root certificate has been saved in /Users/blackm/.step/certs/root_ca.crt.\nYour configuration has been saved in /Users/blackm/.step/config/defaults.json.\n\u003e step ssh config\n✔ /Users/mafro/.ssh/config\n✔ /Users/mafro/.step/ssh/config\n✔ /Users/mafro/.step/ssh/known_hosts\n```\n\nConfigure your SSH client config such that step is used to generate the SSH certificate on demand:\n\n```\n\u003e cat ~/.ssh/config\nHost locke\n    User pi\n    UserKnownHostsFile /Users/blackm/.step/ssh/known_hosts\n    ProxyCommand step ssh proxycommand %r %h %p --provisioner Google\n```\n\nThe `Google` provisioner is the OIDC one created at the beginning.\n\nNow, using this configuration is as simple as `ssh locke`, and the OIDC flow is triggered:\n\n```\n\u003e ssh locke\n✔ Provisioner: Google (OIDC) [client: 824164598483-frmggjqidnm16kjob9ud8a6a6ahvub1v.apps.googleusercontent.com]\nYour default web browser has been opened to visit:\n\nhttps://accounts.google.com/o/oauth2/v2/auth?\u003csnip\u003e\n\n✔ CA: https://ringil:8443\nLinux locke 5.10.17-v7l+ #1414 SMP Fri Apr 30 13:20:47 BST 2021 armv7l\n\nThe programs included with the Debian GNU/Linux system are free software;\nthe exact distribution terms for each program are described in the\nindividual files in /usr/share/doc/*/copyright.\n\nDebian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent\npermitted by applicable law.\nLast login: Thu Jun 17 06:07:51 2021 from 192.168.1.139\npi@locke:~ \u003e\n```\n\nIf you wanted to have a peek at your SSH certificate, as provisioned by your CA:\n\n```\n\u003e step ssh list --raw | step ssh inspect\n-:\n    Type: ecdsa-sha2-nistp256-cert-v01@openssh.com user certificate\n    Public key: ECDSA-CERT SHA256:1p9Ux0LVclOe3wFH9ISo+eUiqoAi/CoK7bE/VSdf2r0\n    Signing CA: ECDSA SHA256:WoobT5Uoi8cddLhcxILd5eLoPiq27iEaVCDV/oL/B6I\n    Key ID: \"m@mafro.net\"\n    Serial: 8826815887645788865\n    Valid: from 2021-06-17T05:44:17 to 2021-06-17T21:44:17\n    Principals:\n        m\n        m@mafro.net\n        mafro\n        pi\n    Critical Options: (none)\n    Extensions:\n        permit-agent-forwarding\n        permit-port-forwarding\n        permit-pty\n        permit-user-rc\n        permit-X11-forwarding\n```\n\n\n### References for oAuth\n\n- https://smallstep.com/blog/diy-single-sign-on-for-ssh/\n- https://github.com/smallstep/certificates/blob/master/docs/provisioners.md#oidc\n\n\nService-specific JWK Provisioner\n--------------------------------\n\nTo auto-provision certificates in a service (such as Cloud Run), we can create a unique `JWK`\nprovisioner dedicated to just that service. An unencrypted private key will need to be made available\non the service - secured in this case in Google KMS.\n\n### Setup a JWK Provisioner\n\nThis step only needs to be done once, on the host running the CA.\n\nGenerate a new keypair and decrypt the keypair's password for securing in KMS, then create the `JWK`\nprovisioner from that keypair:\n\n```\n\u003e step crypto jwk create proxy-jwk.pub proxy-jwk.key\nPlease enter the password to encrypt the private JWK:\nYour public key has been saved in proxy-jwk.pub.\nYour private key has been saved in proxy-jwk.key.\n\u003e step crypto jwe decrypt \u003c proxy-jwk.key \u003e proxy-jwk.unencrypted\nPlease enter the password to decrypt the content encryption key:\n\u003e step ca provisioner add HomeAssistantProxy proxy-jwk.key --type JWK\nPlease enter the password to decrypt proxy-jwk.key:\nPlease enter the password to encrypt the private JWK:\nSuccess! Your `step-ca` config has been updated. To pick up the new configuration SIGHUP (kill -1 \u003cpid\u003e) or restart the step-ca process.\n```\n\nThe `.unencrypted` file should be stored securely in your application (in this case GCP KMS), and\nthen deleted.\n\n### Generate a cert using the JWK provisioner\n\nUse this unencrypted private key to generate your own token, and then certificate, without human\ninteraction:\n\n```\n\u003e TOKEN=$(step ca token token-subject --provisioner HomeAssistantProxy --key proxy-jwk.unencrypted)\n✔ Provisioner: HomeAssistantProxy (JWK) [kid: nCdmAqcD-LAdEfMW7qCtqqTBO7z50FQdHvKEzAS_EeY]\n\u003e step ca certificate proxy-cert /tmp/client.crt /tmp/client.key --token \"$TOKEN\" --force\n✔ CA: https://ringil:8443\n✔ Certificate: /tmp/client.crt\n✔ Private Key: /tmp/client.key\n```\n\nYou can see this in action in the [nginx mTLS proxy](./proxy/docker-entrypoint.sh#L39).\n\n\n## References\n\nhttps://smallstep.com/blog/step-certificates/#using-certificates-with-tls\nhttps://smallstep.com/blog/diy-single-sign-on-for-ssh/\nhttps://gitter.im/smallstep/community\n\n\nGCE Doco\n--------\n\nSome notes and recipes for useful things you can do in GCE.\n\n\n### Running a managed docker image on a VM\n\nGCE can be configured to run a docker container on VM startup - which is a neat way to continue to\nuse docker for development, but target a VM in production.\n\nThe `terraform-google-container-vm` module generates the metadata for a VM instance template, users\njust need to see how to configure the module by using\n[the examples](https://github.com/terraform-google-modules/terraform-google-container-vm/tree/v2.0.0/examples).\n\n```\nmodule vm_container {\n  source = \"github.com/terraform-google-modules/terraform-google-container-vm?ref=v2.0.0\"\n\n  container = {\n    image = format(\"asia.gcr.io/%s/step-ca\", data.google_project.project.project_id)\n  }\n  restart_policy = \"Always\"\n}\n\nresource google_compute_instance_template tpl {\n  region   = var.region\n  project  = data.google_project.project.project_id\n\n  machine_type = \"e2-micro\"\n  metadata     = {\n    gce-container-declaration: module.vm_container.metadata_value\n  }\n}\n\n```\n\n* https://cloud.google.com/compute/docs/containers/deploying-containers\n\n\n### Testing a new docker image without a VM restart\n\nOne can quite easily test a new docker image by restarting the `konlet` service. Assuming the `latest`\ndocker image has been updated on the registry:\n\n0. `IMAGE_ID=$(docker ps --format '{{.ID}}' --filter 'ancestor=asia.gcr.io/step-ca-a3dd5f/step-ca')`\n1. `docker rm -f $IMAGE_ID`\n2. `docker pull asia.gcr.io/step-ca-a3dd5f/step-ca`\n3. `sudo systemctl restart konlet-startup`\n\n\n### Mounting a host volume into the docker image\n\nThe `terraform-google-container-vm` module comes with quite a few useful\n[examples](https://github.com/terraform-google-modules/terraform-google-container-vm/blob/v2.0.0/examples/simple_instance/main.tf),\nbut the following recipe is missing:\n\n```\nmodule vm_container {\n  source = \"github.com/terraform-google-modules/terraform-google-container-vm?ref=v2.0.0\"\n\n  container = {\n    image = format(\"asia.gcr.io/%s/step-ca\", data.google_project.project.project_id)\n\n    volumeMounts = [\n      {\n        name      = \"db\"\n        mountPath = \"/root/.step/db\"\n        readOnly  = false\n      },\n    ]\n  }\n\n  volumes = [\n    {\n      name = \"db\"\n      hostPath = {\n        path = \"/home/db\"\n      }\n    },\n  ]\n}\n```\n\n* [konlet source which helped to figure this out](https://github.com/GoogleCloudPlatform/konlet/blob/master/gce-containers-startup/volumes/volumes_test.go#L381)\n\n\n### Quick SSH via IAP\n\nYou can use Google's Identity-Aware Proxy to help with managing SSH access to VMs in GCE. Ensure you\nhave the right port open on the firewall:\n\n```\nresource google_compute_firewall iap_ssh {\n  project = google_project.project.project_id\n  network = google_compute_network.network.self_link\n  name    = \"allow-ssh-ingress-from-iap\"\n\n  allow {\n    protocol = \"tcp\"\n    ports    = [\"22\"]\n  }\n\n  source_ranges = [\"35.235.240.0/20\"]\n}\n```\n\nAnd then simply use gcloud to connect:\n\n    gcloud compute ssh ca-x  --tunnel-through-iap --zone australia-southeast1-c\n\n\n### Using toolbox on COS\n\nAfter logging into a GCE instance in your shell, use the `toolbox` command to fetch and run a\ndebian-based docker image handy for debugging.\n\n```\nmafro@ca-c3d8 ~ $ toolbox\n20200603-00: Pulling from google-containers/toolbox\n1c6172af85ee: Pull complete\na4b5cec33934: Pull complete\nb7417d4f55be: Pull complete\nfed60196983f: Pull complete\n8e1533dfae69: Pull complete\n112bf8e3d384: Pull complete\n1df10c12cc15: Pull complete\nb33e020bb38a: Pull complete\n938e6be48196: Pull complete\nDigest: sha256:36e2f6b8aa40328453aed7917860a8dee746c101dfde4464ce173ed402c1ec57\nStatus: Downloaded newer image for gcr.io/google-containers/toolbox:20200603-00\ngcr.io/google-containers/toolbox:20200603-00\n0877997d383a6317d60d0ef76af1f5f914e793f4a65b84094bdec09c284e22c3\nmafro-gcr.io_google-containers_toolbox-20200603-00\nPlease do not use --share-system anymore, use $SYSTEMD_NSPAWN_SHARE_instead.\nSpawning container mafro-gcr.io_google-containers_toolbox-20200603-00 on /var/lib/toolbox/mafro-gcr.io_google-containers_toolbox-20200603-00.\nPress ^] three times within 1s to kill container.\nroot@ca-c3d8:~#\n```\n\n* https://cloud.google.com/container-optimized-os/docs/how-to/toolbox\n\n\n### Using gsutil on Container-optimised OS\n\nAs container-optimised OS does not come with `gcloud` and friends, the easiest solution is to simply\nuser docker:\n\n    docker run --rm google/cloud-sdk:alpine gsutil --help\n\n\n### Configuring a startup/shutdown down script via Terraform\n\nA simple metadata key configures a startup/shutdown script:\n\n```\nresource google_compute_instance_template tpl {\n  region   = var.region\n  project  = data.google_project.project.project_id\n\n  machine_type = \"e2-micro\"\n  metadata     = {\n    gce-container-declaration: module.vm_container.metadata_value\n    shutdown-script: file(\"preempt.sh\")\n    startup-script:  file(\"startup.sh\")\n  }\n\n...\n```\n\n* https://cloud.google.com/compute/docs/startupscript\n\n\n### Testing a startup/shutdown down script (in COS)\n\nYou can test a startup script in Container-optimised OS with the following command. Substitute\n`shutdown` to test the shutdown script.\n\n    sudo google_metadata_script_runner --script-type startup --debug\n\n* https://cloud.google.com/compute/docs/startupscript#on_container-optimized_os_ubuntu_and_sles_images\n\n\n### Mounting a GCS bucket via fuse\n\nThe included [`docker-entrypoint.sh`](./docker-entrypoint.sh#L20) shows mounting a GCS bucket before\na docker application starts up.\n\nThe build steps to make `gcsfuse` binary available are in the [`Dockerfile`](./Dockerfile#L5).\n\n* https://serverfault.com/a/968639/89669\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmafrosis%2Fstep-ca-on-gce","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmafrosis%2Fstep-ca-on-gce","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmafrosis%2Fstep-ca-on-gce/lists"}