gpcdesre/Part_3.md

422 lines
17 KiB
Markdown
Raw Normal View History

2020-10-26 16:02:34 +00:00
Google Cloud CI/CD Pipeline (GCP DevOps Engineer Track Part 3)
==============================================================
### Understanding Google Cloud CI/CD Pipelines
#### Big Picture
- Taking Code changes (deltas) and automatically shepherding them through the process to become a running system, that the users of that system can actually use.
- CI/CD system is internal software that serves the purpose of managing other software (internal or external)
- CI/CD deploying to Prod e.g. GCP
- Continuously - Why? - We avoid a lot of problems when we do things continuously, or rather we get loads of problems when we don't do things continuously. Higher cost when things are done regularly
- Error-Prone Humans
Costs or a software Project
43% in Testing
- Cost of removing an issue goes up dramatically as the phases of the project continue
33% Cost reduction from a good QA system
70% of outages are due to changes in a live system
At least 10% (lower bound) cost saving by implementing CI/CD
[Martin Fowler - Software Guru (Agile, Scrum CI/CD)](https://martinfowler.com/articles/continuousIntegration.html#BenefitsOfContinuousIntegration)
* _"break down the barries between customers and development"_
* _"allows your users to get new features more rapidly"_
* _"more rapid feedback on those features"_
* _"more collaborative in the development cycle"_
* _"dramatically easier to find and remove [bugs]"_
* _"dramatically less bugs, both in production and in process"_
* _"reduced risk"_
#### Relating SRE to CI/CD
Martin Fowler - _"Continuous Integration is a software development practice... [that] allows a team to develop cohesive software more rapidly"_ - Make better software - Faster!
Make Software Faster
- Efficiency
- Not just efficiency
- Changes how you interact
Make Better Software
- Feedback Loops
- Other Stuff
- Leads to "Faster"
_"I think the greatest and most wide ranging benefit of Continuous Integration is reduced risk"_
Many many smaller changes instead of single large changes
#### Understanding Continuous Integration
What is CI?
_"Continuous Integraion is a software development practice where members of a team integrate their work frequently, usually each person integrates at least daily - leading to multiple integrations per dat. Each integration is verified by an automated build (including test) to detect integration errors as quickly as possible"_
Purpose:
- Ensure the updated codebase is at least functinoal. Not completely broken. - This is a "Quality Bar"
#### Understanding Continuous Delivery
What is CD?
_"Continuous Delivery is a software development discipline where you build software in such a way that the software can be released to production at any time"_
- Can be a major event
- Making a deployment a big deal is an unesscessary problem.
- Ensure the updated codebase is at least as good as it used to be - so it is releasable
- This is also a "Quality Bar"
Regression - When some functionality broke e.g. a bug specifically when something used to work but now doesn't.
**CD is all about preventing regressions**
If the new feature doesn't work perfectly, the worst case scenario is that at least it worked like it did before.
#### Understanding Continuous Deployment
What is C Deployment?
_"[A]utomatic deployment helps both speed up the process and reduce error. It's also a cheap option since it just uses the same capabilities that you use to deploy into test environments"_
Reducing Errors - Requires high quality
Purpose - Make the newly updated and validated codebase available to the users. This is automation of an action. Absolutely requires excellent automated testing in that continuous delivery stage.
Just because this newly update and validated codebase is available to the users, this does not always mean that the updated functionality will immediately be available to those end users. I would say, in fact, it's ideal if that new functionality is not made available by the deployment... sound strange? Why is this?
Because the risk of making any change is the larger when the known impact of that change is larger, then you should try to reduce the impact of the change instead. If you deployed the new code base and you know that there should be no visible impact on the users, then all of your metrics should actually show that right? The evidence of what your users are doing now should corroborate your story and not contradict it. That's just good science, and of course good science underpins good engineering.
**Feature Flags/toggles** - really valuable to this situation
Really valuable tool in toolbox. Feature flags/toggles are a powerful technique allowing teams to modify system behaviour without changing code. Now the point I'm trying to make, is if you can modify behaviour without modifying the code then you can also use these to modify code without modifying behaviour, and this is how you use them to manage risk. When you're doing something new, you build that new thing into the system, and you continuously integrate what you're doing, but to stop those unfinished changes of yours from breaking everyone else, you should put your changed functionality behind a feature flag. Make it so that the default behaviour is unchanged from how it was before you started making your changes. This means that you're not regessing any previous funtionality and you leave your feature flag defaulting to "off" until you are ready to have other people using your new thing, then you turn it on for them. And by doing this you can then manage the roll-out of the feature completely independently from the rollout of the changed code. In fact, your half finished feature will likely have been deployed several times already, but it won't have caused any problems because you managed its impact with a feature flag and each deployment would have gone through your full CI/CD pipeline to validate the quality is still there. But then, when you fully rolled out that new feature and everyone is using it and you're sure you don't want to roll it back then you can simply remove the feature flag to simplify your codebase to remove that little bit of technical debt.
_"If you deploy into production one extra automated capability you should consider is automated roll-back. Bad things do happen from time to time... Being able to automatically revert also reduces a lot of the tension of deployment, encouraging people to deploy more frequently and thus get new features out to users quickly"_
"We engineer both changes and change management systems to reduce risk, and efficiently build great software"
#### Bringing CI and CD (and CD) Together
|---- "CI" From "Codebase" to "Deployable Build" ----|
Codebase --{Integrate i.e. "Build" (v.)}--> Build (n.) / Artifacts, Containers, compiled code --{Deliver}--> Deployable Build --{Deploy}--> Running System
|---- "CD" From "Build" to "Running System" ----|
2020-10-26 16:02:34 +00:00
- Continuation From "Running System":
Running System --{Reflag}--> Released Feature --{Ask}--> Feedback --{Triage}--> Idea on Backlog --{Code (v.)}--> Code Change & Pull Request (PR) --{Approve}--> Return to "Codebase"
Whole system has come full circle
### Continuous Integration on Google Cloud
2020-10-26 16:02:34 +00:00
#### GCP Continuous Integration Concepts
Challenges of Team-based Software Development
- Multiple Developers working on a single code base and/or related systems:
- Difficult to coordinate updates between multiple developers
- Incompatible updates from different developers = bugs and problems
- Large + infrequent updates = many bugs to fix
Solution: Continuous Integration!
- The 'CI' of CI/CD process
- DevOps culture of submitting smaller code changes, more often:
- Multiple submissions per day
- "Continuously" update code
Benefits:
- Smaller changes = fewer bugs to troubleshoot
- Fast changes = rapid fedback loop
- Rapid feedback loops = quickly resolve issues
- Result: Improved productivity and Return On Investment(ROI)!!
The CI Process - 5x Main components
- Source
- Build
- Test
- Report
- Release
2020-10-26 16:02:34 +00:00
CI Components - How to we make this work?
- Single Shared code repository
- Single source of truth
- Automated Build and Test tool:
- Key word: **AUTOMATION**
- Feedback loop for bugs
- Artifact Repository
- Release destination for built and tested code for future development
Continuous Integration Tools
| | Source Control | Build & Test | Artifact Storage |
| --------- | ------------------------- | ----------------- | --------------------- |
| GCP | Cloud Source Repositories | Cloud Build | Container Registry |
| 3rd Party | Github, Bitbucket | CircleCI, Jenkins | docker hub, Maven etc |
Developer (Commits) > Source Control (Cloud Source Repositories) > {Trigger Build} > Build & Test (Cloud Build) > {Publish Build & Security Scan} > Artifact Management (Container Registry) > Release
> Only manual step is the actual "Commit", everything else is automated through tooling
### Cloud Source Repositories
2020-10-26 16:02:34 +00:00
#### Cloud Source Repository Concepts
| Fully Managed Private Git Repository | Build, test, deploy and debug code right away |
| Native GCP Integration | Integrate with Cloud Build, Cloud Functions, Cloud Operations (formerly Stackdriver) and more |
| Sync/mirror third party repos | One-way mirror from GitHub/Bitbucket to CSR |
| Powerful code search | Google search for your code |
Development Environments and Cross-project access
- Google best practice = separate projects for each environment
- 'prod-project', 'dev-project', 'staging-project', etc
- CSR hosted in single project
- How to access single repo from multiple projects?
- Solution: grant IAM roles to <u>members</u> in other projects
Example: CSR in 'prod-project', accessible by 'John' in 'dev-project'
- Grant IAM access to John in either host project or host repo
- Project level = access to all repos in project
- Repo level = access to individual repo
IAM Roles
- Source repository Admin/Writer/Reader
- Admin: Full access (add roles, create/delete repo)
- Writer: Edit and commit code
- Reader: View only
2020-10-26 16:02:34 +00:00
#### CSR Hands On - Initial Setup and Deploy to Cloud Functions
- Create a repository in a project
- Web console and command line
- Clone Cloud Functions example into repo from GitHub
- Deploy Cloud Function directly from CSR
- Note: Familiarity with Git commands is assumed
```
gcloud services enable sourcerepo.googleapis.com
gcloud services enable cloudfunctions.googleapis.com
gcloud source repos create csr-demo
touch .gitignore && echo 'csr-demo/' > .gitignore
git add -A
git commit -m "Initial Setup and deploy to Cloud Functions"
gcloud source repos clone csr-demo
cd csr-demo/
git clone https://github.com/linuxacademy/content-gcpro-devops-engineer
cd content-gcpro-devops-engineer/
rm -rf .DS_Store .git/
git add -A
git commit -m "Initial Commit to CSR"
git remote -v
git branch -m main
git push origin main
```
- Setup Cloud function, pointing to repository that we cloned making sure to specify the sub-directory where the python code is located, create the function and then call it from the cli
```
➭ gcloud functions call function-1 --region="europe-west2" --data='{"name":"Alex"}'
executionId: 68kl6ybsinvx
result: <h1 style="margin:20px auto;width:800px;">Welcome to the GCP DevOps course,
Alex!</h1><h2>Via Source Control Repo</h2>
```
2020-10-26 16:02:34 +00:00
#### CSR Hands On - Mirror Github and Cross-Project Access
2021-01-27 11:36:15 +00:00
- Mirror external GitHub repo to CSR
- One-way sync from GitHub to CSR
- GitHub is primary 'source of truth'. CSR is 'read-only' copy
- Grant access to user in another project
- Note: Not possible in Cloud Playgrounds
- Note: Granting access as repo/non-project level = cannot view cross-project repo via interface
- One-way sync updates are normally very quick after an update to a source repo, but the sync can be forced by clicking on the gear icon and clicking 'sync from GitHub'
> Minimum scope (Source repository Writer role) to provide user permissions to clone/edit/commit a repo is by specifying the user at the repo level (clicking gear icon on repo -> Permissions). The user however cannot browse or discover the repo through the webUI, for that the user needs permissions at the project level. To discover add the user at the project level to IAM with "Source Repository Reader" role. This permissions will allow the user read permissions to every other repository within the project.
2020-10-26 16:02:34 +00:00
#### Hands On Lab - Migration Source Code to a Google Cloud Source Repository
2021-01-27 11:36:15 +00:00
> Completed
2020-10-26 16:02:34 +00:00
#### Hands On Lab - Inteegrating Google Cloud Functions
2021-01-27 11:36:15 +00:00
> Completed
2020-10-26 16:02:34 +00:00
2021-01-27 11:36:15 +00:00
### Cloud Build
2020-10-26 16:02:34 +00:00
#### Importance of Automation
2021-01-27 11:36:15 +00:00
Life of a Kubernetes Container Deployment (i.e. manual 'stuff' you must do)
- Update code
- Build a docker container ('docker build')
- Push container to registry ('docker push')
- In kubernetes, update deployment YAML file
- Apply deployment YAML ('kubectl apply')
- Make sure nothing broke and it's working correctly
- Do it all again!
> Google calls this..... "Infinite loop of Pain and Suffering"
- More manual actions = greate chance of human error
- Increased toil
- SRE objective = reduce toil
- Toil = manual and repetitive work that should be automated
- Solution: Automate it!
- Google 'Cloud Build' = 'automation engine'
2020-10-26 16:02:34 +00:00
#### Cloud Build Concepts
2021-01-27 11:36:15 +00:00
What is the Cloud Build service?
- Fully managed CI/CD engine
- Import source code
- Build in managed space
- Create artifacts
- Docker images, Java archive, Go applications, and more
How it works - high level overview
- Prepare source code
- Include build config file that calls 'Cloud Builder' (cloudbuild.yaml)
- Submit build (manual or automatic) to the 'Cloud Build' Service
- Cloud Build will execute build steps as defined
- Example: Build Docker container, Push to Container Registry, Deploy to service
- Completed artifact (container image) pushed to GCP 'Container Registry'
Cloud Builders?
- Specialized Container images that run the build process
- Packaged with common languages and tools
- Google-manage, community-managed, public Docker Hub images
- Run specific commands inside builder containers
- Can also use custom build steps
Build File
- Provides instructions for Cloud Build to perform tasks using cloud builders
- Tells the cloud builders what to do
- YAML or JSON format
- Named cloudbuild.yaml/json
- Provides parameters such as builder image, arguments (steps), environment variables, and others
- Example: use docker and gcloud cloud builders to build and push a Docker file, then deploy container to Cloud Run
Building Docker files - two methods
- Build file (cloudbuild.yaml)
- Dockerfile directly handles build steps and pushed to Container Registry
- Add --tag option to build command
Automate build submissions with triggers
- Why automate?
- Reduce toil
- Reduce human error
How Triggers Work:
- Cloud Build looks for conditions, then executes build process when met
- Common triggers:
- Commit to repo/subdirectory/branch
- Commit tags
- Triggers sync to CSR, GitHub and BitBucket
- Pub/Sub for further automation
- Cloud Build automatically creates and publishes to own Pub/Sub topic for further automation
To Summarize:
- Cloud Build uses specialized cloud builders (containers) to execute build steps that you submit in a build file (cloudbuild.yaml config file)
- The build submission process can be done manually or automatically using <u>triggers</u>
![Picture](./img/Cloud-Build-Process.png)
2020-10-26 16:02:34 +00:00
#### Cloud Build Access Control
2021-01-27 11:36:15 +00:00
- End user IAM roles
- Cloud Build Editor, Cloud Build Viewer
- Editor: create, delete, edit, run and view builds
- Viewer: view build and build history only
- Cloud Build service account
- Automatically created when enabling API
- Executes builds on your behalf
- May need additional IAM roles to interact with other GCP services (App engine, GKE, etc)
- Scenario: Developers using Cloud Build need Cloud Build to deploy to their GKE cluster
- Solution: Grant the K8's Engine Developer role to the Cloud Build Service Account
2020-10-26 16:02:34 +00:00
#### Perspective: Access Control
#### Hands On - Prepare Cloud Build Environment
2021-01-27 11:36:15 +00:00
- Setup Cloud Source Repository and Cloud Build Service
- Explore app we will deploy
- Manually submit build using Dockerfile
- Deploy container to Cloud Run
- Assign Cloud Run Admin role to Cloud Build service account
- Manually submit build using build file to build, push, and deploy to Cloud Run
2020-10-26 16:02:34 +00:00
#### Hands On - Automate Build with Triggers
#### Best Practices for Build Performance
#### Hands On Lab - Establishing a CI/CD Pipeline with Google Cloud
#### Hands On Lab - Triggering a CI/CD Pipeline with Google Cloud Build
### Artifact Management with Container Registry
#### Container Registry and Artifact Registry
#### What is Artifact Management?
#### Container Registry Concepts
#### Container Registry Hands On
#### Milestone: Changing Gears
### Continuous Deployment/Delivery Overview
#### GCP Continuous Deployment Concepts
#### Importance of Deployment Automation
#### Deployment Models
#### Continuous Deployment Tools
### Spinnaker
#### Spinnaker Concepts
#### Hands On - Set Up Spinnaker
#### Hands On - Deploy Sample App/Pipeline
#### Milestone: Are We There, Yet?
### Securing the Deployment Pipeline
#### Managing Secrets
#### Container Analysis and Vulnerability Scanning
#### Binary Authorization
### Full Development Pipeline
#### Full CI/CD Demo - Concepts
#### Create Spinnaker Cluster
#### Create App Repositories and Pipelines
#### Deploy and Manage Application
#### Milestone: Continuity
#### Hands On Lab: Create a CI/CD Pipeline on Google Cloud with Spinnaker