Cloud Engineer LP 1
Cloud Engineer LP 1
|
|
Folder Level - Operations Sales and Marketing
Logistics
| | |
B2B Supply Chain ECommerce App
Transportation App
App
|
Project Level B2B Dev B2B Staging B2B Production
===================================================================================
=========================================================================
So during the peak the company had to do "PEAK LOAD Provisioning" which means to
"Procure"(Buy) infrastructure "for peak load"
Note: Once bought the infrastructure would be doing nothing during periods of low
loads and you would be paying for it
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
--> Imagine Another scenario where a startup becomes popular
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
===================================================================================
=========================================================================
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
1. Google Compute
Engine(GCE)
- Features(GCE)
Create and manage lifecycle of virtual machine(VM) instances i.e., start, restart,
stop...
Load Balancing and Auto Scaling for multiple VM instances
Attach Storage(& Network Storage) to your VM instances
Manage network connectivity and configuration for your VM instances
- Machine Family
General-Purpose
Compute-Optimized
Memory-Optimized
GPU
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
Note: An external IP address get reset after stopping and starting a server
Search for "External IP Address" in VPC section >> click on "Reserve Static
Address" and enter the details >> Click on "change" in the same row and assign a
VM instance to the external IP
Note: You are "billed for" an static IP when "you are NOT using it"
Make sure that you explicitly release an static IP when you are not using it
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
Executing these steps manually requires a lot of steps and time. So how do we
reduce the number of steps in creating an VM instance and setting up a HTTP server?
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
A. Startup Script
Create VM instance >> Under "Firewall", click on "Management" >> Under "Management"
there is "Startup script" under "Automation" >> Paste your script and click on
launch
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
B. Instance Template
- Why do we need to specify all the VM instance details(Image, instance type etc)
every time you launch an instance?
How about creating an instance template ?
Define machine type, image, labels, startup script and other properties
- "CANNOT" be updated
to make a change, copy an existing template and modify it
Virtual Machines >> Instance Templates >> Paste the script you want >> Three dots
on the same row >> click on create VM instance
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
Now, Create "VM instance" >> in boot disk select "custom image" >> create.
Note: You can now create instances by clicking the three dots
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
===================================================================================
=========================================================================
Discounts
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
Virtual Machine >> Committed Use Discounts >> Purchase Commitment >> Enter the
details and purchase
--> 3. Preemptible VM
- RESTRICTIONS:
NOT always available
NO SLA and CANNOT be migrated to regular VMs
NO Automatic Restarts
Free Tier credits not applicable
VM Machine >> VM instance >> Create VM >> Under Firewall, there are other
options(Management, Security...) >> Under "Management" click on "Pre-emptibility"
NOTE: You can write a script such that if a VM is getting preempted, it can
automatically save it's data on the persistent disk
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
===================================================================================
=========================================================================
Billing
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
Billing >> Budgets and Alerts >> Create Budget >> Enter your specified budget, set
thresholds notifications....
Billing >> Billing Export >> You can now either export it as a file or export it to
Big-Query where you can run searches
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
===================================================================================
=========================================================================
- How do you keep your VM instances running when a host system needs to be
updated(a software or a hardware update needs to be performed)?
When there is a update from GCP on your instance and in case if it is running, it
will be terminated.
VM Machine >> New VM instance >> Under firewall, Management, security, disks... >>
Under "Management" >> "On Host maintenance"(Migrate VM instance automatically
enabled) / "Automatic Restart"("On" default)
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
- What do you do when predefined VM options are NOT appropriate for your workload
Create a machine type customized to your needs(a Custom Machine Type)
Create VM machine >> VM instance >> Machine Family >> Machine Type >> Custom
Machine >> Set the Cores and Size accordingly
- How do you accelerate math intensive and graphic-intensive workloads for AI/ML
etc?
- Add a GPU to your virtual machine:
High performance for math intensive and graphics intensive workloads
Higher cost
(REMEMBER) Use images with GPU libraries for (deep learning) installed
(OTHERWISE, GPU will not be used)
- GPU restrictions:
NOT Supported on all machine types(For example, not supported on shared-core or
memory-optimized machine types)
On host maintenance can only have the value "Terminate VM instance"
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
- You can only change machine type( adjust the number of vCPU and memory) of a
stopped instance
You CANNOT change the machine type of a running instance
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
SOLUTION: Project
Billing Account
Compute Engine APIs should be enabled(Remember to enable the Compute
Engine API when you create a new project) Disabled in default.
- 2. You want dedicated hardware for your compliance, licensing, and management
need
- How to setup:
Virtual Machine >> Sole Tenant nodes >> Create Node group >> Name, Region,
template(existing/create) >> Create
Virtual Machine >> Virtual instance >> Create VM >> Scroll down to Management,
Security, Disks, Sole Tenants >> Sole Tenancy >> Enter the Affinity Labels
NOTE: Keep a note on Affinity Labels while creating a node template with which can
group nodes.
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
===================================================================================
=========================================================================
---> 2. Gcloud
- Installation
You can also use Gcloud from cloud shell(Pre-built in Google Console)
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
Scenario: You are working on multiple projects from the same machine. You would
want to be able to execute commands using different configurations
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
- EXAMPLES:
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
- Options
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
NOTE: Additional Option using the console: Compute >> Virtual Machine >> Settings
>> Settings >> Region/Zone
NOTE: Priority Option 3(if exists) overrides Option 2(if exists) overrides Option 1
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
===================================================================================
=========================================================================
3. Instance Groups
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
- Important Features:
Maintain certain number of instances
If an instance crashes, MIG launches another instance
Auto healing: Configure a Health check with initial delay (How long should
you wait for your app to initialize before running a health check?)
--> Demo
>> Virtual Machine >> Instance template >> Make sure a instance template exists >>
Instance Groups >> instance groups >> create instance group
NOTE: If you are grouping the existing instances then it might be "Unmanaged
Instance Group"
If you create a group of instances based on instance template then you are creating
a "MIG"
NOTE: There are again two types in MIGs, they are stateless and stateful
Stateful - If you need to create a database and does not want to loose any
instances
Create >> Enter the group name >> Fill in the details like instance template, Auto
scaling factors, No of VMs for auto scaling, health check....
NOTE: You can click the instance group to explore the remaining
factors/configurations. You can also edit the group i.e., health matrix, instances
count,
scaling
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
NOTE: In rolling you update set of instances i.e., say if you have ten instances,
you update two instances first, then again two and so on.
NOTE: Canary Testing is where you configure a canary template, test it out on set
of instance say two and then update the remaining instances
--> Demo:
Virtual Machine >> Instance Group >> Select a MIG >> update VMs >> Select new
template, Select if you want canary testing or not >> Select update type
Restart/Replace >> Select the number of instances that you want to make
unavailable(Max-unavailable) or temporary additional instances(Max-surge)
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
D. You want high availability in an MIG even when there are hardware/software
updates
Use an instance template with availability policy automatic restart: enabled and
on-host maintenance: migrate. Ensures live migration and automatic restarts.
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
--> Playing with Managed Instance Groups - Basics of using Google CLI
existing one
--most-disruptive-allowed-action=none(default)/refresh/replace/restart
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
===================================================================================
=========================================================================
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
- Important Features
- Health Check - Route to healthy instances
Recover from failure
- Auto Scaling
- Enables:
High Availability
Auto Scaling
Resiliency
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
--> Demo
NOTE: TCP provides more resiliency than UDP but UDP provides you more performance
than TCP.
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
- Backend - Group of endpoints that receive traffic from Google cloud load
balancer(example: instance group(usually MIGs))
- Host and Path Rules(For HTTP(S) Load Balancing) - Define rules redirecting the
traffic to different backends:
Based on path - ABC.com/a vs ABC.com/b
Based on host - a.ABC.com vs b.ABC.com
Based on HTTP headers (Authorization header) and methods(POST, GET, etc)
Client < ------------ > Google Load Balancer < --------------- > VM
Instances
- SSL/TLS Termination/Offloading
- Client to Load Balancer: HTTP/TLS
- Load Balancer to VM instance: HTTP/TCP
Hierarchy --> Instance Template >> Instance Group >> Load Balancer
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
IPv4/IPv6 clients >> External LB >> i. HTTP/HTTPS Traffic >> Regional? >>
Regional LB(If the traffic is Regional)
ii. HTTP/HTTPS Traffic >> Regional? >>
External/Classic LB(If the traffic is global)
iii. TCP traffic >> SSL Offload(Yes) >>
SSL proxy
iv. TCP traffic >> SSL Offload(No) >>
Need Global LB or IPv6 >> TCP proxy
v. TCP traffic >> SSL offload(No) >>
Preserve client IP(Yes) >> External Network LB
vi. External LB is also recommended for
UDP and ICMP traffic
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
Load balancer >> Types of Traffic >> Proxy or Pass-Through >> Destination Ports
i. External HTTP(s) >> Global, External, HTTP or HTTPS >> Proxy >> HTTP on 80/8080,
HTTPS on 443
ii. Internal HTTP(S) >> Regional, Internal, HTTP or HTTPS >> Proxy >> HTTP on
80/8080, HTTPS on 443
iii. SSL Proxy >> Global, External, TCP with SSL Offload >> Proxy >> A big list
iv. TCP Proxy >> Global, External, TCP without SSL Offload >> Proxy >> A big list
v. External Network(TCP/UDP) >> Regional, External, TCP, or UDP >> Pass-Through >>
any
vi. Internal TCP/UDP >> Regional , Internal, TCP, or UDP >> Pass-through >> any
NOTE: Proxy requests are those in which content is hidden whereas Pass-through are
ones in which information is visible
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
Create multiple MIGs for your VM instances in multiple regions. Load Balance
using a LB.
- 3. You want to route requests to multiple microservices using the same load
balancer
Create individual MIGs and backends for each microservices. Create host and
path rules to redirect to specific microservice backend based on the
path(/microservice-a, /microservice-b etc). You can route to a backend Cloud
Storage Bucket as well.
- 4. You want to load balance Global external HTTPS traffic across backend
instances, across multiple regions
- 5. You want SSL termination for global non-HTTPS traffic with load balancing
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
===================================================================================
=========================================================================
5. Managed Service
in GCP
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
- Do you want to continue running applications in the cloud, the same way you run
them in your data center?
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
- Varieties:
- CAAS(Container as a Service): Container instead of Apps
- FAAS(Function as a Service): Functions instead of Apps
- Databases - Relational and NoSQL, Queues, AI, ML, Operations, etc.
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
--> Microservices
- How can we have one way of deploying Go, Java, Python, or JavaScript..
Applications/Microservices.
- Enter Containers
- Advantages
- Docker containers are lightweight
Compared to VMs they do not have a guest OS
- Docker provides isolation for containers
- Docker is cloud neutral
- Say you have made docker images of your application to use it everywhere but how
do deploy it to a cluster of VMs?
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
--> Serverless
- What if you don't need to worry about servers and focus on your code?
- Enter Serverless
- Remember: Serverless does NOT mean "No Servers"
- You focus on code and the cloud managed service takes care of all that is
needed to scale your code to serve million of requests!
- And you pay for requests and NOT servers!
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
- 1. Compute Engine: High performed and general purpose VMs that scale gradually
-- IaaS
- 4. Cloud Functions: Build event driven applications using simple, single purpose
functions -- FaaS, Serverless
- 5. Cloud Run: Develop and deploy scalable containerized applications. Does NOT
need a cluster --CaaS(Serverless)
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
===================================================================================
=========================================================================
6. App Engine
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
- Supports:
- Go, Java, Node.js, PHP, Python, Ruby, using pre-configured runtimes
- Use custom run-time and write code in any language
- Connect to variety of Google Cloud storage products(Cloud SQL etc)
- Features:
- Automatic load balancing and Auto scaling
- Managed platform updates and Application health monitoring
- Application versioning
- Traffic Splitting
- Compute Engine
- IAAS
- More Flexibility
- MORE Responsibility
- Choosing Image
- Installing Software
- Choosing Hardware
- Fine grained Access/Permissions(Certificates/Firewalls)
- Availability
- App Engine
- PaaS
- Serverless
- LESSER Responsibility
- LOWER Flexibility
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
Application
|
---------------------------------------------
|
|
Service
Service
|
|
-------------------
-------------------------
| | |
|
Version Version
|
--------------
| |
Instance Instance
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
FEATURE STANDARD
FLEXIBLE
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
>> App Engine >> Enable API(Search App Engine Admin API) >> Choose Region >>
Language >> Environment
>> Cloud Shell >> Open Editor >> Open in New Window >> Open Folder >> Choose the
home Folder >> Select the files from the downloaded file >> Drag and Drop
on the explorer part of the console
>> "cd default-services" >> "gcloud config list" >> "gcloud config set project
PROJECT_ID" >> "gcloud app deploy" >> press Y >> Error(permission denied) >>
IAM >> Edit member >> edit role >> select a role >> storage object viewer
permission >> save >> deploy again >> use the URL generated to access
>> "gcloud app services list" >> "gcloud app versions list" >> "gcloud app
instances list"
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
>> "gcloud app deploy --version=v2" >> Yes >> "gcloud app browse" >> "gcloud app
browse --version=VERSION_ID"(to list the URL of previous versions)
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
>> create a new version of the application >> Now you do not want to switch traffic
immediately and want the current version to be live but slowly switch the traffic
>> "gcloud app deploy --version-v3 --no-promote >> Yes >> Use the URL generated to
test it.
>> "gcloud app services set-traffic --splits=v3=.5, v2=0.5" >> "watch curl URL"(to
check the requests)
NOTE: Splitting traffic by IP is the default option but not a good idea as it may
cause confusion
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
--> Creating New Service and Playing with App Engine
- Apart from the default service you can perform number of other additional
services
>> "cd ../my-first-service/" >> "gcloud app deploy" >> Yes >> "gcloud app services
list"
>> "gcloud app browse"(active version of default service) >> "gcloud app browse --
service=SERVICE_NAME"(activate your required service)
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
- Go through the video again to know how to configure services in app.yaml file
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
NOTE: App Engine >> App Engine Setting >> Custom Domain
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
- Random: Do it Randomly
- How do I do it?
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
- Other Commands
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
- Use Cases:
- Send a report by email every day
- Refresh cache data every 30minutes
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
dispatch:
- url: "*/mobile/*" (specify the url)
service: mobile-frontend (specify the service for the
traffic)
- url: "*/work/*"
service: static-backend
queue:
- name: fooqueue
rate: 1/s
retry_parameters:
task_retry_limit: 7
task_age_limit:2d
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
- Scenario 1: I want to create two Google App Engine Apps in the same project
- Not possible. You can only have one App Engine App per project.
However you can have multiple service and multiple versions for each service
- Scenario 2: I want to create two google app engine services inside the same app
- Yes. You can create a multiple services under the same app. Each
service can have multiple versions as well
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
===================================================================================
=========================================================================
7. GKE: Google
Kubernetes Engine
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
--> Kubernetes
Container Image
Configuration
|
|
|
|
|
|
|
______________________________________________________________|
|
|
|
|
Container
Orchestrator(Kubernetes)
|
|
|
|
Cluster
|
|
_______________________________|
__________________________________
| |
|
Virtual Server 1 Virtual
Server 2 Virtual Server 3
- Minimize operations with auto-repair (repair failed nodes) and auto-upgrade (use
latest version of k8 always) features
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
NOTE: For Kubernetes the command usually starts with "gcloud container"
>> "gcloud config set project PROJECT_ID" >> "gcloud container clusters get-
credentials NAME --zone-us-central1-c --project PROJECT_NAME"
NOTE: You need to connect to the clusters using either the console or command line
Cluster
|
|
|
-----------------------------------------------------------------------------------
--------------------
| |
|
| |
|
| |
|
Node Pool 1 Node Pool 2
Node Pool 3......
|
|
|
-----------------------
| |
Node 1 Node 2
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
>> do a walkthrough >> Workloads >> Services and Ingress(Rules for Routing External
HTTP Traffic)
--> Auto-Scaling
NOTE: configmap in simple words: Say you need to make some changes in the
configuration of an application, after sometime, at some part. Instead of
rewriting it as a whole you can create a configmap where you can make the
changes there. Say URL, Tokens, SSL.
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
>> Click on the cluster >> Instead of entering commands in command line, you can
edit the yaml file >> overview, details, events, logs, YAML
NOTE: Look at the deployment and Service file provided in the course
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
- 11. Deploy a new microservice which needs nodes with a GPU attached
- Attach a new node pool with GPU instances to your cluster
- "gcloud container node-pools create POOL_NAME --cluster
CLUSTER_NAME"
- "gcloud container node-pools list --cluster CLUSTER_NAME"
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
- 1. Zonal Cluster: Single Zone - Single Control planes. Nodes running in the same
zone
Multi-zonal - Single Control plane, but nodes running in
multiple zones
- 4. Alpha Cluster: Clusters with alpha APIs - early feature API's. Used to test
new K8S features.
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
- A pod contains one or more container(usually one pod contains one container)
>> kubectl get pods(Info on pods) >> kubectl get deployment(No. of nodes) >>
kubectl get deployment -o wide >> kubectl get pods -o wide
- Network
- Storage
- IP Address
- Pods
- Volumes(Shared persistent disks)
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
Cluster
|
|_ _ _Node 1(use resize to scale up/down)
| |
| |_ _ _ Pod 1 (use replica to scale up/down) - Deployment (Microservice)
| | |
| | |_ _ _ Container 1 (Running micro-service-1)
| | |
| | |_ _ _ Container 2 (Running micro-service-2)
| |
| |_ _ _ Pod 2
| |
| |_ _ _ Container 1
|
|
|_ _ _Node 2
- Replica set ensures that a specific number of pods are running for a specific
microservice version.
**NOTE: Say you have replica set for v1 and updated the deployment to v2, still
the replica sets are of v1
>> “kubectl exec -it POD_NAME --bin/bash” >> Enter the container bash
>> kubectl delete pod >> kubectl delete pod POD_NAME >>
NOTE: If you update a deployment, the old deployment still exists with replica
sets(pods), if you want new replica sets pods for the updated version, you
need to scale it up again
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
- Create Service
- kubectl expose deployment name --type=LoadBalancer --port=80
- Expose PODs to outside world using a stable IP address
- Ensures that the external world does not get impacted as pods
go down and come up
- Three Types:
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
- You can secure your container images. Analyze for vulnerabilities and enforce
deployment policies
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
GKE Remember:
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
- 1. You want to keep your costs low and optimize your GKE implementation
- Create a new node pool with GKE sandbox. Deploy untrusted code to sandbox
node pool
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
GKE - Cluster Management - Command Line
- 1. Create Cluster
- 2. Resize Cluster
- 3. Autoscale Cluster
- 4. Delete cluster
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
- 2. Create a Deployment
- 3. Create Service
- 4. Scale Deployment
- 5. Autoscale Deployment
- 6. Delete Deployment
- 8. Rollback Deployment
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
===================================================================================
=========================================================================
8. Google Cloud
Functions
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
- 2 product versions
- Cloud Functions (1st gen): First version
- Cloud Functions (2nd gen): New Function built on top of cloud run
and eventarc
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
>> Cloud Functions >> Enable API >> Create Functions >> 1st/2nd Gen(advanced
features) >> 1st Gen >> Name >> Region >> copy the URL >> Select Trigger Type >>
Allow unauthenticated invocations >> uncheck the http requests >> save >> set
runtime build connections to minimum >> next
>> Select the function >> Testing >> Test the function
NOTE: You can edit the function code whenever you want and you can look at the logs
in the logs section
NOTE: The difference between the 1st and 2nd Gen is the memory and timeout duration
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
===================================================================================
=========================================================================
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
>> Cloud Run >> Create Service >> Choose the service(image) you want to deploy from
the artifacts and registry section you can also create an image from a source
repository and use the image for deploying >> Name >> Zone >> CPU Allocation(i.
Only allocate when request is raised(charged per invocation), ii. CPU is always
allocated), choose i >> Auto-scaling(can be scaled down to zero but recommended to
1) >> Allow all traffic >> Authentication(Allow unauthenticated request) >> create
>> Inside a service, you can have multiple revisions >> Edit and Deploy a new
revision >> Configure new image, cpu, timeout, max request, autoscaling >> create
Note: Cold Start: If a request is sent to a service and there is no instance, cloud
run will take some time to initiate a new instance
- Cloud Run for Anthos: Deploy your workloads to Anthos clusters running on-premise
or on Google Cloud
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
===================================================================================
=========================================================================
Cloud Functions -
Second Generation
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
>> Cloud Function >> Create >> 2nd Gen >> Name >> Region >> Next >> Runtime >>
Deploy >> URL
>> Cloud Run >> you can see a cloud run service created for cloud function >> You
can also see the revisions >> Click on three dots next to the version to “Manage
Traffic”
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
- 1st Gen uses the typical serverless functions architecture ( The above
architecture)
>> Cloud Functions >> Select a function >> Edit and Deploy new revision >> Scroll
Down >> Maximum requests per container(Set Concurrency for Cloud Function)
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
- “--gen2 (Use 2nd gen. If this option is not present, 1st gen will be used)
- “--source”
- zip file from Google Storage
(gs://my-source-bucket/my_function_source.zip) (OR)
- Source Repo (https://URL/project/${PROJECT}/repos/${REPO}) (OR)
- Local file system
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
===================================================================================
=========================================================================
Encryption
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
- Examples:
- Data copied from on-premise to cloud storage
- An application talking to a database
- Two Types:
- In and out of the cloud (The internet)
- Within cloud
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
-->> Encryption
- If you store data as it is, what would happen if an unauthorized entity gets
access to it?
- Imagine losing an unencrypted hard disk
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
- Control their use in your applications and GCP services (Customer-Managed Key)
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
>> Security >> Cryptographic Keys >> Enable API >> Create a key ring(a key holder)
>> KEY_RING_NAME >> REGIONAL/GLOBAL, GLOBAL >> i. Generate key, ii. Import key,
iii. External key manager(not for global keys) >> KEY_NAME >> Protection
Level(Software/HSM) >> Software >> Purpose >> Symmetric encrypt/decrypt >> Create
>> VM Instance >> Management, Security, Disks, Networking, Sole Tenancy >> Disk >>
Customer-managed key >> Grant permission
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
===================================================================================
=========================================================================
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
- You have created a file share to share a set of files with your colleagues in a
enterprise. What type of storage are you using?
- File Storage
|
File Storage ------------------
|
_______ Storage
|
|
|______________________ Virtual Server
B ________________|
|________ Storage
**File Storage
**Block Storage
- Typically, one block storage device can be connected to ONE virtual server
- (EXCEPTIONS) You can attach read only block devices with multiple
virtual servers and certain cloud providers are exploring multi-writer disks
as well
- HOWEVER, you can connect multiple different block storage devices to one virtual
server
- Used as,
- Direct Attached Storage(DAS): Similar to a hard disk
- Storage Area Network(SAN): High speed network connecting a pool of
storage devices
Used by databases - Oracle and Microsoft SQL
Server
- Media workflows need huge shared storage for supporting processes like video
editing
- Enterprise users need a quick way to share files in a secure and organized way
- Block Storage:
- i. Persistent Disks: Network Block Storage
- Zonal: Data replicated in one zone
- Regional: Data replicated in multiple zone
- ii. Local SSDs: Local Block Storage
NOTE: Configure it in Boot Disk, You can add new disks in networking, disks,
security, management
NOTE: You can also add existing disk
NOTE: Some machine types allow addition of local SSD
- File Storage:
- Filestore: High performance file storage
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
- REMEMBER:
- Advantages:
- Ideal for use cases needing high IOPs while storing temporary information
Examples: Caches, temporary data, scratch files etc
- Disadvantage:
- Ephemeral Storage
Lower Durability, Lower Availability , Lower Flexibility compared
to PDs
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
- Provisioned Capacity
- Very Flexible:
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
- 4. Snapshots Supported
Not Supported
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
Feature Standard
Balanced SSD
- 2. Referred to as pd-standard
pd-balanced pd-ssd
- 5. Cost Cheapest
In Between Expensive
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
-->> RECOMMENDATION
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
>> Create a VM instance >> Management, Security, Disks >> Add Disk >> Create
NOTE: If you terminate a VM then automatically the persistent disk also perishes.
To avoid that use the following steps:
>> New Instance >> Disk >> Boot Disk >> Advance >> Keep Boot Disk
>> Existing VM >> Edit >> Boot Disk >> Advance >> Keep Boot Disk
>> Disk >> Click the three dots next to any of the persistent disk >> Create
Snapshot >> Name >> Create
NOTE: You can use this snapshot to create a VM instance as it contains the Boot-
Disk Configuration
>> Disks >> Create >> Select a Source >> Disk from snapshot
>> Schedule Snapshot >> Frequency >> Start Time >> Set Autodelete >> Create >>
Disks >> Select a disk >> edit >> snapshot schedule
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
>> Click on three dots next to a VM instance >> Create VM Image >> Set up >> Create
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
-->> Comparison
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
- Actions: create/delete/deprecate/describe/export/import/list/update
- Creating Images
- gcloud compute images create IMAGE_NAME
- From Disk: gcloud compute images create IMAGE_NAME --
source-disk DISK_NAME --source-disk-zone DISK_ZONE
- From a snapshot: gcloud compute images create IMAGE_NAME
--source-snapshot SNAPSHOT_NAME
- From another image: gcloud compute images create
NEW_IMAGE_NAME --source-image SOURCE_IMAGE_NAME --source-image-project
SOURCE_IMAGE_PROJECT
- From latest non deprecated image from a family: --
source-image-family=source-image-family --source-image-project=source-image-
project
- Deprecated Image
- gcloud compute images deprecate IMAGE --state=DEPRECATED
- Other Examples:
- gcloud compute images delete my-image1 my-image2
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
1. Global
i. Images
ii. Snapshots
iii. Instance Templates (Unless you use zonal resources in your template)
2. Regional
3. Zonal
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
- 1. You want very high IOPS but your data can be lost without a problem
- Local SSDs
- 2. You want to create a high performance file sharing system in GCP which can be
attached with multiple VMS
- Filestore
- 3. You want to backup your VM configuration along with all of its attached
Persistent Disks
- 4. You want to make it easy to launch VMs with hardened OS and customized
software
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
===================================================================================
=========================================================================
Object Storage - Cloud
Storage
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
-->> Demo
>> Cloud Storage >> create bucket >> Name(Must be unique globally) >> Region/Dual-
Region/Multi-Region >> Choose storage class >> Create
>> Drag n Drop the files (2030, cloud....) into the bucket
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
NOTE: If you open an object (Say a image here, which is an object) you can find the
URI which is the Key and object itself is a value
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
-->> Cloud Storage - Objects and Buckets
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
- Storage classes help to optimize your costs based on your access needs
- Designed for durability of 99.99999999999% (11 9’s)
- i. Standard
ii. Nearline Storage
iii. Coldline Storage
iv. Archive Storage
NOTE: You can configure default class for storage but you can specify storage class
at object level
NOTE: You can have objects with different classes at different level in same Bucket
NOTE: Default class will be assigned if an object is not specified a class
-->> Feature
- Unlimited storage
- Autoscaling (No configuration needed)
- No minimum object size
- Committed SLA is 99.95% for multi region and 99.99% for single region for
Standard, Nearline, and Coldline Storage classes
- No committed SLA for Archive Storage
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
1. Upload
- i. Simple Upload
2. Download
- i. Simple Download
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
NOTE: If the concurrent version is deleted then the object is entirely deleted
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
- Allowed Transitions
- (Standard or Multi-Regional) to (Nearline or Coldline or Archive)
- Nearline to (Coldline to Archive)
>> Rule:
{
“Lifecycle”: {
“rule”: [
{
“action”: {”type” : “delete”}, -->> Deletes an object if not
used for 30 days
“condition”: {
“age”: 30,
“isLive”: true
}
},
{
“action”: {
“type”: “SetStorageClass”,
“StorageClass”: “NEARLINE”,
},
“condition”: {
“age”: 365,
“matchesStoageClass”: {“STANDARD”},
}
}
}
}
}
>> Cloud Storage >> Bucket >> Lifecycle >> Manage Lifecycle
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
>> Open the bucket >> Configuration >> Encryption Type >> Google Managed
Key/Customer Managed Encryption key
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
- 2. You want to permanently store application for regulatory reasons. You do not
expect to access them at all.
- 3. Log files stored in Cloud Storage. You expect to access them once in a
quarter.
- Cold Line
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
-->> Cloud Storage - Command Line - gsutil
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
===================================================================================
=========================================================================
Authentication and
Authorization in GCP (IAM)
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
- You have resources in the cloud (examples - a virtual server, a database etc)
- You have identities (human and non-human) that need to access those resources and
perform actions
- For example: launch (stop, start, or terminate) a virtual server
- Identities can be
- A GCP User (Google Account or Externally Authenticated User)
- A Group of GCP user
- An application running in GCP
- An application running in your database center
- Unauthenticated users
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
- Three Types:
- Custom Roles: When predefined roles are NOT sufficient, you can create
your own custom roles
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
- resourcemanager.projects.get
- resourcemanager.projects.list
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
- Member: Who?
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
>> Search >> IAM >> Add >> Member >> Email/ID >> Assign Role
>> Policy Troubleshooter >> Enter ID >> Select project in Suggestions >> enter
permission to check >> add more
- gcloud projects
- “gcloud projects add-iam-policy-binding”: Add IAM policy binding
- “gcloud projects get-iam-policy”: Get IAM policy for a project
- “gcloud projects remove-iam-policy-binding”: Remove IAM policy
binding
- “gcloud projects set-iam-policy”: Set the IAM policy
- “ gcloud projects delete”: Delete a project
- gcloud iam
- “gcloud iam roles describe”: Describe an IAM role
- “gcloud iam roles create”: create an iam role (--project, --
permissions, --stage)
- “gcloud iam roles copy”: Copy an IAM role
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
-->> Service Accounts
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
>> Service Accounts >> Create Service Account >> Name >> Create >> Grant
permissions >> Continue >> Grant users access to this service account
>> VM >> Add VM Instance >> Specify a service account >> Create >> SSH >> create a
bucket >> gsutil mb gs://BUCKET_NAME >> Access Denied Error >> Edit the
role/permission for the service account >> choose cloud storage (GCS)
NOTE: You can use the service account for a VM to restrict the permissions of users
using it (say if you do not want any user to assign a bucket to the VM
you can describe that in your service account)
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
-->> Scenarios
-> 1. Use Case 1: VM <--> Cloud Storage
iii. Make the Service Account Key File Accessible to your application
- Set environmental variable GOOGLE_APPLICATION_CREDENTIALS
export GOOGLE_APPLICATION_CREDENTIALS=”/PATH_TO_THE_KEY_FILE”
- Make calls from outside GCP to Google APIs with short lived permissions
- Few hours or shorter
Less risk compared to sharing service account keys!
- Credential Types:
- Example
- When a member needs elevated permissions, he can assume the service account
role (Create OAuth 2.0 access token for service account)
- OpenID Connect ID tokens is recommended for service to service authentications:
- A service in GCP needs to authenticate itself to a service in other
cloud.
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
- It is both. You can attack roles with Service Account (Identity). You
can let other members access a SA by granting them a role on the Service
Account (resource)
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
- ACL: Define who has access to your buckets and objects, as well as what level of
access they have
- Use uniform access when all users have same level of access across all objects in
a bucket
- Fine grained access with ACLs can be used when you need to customize the access
to an object level
>> Cloud Storage >> Pick a bucket >> Permissions >> Access Control >> Fine
Grained/Uniform >> Switch to uniform
NOTE: If you are using uniform level access, you cannot have ACL at objects level
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
- You would want to allow a user limited time access to your objects:
- Users do NOT need Google accounts
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
- 1. Create a bucket with the name as website name (Name of the bucket should match
DNS name of the website)
- Verify the domain is used by you
===================================================================================
=========================================================================
Database in GP
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
-->> Recovery Point Objective (RPO) and Recovery Time Objective (RTO)
- 3. Data is critical (RPO - 1 minute) but I can tolerate downtime of a few hours
(RTO - few hours)
- Create regular data snapshots and transaction logs. Create database from
snapshots and transaction logs when a failure happens
- 4. Data can be lost without a problem (for example: cached data)