GKE Autopilot Cluster: Pay for Pods, Not Nodes

GKE Autopilot Cluster: Pay for Pods, Not Nodes

If you're already on Google Cloud, it's highly recommended to use GKE Autopilot Cluster: you only pay for resources requested by your pods (system pods and unused resources are free in Autopilot Cluster). No need to pay for surplus node pools anymore! Plus the entire cluster applies Google's best practices by default.

ref:
https://cloud.google.com/kubernetes-engine/pricing#compute

Create an Autopilot Cluster

DO NOT enable Private Nodes, otherwise you MUST pay for a Cloud NAT Gateway (~$32/month) for them to access the internet (to pull images, etc.).

# create
gcloud container clusters create-auto my-auto-cluster \
--project YOUR_PROJECT_ID \
--region us-west1

# connect
gcloud container clusters get-credentials my-auto-cluster \
--project YOUR_PROJECT_ID \
--region us-west1

You can update some configurations later on Google Cloud Console.

ref:
https://docs.cloud.google.com/sdk/gcloud/reference/container/clusters/create-auto

Autopilot mode works in both Autopilot and Standard clusters. You don't necessarily need to create a new Autopilot cluster; you can simply deploy your pods in Autopilot mode as long as your Standard cluster meets the requirements:

gcloud container clusters check-autopilot-compatibility my-cluster \
--project YOUR_PROJECT_ID \
--region us-west1

ref:
https://cloud.google.com/kubernetes-engine/docs/concepts/about-autopilot-mode-standard-clusters
https://cloud.google.com/kubernetes-engine/docs/how-to/autopilot-classes-standard-clusters

Deploy Workloads in Autopilot Mode

The only thing you need to do is add one magical config: nodeSelector: cloud.google.com/compute-class: "autopilot". That's it. You don't need to create or manage any node pools beforehand, just write some YAMLs and kubectl apply. All workloads with cloud.google.com/compute-class: "autopilot" will run in Autopilot mode.

More importantly, you are only billed for the CPU/memory resources your pods request, not for nodes that may have unused capacity or system pods (those running under the kube-system namespace). Autopilot mode is both cost-efficient and developer-friendly.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      nodeSelector:
        cloud.google.com/compute-class: "autopilot"
      containers:
        - name: nginx
          image: nginx:1.29.3
          ports:
            - name: http
              containerPort: 80
          resources:
            requests:
              cpu: 100m
              memory: 128Mi
            limits:
              cpu: 500m
              memory: 256Mi

If your workloads are fault-tolerant (stateless), you can use Spot instances to save a significant amount of money. Just change the nodeSelector to autopilot-spot:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
spec:
  template:
    spec:
      nodeSelector:
        cloud.google.com/compute-class: "autopilot-spot"
      terminationGracePeriodSeconds: 25 # spot instances have a 25s warning before preemption

ref:
https://docs.cloud.google.com/kubernetes-engine/docs/how-to/autopilot-classes-standard-clusters

You will see something like this in your Autopilot cluster:

kubectl get nodes
NAME                             STATUS   ROLES    AGE     VERSION
gk3-my-auto-cluster-nap-xxx      Ready    <none>   2d18h   v1.33.5-gke.1201000
gk3-my-auto-cluster-nap-xxx      Ready    <none>   1d13h   v1.33.5-gke.1201000
gk3-my-auto-cluster-pool-1-xxx   Ready    <none>   86m     v1.33.5-gke.1201000

The nap nodes are auto-provisioned by Autopilot for your workloads, while pool-1 is a default node pool created during cluster creation. System pods may run on either, but in Autopilot cluster, you are never billed for the nodes themselves (neither nap nor pool-1), nor for the system pods. You only pay for the resources requested by your application pods.

FYI, the minimum resources for Autopilot workloads are:

  • CPU: 50m
  • Memory: 52Mi

Additionally, Autopilot applies the following default resource requests if not specified:

  • Containers in DaemonSets
    • CPU: 50m
    • Memory: 100Mi
    • Ephemeral storage: 100Mi
  • All other containers
    • Ephemeral storage: 1Gi

ref:
https://docs.cloud.google.com/kubernetes-engine/docs/concepts/autopilot-resource-requests

Exclude Prometheus Metrics

You may see Prometheus Samples Ingested in your billing. If you don't need (or don't care about) Prometheus metrics for observability, you could exclude them:

  • Go to Google Cloud Console -> Monitoring -> Metrics Management -> Excluded Metrics -> Metrics Exclusion
  • If you want to exclude all:
    • prometheus.googleapis.com/.*
  • If you only want to exclude some:
    • prometheus.googleapis.com/container_.*
    • prometheus.googleapis.com/kubelet_.*

