Repository: sethvargo/vault-kubernetes-workshop Branch: master Commit: 93167dbb019e Files: 31 Total size: 52.1 KB Directory structure: gitextract_wbnchg1l/ ├── .github/ │ ├── lock.yml │ └── reaction.yml ├── .gitignore ├── LICENSE ├── README.md ├── k8s/ │ ├── db-sidecar.yaml │ ├── kv-sidecar.yaml │ └── vault.yaml └── scripts/ ├── 00-install-vault.sh ├── 01-enable-services.sh ├── 02-setup-storage.sh ├── 03-setup-kms.sh ├── 04-create-iam-service-account.sh ├── 05-create-k8s-cluster.sh ├── 06-create-public-ip.sh ├── 07-create-certs.sh ├── 08-setup-config.sh ├── 09-deploy-vault.sh ├── 10-deploy-lb.sh ├── 11-setup-comms.sh ├── 12-setup-static-kv.sh ├── 13-create-another-cluster.sh ├── 14-create-service-account.sh ├── 15-setup-vault-comms-k8s.sh ├── 16-create-kv-role.sh ├── 17-run-kv-sidecar.sh ├── 18-setup-dynamic-creds.sh ├── 19-run-db-sidecar.sh ├── 20-cleanup.sh ├── __helpers.sh └── kubectl-logs.sh ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/lock.yml ================================================ daysUntilLock: 90 lockLabel: false lockComment: false ================================================ FILE: .github/reaction.yml ================================================ reactionComment: false ================================================ FILE: .gitignore ================================================ tls/ ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: README.md ================================================ # Vault Kubernetes Workshop on Google Cloud Platform ## Prerequisites & Caveats - This workshop is designed to be run on [Google Cloud Shell][cs]. It may work in other environments without modification, but the materials are only tested and guaranteed against Cloud Shell. - You must have a Google Cloud Platform account and be authenticated as a project owner. Again, if you are using Cloud Shell, this happens automatically. If you are running locally, you will need to download and install the [Google Cloud SDK][sdk], and then authenticate to Google Cloud appropriately. - There are places where this workshop sacrifices "best practices" for "things feasible to complete in the duration of a workshop". In particular, this workshop generates self-signed SSL certificates and does not encrypt the resulting keys. For more details on a production-hardened setup, please see the [Vault production hardening docs][vault-prod-hardening]. - You must clone this repo: ```text git clone https://github.com/sethvargo/vault-kubernetes-workshop cd vault-kubernetes-workshop ``` ## 00 Install Vault The first step is to install Vault. To install the Vault binary in the current working directory, run the install script. ```text ./scripts/00-install-vault.sh ``` This will install Vault using the `sethvargo/hashicorp-installer` Docker container which verifies GPG signatures and checksums from the download. This represents a "best practices" installation for installing secure software like Vault. By verifying the signature of the SHASUMs and then verifying the SHASUMs themselves, we guarantee both the integrity of the download and ensure the binary has not been tampered with beyond it's original publishing. For added security, you can download and compile Vault yourself from source, but that is out of scope for this workshop. Cloud Shell does not persist things in `/usr/local/bin` or `/usr/bin` between sessions. As such, Vault will be installed in `~/bin`. We recommend installing other binaries or software you need between sessions in this folder. ## 01 Enable Services By default, a new Google Cloud project does not have many services enabled. Enable the required services (this only needs to be done once per project): ```text ./scripts/01-enable-services.sh ``` This will make the necessary calls to enable the enable the right APIs on your project. This process can take some time, but it is idempotent (you can run it multiple times to achieve the same result). ## 02 Setup Storage Vault requires a storage backend to persist its data. This workshop leverages [Google Cloud Storage][gcs]. Vault does not automatically create the storage bucket, so we need to create: ```text ./scripts/02-setup-storage.sh ``` Cloud Storage bucket names must be globally unique across all of Google Cloud. The bucket will be named "${PROJECT}-vault-storage". For security purposes, it is not recommended that other applications or services have access to this bucket. Even though the data is encrypted at rest, it is best to limit the scope of access as much as possible. ## 03 Setup KMS Vault will leverage [Google Cloud KMS][kms] to encrypt its unseal keys for auto-unsealing and auto-scaling purposes. We must create the KMS key in advance: ```text ./scripts/03-setup-kms.sh ``` ## 04 Create IAM Service Account It is a best practice to create a limited, dedicated service account that has only the required permissions. Create a dedicated service account in the project and grant it the most minimal set of permissions, in particular: - The ability to read/write to the Cloud Storage bucket created above - The ability to encrypt/decrypt data with the KMS key created above - The ability to generate new service accounts (not required to use Vault, but helpful if you plan to use the Vault GCP secrets engine) ```text ./scripts/04-create-iam-service-account.sh ``` ## 05 Create Kubernetes Cluster Next we need to create the [Google Kubernetes Engine][gke] (GKE) cluster which will run Vault. It is recommended that you run Vault in a dedicated namespace or (even better) a dedicated cluster and a dedicated project. Vault will then act as a service with an IP/DNS entry that other projects and services query. ```text ./scripts/05-create-k8s-cluster.sh ``` This will create the cluster and attach the service account created in the previous step to the cluster. It also ensures the cluster has the correct oauth scopes. ## 06 Create Public IP This step creates and reserves a regional public IP address. In a future step, we will attach this reserved IP address to a Kubernetes load balancer. For now, we will just reserve the dedicated IP address. ```text ./scripts/06-create-public-ip.sh ``` We use a regional IP address instead of a global IP address because global IPs perform load balancing at L7 whereas regional IP addresses perform load balancing at L4. Ideally we do not want the load balancer to perform TLS termination, and let Vault manage TLS, etc. While recent versions of Vault do support advanced routing like `X-Forwarded-For` headers, it is still a better practice to let Vault fully manage the TLS and thus use an L4 load balancer. This step is not required if you are comfortable assigning your Vault Kubernetes service an ephemeral IP or will manage it via an external DNS service. ## 07 Create Certificates This is arguably the most complex and nuanced piece of the workshop - generating Vault's certificate authority and server certificates for TLS. Vault can run without TLS, but this is _highly_ discouraged. This step could be replaced with a trusted CA like Let's Encrypt, but that is out of scope for this workshop. ```text ./scripts/07-create-certs.sh ``` This will create the Certificate Authority (`ca.key`, `ca.crt`) and Vault certificate (`vault.key`, `vault.crt`). In a future step, we will put these values in a Kubernetes secret so our pods can access them. ## 08 Create Config Next we create the config map and secrets to store our data for our pods. The insecure data such as the storage bucket name and IP address are placed in a configmap. The secure data like the TLS certificates are put in a Kubernetes secret. ```text ./scripts/08-setup-config.sh ``` ## 09 Deploy Vault The next step is to actually deploy Vault as a StatefulSet on Kubernetes. The reason we use a StatefulSet is two-fold: 1. It guarantees exactly one service starts at a time. This is required by the [vault-init][vault-init] sidecar service. 1. It gives us consistent naming for referencing the Vault servers (which is nice for a workshop). ```text ./scripts/09-deploy-vault.sh ``` Vault will automatically be initialized and unsealed via the vault-init service. ## 10 Deploy Load Balancer Even though Vault is deployed, it is not publicly accessible. We need to create a Kubernetes Service Load Balancer to forward from the IP address reserved in the previous steps to the pods we just created. ```text ./scripts/10-deploy-lb.sh ``` The load balancer listens on port 443 and forwards to port 8200 on the containers. For production-hardened scenarios, you may want to include firewall rules to limit access to Vault at the network layer. ## 11 Setup Comms Lastly, we need to configure our local Vault CLI to communicate with these newly-created Vault servers through the Load Balancer. Since we used custom TLS certificates, we'll need to trust the appropriate CA, etc. This will: - Set `VAULT_ADDR` to the Load Balancer address - Set `VAULT_CAPATH` to the path of the CA cert created in previous steps for properly verifying the TLS connection - Set `VAULT_TOKEN` to the decrypted root token by decrypting it from KMS ```text ./scripts/11-setup-comms.sh ``` At this point, the local Vault CLI is configured to communicate with our Vault cluster. Verify by running `vault status`: ```text vault status ``` ## 12 Setup Static KV Next we will explore techniques for retrieving static (i.e. non-expiring) credentials from Vault. The kv secrets engine is commonly used with legacy applications which cannot handle graceful restarts or when secrets cannot be dynamically generated by Vault. ```text ./scripts/12-setup-static-kv.sh ``` This will: 1. Enable the KV secrets engine 1. Create a policy to read data from a subpath 1. Store some static username/password data in the secrets engine Try reading back the secret by running: ```text vault kv get kv/myapp/config ``` You can also read the data via a request tool like curl. ```text curl -k -H "x-vault-token:${VAULT_TOKEN}" "${VAULT_ADDR}/v1/kv/myapp/config" ``` ## 13 Another Cluster Next we are going to create another Kubernetes cluster. There is no requirement that our Vault servers run under Kubernetes (they could be running on dedicated VMs or as a managed service). It is a best practice to treat the Vault server cluster as a "service" through which other applications and services request credentials. As such, moving forward, the Vault cluster will be treated simply as an IP address. We will not leverage K8S for "discovering" the Vault cluster, etc. **To put it another way, completely forget that Vault is running in Kubernetes. If it helps, think that Vault is running in a PaaS like Heroku instead.** Next create the Kubernetes cluster where our services will actually run. This is completely separate from the Vault K8S cluster. In fact, on GCP, is it recommended that you run these in completely separate projects. For the purpose of this workshop, we will run them in the same project. ```text ./scripts/13-create-another-cluster.sh ``` This will provision a new Kubernetes cluster named "my-apps". We will deploy all future apps and services in this cluster. Unlike the previous cluster, this cluster does not attach a service account. ## 14 Service Account In our cluster, services will authenticate to Vault using the [Kubernetes auth method][vault-k8s-auth-method]. In this model, services present their JWT token to Vault as part of an authentication request. Vault takes that signed JWT token and, using the token reviewer API, verifies the token is authenticated. If the authentication is successful, Vault generates a token and maps a series of configured policies onto the token which is returned to the caller. ```text ./scripts/14-create-service-account.sh ``` This will create a dedicated service account named "vault-auth" and grant that service account the ability to communicate with the token reviewer API. ## 15 Configure Vault to talk to Kubernetes Next we need to configure the Vault cluster to talk to our new Kubernetes cluster ("my-apps"). We will need to give Vault the IP address of the cluster, the CA information, and the service account to use for accessing the token reviewer API. ```text ./scripts/15-setup-vault-comms-k8s.sh ``` This process will: 1. Look up the service account JWT token (this is how Vault will talk to the Kubernetes API) 1. Extract the Kubernetes host from the local kube configuration (this where Vault will make API requests) 1. Extract the Kubernetes CA from the local kube configuration (this is how Vault will authenticate requests) 1. Enable the Kubernetes auth method in Vault 1. Give Vault the service account JWT, host, and CA so that Vault can communicate with Kubernetes There are other techniques for retrieving some of these values, but leveraging `kubectl` makes it easy to script. ## 16 Create KV Role Typically this process is done by a security team or operations team. We need to configure Vault to map an application or service in Kubernetes to a series of policies in Vault. That way, when an application successfully authenticates to Vault via its JWT token, Vault knows which policies to assign to the response. ```text ./scripts/16-create-kv-role.sh ``` This will create a role named "myapp-role" that permits pods in the "default" namespace with the "default" service account to receive a Vault token that has the "myapp-kv-rw" policy attached. ## 17 Sidecar Static App This is one of the most common techniques for injecting Vault secrets into an application. 1. An init container pulls the service account JWT token and performs the auth mechanism for that service account. If successful, it stores the resulting _Vault_ token in somewhere on a shared volume mount. 1. A tool like [Consul Template][consul-template] runs as the first container. This tool uses the Vault token acquired by the init container and makes the appropriate API calls to Vault based off of a template file. The template file can reference one or more Vault credentials. Consul Template writes the rendered file with the secrets from Vault to a shared volume mount which the app reads. 1. The app reads credentials. In this example, our application is a dummy application that just reads the contents of `/etc/secrets/config` repeatedly. ```text ./scripts/17-run-kv-sidecar.sh ``` Verify the app is authenticating and retrieving secrets from Vault: ```text ./scripts/kubectl-logs.sh kv-sidecar ``` ## 18 Setup Dynamic Credentials Next we configure Vault to generate dynamic credentials. Vault can generate many types of dynamic credentials like database credentials, certificates, etc. For this example, we will leverage the GCP secrets engine to dynamically generate Google Cloud Platform CloudSQL MySQL users. ```text ./scripts/18-setup-dynamic-creds.sh ``` This will: 1. Create a CloudSQL database 1. Enable the `database` secrets engine 1. Configure the `database` secrets engine 1. Create a "role" which configures the permissions the SQL user has 1. Create a new policy which allows generating these dynamic credentials 1. Update the Vault Kubernetes auth mapping to include this new policy when authenticating This process can take up to 10 minutes to complete. ## 19 Sidecar Dynamic App In this example, we follow the same pattern as the static KV secrets, but our sidecar application will pull dynamic credentials from Vault. In this case, we will be creating a database password. ```text ./scripts/19-run-db-sidecar.sh ``` This also configures a command to run which will signal the application when the underlying service account changes. This is important as we need to notify the application (which is not aware of Vault's existence) that it should reload its configuration. Verify the app is authenticating and retrieving secrets from Vault: ```text ./scripts/kubectl-logs.sh db-sidecar ``` [cs]: https://cloud.google.com/shell [gcs]: https://cloud.google.com/storage [gke]: https://cloud.google.com/gke [kms]: https://cloud.google.com/kms [sdk]: https://cloud.google.com/sdk [consul-template]: https://github.com/hashicorp/consul-template [vault-init]: https://github.com/sethvargo/vault-init [vault-k8s-auth-method]: https://www.vaultproject.io/docs/auth/kubernetes.html [vault-prod-hardening]: https://www.vaultproject.io/guides/operations/production.html ================================================ FILE: k8s/db-sidecar.yaml ================================================ --- apiVersion: apps/v1 kind: Deployment metadata: name: db-sidecar labels: app: db-sidecar spec: replicas: 1 selector: matchLabels: app: db-sidecar template: metadata: labels: app: db-sidecar spec: shareProcessNamespace: true volumes: - name: secrets emptyDir: {} - name: vault-tls secret: secretName: vault-tls - name: vault-token emptyDir: medium: Memory securityContext: runAsUser: 1000 runAsGroup: 1000 initContainers: # The vault-authenticator container authenticates the container using the # kubernetes auth method and puts the resulting token on the filesystem. - name: vault-authenticator image: sethvargo/vault-kubernetes-authenticator:0.2.0 imagePullPolicy: IfNotPresent volumeMounts: - name: vault-token mountPath: /var/run/secrets/vaultproject.io - name: vault-tls mountPath: /etc/vault/tls env: - name: VAULT_ADDR valueFrom: configMapKeyRef: name: vault key: vault_addr - name: VAULT_CACERT value: /etc/vault/tls/ca.crt - name: VAULT_ROLE value: myapp-role containers: # The consul-template container will pull secrets from Vault and expose # them as files on disk. - name: consul-template image: hashicorp/consul-template:0.20.0-light imagePullPolicy: IfNotPresent securityContext: capabilities: add: ['SYS_PTRACE'] volumeMounts: - name: secrets mountPath: /etc/secrets - name: vault-tls mountPath: /etc/vault/tls - name: vault-token mountPath: /var/run/secrets/vaultproject.io env: - name: VAULT_ADDR valueFrom: configMapKeyRef: name: vault key: vault_addr - name: VAULT_CACERT value: /etc/vault/tls/ca.crt - name: CT_LOCAL_CONFIG value: | vault { vault_agent_token_file = "/var/run/secrets/vaultproject.io/.vault-token" ssl { ca_cert = "/etc/vault/tls/ca.crt" } retry { backoff = "1s" } } template { contents = </dev/null && pwd)/__helpers.sh" echo "--> Unpacking and installing" docker run -v $HOME/bin:/software sethvargo/hashicorp-installer vault 1.1.2 sudo chown $(whoami):$(whoami) $HOME/bin/vault sudo chmod +x $HOME/bin/vault echo "--> Setting PATH" export PATH="${PATH}:${HOME}/bin" echo "--> Installing completions" vault -autocomplete-install || true echo "--> Done!" exec $SHELL ================================================ FILE: scripts/01-enable-services.sh ================================================ #!/usr/bin/env bash set -Eeuo pipefail source "$(cd "$(dirname "${0}")" &>/dev/null && pwd)/__helpers.sh" gcloud services enable \ --async \ --project="$(google-project)" \ cloudapis.googleapis.com \ cloudkms.googleapis.com \ cloudresourcemanager.googleapis.com \ cloudshell.googleapis.com \ container.googleapis.com \ containerregistry.googleapis.com \ iam.googleapis.com ================================================ FILE: scripts/02-setup-storage.sh ================================================ #!/usr/bin/env bash set -Eeuo pipefail source "$(cd "$(dirname "${0}")" &>/dev/null && pwd)/__helpers.sh" gsutil mb -p "$(google-project)" "gs://$(google-project)-vault-storage" ================================================ FILE: scripts/03-setup-kms.sh ================================================ #!/usr/bin/env bash set -Eeuo pipefail source "$(cd "$(dirname "${0}")" &>/dev/null && pwd)/__helpers.sh" gcloud kms keyrings create vault \ --project="$(google-project)" \ --location="$(google-region)" gcloud kms keys create vault-init \ --project="$(google-project)" \ --location="$(google-region)" \ --keyring="vault" \ --purpose="encryption" ================================================ FILE: scripts/04-create-iam-service-account.sh ================================================ #!/usr/bin/env bash set -Eeuo pipefail source "$(cd "$(dirname "${0}")" &>/dev/null && pwd)/__helpers.sh" SERVICE_ACCOUNT="vault-server@$(google-project).iam.gserviceaccount.com" # Create the service account gcloud iam service-accounts create vault-server \ --project="$(google-project)" \ --display-name="vault server" # (Optional) grant the service account the ability to generate new service # accounts. This is required to use the Vault GCP secrets engine, otherwise it # can be omitted. ROLES=( "roles/resourcemanager.projectIamAdmin" "roles/iam.serviceAccountAdmin" "roles/iam.serviceAccountKeyAdmin" "roles/iam.serviceAccountTokenCreator" "roles/iam.serviceAccountUser" "roles/viewer" ) for role in "${ROLES[@]}"; do gcloud projects add-iam-policy-binding "$(google-project)" \ --member "serviceAccount:${SERVICE_ACCOUNT}" \ --role "${role}" done # Grant the service account the ability to read and write objects in our storage # bucket gsutil iam ch \ "serviceAccount:${SERVICE_ACCOUNT}:objectAdmin" \ "serviceAccount:${SERVICE_ACCOUNT}:legacyBucketReader" \ "gs://$(google-project)-vault-storage" # Grant the service account the ability to access the Cloud KMS crypto key gcloud kms keys add-iam-policy-binding vault-init \ --project="$(google-project)" \ --location="$(google-region)" \ --keyring="vault" \ --member="serviceAccount:${SERVICE_ACCOUNT}" \ --role="roles/cloudkms.cryptoKeyEncrypterDecrypter" ================================================ FILE: scripts/05-create-k8s-cluster.sh ================================================ #!/usr/bin/env bash set -Eeuo pipefail source "$(cd "$(dirname "${0}")" &>/dev/null && pwd)/__helpers.sh" SERVICE_ACCOUNT="vault-server@$(google-project).iam.gserviceaccount.com" gcloud container clusters create vault \ --project="$(google-project)" \ --cluster-version="$(gke-latest-master-version)" \ --enable-autorepair \ --enable-autoupgrade \ --enable-ip-alias \ --machine-type="n1-standard-2" \ --node-version="$(gke-latest-node-version)" \ --num-nodes="1" \ --region="$(google-region)" \ --scopes="cloud-platform" \ --service-account="${SERVICE_ACCOUNT}" ================================================ FILE: scripts/06-create-public-ip.sh ================================================ #!/usr/bin/env bash set -Eeuo pipefail source "$(cd "$(dirname "${0}")" &>/dev/null && pwd)/__helpers.sh" gcloud compute addresses create vault \ --project="$(google-project)" \ --region="$(google-region)" ================================================ FILE: scripts/07-create-certs.sh ================================================ #!/usr/bin/env bash set -Eeuo pipefail source "$(cd "$(dirname "${0}")" &>/dev/null && pwd)/__helpers.sh" LB_IP="$(vault-lb-ip)" DIR="$(pwd)/tls" rm -rf "${DIR}" mkdir -p "${DIR}" # Create the conf file cat > "${DIR}/openssl.cnf" << EOF [req] default_bits = 2048 encrypt_key = no default_md = sha256 prompt = no utf8 = yes distinguished_name = req_distinguished_name req_extensions = v3_req [req_distinguished_name] C = US ST = California L = The Cloud O = Demo CN = vault [v3_req] basicConstraints = CA:FALSE subjectKeyIdentifier = hash keyUsage = digitalSignature, keyEncipherment extendedKeyUsage = clientAuth, serverAuth subjectAltName = @alt_names [alt_names] IP.1 = ${LB_IP} DNS.1 = vault.default.svc.cluster.local EOF # Generate Vault's certificates and a CSR openssl genrsa -out "${DIR}/vault.key" 2048 openssl req \ -new -key "${DIR}/vault.key" \ -out "${DIR}/vault.csr" \ -config "${DIR}/openssl.cnf" # Create our CA openssl req \ -new \ -newkey rsa:2048 \ -days 120 \ -nodes \ -x509 \ -subj "/C=US/ST=California/L=The Cloud/O=Vault CA" \ -keyout "${DIR}/ca.key" \ -out "${DIR}/ca.crt" # Sign CSR with our CA openssl x509 \ -req \ -days 120 \ -in "${DIR}/vault.csr" \ -CA "${DIR}/ca.crt" \ -CAkey "${DIR}/ca.key" \ -CAcreateserial \ -extensions v3_req \ -extfile "${DIR}/openssl.cnf" \ -out "${DIR}/vault.crt" # Export combined certs for vault cat "${DIR}/vault.crt" "${DIR}/ca.crt" > "${DIR}/vault-combined.crt" ================================================ FILE: scripts/08-setup-config.sh ================================================ #!/usr/bin/env bash set -Eeuo pipefail source "$(cd "$(dirname "${0}")" &>/dev/null && pwd)/__helpers.sh" DIR="$(pwd)/tls" kubectl create configmap vault \ --cluster="$(gke-cluster-name "vault")" \ --from-literal="load_balancer_address=$(vault-lb-ip)" \ --from-literal="gcs_bucket_name=$(google-project)-vault-storage" \ --from-literal="kms_project=$(google-project)" \ --from-literal="kms_region=$(google-region)" \ --from-literal="kms_key_ring=vault" \ --from-literal="kms_crypto_key=vault-init" \ --from-literal="kms_key_id=projects/$(google-project)/locations/$(google-region)/keyRings/vault/cryptoKeys/vault-init" kubectl create secret generic vault-tls \ --cluster="$(gke-cluster-name "vault")" \ --from-file="${DIR}/ca.crt" \ --from-file="vault.crt=${DIR}/vault-combined.crt" \ --from-file="vault.key=${DIR}/vault.key" ================================================ FILE: scripts/09-deploy-vault.sh ================================================ #!/usr/bin/env bash set -Eeuo pipefail source "$(cd "$(dirname "${0}")" &>/dev/null && pwd)/__helpers.sh" kubectl apply \ --cluster="$(gke-cluster-name "vault")" \ --filename="k8s/vault.yaml" ================================================ FILE: scripts/10-deploy-lb.sh ================================================ #!/usr/bin/env bash set -Eeuo pipefail source "$(cd "$(dirname "${0}")" &>/dev/null && pwd)/__helpers.sh" kubectl apply \ --cluster="$(gke-cluster-name "vault")" \ --filename=-</dev/null && pwd)/__helpers.sh" export VAULT_CACERT="$(pwd)/tls/ca.crt" export VAULT_ADDR="https://$(vault-lb-ip):443" export VAULT_TOKEN="$(gsutil cat "gs://$(google-project)-vault-storage/root-token.enc" | \ base64 --decode | \ gcloud kms decrypt \ --project="$(google-project)" \ --location="$(google-region)" \ --keyring="vault" \ --key="vault-init" \ --ciphertext-file - \ --plaintext-file -)" export PATH="${PATH}:${HOME}/bin" alias vualt=vault exec $SHELL ================================================ FILE: scripts/12-setup-static-kv.sh ================================================ #!/usr/bin/env bash set -Eeuo pipefail source "$(cd "$(dirname "${0}")" &>/dev/null && pwd)/__helpers.sh" # Enable kv secrets engine - this used to be enabled by default at secret/, but # that's not the case anymore. vault secrets enable kv # This creates a policy that allows reading, writing, and deleting from anything # under "myapp" in the kv secrets engine just created. This policy still must # be attached to tokens in order to receive the permission(s). vault policy write myapp-kv-rw - </dev/null && pwd)/__helpers.sh" # Create a cluster to do process namespace sharing gcloud container clusters create my-apps \ --project="$(google-project)" \ --cluster-version="$(gke-latest-master-version)" \ --enable-autorepair \ --enable-autoupgrade \ --enable-ip-alias \ --machine-type=n1-standard-2 \ --node-version="$(gke-latest-node-version)" \ --num-nodes=1 \ --region="$(google-region)" \ --scopes="cloud-platform" ================================================ FILE: scripts/14-create-service-account.sh ================================================ #!/usr/bin/env bash set -Eeuo pipefail source "$(cd "$(dirname "${0}")" &>/dev/null && pwd)/__helpers.sh" kubectl create serviceaccount vault-auth \ --cluster="$(gke-cluster-name "my-apps")" kubectl apply \ --cluster="$(gke-cluster-name "my-apps")" \ --filename=-</dev/null && pwd)/__helpers.sh" DIR="$(pwd)/tls" # Get the name of the secret corresponding to the service account SECRET_NAME="$(kubectl get serviceaccount vault-auth \ --cluster="$(gke-cluster-name "my-apps")" \ -o go-template='{{ (index .secrets 0).name }}')" # Get the actual token reviewer account TR_ACCOUNT_TOKEN="$(kubectl get secret ${SECRET_NAME} \ --cluster="$(gke-cluster-name "my-apps")" \ -o go-template='{{ .data.token }}' | base64 --decode)" # Get the host for the cluster (IP address) K8S_HOST="$(kubectl config view --raw \ -o go-template="{{ range .clusters }}{{ if eq .name \"$(gke-cluster-name "my-apps")\" }}{{ index .cluster \"server\" }}{{ end }}{{ end }}")" # Get the CA for the cluster K8S_CACERT="$(kubectl config view --raw \ -o go-template="{{ range .clusters }}{{ if eq .name \"$(gke-cluster-name "my-apps")\" }}{{ index .cluster \"certificate-authority-data\" }}{{ end }}{{ end }}" | base64 --decode)" # Enable the Kubernetes auth method vault auth enable kubernetes # Configure Vault to talk to our Kubernetes host with the cluster's CA and the # correct token reviewer JWT token vault write auth/kubernetes/config \ kubernetes_host="${K8S_HOST}" \ kubernetes_ca_cert="${K8S_CACERT}" \ token_reviewer_jwt="${TR_ACCOUNT_TOKEN}" # Create a config map to store the vault address kubectl create configmap vault \ --cluster="$(gke-cluster-name "my-apps")" \ --from-literal "vault_addr=https://$(vault-lb-ip)" # Create a secret for our CA kubectl create secret generic vault-tls \ --cluster="$(gke-cluster-name "my-apps")" \ --from-file "${DIR}/ca.crt" ================================================ FILE: scripts/16-create-kv-role.sh ================================================ #!/usr/bin/env bash set -Eeuo pipefail source "$(cd "$(dirname "${0}")" &>/dev/null && pwd)/__helpers.sh" vault write auth/kubernetes/role/myapp-role \ bound_service_account_names="default" \ bound_service_account_namespaces="default" \ policies="default,myapp-kv-rw" \ ttl="15m" ================================================ FILE: scripts/17-run-kv-sidecar.sh ================================================ #!/usr/bin/env bash set -Eeuo pipefail source "$(cd "$(dirname "${0}")" &>/dev/null && pwd)/__helpers.sh" kubectl apply \ --cluster="$(gke-cluster-name "my-apps")" \ --filename="k8s/kv-sidecar.yaml" ================================================ FILE: scripts/18-setup-dynamic-creds.sh ================================================ #!/usr/bin/env bash set -Eeuo pipefail source "$(cd "$(dirname "${0}")" &>/dev/null && pwd)/__helpers.sh" # Create CloudSQL instance gcloud sql instances create my-instance \ --project="$(google-project)" \ --activation-policy="always" \ --authorized-networks="0.0.0.0/0" \ --database-version="MYSQL_5_7" \ --no-backup \ --region="$(google-region)" \ --tier="db-n1-standard-1" INSTANCE_IP="$(gcloud sql instances describe my-instance --project="$(google-project)" --format='value(ipAddresses[0].ipAddress)')" # Change password gcloud sql users set-password root \ --project="$(google-project)" \ --host="%" \ --instance="my-instance" \ --password="my-password" # Enable the gcp secrets engine vault secrets enable database # Configure the database secrets engine TTLs vault write database/config/my-cloudsql-db \ plugin_name="mysql-database-plugin" \ connection_url="{{username}}:{{password}}@tcp(${INSTANCE_IP}:3306)/" \ allowed_roles="readonly" \ username="root" \ password="my-password" # Rotate the root cred vault write -f database/rotate-root/my-cloudsql-db # Create a role which will create a readonly user vault write database/roles/readonly \ db_name="my-cloudsql-db" \ creation_statements="CREATE USER '{{name}}'@'%' IDENTIFIED BY '{{password}}'; GRANT SELECT ON *.* TO '{{name}}'@'%';" \ default_ttl="1h" \ max_ttl="24h" # Create a new policy which allows generating these dynamic credentials vault policy write myapp-db-r -</dev/null && pwd)/__helpers.sh" kubectl apply \ --cluster="$(gke-cluster-name "my-apps")" \ --filename="k8s/db-sidecar.yaml" ================================================ FILE: scripts/20-cleanup.sh ================================================ #!/usr/bin/env bash set -Eeuo pipefail source "$(cd "$(dirname "${0}")" &>/dev/null && pwd)/__helpers.sh" SERVICE_ACCOUNT="vault-server@$(google-project).iam.gserviceaccount.com" kubectl delete deployment kv-sidecar \ --cluster="$(gke-cluster-name "my-apps")" \ --force \ --grace-period=0 kubectl delete deployment sa-sidecar \ --cluster="$(gke-cluster-name "my-apps")" \ --force \ --grace-period=0 gcloud container clusters delete my-apps \ --async \ --quiet \ --project="$(google-project)" \ --region="$(google-region)" vault lease revoke -prefix gcp/ kubectl delete service vault \ --cluster="$(gke-cluster-name "vault")" kubectl delete statefulsets vault \ --cluster="$(gke-cluster-name "vault")" \ --grace-period=0 \ --force gcloud container clusters delete vault \ --async \ --quiet \ --project="$(google-project)" \ --region="$(google-region)" gcloud compute addresses delete vault \ --quiet \ --project="$(google-project)" \ --region="$(google-region)" gcloud iam service-accounts delete "${SERVICE_ACCOUNT}" \ --quiet \ --project="$(google-project)" gsutil -m rm -rf "gs://$(google-project)-vault-storage" gsutil rb -f "gs://$(google-project)-vault-storage" ================================================ FILE: scripts/__helpers.sh ================================================ # google-project returns the name of the current project, accounting for a # variety of common environments. If no project is found in any of the common # places, an error is returned. google-project() { ( set -Eeuo pipefail local project="${PROJECT:-${GOOGLE_PROJECT:-${GOOGLE_CLOUD_PROJECT:-${DEVSHELL_PROJECT_ID:-}}}}" if [ -z "${project:-}" ]; then echo "Missing project ID. Please set PROJECT, GOOGLE_PROJECT, or" echo "GOOGLE_CLOUD_PROJECT to the ID of your project to continue:" echo "" echo " export GOOGLE_CLOUD_PROJECT=$(whoami)-foobar123" echo "" return 127 fi echo "${project}" ) } # google-region returns the region in which resources should be created. This # variable must be changed before running any commands. google-region() { ( echo "us-east4" ) } # gke-cluster-name is the name of the cluster for the given suffix. gke-cluster-name() { ( set -Eeuo pipefail echo "gke_$(google-project)_$(google-region)_${1}" ) } # gke-latest-master-version returns the latest GKE master version. gke-latest-master-version() { ( set -Eeuo pipefail gcloud container get-server-config \ --project="$(google-project)" \ --region="$(google-region)" \ --format='value(validMasterVersions[0])' \ 2>/dev/null ) } # gke-latest-node-version returns the latest GKE node version. gke-latest-node-version() { ( set -Eeuo pipefail gcloud container get-server-config \ --project="$(google-project)" \ --region="$(google-region)" \ --format='value(validNodeVersions[0])' \ 2>/dev/null ) } vault-lb-ip() { ( set -Eeuo pipefail gcloud compute addresses describe vault \ --project="$(google-project)" \ --region="$(google-region)" \ --format='value(address)' ) } ================================================ FILE: scripts/kubectl-logs.sh ================================================ #!/usr/bin/env bash set -Eeuo pipefail source "$(cd "$(dirname "${0}")" &>/dev/null && pwd)/__helpers.sh" if [ -z "${1:-}" ]; then echo "Missing pod name!" exit 1 fi POD="$(kubectl get pods \ --cluster="$(gke-cluster-name "my-apps")" \ --selector="app=${1}" \ -o=jsonpath='{.items[0].metadata.name}')" kubectl logs "${POD}" -c "app" \ --context="$(gke-cluster-name "my-apps")" \