mirror of
https://github.com/sanjeed5/awesome-cursor-rules-mdc.git
synced 2026-11-30 14:52:55 +08:00
Add comprehensive MDC files for various technologies and frameworks
Generate a large set of Markdown Configuration (MDC) files covering best practices across multiple domains, including: - AI/ML libraries (PyTorch, TensorFlow, scikit-learn) - Backend frameworks (Django, FastAPI, Express, Spring Boot) - Frontend frameworks (React, Vue, Angular) - Cloud platforms (AWS, Azure, GCP) - Development tools (Docker, Kubernetes, Terraform) - State management libraries - UI component libraries - Web technologies and APIs Enhance project documentation with detailed, standardized best practice guidelines for different technologies and frameworks
This commit is contained in:
@@ -0,0 +1,344 @@
|
||||
---
|
||||
description: Comprehensive rules and best practices for AWS development using Terraform, covering code organization, security, performance, and testing. Adherence to these guidelines ensures maintainable, secure, and efficient infrastructure code.
|
||||
globs: **/*.tf
|
||||
---
|
||||
# AWS Development Best Practices using Terraform
|
||||
|
||||
This document outlines best practices for developing and maintaining AWS infrastructure using Terraform. Following these guidelines will help ensure your code is maintainable, secure, and efficient.
|
||||
|
||||
## 1. Code Organization and Structure
|
||||
|
||||
### 1.1 Directory Structure
|
||||
|
||||
- **Root Module**: The primary entry point for your infrastructure definition. Contains `main.tf`, `variables.tf`, `outputs.tf`, `providers.tf`, `versions.tf` and `locals.tf`.
|
||||
- **Modules Directory**: Reusable components of your infrastructure. Each module should have its own directory under `modules/`.
|
||||
- **Examples Directory**: Demonstrates how to use the modules. Each example should be a self-contained Terraform configuration.
|
||||
- **Scripts Directory**: Custom scripts used by Terraform.
|
||||
- **Templates Directory**: Templates for files that are read using the `templatefile` function, using the extension `.tftpl`.
|
||||
- **Files Directory**: Contains static files referenced by Terraform (e.g., startup scripts).
|
||||
- **Helpers Directory**: Contains utility scripts that are *not* directly called by Terraform.
|
||||
- **.tfvars files**: Files containing variable definitions. Use `terraform.tfvars` for common values and create environment specific files in the `envs/` directory (e.g., `envs/dev/terraform.tfvars`, `envs/prod/terraform.tfvars`).
|
||||
- **.gitignore**: Specifies intentionally untracked files that Git should ignore.
|
||||
- **docs/**: Place any supplemental documentation in a `docs/` subdirectory.
|
||||
- **CODEOWNERS**: File to document who is responsible for the module. Before any merge request is merged, an owner should approve it.
|
||||
|
||||
Example:
|
||||
|
||||
|
||||
├── .terraform/ # Terraform working directory
|
||||
├── modules/
|
||||
│ ├── ec2/
|
||||
│ │ ├── main.tf
|
||||
│ │ ├── variables.tf
|
||||
│ │ ├── outputs.tf
|
||||
│ │ └── README.md
|
||||
│ ├── s3/
|
||||
│ │ ├── main.tf
|
||||
│ │ ├── variables.tf
|
||||
│ │ ├── outputs.tf
|
||||
│ │ └── README.md
|
||||
├── examples/
|
||||
│ ├── ec2/
|
||||
│ │ ├── main.tf
|
||||
│ │ ├── variables.tf
|
||||
│ │ ├── outputs.tf
|
||||
│ │ └── README.md
|
||||
│ ├── s3/
|
||||
│ │ ├── main.tf
|
||||
│ │ ├── variables.tf
|
||||
│ │ ├── outputs.tf
|
||||
│ │ └── README.md
|
||||
├── scripts/
|
||||
│ ├── configure_instance.sh
|
||||
├── templates/
|
||||
│ ├── user_data.tftpl
|
||||
├── files/
|
||||
│ ├── application.conf
|
||||
├── helpers/
|
||||
│ ├── backup_database.sh
|
||||
├── terraform.tfvars
|
||||
├── envs/
|
||||
│ ├── dev/
|
||||
│ │ ├── terraform.tfvars
|
||||
│ ├── prod/
|
||||
│ │ ├── terraform.tfvars
|
||||
├── main.tf
|
||||
├── variables.tf
|
||||
├── outputs.tf
|
||||
├── providers.tf
|
||||
├── versions.tf
|
||||
├── locals.tf
|
||||
└── .gitignore
|
||||
|
||||
|
||||
### 1.2 File Naming Conventions
|
||||
|
||||
- `main.tf`: Primary entry point for resource definitions.
|
||||
- `variables.tf`: Variable declarations.
|
||||
- `outputs.tf`: Output declarations.
|
||||
- `providers.tf`: Provider configuration.
|
||||
- `versions.tf`: Terraform and provider version constraints.
|
||||
- `locals.tf`: Local variable definitions.
|
||||
- `*.tfvars`: Variable value files. Use `terraform.tfvars` for default values and `env/<environment>.tfvars` for environment-specific values.
|
||||
|
||||
### 1.3 Module Organization
|
||||
|
||||
- **Reusable Modules**: Create modules for common infrastructure components (e.g., EC2 instances, S3 buckets, VPCs).
|
||||
- **Module Composition**: Compose complex infrastructure by combining smaller, reusable modules.
|
||||
- **Module Versioning**: Use version control (e.g., Git tags) to manage module versions.
|
||||
- **Module Naming**: Module repositories must use the format `terraform-<PROVIDER>-<NAME>`. For example: `terraform-aws-ec2`
|
||||
- **Module sources**: When referencing another module on a public registry, pin the Git commit hash by pointing directly to the underlying Git repo URL. Example:
|
||||
|
||||
terraform
|
||||
module "lambda" {
|
||||
source = "github.com/terraform-aws-modules/terraform-aws-lambda.git?ref=e78cdf1f82944897ca6e30d6489f43cf24539374" # --> v4.18.0
|
||||
}
|
||||
|
||||
|
||||
### 1.4 Component Architecture
|
||||
|
||||
- **Layered Architecture**: Separate infrastructure into logical layers (e.g., network, compute, data).
|
||||
- **Loose Coupling**: Design components to be loosely coupled, minimizing dependencies between them.
|
||||
- **Clear Abstractions**: Use modules to create clear abstractions for complex infrastructure components.
|
||||
|
||||
### 1.5 Code Splitting Strategies
|
||||
|
||||
- **Functional Decomposition**: Split code into smaller, manageable functions.
|
||||
- **Resource Grouping**: Group related resources into separate files or modules.
|
||||
- **Environment Separation**: Use separate files or modules for environment-specific configurations.
|
||||
- **Service-Based Separation**: Separate resources by service (e.g., `iam.tf`, `ec2.tf`, `s3.tf`) only if they exceed 150 lines in `main.tf`.
|
||||
|
||||
## 2. Common Patterns and Anti-patterns
|
||||
|
||||
### 2.1 Design Patterns Specific to AWS
|
||||
|
||||
- **Immutable Infrastructure**: Deploy new infrastructure components instead of modifying existing ones.
|
||||
- **Infrastructure as Code (IaC)**: Manage infrastructure through code, using tools like Terraform.
|
||||
- **Blue/Green Deployments**: Deploy new versions of applications alongside existing ones, then switch traffic.
|
||||
- **Canary Deployments**: Deploy new versions of applications to a small subset of users before rolling them out to everyone.
|
||||
|
||||
### 2.2 Recommended Approaches for Common Tasks
|
||||
|
||||
- **Creating VPCs**: Use the `terraform-aws-modules/vpc/aws` module for creating VPCs.
|
||||
- **Creating EC2 Instances**: Use the `terraform-aws-modules/ec2-instance/aws` module for creating EC2 instances.
|
||||
- **Creating S3 Buckets**: Use the `terraform-aws-modules/s3-bucket/aws` module for creating S3 buckets.
|
||||
- **Managing IAM Roles**: Use the `aws_iam_role` and `aws_iam_policy` resources to manage IAM roles and policies.
|
||||
- **Using Data Sources**: Utilize data sources (e.g., `aws_ami`, `aws_vpc`) to fetch information about existing AWS resources.
|
||||
- **Resource Tagging**: Tag all AWS resources for cost allocation, automation, and identification.
|
||||
- **State File Storage**: Use a remote backend (e.g., S3 with DynamoDB locking) for storing Terraform state.
|
||||
|
||||
### 2.3 Anti-patterns and Code Smells to Avoid
|
||||
|
||||
- **Hardcoding Values**: Avoid hardcoding values in your code. Use variables instead.
|
||||
- **Storing Secrets in Code**: Never store secrets (e.g., passwords, API keys) in your code. Use AWS Secrets Manager or other secret management solutions.
|
||||
- **Overly Complex Modules**: Avoid creating modules that are too complex and difficult to understand.
|
||||
- **Ignoring Errors**: Always handle errors gracefully.
|
||||
- **Manual Infrastructure Changes**: Avoid making manual changes to infrastructure outside of Terraform.
|
||||
- **Using embedded resource attributes**: avoid using these embedded resource attributes and instead you should use the unique resource to attach that pseudo-resource. These resource relationships can cause chicken/egg issues that are unique per resource.
|
||||
|
||||
### 2.4 State Management Best Practices
|
||||
|
||||
- **Remote Backend**: Use a remote backend (e.g., S3 with DynamoDB locking) for storing Terraform state. This allows for collaboration and prevents data loss.
|
||||
- **State Locking**: Enable state locking to prevent concurrent modifications to the state file.
|
||||
- **State Encryption**: Encrypt the state file at rest and in transit.
|
||||
- **Workspace Management**: Use Terraform workspaces to manage multiple environments (e.g., development, staging, production).
|
||||
- **Secure State Access**: Restrict access to the state file to authorized users and systems only. Consider implementing least privilege principles.
|
||||
- **Versioning**: Implement a mechanism for versioning your state files, which could include frequent backups and using version control systems.
|
||||
- **Avoid local state**: Never store Terraform state locally.
|
||||
|
||||
### 2.5 Error Handling Patterns
|
||||
|
||||
- **Validation Rules**: Use validation rules within variable definitions to check input values.
|
||||
- **Error Propagation**: Propagate errors up the call stack to be handled at a higher level.
|
||||
- **Retry Logic**: Implement retry logic for transient errors (e.g., network errors, API throttling).
|
||||
- **Logging**: Log errors and warnings to aid in debugging.
|
||||
- **Custom Error Messages**: Provide clear and informative error messages to users.
|
||||
- **Panic Handling**: Avoid using `panic()` function that stops the execution, implement error handling.
|
||||
|
||||
## 3. Performance Considerations
|
||||
|
||||
### 3.1 Optimization Techniques
|
||||
|
||||
- **Efficient Resource Usage**: Use the appropriate instance types and storage classes for your workloads.
|
||||
- **Caching**: Implement caching to reduce latency and improve performance.
|
||||
- **Load Balancing**: Use load balancing to distribute traffic across multiple instances.
|
||||
- **Content Delivery Networks (CDNs)**: Use CDNs to deliver static content closer to users.
|
||||
- **Database Optimization**: Optimize database queries and indexing for faster performance.
|
||||
- **Parallelization**: Use `for_each` and `count` to parallelize resource creation and modification.
|
||||
|
||||
### 3.2 Memory Management
|
||||
|
||||
- **Resource Limits**: Set resource limits on EC2 instances and other AWS resources.
|
||||
- **Memory Profiling**: Use memory profiling tools to identify memory leaks and optimize memory usage.
|
||||
- **Garbage Collection**: Configure garbage collection settings for your applications.
|
||||
|
||||
### 3.3 Rendering Optimization
|
||||
|
||||
- **Minimize Rendering**: Minimize the amount of data that needs to be rendered.
|
||||
- **Efficient Templates**: Use efficient templates to generate configuration files.
|
||||
|
||||
### 3.4 Bundle Size Optimization
|
||||
|
||||
- **Code Splitting**: Split code into smaller bundles that can be loaded on demand.
|
||||
- **Tree Shaking**: Remove unused code from your bundles.
|
||||
- **Minification**: Minify your code to reduce bundle sizes.
|
||||
- **Compression**: Compress your bundles to reduce download times.
|
||||
|
||||
### 3.5 Lazy Loading Strategies
|
||||
|
||||
- **Lazy Loading of Resources**: Load resources only when they are needed.
|
||||
- **Virtualization**: Use virtualization to reduce the number of resources that need to be loaded.
|
||||
|
||||
## 4. Security Best Practices
|
||||
|
||||
### 4.1 Common Vulnerabilities and How to Prevent Them
|
||||
|
||||
- **IAM Misconfiguration**: Prevent IAM misconfiguration by following the principle of least privilege.
|
||||
- **Unsecured S3 Buckets**: Secure S3 buckets by enabling encryption, access logging, and versioning.
|
||||
- **Security Group Misconfiguration**: Configure security groups to allow only necessary traffic.
|
||||
- **SQL Injection**: Prevent SQL injection by using parameterized queries and input validation.
|
||||
- **Cross-Site Scripting (XSS)**: Prevent XSS by sanitizing user input and output.
|
||||
- **Cross-Site Request Forgery (CSRF)**: Prevent CSRF by using anti-CSRF tokens.
|
||||
- **Exposed Secrets**: Avoid exposing secrets by using AWS Secrets Manager and IAM roles.
|
||||
|
||||
### 4.2 Input Validation
|
||||
|
||||
- **Validate User Input**: Validate user input to prevent malicious code from being injected into your application.
|
||||
- **Use Data Types**: Use appropriate data types for your variables to prevent type-related errors.
|
||||
- **Regular Expressions**: Use regular expressions to validate complex input patterns.
|
||||
|
||||
### 4.3 Authentication and Authorization Patterns
|
||||
|
||||
- **IAM Roles**: Use IAM roles to grant permissions to AWS resources.
|
||||
- **Multi-Factor Authentication (MFA)**: Enable MFA for all user accounts.
|
||||
- **Principle of Least Privilege**: Grant users only the permissions they need to perform their tasks.
|
||||
- **AWS Cognito**: Use AWS Cognito to manage user authentication and authorization.
|
||||
- **API Gateway Authorization**: Implement authorization at the API Gateway level to control access to your APIs.
|
||||
|
||||
### 4.4 Data Protection Strategies
|
||||
|
||||
- **Encryption at Rest**: Encrypt data at rest using AWS KMS, S3 encryption, or other encryption solutions.
|
||||
- **Encryption in Transit**: Encrypt data in transit using HTTPS, TLS, or other encryption protocols.
|
||||
- **Data Masking**: Mask sensitive data to prevent unauthorized access.
|
||||
- **Data Redaction**: Redact sensitive data from logs and other output.
|
||||
|
||||
### 4.5 Secure API Communication
|
||||
|
||||
- **HTTPS**: Use HTTPS for all API communication.
|
||||
- **API Keys**: Use API keys to authenticate API requests.
|
||||
- **OAuth 2.0**: Use OAuth 2.0 for authorization.
|
||||
- **Rate Limiting**: Implement rate limiting to prevent abuse.
|
||||
- **Web Application Firewall (WAF)**: Use a WAF to protect your APIs from common web attacks.
|
||||
|
||||
## 5. Testing Approaches
|
||||
|
||||
### 5.1 Unit Testing Strategies
|
||||
|
||||
- **Test Individual Modules**: Unit test individual Terraform modules to ensure they are working correctly.
|
||||
- **Mock AWS Resources**: Mock AWS resources to isolate your modules from external dependencies.
|
||||
- **Test Variable Validation**: Verify variable validation rules work as expected.
|
||||
- **Test Output Values**: Check that module outputs are correct.
|
||||
|
||||
### 5.2 Integration Testing
|
||||
|
||||
- **Test Module Integration**: Test how modules interact with each other.
|
||||
- **Deploy to Test Environment**: Deploy your infrastructure to a test environment and verify that it is working correctly.
|
||||
- **Automated Tests**: Write automated tests to verify that your infrastructure is working correctly.
|
||||
|
||||
### 5.3 End-to-End Testing
|
||||
|
||||
- **Test Full Infrastructure**: Test the entire infrastructure from end to end.
|
||||
- **Simulate User Behavior**: Simulate user behavior to verify that your infrastructure is working correctly.
|
||||
- **Monitor Performance**: Monitor performance to identify any performance bottlenecks.
|
||||
|
||||
### 5.4 Test Organization
|
||||
|
||||
- **Separate Test Directory**: Create a separate directory for your tests.
|
||||
- **Test Naming Conventions**: Use clear naming conventions for your tests.
|
||||
- **Test Documentation**: Document your tests to explain what they are testing.
|
||||
|
||||
### 5.5 Mocking and Stubbing
|
||||
|
||||
- **Use Mock Objects**: Use mock objects to isolate your code from external dependencies.
|
||||
- **Use Stub Objects**: Use stub objects to provide canned responses to external dependencies.
|
||||
- **Terratest**: Utilize Terratest for creating test environments and performing infrastructure tests.
|
||||
|
||||
## 6. Common Pitfalls and Gotchas
|
||||
|
||||
### 6.1 Frequent Mistakes Developers Make
|
||||
|
||||
- **Forgetting to Enable State Locking**: Enabling state locking is crucial for preventing corruption and ensuring integrity when multiple users work on the same Terraform project.
|
||||
- **Overlooking IAM Permissions**: Ensuring the Terraform service account has the necessary IAM permissions to create, modify, and delete resources is vital.
|
||||
- **Incorrect Resource Dependencies**: Managing resource dependencies correctly to prevent errors during creation or deletion.
|
||||
- **Handling Sensitive Data Insecurely**: Implementing robust measures for managing sensitive data, such as API keys and passwords, by using AWS Secrets Manager or other appropriate services.
|
||||
- **Neglecting to Monitor Infrastructure**: Setting up comprehensive monitoring and alerting to detect and respond to infrastructure issues promptly.
|
||||
- **Using hardcoded values**: Always use variables
|
||||
|
||||
### 6.2 Edge Cases to be Aware Of
|
||||
|
||||
- **Resource Limits**: Be aware of AWS resource limits and plan accordingly.
|
||||
- **Availability Zones**: Understand the implications of availability zones and design your infrastructure to be resilient to AZ failures.
|
||||
- **Data Consistency**: Understand the consistency models of different AWS services and design your applications accordingly.
|
||||
- **API Throttling**: Be aware of API throttling limits and implement retry logic.
|
||||
|
||||
### 6.3 Version-Specific Issues
|
||||
|
||||
- **Terraform Version Compatibility**: Ensure that your Terraform code is compatible with the version of Terraform you are using.
|
||||
- **Provider Version Compatibility**: Ensure that your Terraform providers are compatible with the version of Terraform you are using.
|
||||
- **AWS API Version Compatibility**: Be aware of changes to the AWS API and update your code accordingly.
|
||||
|
||||
### 6.4 Compatibility Concerns
|
||||
|
||||
- **Backwards Compatibility**: Ensure that your changes are backwards compatible.
|
||||
- **Cross-Region Compatibility**: Ensure that your infrastructure is compatible across different AWS regions.
|
||||
- **Cross-Account Compatibility**: Ensure that your infrastructure is compatible across different AWS accounts.
|
||||
|
||||
### 6.5 Debugging Strategies
|
||||
|
||||
- **Terraform Plan**: Use `terraform plan` to preview changes before applying them.
|
||||
- **Terraform Show**: Use `terraform show` to inspect the current state of your infrastructure.
|
||||
- **Terraform Graph**: Use `terraform graph` to visualize the dependencies between resources.
|
||||
- **Terraform Console**: Use `terraform console` to evaluate Terraform expressions.
|
||||
- **AWS CloudTrail**: Use AWS CloudTrail to audit API calls and identify errors.
|
||||
- **CloudWatch Logs**: Use CloudWatch Logs to collect and analyze application logs.
|
||||
- **Enable Debug Logging**: Enable debug logging to get more detailed information about what Terraform is doing.
|
||||
|
||||
## 7. Tooling and Environment
|
||||
|
||||
### 7.1 Recommended Development Tools
|
||||
|
||||
- **Terraform CLI**: The Terraform command-line interface.
|
||||
- **IDE with Terraform Support**: Use an IDE with Terraform support (e.g., VS Code with the Terraform extension).
|
||||
- **tfenv**: Use tfenv to manage multiple versions of Terraform.
|
||||
- **AWS CLI**: The AWS command-line interface.
|
||||
- **jq**: A command-line JSON processor.
|
||||
|
||||
### 7.2 Build Configuration
|
||||
|
||||
- **Makefile**: Use a Makefile to automate common build tasks (e.g., `terraform init`, `terraform plan`, `terraform apply`).
|
||||
- **.terraformignore**: Create a `.terraformignore` to prevent files from being included in the Terraform package.
|
||||
|
||||
### 7.3 Linting and Formatting
|
||||
|
||||
- **terraform fmt**: Use `terraform fmt` to automatically format your Terraform code.
|
||||
- **terraform validate**: Use `terraform validate` to validate your Terraform code.
|
||||
- **tflint**: Use `tflint` to lint your Terraform code.
|
||||
- **pre-commit hooks**: Enforce code quality standards using pre-commit hooks.
|
||||
|
||||
### 7.4 Deployment Best Practices
|
||||
|
||||
- **Automated Deployments**: Use automated deployments to reduce errors and improve consistency.
|
||||
- **Infrastructure as Code (IaC)**: Manage infrastructure as code using tools like Terraform.
|
||||
- **Immutable Infrastructure**: Deploy new infrastructure components instead of modifying existing ones.
|
||||
- **Blue/Green Deployments**: Deploy new versions of applications alongside existing ones, then switch traffic.
|
||||
- **Canary Deployments**: Deploy new versions of applications to a small subset of users before rolling them out to everyone.
|
||||
|
||||
### 7.5 CI/CD Integration
|
||||
|
||||
- **Integrate with CI/CD Pipeline**: Integrate Terraform with your CI/CD pipeline.
|
||||
- **Automated Testing**: Run automated tests as part of your CI/CD pipeline.
|
||||
- **Automated Deployments**: Automatically deploy your infrastructure as part of your CI/CD pipeline.
|
||||
- **Version Control**: Store your Terraform code in version control.
|
||||
- **Terraform Cloud/Enterprise**: Use Terraform Cloud/Enterprise for remote state management and collaboration.
|
||||
|
||||
This document provides a comprehensive set of best practices for AWS development using Terraform. By following these guidelines, you can ensure your code is maintainable, secure, and efficient.
|
||||
@@ -0,0 +1,347 @@
|
||||
---
|
||||
description: This rule provides comprehensive best practices for developing Azure applications, covering code organization, security, performance, testing, and common pitfalls. It aims to improve code quality, security posture, and overall efficiency when working with the Azure ecosystem.
|
||||
globs: **/*.{az,tf,bicep,py,js,ts,json,yml,yaml,ps1,sh,cs,java}
|
||||
---
|
||||
# Azure Library Best Practices and Coding Standards
|
||||
|
||||
This document outlines the recommended best practices for developing applications and infrastructure using Azure services. It covers various aspects including code organization, security, performance, testing, and tooling to ensure robust, scalable, and secure solutions.
|
||||
|
||||
## 1. Code Organization and Structure
|
||||
|
||||
A well-organized codebase is crucial for maintainability, scalability, and collaboration. The following guidelines provide a structured approach to organizing your Azure projects.
|
||||
|
||||
### Directory Structure Best Practices
|
||||
|
||||
Adopt a modular and logical directory structure based on the application's architecture and components.
|
||||
|
||||
* **`src/`**: Contains the source code of your application.
|
||||
* **`modules/`**: Groups related functionalities into independent modules.
|
||||
* **`components/`**: Contains reusable UI or logical components.
|
||||
* **`services/`**: Encapsulates external service integrations (e.g., Azure Storage, Cosmos DB).
|
||||
* **`models/`**: Defines data models and schemas.
|
||||
* **`utils/`**: Contains utility functions and helper classes.
|
||||
* **`infra/` or `terraform/` or `bicep/`**: Infrastructure-as-Code definitions (Terraform, Bicep, Azure Resource Manager templates).
|
||||
* **`config/`**: Configuration files for different environments (development, staging, production).
|
||||
* **`scripts/`**: Automation scripts for deployment, build processes, etc.
|
||||
* **`tests/`**: Unit, integration, and end-to-end tests.
|
||||
* **`docs/`**: Documentation for the project and its components.
|
||||
|
||||
Example:
|
||||
|
||||
|
||||
my-azure-project/
|
||||
├── src/
|
||||
│ ├── modules/
|
||||
│ │ ├── user-management/
|
||||
│ │ │ ├── ...
|
||||
│ │ ├── data-processing/
|
||||
│ │ │ ├── ...
|
||||
│ ├── components/
|
||||
│ │ ├── button/
|
||||
│ │ │ ├── ...
|
||||
│ ├── services/
|
||||
│ │ ├── storage-service.js
|
||||
│ │ ├── cosmosdb-service.js
|
||||
│ ├── models/
|
||||
│ │ ├── user.js
|
||||
│ ├── utils/
|
||||
│ │ ├── logger.js
|
||||
├── infra/
|
||||
│ ├── main.tf
|
||||
│ ├── variables.tf
|
||||
│ ├── outputs.tf
|
||||
├── config/
|
||||
│ ├── development.json
|
||||
│ ├── production.json
|
||||
├── scripts/
|
||||
│ ├── deploy.sh
|
||||
│ ├── build.sh
|
||||
├── tests/
|
||||
│ ├── unit/
|
||||
│ ├── integration/
|
||||
│ ├── e2e/
|
||||
├── docs/
|
||||
│ ├── README.md
|
||||
├── .gitignore
|
||||
├── package.json
|
||||
|
||||
|
||||
### File Naming Conventions
|
||||
|
||||
Maintain consistency in file naming to improve readability and searchability.
|
||||
|
||||
* Use descriptive names that reflect the file's purpose.
|
||||
* Use a consistent case (e.g., camelCase or kebab-case).
|
||||
* Use appropriate file extensions (e.g., `.js`, `.ts`, `.py`, `.tf`, `.bicep`).
|
||||
* For React components, use `ComponentName.jsx` or `ComponentName.tsx`.
|
||||
|
||||
Example:
|
||||
|
||||
* `user-service.js` (for a user service module)
|
||||
* `UserProfile.jsx` (for a user profile component)
|
||||
* `storage-account.tf` (for a Terraform file defining a storage account)
|
||||
|
||||
### Module Organization
|
||||
|
||||
Divide the application into independent and reusable modules based on functionality.
|
||||
|
||||
* Each module should have a clear responsibility and a well-defined interface.
|
||||
* Minimize dependencies between modules to promote loose coupling.
|
||||
* Consider using a module bundler (e.g., Webpack, Parcel) to manage dependencies and optimize the build process.
|
||||
|
||||
Example:
|
||||
|
||||
A `user-management` module could contain components and services related to user authentication, authorization, and profile management.
|
||||
|
||||
### Component Architecture
|
||||
|
||||
For UI-based applications, adopt a component-based architecture (e.g., React, Angular, Vue.js).
|
||||
|
||||
* Divide the UI into reusable components with clear inputs and outputs.
|
||||
* Follow the principles of single responsibility and separation of concerns.
|
||||
* Use a component library (e.g., Material UI, Ant Design) to accelerate development and maintain consistency.
|
||||
|
||||
### Code Splitting Strategies
|
||||
|
||||
Improve initial load time by splitting the application into smaller chunks that can be loaded on demand.
|
||||
|
||||
* Use dynamic imports to load modules only when they are needed.
|
||||
* Configure your module bundler to create separate chunks for different parts of the application.
|
||||
* Consider using route-based code splitting for single-page applications.
|
||||
|
||||
## 2. Common Patterns and Anti-patterns
|
||||
|
||||
Understanding common patterns and anti-patterns is essential for building efficient, maintainable, and reliable Azure applications.
|
||||
|
||||
### Design Patterns Specific to Azure
|
||||
|
||||
* **Retry Pattern:** Implement retry logic to handle transient failures when interacting with Azure services.
|
||||
* **Circuit Breaker Pattern:** Prevent cascading failures by temporarily blocking access to a service that is experiencing problems.
|
||||
* **Queue-Based Load Leveling:** Use queues (e.g., Azure Queue Storage, Azure Service Bus) to decouple components and handle bursts of traffic.
|
||||
* **Cache-Aside Pattern:** Use a cache (e.g., Azure Cache for Redis) to improve performance by storing frequently accessed data.
|
||||
* **Gateway Aggregation Pattern:** Expose multiple backend services through a single API gateway (e.g., Azure API Management).
|
||||
|
||||
### Recommended Approaches for Common Tasks
|
||||
|
||||
* **Configuration Management:** Use Azure App Configuration to manage application settings and feature flags.
|
||||
* **Secret Management:** Use Azure Key Vault to securely store and manage secrets, keys, and certificates.
|
||||
* **Logging and Monitoring:** Use Azure Monitor to collect and analyze logs, metrics, and traces.
|
||||
* **Identity and Access Management:** Use Azure Active Directory (Azure AD) for authentication and authorization.
|
||||
* **Data Storage:** Choose the appropriate Azure storage service based on your data requirements (e.g., Azure Blob Storage for unstructured data, Azure Cosmos DB for NoSQL data, Azure SQL Database for relational data).
|
||||
|
||||
### Anti-Patterns and Code Smells to Avoid
|
||||
|
||||
* **Hardcoding Secrets:** Never hardcode secrets or API keys in your code. Use Azure Key Vault to manage them securely.
|
||||
* **Ignoring Errors:** Always handle errors gracefully and log relevant information for debugging.
|
||||
* **Over-Engineering:** Avoid unnecessary complexity and focus on delivering business value.
|
||||
* **Long-Running Transactions:** Keep transactions short and avoid holding resources for extended periods.
|
||||
* **Tight Coupling:** Design components and modules to be loosely coupled to improve maintainability and testability.
|
||||
* **Monolithic Functions:** Avoid creating large, complex functions. Break them down into smaller, more manageable units.
|
||||
|
||||
### State Management Best Practices
|
||||
|
||||
* For serverless functions, design for statelessness whenever possible. Store state in external storage services like Azure Cosmos DB or Azure Storage.
|
||||
* For web applications, use appropriate state management techniques (e.g., cookies, sessions, local storage, or dedicated state management libraries like Redux or Zustand).
|
||||
* Consider using distributed caching (e.g., Azure Cache for Redis) to improve performance and scalability.
|
||||
|
||||
### Error Handling Patterns
|
||||
|
||||
* Use try-catch blocks to handle exceptions gracefully.
|
||||
* Log errors with sufficient detail to aid in debugging.
|
||||
* Implement a centralized error handling mechanism to catch and handle unhandled exceptions.
|
||||
* Provide meaningful error messages to the user.
|
||||
* Use Polly library for implementing resilience policies like retry, circuit breaker, and timeout.
|
||||
|
||||
## 3. Performance Considerations
|
||||
|
||||
Optimizing performance is crucial for delivering a responsive and scalable Azure application.
|
||||
|
||||
### Optimization Techniques
|
||||
|
||||
* **Caching:** Implement caching at various levels (e.g., browser, server, database) to reduce latency and improve performance.
|
||||
* **Compression:** Enable compression (e.g., Gzip) to reduce the size of HTTP responses.
|
||||
* **Connection Pooling:** Use connection pooling to reuse database connections and reduce connection overhead.
|
||||
* **Content Delivery Network (CDN):** Use Azure CDN to cache static assets closer to users.
|
||||
* **Database Optimization:** Optimize database queries and indexes to improve query performance.
|
||||
* **Asynchronous Operations:** Use asynchronous operations to avoid blocking the main thread.
|
||||
|
||||
### Memory Management
|
||||
|
||||
* **Dispose Resources:** Dispose of disposable resources (e.g., database connections, file streams) properly to avoid memory leaks.
|
||||
* **Garbage Collection:** Be aware of garbage collection behavior and avoid creating unnecessary objects.
|
||||
* **Large Object Heap (LOH):** Be mindful of the LOH and avoid allocating large objects frequently.
|
||||
|
||||
### Rendering Optimization
|
||||
|
||||
* **Virtualization:** Use virtualization techniques (e.g., React Virtualized, Angular CDK Virtual Scroll) to efficiently render large lists of data.
|
||||
* **Debouncing and Throttling:** Use debouncing and throttling to limit the frequency of event handlers.
|
||||
* **Lazy Loading:** Load images and other resources only when they are visible on the screen.
|
||||
|
||||
### Bundle Size Optimization
|
||||
|
||||
* **Tree Shaking:** Use tree shaking to remove unused code from your bundles.
|
||||
* **Code Splitting:** Split your code into smaller chunks that can be loaded on demand.
|
||||
* **Minification:** Minify your code to reduce its size.
|
||||
* **Image Optimization:** Optimize images by compressing them and using appropriate formats.
|
||||
|
||||
### Lazy Loading Strategies
|
||||
|
||||
* **Component-Based Lazy Loading:** Load components only when they are needed.
|
||||
* **Route-Based Lazy Loading:** Load modules associated with specific routes only when those routes are accessed.
|
||||
* **Image Lazy Loading:** Load images only when they are scrolled into view.
|
||||
|
||||
## 4. Security Best Practices
|
||||
|
||||
Security should be a top priority when developing Azure applications.
|
||||
|
||||
### Common Vulnerabilities and How to Prevent Them
|
||||
|
||||
* **SQL Injection:** Use parameterized queries or an ORM to prevent SQL injection attacks.
|
||||
* **Cross-Site Scripting (XSS):** Sanitize user input and output to prevent XSS attacks.
|
||||
* **Cross-Site Request Forgery (CSRF):** Use anti-CSRF tokens to prevent CSRF attacks.
|
||||
* **Authentication and Authorization Flaws:** Implement robust authentication and authorization mechanisms.
|
||||
* **Insecure Direct Object References (IDOR):** Validate that users have access to the resources they are requesting.
|
||||
* **Security Misconfiguration:** Follow security best practices for configuring Azure services.
|
||||
* **Sensitive Data Exposure:** Protect sensitive data by encrypting it at rest and in transit.
|
||||
|
||||
### Input Validation
|
||||
|
||||
* Validate all user input on both the client and server sides.
|
||||
* Use a schema validation library (e.g., Joi, Yup) to define and enforce data validation rules.
|
||||
* Sanitize user input to remove potentially malicious characters.
|
||||
|
||||
### Authentication and Authorization Patterns
|
||||
|
||||
* Use Azure Active Directory (Azure AD) for authentication and authorization.
|
||||
* Implement role-based access control (RBAC) to restrict access to resources based on user roles.
|
||||
* Use multi-factor authentication (MFA) to enhance security.
|
||||
* Follow the principle of least privilege.
|
||||
* Leverage Managed Identities for Azure resources to securely access other Azure services.
|
||||
|
||||
### Data Protection Strategies
|
||||
|
||||
* Encrypt sensitive data at rest using Azure Storage Service Encryption (SSE) or Azure Disk Encryption.
|
||||
* Encrypt data in transit using TLS/SSL.
|
||||
* Use Azure Key Vault to store and manage encryption keys.
|
||||
* Implement data masking and tokenization to protect sensitive data.
|
||||
|
||||
### Secure API Communication
|
||||
|
||||
* Use HTTPS for all API communication.
|
||||
* Implement API authentication using API keys, tokens, or OAuth 2.0.
|
||||
* Use rate limiting to prevent abuse.
|
||||
* Use Azure API Management to manage and secure your APIs.
|
||||
|
||||
## 5. Testing Approaches
|
||||
|
||||
Thorough testing is essential for ensuring the quality and reliability of your Azure applications.
|
||||
|
||||
### Unit Testing Strategies
|
||||
|
||||
* Write unit tests for individual components and functions.
|
||||
* Use a unit testing framework (e.g., Jest, Mocha, JUnit, pytest).
|
||||
* Aim for high code coverage.
|
||||
* Follow the Arrange-Act-Assert pattern.
|
||||
* Use mocks and stubs to isolate the code under test.
|
||||
|
||||
### Integration Testing
|
||||
|
||||
* Write integration tests to verify the interaction between different components and services.
|
||||
* Test the integration with Azure services (e.g., Azure Storage, Cosmos DB).
|
||||
* Use a testing environment that closely resembles the production environment.
|
||||
|
||||
### End-to-End Testing
|
||||
|
||||
* Write end-to-end tests to verify the entire application workflow.
|
||||
* Use a testing framework (e.g., Cypress, Selenium, Playwright).
|
||||
* Automate end-to-end tests as part of your CI/CD pipeline.
|
||||
|
||||
### Test Organization
|
||||
|
||||
* Organize tests into a clear directory structure.
|
||||
* Use descriptive test names.
|
||||
* Group related tests together.
|
||||
|
||||
### Mocking and Stubbing
|
||||
|
||||
* Use mocks to simulate the behavior of external dependencies.
|
||||
* Use stubs to provide predefined responses for API calls.
|
||||
* Use a mocking framework (e.g., Mockito, Jest Mocks).
|
||||
|
||||
## 6. Common Pitfalls and Gotchas
|
||||
|
||||
Be aware of common pitfalls and gotchas to avoid making mistakes when developing Azure applications.
|
||||
|
||||
### Frequent Mistakes Developers Make
|
||||
|
||||
* **Insufficient Resource Sizing:** Underestimating the required resources can lead to performance issues.
|
||||
* **Ignoring Azure Service Limits:** Being unaware of Azure service limits can cause unexpected errors.
|
||||
* **Improper Error Handling:** Inadequate error handling can make it difficult to diagnose and resolve issues.
|
||||
* **Lack of Monitoring:** Failing to monitor the application's performance and health can lead to undetected problems.
|
||||
* **Neglecting Security:** Overlooking security best practices can expose the application to vulnerabilities.
|
||||
|
||||
### Edge Cases to Be Aware Of
|
||||
|
||||
* **Network Latency:** Be aware of network latency when interacting with Azure services.
|
||||
* **Transient Faults:** Implement retry logic to handle transient faults.
|
||||
* **Resource Contention:** Be aware of resource contention and design the application to handle it gracefully.
|
||||
* **Data Consistency:** Understand the data consistency models of Azure storage services.
|
||||
|
||||
### Version-Specific Issues
|
||||
|
||||
* Be aware of breaking changes in Azure SDKs and APIs.
|
||||
* Keep your dependencies up to date.
|
||||
* Test your application with different versions of Azure services.
|
||||
|
||||
### Compatibility Concerns
|
||||
|
||||
* Ensure that your application is compatible with the target Azure environment.
|
||||
* Test your application on different browsers and devices.
|
||||
|
||||
### Debugging Strategies
|
||||
|
||||
* Use Azure Monitor to collect and analyze logs, metrics, and traces.
|
||||
* Use remote debugging to debug your application running in Azure.
|
||||
* Use logging to track the flow of execution and identify errors.
|
||||
* Use breakpoints to pause execution and inspect variables.
|
||||
|
||||
## 7. Tooling and Environment
|
||||
|
||||
Choosing the right tools and environment can significantly improve your development experience.
|
||||
|
||||
### Recommended Development Tools
|
||||
|
||||
* **Visual Studio Code:** A popular code editor with excellent support for Azure development.
|
||||
* **Azure CLI:** A command-line tool for managing Azure resources.
|
||||
* **Azure PowerShell:** A PowerShell module for managing Azure resources.
|
||||
* **Terraform:** An infrastructure-as-code tool for provisioning and managing Azure resources.
|
||||
* **Bicep:** A declarative language for deploying Azure resources.
|
||||
* **Azure SDKs:** Libraries for interacting with Azure services from various programming languages.
|
||||
|
||||
### Build Configuration
|
||||
|
||||
* Use a build automation tool (e.g., Azure DevOps, Jenkins, GitHub Actions) to automate the build process.
|
||||
* Configure your build process to run tests, linters, and code formatters.
|
||||
* Use environment variables to configure your application for different environments.
|
||||
|
||||
### Linting and Formatting
|
||||
|
||||
* Use a linter (e.g., ESLint, Pylint) to enforce code style guidelines.
|
||||
* Use a code formatter (e.g., Prettier, Black) to automatically format your code.
|
||||
* Configure your editor to automatically run the linter and formatter on save.
|
||||
|
||||
### Deployment Best Practices
|
||||
|
||||
* Use Infrastructure-as-Code (IaC) to automate the deployment of Azure resources.
|
||||
* Use a deployment pipeline (e.g., Azure Pipelines, GitHub Actions) to automate the deployment process.
|
||||
* Use blue-green deployments or canary deployments to minimize downtime.
|
||||
* Implement rollback strategies to quickly revert to a previous version if necessary.
|
||||
|
||||
### CI/CD Integration
|
||||
|
||||
* Integrate your CI/CD pipeline with Azure DevOps, GitHub Actions, or other CI/CD tools.
|
||||
* Automate the build, test, and deployment processes.
|
||||
* Use environment variables to configure your application for different environments.
|
||||
* Implement automated testing to catch errors early in the development cycle.
|
||||
|
||||
By following these best practices, you can build robust, scalable, secure, and maintainable Azure applications.
|
||||
@@ -0,0 +1,196 @@
|
||||
---
|
||||
description: This rule provides best practices for developing and managing infrastructure and applications on Google Cloud Platform (GCP), encompassing code organization, security, performance, and deployment strategies.
|
||||
globs: **/*.{tf,py,js,go,java,proto,sh,yaml,yml}
|
||||
---
|
||||
---
|
||||
## GCP Library Best Practices
|
||||
|
||||
This document outlines best practices for developing and managing applications and infrastructure on Google Cloud Platform (GCP). It covers various aspects, including code organization, common patterns, performance, security, testing, common pitfalls, and tooling.
|
||||
|
||||
### 1. Code Organization and Structure
|
||||
|
||||
- **Follow a Standard Module Structure (especially for Terraform)**:
|
||||
- Start every module with a `main.tf` file. This file contains the primary resources defined in the module.
|
||||
- Include a `README.md` file for module documentation. This should explain the module's purpose, usage, inputs, and outputs.
|
||||
- Group related resources logically in separate files (e.g., `network.tf`, `compute.tf`, `storage.tf`).
|
||||
- Use folders to logically group files.
|
||||
- **Directory Structure Best Practices:**
|
||||
- `modules/`: Contains reusable Terraform modules. Each module should encapsulate a specific set of resources or functionality.
|
||||
- `environments/`: Contains environment-specific configurations (e.g., `dev/`, `staging/`, `prod/`). Each environment directory should contain its own `terraform.tfvars` and `backend.tf` (or equivalent).
|
||||
- `scripts/`: Contains utility scripts (e.g., Python, Bash) for automation.
|
||||
- `docs/`: Contains documentation for the project.
|
||||
- `examples/`: Contains example configurations or usage scenarios.
|
||||
- **File Naming Conventions:**
|
||||
- Use descriptive names for Terraform files (e.g., `vpc.tf`, `firewall.tf`, `iam.tf`).
|
||||
- Use underscores for resource names and avoid repeating resource types in names (e.g., `instance_web_server` instead of `web_server_instance`).
|
||||
- Use consistent naming conventions for variables and outputs.
|
||||
- **Module Organization:**
|
||||
- Keep modules small and focused. Each module should have a single responsibility.
|
||||
- Use input variables to parameterize modules. This makes them reusable and configurable.
|
||||
- Define outputs for modules to expose important information. This allows other modules or configurations to consume the module's results.
|
||||
- **Component Architecture (for application code):**
|
||||
- Adopt a layered architecture (e.g., presentation, business logic, data access).
|
||||
- Use dependency injection to decouple components and improve testability.
|
||||
- Design components for reusability and maintainability.
|
||||
- Use well-defined interfaces between components.
|
||||
- **Code Splitting Strategies (especially for client-side code):**
|
||||
- Split code into logical chunks based on functionality or features.
|
||||
- Use lazy loading to load code only when it's needed. This can improve initial page load time.
|
||||
- Consider using code splitting tools like Webpack or Parcel.
|
||||
|
||||
### 2. Common Patterns and Anti-patterns
|
||||
|
||||
- **Design Patterns Specific to GCP:**
|
||||
- **Service Facade:** Abstract complex GCP service interactions behind a simple interface.
|
||||
- **Pub/Sub Fanout:** Use Cloud Pub/Sub to distribute messages to multiple subscribers for parallel processing.
|
||||
- **Cloud Functions Chaining:** Chain Cloud Functions together to create complex workflows.
|
||||
- **Idempotent Operations:** Ensure operations can be safely retried without unintended side effects, especially crucial in distributed systems like GCP.
|
||||
- **Recommended Approaches for Common Tasks:**
|
||||
- **Configuration Management:** Use environment variables or Cloud KMS for storing sensitive configuration data.
|
||||
- **Secret Management:** Use Cloud Secret Manager to securely store and manage secrets.
|
||||
- **Data Storage:** Choose the appropriate storage solution based on the data type and access patterns (e.g., Cloud Storage for objects, Cloud SQL for relational data, Cloud Datastore for NoSQL data).
|
||||
- **Logging:** Use Cloud Logging for centralized logging and monitoring.
|
||||
- **Monitoring:** Utilize Cloud Monitoring and Cloud Trace for performance monitoring and troubleshooting.
|
||||
- **Identity and Access Management (IAM):** Adopt the principle of least privilege. Grant users and service accounts only the necessary permissions.
|
||||
- **Anti-patterns and Code Smells to Avoid:**
|
||||
- **Hardcoding Credentials:** Never hardcode credentials in code or configuration files. Use environment variables, secret management, or IAM roles.
|
||||
- **Overly Complex IAM Roles:** Avoid creating overly complex IAM roles with too many permissions. This can lead to security vulnerabilities.
|
||||
- **Ignoring Error Handling:** Always handle errors gracefully and provide informative error messages.
|
||||
- **Long-Running Processes in Cloud Functions:** Cloud Functions have time limits. Offload long-running processes to other services like Cloud Run or Compute Engine.
|
||||
- **Lack of Monitoring:** Failing to monitor your application can lead to undetected performance issues and errors.
|
||||
- **Ignoring Security Updates:** Regularly update your dependencies and software to address security vulnerabilities.
|
||||
- **State Management Best Practices:**
|
||||
- **Use Terraform State:** Store Terraform state remotely in Cloud Storage for collaboration and version control.
|
||||
- **Stateless Applications:** Design applications to be stateless whenever possible. If state is required, store it in a persistent storage solution like Cloud SQL or Cloud Datastore.
|
||||
- **Avoid Local Storage:** Do not rely on local storage for persistent data. Use Cloud Storage or other persistent storage solutions.
|
||||
- **Error Handling Patterns:**
|
||||
- **Centralized Error Handling:** Implement a centralized error handling mechanism to handle exceptions consistently.
|
||||
- **Logging and Monitoring:** Log all errors to Cloud Logging and set up alerts for critical errors in Cloud Monitoring.
|
||||
- **Retry Mechanisms:** Implement retry mechanisms for transient errors.
|
||||
- **Circuit Breaker Pattern:** Use the circuit breaker pattern to prevent cascading failures in distributed systems.
|
||||
|
||||
### 3. Performance Considerations
|
||||
|
||||
- **Optimization Techniques:**
|
||||
- **Caching:** Implement caching at various levels (e.g., browser, CDN, server-side) to reduce latency and improve performance. Consider using Cloud CDN or Memorystore.
|
||||
- **Load Balancing:** Use Cloud Load Balancing to distribute traffic across multiple instances for high availability and scalability.
|
||||
- **Database Optimization:** Optimize database queries and indexing to improve performance. Consider using Cloud SQL Insights for query analysis.
|
||||
- **Asynchronous Operations:** Use asynchronous operations for long-running tasks to prevent blocking the main thread.
|
||||
- **Memory Management (for application code):**
|
||||
- **Efficient Data Structures:** Choose appropriate data structures to minimize memory usage.
|
||||
- **Garbage Collection:** Understand how garbage collection works in your chosen language and optimize code to minimize memory leaks.
|
||||
- **Resource Pooling:** Use resource pooling to reuse expensive resources like database connections.
|
||||
- **Rendering Optimization (for web applications):**
|
||||
- **Minimize DOM Manipulation:** Minimize DOM manipulation to improve rendering performance.
|
||||
- **Use Virtual DOM:** Use a virtual DOM library like React or Vue.js to optimize rendering updates.
|
||||
- **Optimize Images:** Optimize images for web use by compressing them and using appropriate formats (e.g., WebP).
|
||||
- **Bundle Size Optimization (for web applications):**
|
||||
- **Code Splitting:** Split code into smaller chunks to reduce initial bundle size.
|
||||
- **Tree Shaking:** Use tree shaking to remove unused code from the bundle.
|
||||
- **Minification:** Minify code to reduce bundle size.
|
||||
- **Lazy Loading Strategies (for web applications):**
|
||||
- **Lazy Load Images:** Lazy load images that are not initially visible on the page.
|
||||
- **Lazy Load Modules:** Lazy load modules that are not immediately required.
|
||||
- **Intersection Observer:** Use the Intersection Observer API to detect when elements are visible in the viewport.
|
||||
|
||||
### 4. Security Best Practices
|
||||
|
||||
- **Common Vulnerabilities and How to Prevent Them:**
|
||||
- **SQL Injection:** Prevent SQL injection by using parameterized queries or object-relational mappers (ORMs).
|
||||
- **Cross-Site Scripting (XSS):** Prevent XSS by sanitizing user inputs and encoding outputs.
|
||||
- **Cross-Site Request Forgery (CSRF):** Prevent CSRF by using anti-CSRF tokens.
|
||||
- **Authentication and Authorization:** Implement strong authentication and authorization mechanisms to protect sensitive data.
|
||||
- **Input Validation:**
|
||||
- **Validate All Inputs:** Validate all user inputs on both the client-side and server-side.
|
||||
- **Use Regular Expressions:** Use regular expressions to validate input formats.
|
||||
- **Sanitize Inputs:** Sanitize inputs to remove potentially malicious characters.
|
||||
- **Authentication and Authorization Patterns:**
|
||||
- **Identity-Aware Proxy (IAP):** Use IAP to control access to applications running on Compute Engine, GKE, and App Engine.
|
||||
- **Firebase Authentication:** Use Firebase Authentication to easily implement authentication in web and mobile applications.
|
||||
- **OAuth 2.0:** Use OAuth 2.0 for delegated authorization.
|
||||
- **Service Accounts:** Use service accounts to authenticate applications running on GCP.
|
||||
- **Data Protection Strategies:**
|
||||
- **Encryption at Rest:** Encrypt data at rest using Cloud KMS or Cloud Storage encryption.
|
||||
- **Encryption in Transit:** Encrypt data in transit using HTTPS (TLS).
|
||||
- **Data Loss Prevention (DLP):** Use Cloud DLP to prevent sensitive data from being leaked.
|
||||
- **Secure API Communication:**
|
||||
- **HTTPS:** Always use HTTPS for API communication.
|
||||
- **API Keys:** Use API keys to authenticate API clients.
|
||||
- **JWTs:** Use JWTs for secure API authorization.
|
||||
- **Rate Limiting:** Implement rate limiting to prevent abuse.
|
||||
|
||||
### 5. Testing Approaches
|
||||
|
||||
- **Unit Testing Strategies:**
|
||||
- **Test Individual Units:** Test individual units of code (e.g., functions, classes) in isolation.
|
||||
- **Use Mocking:** Use mocking to isolate units of code from dependencies.
|
||||
- **Test Edge Cases:** Test edge cases and boundary conditions.
|
||||
- **Integration Testing:**
|
||||
- **Test Interactions:** Test the interactions between different units of code or components.
|
||||
- **Test Database Interactions:** Test interactions with databases and other external systems.
|
||||
- **Use Test Databases:** Use test databases to avoid affecting production data.
|
||||
- **End-to-End Testing:**
|
||||
- **Test Complete Workflows:** Test complete workflows from start to finish.
|
||||
- **Simulate User Interactions:** Simulate user interactions to ensure the application behaves as expected.
|
||||
- **Use Automated Testing Tools:** Use automated testing tools to automate end-to-end tests.
|
||||
- **Test Organization:**
|
||||
- **Organize Tests by Component:** Organize tests by component or module.
|
||||
- **Use a Consistent Naming Convention:** Use a consistent naming convention for test files and test cases.
|
||||
- **Keep Tests Separate from Code:** Keep tests separate from production code.
|
||||
- **Mocking and Stubbing:**
|
||||
- **Use Mocking Libraries:** Use mocking libraries to create mock objects and stubs.
|
||||
- **Mock External Dependencies:** Mock external dependencies like APIs and databases.
|
||||
- **Stub Responses:** Stub responses from external services to control test behavior.
|
||||
|
||||
### 6. Common Pitfalls and Gotchas
|
||||
|
||||
- **Frequent Mistakes Developers Make:**
|
||||
- **Incorrect IAM Permissions:** Assigning overly broad IAM permissions.
|
||||
- **Misconfiguring Network Settings:** Misconfiguring firewall rules or VPC settings.
|
||||
- **Ignoring Cost Optimization:** Failing to optimize resource usage and costs.
|
||||
- **Not Using Managed Services:** Trying to manage infrastructure manually instead of using GCP managed services.
|
||||
- **Lack of Automation:** Not automating deployments and infrastructure management.
|
||||
- **Edge Cases to be Aware of:**
|
||||
- **Network Latency:** Account for network latency in distributed systems.
|
||||
- **Concurrency Issues:** Handle concurrency issues correctly in multi-threaded applications.
|
||||
- **Data Consistency:** Ensure data consistency across distributed systems.
|
||||
- **Version-Specific Issues:**
|
||||
- **API Compatibility:** Be aware of API compatibility issues when upgrading GCP SDKs or services.
|
||||
- **Deprecated Features:** Avoid using deprecated features.
|
||||
- **Compatibility Concerns:**
|
||||
- **Cross-Browser Compatibility:** Ensure web applications are compatible with different browsers.
|
||||
- **Mobile Compatibility:** Ensure web applications are responsive and compatible with mobile devices.
|
||||
- **Debugging Strategies:**
|
||||
- **Use Cloud Debugger:** Use Cloud Debugger to debug applications running on GCP.
|
||||
- **Use Logging:** Use Cloud Logging to log debug information.
|
||||
- **Use Monitoring:** Use Cloud Monitoring to monitor application performance and identify issues.
|
||||
- **Local Debugging:** Debug applications locally before deploying them to GCP.
|
||||
|
||||
### 7. Tooling and Environment
|
||||
|
||||
- **Recommended Development Tools:**
|
||||
- **Google Cloud SDK (gcloud):** Command-line tool for interacting with GCP services.
|
||||
- **Terraform:** Infrastructure as code tool for managing GCP resources.
|
||||
- **IDE with GCP Support:** Use an IDE with GCP support (e.g., VS Code with the Google Cloud Code extension).
|
||||
- **Docker:** Containerization platform for building and deploying applications.
|
||||
- **Build Configuration:**
|
||||
- **Use Build Automation Tools:** Use build automation tools like Maven, Gradle, or npm.
|
||||
- **Define Build Steps:** Define clear build steps for compiling, testing, and packaging applications.
|
||||
- **Manage Dependencies:** Manage dependencies using dependency management tools like Maven, Gradle, or npm.
|
||||
- **Linting and Formatting:**
|
||||
- **Use Linters:** Use linters to enforce code style and identify potential issues.
|
||||
- **Use Formatters:** Use formatters to automatically format code.
|
||||
- **Configure Linters and Formatters:** Configure linters and formatters to match project coding standards.
|
||||
- **Deployment Best Practices:**
|
||||
- **Automate Deployments:** Automate deployments using CI/CD pipelines.
|
||||
- **Use Infrastructure as Code:** Use infrastructure as code (e.g., Terraform) to manage infrastructure.
|
||||
- **Blue/Green Deployments:** Use blue/green deployments to minimize downtime.
|
||||
- **Canary Deployments:** Use canary deployments to gradually roll out new features.
|
||||
- **Rollback Strategy:** Have a rollback strategy in place to revert to a previous version if necessary.
|
||||
- **CI/CD Integration:**
|
||||
- **Use Cloud Build:** Use Cloud Build for CI/CD pipelines on GCP.
|
||||
- **Integrate with Version Control:** Integrate CI/CD pipelines with version control systems (e.g., GitHub, GitLab, Cloud Source Repositories).
|
||||
- **Automate Testing:** Automate testing as part of the CI/CD pipeline.
|
||||
- **Automate Deployments:** Automate deployments as part of the CI/CD pipeline.
|
||||
|
||||
By following these best practices, developers can build robust, secure, and scalable applications and infrastructure on Google Cloud Platform.
|
||||
Reference in New Issue
Block a user