It's worth noting that excluding Prometheus metrics won't affect your HorizontalPodAutoscaler (HPA) which is using Metrics Server instead.

ref:
https://console.cloud.google.com/monitoring/metrics-management/excluded-metrics
https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/cost-controls

Surviving the Digital Dark Forest: Tips for Staying Safe Online

Surviving the Digital Dark Forest: Tips for Staying Safe Online

How I learned to "start worrying" and to embrace the illusion of safety.

Digital security and privacy have become more important than ever. With cyber threats constantly evolving, it is crucial to stay up-to-date with best practices and take proactive measures to protect your online presence. This comprehensive guide covers a wide range of security and privacy recommendations for various platforms and scenarios, aiming to help you fortify your digital life and assets.

General

  • Use a password manager: 1Password or Bitwarden.
    • Never reuse passwords.
    • Use strong passwords.
  • Always enable TOTP-based 2FA (Time-based One-Time Password).
    • Avoid SMS-based 2FA which is vulnerable to SIM swap attack.
    • Even you don't use SMS-based 2FA, your phone number might be used as a "Recovery Method".
  • Avoid using your password manager to generate one-time passwords for critical accounts.
  • Use Passkey.
  • Use security keys: YubiKey.
  • Use different email addresses when registering services if possible.
  • Always use HTTPS.
  • Don't blindly click links you see in your emails or search results; they could be scams!
    • Instead, add your frequently visited websites to your browser bookmarks.
  • Carefully review requested permissions when you connect third-party apps to your critical accounts.
  • Regularly review authenticated devices or sessions for your critical accounts.
    • Revoked them if you're not sure what they are.
    • Explicitly logout after finishing your operations or use Incognito mode.
  • Be skeptical of urgent requests, even from "known" contacts.
  • Have an incident response plan ready BEFORE you need it.
    • If your computer is compromised:
      • Immediately disconnect from network (disable Wi-Fi/unplug ethernet cable) to prevent further data exfiltration.
      • DO NOT reboot or shutdown: this preserves evidence in memory and may prevent malware from establishing persistence.
      • Document everything: take photos of screen, note the time, and any suspicious behavior observed
      • Use a different device to change critical passwords and revoke sessions.
  • Do things that can calm your anxiety.
  • Read Personal Security Checklist.
  • Read An ultimate list of rules any on-chain survivor should follow to stay safe.

Privacy

Credit Card

  • Use different credit cards with different merchants.
    • Some for online shopping.
    • Some for physical payments or Apple Pay/Google Pay.
  • Prefer credit cards over debit cards.
    • Credit card fraud protection is superior because fraudulent charges don't immediately deplete your bank account balance.
  • Set spending limits.

Crypto

  • For large amounts of assets, always store them in hardware wallets or multisig wallets.
  • Use multiple hardware wallets from different vendors: Trezor or Ledger.
    • Some should only hold assets and never interact with DeFi apps.
    • Some are used for trading or farming.
  • Use hardware wallet's hidden wallet with custom passphrase.
  • Always verify transaction details on hardware wallet screens, not just computer screens.
    • Even the Safe UI was spoofed in the infamous Bybit hack.
  • Write your seed phrases on paper or metal, and store them in a physical safe.
    • Keep at least 2 copies in different locations.
    • Never store a hardware wallet's seed phrase digitally, NEVER.
  • Verify backups of your seed phrases every 3 months.
  • Use multisig wallets: Gnosis Safe.
  • Only store a small amount of assets in hot wallets.
    • If you follow this rule, it might be acceptable to store the seed phrase in a password manager.
    • Furthermore, encrypt the seed phrase before storing it.
  • When transferring tokens to a new address, always send a small amount first, and make sure you can transfer them out.
    • It may waste gas, but it's better than losing funds.
  • Add addresses to contacts or whitelists.
  • Always approve tokens with the exact amount, never use infinite (type(uint256).max) approval.
    • It may waste gas, but it's better than losing funds.
  • Always check the slippage setting before swapping.
  • Review your token approvals regularly: Revoke.cash.
    • Before revoking an approval, you should check the original approve() tx is initiated by you.
    • Attackers can create a fake ERC-20 token and set allowance for you.
  • Signing could be dangerous.
    • If it's a clear, human-readable message, it's probably safe to sign.
    • If it contains a large amount of data, read carefully before signing.
    • If the message starts with 0x, just don't sign.
    • Especially, there are "permit" signatures.
  • Use browser extensions or wallets that can simulate/preview transactions.
  • Learn how to decode a transaction.
  • Use Etherscan's Watch List to monitor your account activities.
    • Though the notification might be a bit delayed, it's not real-time.
  • Website (domain name or frontend code) can be hacked as well, even if smart contracts are secure.
  • Read Blockchain Dark Forest Selfguard Handbook.

macOS

  • Use an application firewall and network monitor: Little Snitch.
  • Use an antivirus software: Bitdefender Antivirus.
  • Turn on Firewall.
    • System Settings > Network > Firewall > Options > Block all incoming connections
  • Turn on FileVault which provides full disk encryption.
    • System Settings > Privacy & Security > FileVault
  • Power off your computer when not in use, in order for the disk to be encrypted.
  • Automatically lock your screen when idle.
    • System Settings > Lock Screen > Require password after screen saver begins or display is turned off
  • Set one of Hot Corners to "Lock Screen" and always trigger it when you're away from the keyboard.
    • System Settings > Desktop & Dock > Hot Corners
  • Disable AirDrop and Handoff.
    • System Settings > General > Airdrop & Handoff
  • Exclude sensitive folders from Spotlight.
    • System Settings > Siri & Spotlight > Spotlight Privacy
  • Don't use any apps that can read your clipboard or what you type.
  • Don't use third-party input tools if possible.
  • Create separate browser profiles for different use cases.
    • One for daily activities.
    • One for financial activities, don't install any extensions other than the password manager.
    • Use Incognito mode.
    • Even better: use an isolated computer.
  • The fewer browser extensions installed, the better.
    • Carefully review requested permissions when installing/upgrading browser extensions.
    • Be aware of developers might sell their extension to someone else.
  • Disable Chrome's Preload pages.
    • Chrome > Settings > Performance > Preload pages
  • Install OS security patches as soon as possible.
  • Use Dangerzone if you're working with PDFs.
  • Read macOS Security and Privacy Guide.

iOS

  • Enable Data Protection (Erase all data after 10 failed passcode attempts).
    • Settings > Touch ID & Passcode > Erase Data
  • Change the default PIN of your SIM card.
    • Settings > Cellular > SIM PIN > Change PIN
  • Disable Predictive Text.
    • Settings > General > Keyboards > Predictive
    • Settings > General > Transfer or Reset iPhone > Reset > Reset Keyboard Dictionary
  • Turn off AirDrop.
  • Don't use third-party keyboard apps.
    • These apps will be able to access everything you type: passwords, messages, search terms, etc.
  • Restart your device regularly, ex: once a week.
  • Rapidly press the side button 5 times to enter Emergency SOS mode when needed.
    • Under Emergency SOS mode, your passcode is required to re-enable Touch ID or Face ID.
    • Use it when your device is about to be taken away.
  • Read Telegram & Discord Security Best Practices.
  • Read Privacy Guides - iOS Overview.

Developer

  • Always create API keys with minimum permissions and set a short expiration time if possible.
  • Create distinct API keys for different purposes, services, or machines.
    • Deactivate the API key if you're not using it.
  • Avoid storing credentials in plain text on disk, such as in .env files or ~/.aws/credentials.
    • Instead, store them in 1Password Environments and source them with 1Password CLI.
  • If you're unsure, run the program inside a non-root Docker container.
  • The fewer IDE/editor plugins installed, the better.
  • Be aware of Supply Chain Attack.
    • Run tools like npm audit or pip-audit to check.
  • Enable security-related features on your GitHub repos.
  • Sign your Git commits.

Wi-Fi

  • Avoid using Wi-Fi routers and IoT devices made in China if possible.
    • Due to documented security vulnerabilities and potential mandatory backdoor requirements.
  • Must change the default username/password of your devices.
  • Create a dedicated Wi-Fi network (guest network) for IoT devices.
  • Keep your device firmware up-to-date.
  • Use WPA3-Personal if possible.
  • Disable remote access on your router.
    • If you really want to visit your router's management console through the Internet, set IP whitelist at least.
  • Disable WPS (Wi-Fi Protected Setup) which is vulnerable to brute-force attack.
  • Avoid using public Wi-Fi.

Physical

  • Be cautious when plugging USB devices into your computer.
    • Don't charge devices from your computer if possible.
  • Be vigilant for key loggers.
    • Bring your own keyboard and USB hub when necessary.
  • Cover your laptop's camera with a sticky note.
  • Use certified and well-protected extension cords.
  • Get fire and earthquake insurance for your house.
  • Shred or redact sensitive documents.
    • Instead of simply disposing of them in the trash.

Personal

  • Never share where you live or post photos that could potentially reveal your location.
    • Like a photo of the view from your window, such data can be exploited via OSINT (Open-Source INTelligence).
    • If you really want to share where you've been (such as during travel), only post them after you're back home.
  • Don't reveal information during "inbound" calls.
    • Only share sensitive data during communications that you initiate.
  • Be aware that even if you take all precautions, you may still be vulnerable to a $5 wrench attack.
    • So keep things low-key.

And don't forget: security is always a trade-off.

Pipenv and Pipfile: The officially recommended Python packaging tool

Pipenv and Pipfile: The officially recommended Python packaging tool

You no longer need to use pip and virtualenv separately. Use pipenv instead.

ref:
https://github.com/pypa/pipenv
https://pipenv.kennethreitz.org/en/latest/

Install

$ pip install pipenv

ref:
https://pipenv.kennethreitz.org/en/latest/install/#installing-pipenv

Usage

$ pyenv global 3.7.4

# initialize project virtualenv with a specific Python version
# automatically generate both Pipfile and Pipfile.lock from requirements.txt if it exists
$ pipenv --three

$ cd /path/to/project-contains-Pipfile
$ pipenv install

$ pipenv install pangu
$ pipenv install -r requirements.txt

# install packages to dev-packages
$ pipenv install --dev \
autopep8 \
flake8 \
flake8-bandit \
flake8-blind-except \
flake8-bugbear \
flake8-builtins \
flake8-comprehensions \
flake8-debugger \
flake8-mutable \
flake8-pep3101 \
flake8-print \
flake8-string-format \
ipdb \
jedi \
mypy \
pep8-naming \
ptvsd \
pylint \
pylint-celery \
pylint-common \
pylint-flask \
pytest \
watchdog

# switch your shell environment to project virtualenv
$ pipenv shell
$ exit

# uninstall everything
$ pipenv uninstall --all

# remove project virtualenv
$ pipenv --rm

ref:
https://pipenv.kennethreitz.org/en/latest/install/

Example Pipfile

[[source]]
url = "https://pypi.python.org/simple" 
verify_ssl = true 
name = "pypi" 

[requires] 
python_version = "3.7"

[packages] 
celery = "==4.2.1"
flask = "==1.0.2"
requests = ">=2.0.0" 

[dev-packages] 
flake8 = "*" 
ipdb = "*" 
pylint = "*" 

[scripts]
web = "python -m flask run -h 0.0.0.0"
worker = "celery -A app:celery worker --pid= -l info -E --purge"
scheduler = "celery -A app:celery beat -l info --pid="
shell = "flask shell"

ref:
https://pipenv.kennethreitz.org/en/latest/basics/#example-pipfile-pipfile-lock

nvm: Node.js Version Manager

nvm: Node.js Version Manager

A simple Node.js version manager.

Install nvm

$ curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.34.0/install.sh | bash

ref:
https://github.com/nvm-sh/nvm

Install Node.js

You could also simply run brew install node if you don't really care about what version you installed.

# list available Node.js versions
$ nvm ls-remote

# install the latest LTS version
$ nvm install --lts

$ nvm install 12.13.0 && \
  nvm use 12.13.0 && \
  nvm alias default 12.13.0

# list installed Node.js versions
$ nvm ls

ref:
https://nodejs.org/en/

Install Node.js Packages

# install the package globally
$ npm install -g pangu

# install the package in the current folder
# which generate `package.json` in the same folder
$ npm init
$ npm install pangu
pyenv: Python Version Manager

pyenv: Python Version Manager

A simple Python version manager. It is recommended to use pyenv and pipenv together.

ref:
https://github.com/yyuu/pyenv

Install

Before doing the following steps, you must install Command Line Tools.

$ brew update
$ brew install readline openssl

$ brew install pyenv
# or
$ brew upgrade pyenv
To enable shims and autocompletion add to your profile:
  if which pyenv > /dev/null; then eval "$(pyenv init -)"; fi

$ pyenv --version
pyenv 1.2.14

ref:
https://github.com/vinta/HAL-9000/blob/master/playbooks/roles/python/files/pyenv_profile.sh

Usage

# list available Python versions
$ pyenv install -l

# install a certain version
$ pyenv install 2.7.16
$ pyenv install 3.7.4

# list installed Python versions
$ pyenv versions

# set the default Python version
$ pyenv global 3.5.1

# you can set both Python 2 and 3
$ pyenv global 3.7.4 2.7.16

# switch to the system default Python version
$ pyenv global system

# set the Python version for the current folder
# which generates `.python-version` in the same folder
$ pyenv local 3.7.4

# set the Python version for the current shell
$ pyenv shell 3.7.4

ref:
https://github.com/pyenv/pyenv/blob/master/COMMANDS.md