Aller au contenu

Aide-mémoire env0

Vue d’ensemble

env0 est une plateforme de gestion d’Infrastructure as Code (IaC) qui automatise et gouverne Terraform, Pulumi, CloudFormation et d’autres outils IaC. Elle offre des workflows collaboratifs, l’application de politiques, la gestion des coûts et la détection de dérive pour aider les équipes à gérer l’infrastructure cloud à grande échelle avec confiance et contrôle.

⚠️ Note : Offre gratuite disponible pour les petites équipes. Les plans payants commencent à 4$/utilisateur/mois pour les fonctionnalités avancées.

Premiers pas

Configuration du compte

# Sign up process:
# 1. Visit env0.com
# 2. Create account with email or SSO
# 3. Connect your cloud providers
# 4. Link version control repositories
# 5. Create your first project

# Initial configuration:
# - Organization settings
# - User roles and permissions
# - Cloud provider credentials
# - VCS integration (GitHub, GitLab, Bitbucket)
# - Notification preferences

Création de projet

# Project setup workflow:
# 1. Create new project
# 2. Select IaC framework (Terraform, Pulumi, etc.)
# 3. Connect repository
# 4. Configure deployment settings
# 5. Set up environments
# 6. Define approval workflows

# Project types supported:
# - Terraform
# - Pulumi
# - CloudFormation
# - Terragrunt
# - Kubernetes manifests
# - Helm charts

Gestion des environnements

# Environment hierarchy:
# Organization → Projects → Environments

# Environment types:
# - Development: Testing and experimentation
# - Staging: Pre-production validation
# - Production: Live infrastructure
# - Sandbox: Isolated testing environments

Intégration Terraform

Structure du dépôt

# Recommended Terraform structure
project-root/
├── main.tf                 # Main configuration
├── variables.tf            # Variable definitions
├── outputs.tf              # Output definitions
├── versions.tf             # Provider versions
├── terraform.tfvars        # Default variable values
├── environments/
   ├── dev/
   └── terraform.tfvars
   ├── staging/
   └── terraform.tfvars
   └── prod/
       └── terraform.tfvars
└── modules/
    ├── vpc/
    ├── compute/
    └── database/

Configuration de l’environnement

# env0.yml configuration file
version: 1

deploy:
  before:
    - echo "Pre-deployment setup"
    - terraform --version
    - aws --version
  
  after:
    - echo "Post-deployment cleanup"
    - terraform output -json > outputs.json

destroy:
  before:
    - echo "Pre-destroy validation"
    - terraform plan -destroy
  
  after:
    - echo "Infrastructure destroyed"

variables:
  - name: AWS_REGION
    value: us-west-2
    scope: environment
  
  - name: INSTANCE_TYPE
    value: t3.micro
    scope: project

terraformVersion: "1.5.0"

Gestion des variables

# Variable types in env0:
# - Environment variables
# - Terraform variables
# - Project-level variables
# - Organization-level variables

# Variable scopes:
# - Organization: Available to all projects
# - Project: Available to all environments in project
# - Environment: Specific to single environment

# Variable sources:
# - Manual input
# - AWS Parameter Store
# - HashiCorp Vault
# - Azure Key Vault
# - Environment files

Workflows de déploiement

Déploiements automatisés

# Trigger types:
# - Git push to branch
# - Pull request creation
# - Manual deployment
# - Scheduled deployment
# - API trigger
# - Webhook trigger

# Deployment process:
# 1. Code checkout
# 2. Environment preparation
# 3. Pre-deployment hooks
# 4. Terraform plan generation
# 5. Approval workflow (if required)
# 6. Terraform apply
# 7. Post-deployment hooks
# 8. Notification and reporting

Workflows d’approbation

# Approval configuration
approvals:
  - type: manual
    users:
      - admin@company.com
      - devops-lead@company.com
    required_approvals: 2
    
  - type: policy
    conditions:
      - cost_increase > 100
      - resource_count > 50
      - contains_production_data: true

# Auto-approval conditions
auto_approve:
  - branch: develop
    environment: development
  
  - cost_change: < 10
    resource_change: < 5

Politiques de déploiement

# OPA (Open Policy Agent) policy example
package env0.deployment

# Deny deployment if cost increase is too high
deny[msg] {
    input.cost_estimation.monthly_cost_change > 1000
    msg := "Monthly cost increase exceeds $1000 limit"
}

# Require approval for production deployments
require_approval[msg] {
    input.environment.name == "production"
    msg := "Production deployments require manual approval"
}

# Enforce resource tagging
deny[msg] {
    resource := input.planned_resources[_]
    resource.type == "aws_instance"
    not resource.tags.Environment
    msg := sprintf("Instance %s missing Environment tag", [resource.name])
}

Gestion des coûts

Estimation des coûts

# Cost estimation features:
# - Pre-deployment cost preview
# - Monthly cost projections
# - Cost comparison between environments
# - Historical cost tracking
# - Budget alerts and limits

# Cost policies:
# - Maximum monthly cost per environment
# - Cost increase thresholds
# - Resource-specific cost limits
# - Team budget allocation

Contrôles budgétaires

# Budget configuration
budgets:
  - name: "Development Environment"
    limit: 500
    period: monthly
    alerts:
      - threshold: 80
        recipients:
          - dev-team@company.com
      - threshold: 95
        recipients:
          - finance@company.com
          - devops@company.com

  - name: "Production Environment"
    limit: 5000
    period: monthly
    auto_destroy: false
    alerts:
      - threshold: 90
        recipients:
          - all-hands@company.com

Optimisation des coûts

# Cost optimization features:
# - Resource rightsizing recommendations
# - Unused resource detection
# - Reserved instance recommendations
# - Spot instance suggestions
# - Idle resource identification

# Cost reporting:
# - Daily cost breakdown
# - Weekly cost summaries
# - Monthly cost reports
# - Cost attribution by team/project
# - Trend analysis and forecasting

Détection de dérive

Surveillance de la dérive

# Drift detection setup:
# 1. Enable drift detection for environment
# 2. Configure detection schedule
# 3. Set up notification channels
# 4. Define drift resolution policies

# Drift types detected:
# - Resource configuration changes
# - Resource additions outside Terraform
# - Resource deletions
# - Tag modifications
# - Security group changes

Résolution de la dérive

# Drift resolution configuration
drift_detection:
  enabled: true
  schedule: "0 */6 * * *"  # Every 6 hours
  
  resolution:
    auto_fix:
      - type: tag_changes
        action: revert
      
      - type: security_group_changes
        action: notify_and_revert
    
    manual_review:
      - type: resource_additions
      - type: resource_deletions
      - type: configuration_changes

  notifications:
    slack:
      webhook: "https://hooks.slack.com/services/..."
      channel: "#infrastructure-alerts"
    
    email:
      recipients:
        - devops@company.com
        - security@company.com

Correction de la dérive

# Drift remediation options:
# 1. Auto-revert: Automatically fix detected drift
# 2. Import: Import drifted resources into Terraform state
# 3. Update code: Modify Terraform code to match current state
# 4. Manual review: Require human intervention
# 5. Ignore: Mark drift as acceptable

# Remediation workflow:
# 1. Drift detected and categorized
# 2. Policy evaluation
# 3. Automatic remediation (if configured)
# 4. Notification to relevant teams
# 5. Manual review (if required)
# 6. Resolution tracking and reporting

Sécurité et conformité

Policy as Code

# Security policy examples
package env0.security

# Require encryption for S3 buckets
deny[msg] {
    resource := input.planned_resources[_]
    resource.type == "aws_s3_bucket"
    not resource.server_side_encryption_configuration
    msg := sprintf("S3 bucket %s must have encryption enabled", [resource.name])
}

# Enforce security group restrictions
deny[msg] {
    resource := input.planned_resources[_]
    resource.type == "aws_security_group"
    rule := resource.ingress[_]
    rule.cidr_blocks[_] == "0.0.0.0/0"
    rule.from_port <= 22
    rule.to_port >= 22
    msg := sprintf("Security group %s allows SSH from anywhere", [resource.name])
}

# Require specific tags
required_tags := ["Environment", "Owner", "Project"]

deny[msg] {
    resource := input.planned_resources[_]
    resource.type in ["aws_instance", "aws_rds_instance"]
    tag := required_tags[_]
    not resource.tags[tag]
    msg := sprintf("Resource %s missing required tag: %s", [resource.name, tag])
}

Cadres de conformité

# Compliance configuration
compliance:
  frameworks:
    - name: "SOC 2"
      policies:
        - encryption_at_rest
        - access_logging
        - network_security
    
    - name: "PCI DSS"
      policies:
        - data_encryption
        - network_segmentation
        - access_controls
    
    - name: "HIPAA"
      policies:
        - data_protection
        - audit_logging
        - access_management

  reporting:
    frequency: weekly
    recipients:
      - compliance@company.com
      - security@company.com

Contrôle d’accès

# Role-based access control (RBAC):
# - Organization Admin: Full access
# - Project Admin: Project-level management
# - Environment Admin: Environment-specific control
# - Developer: Read access and limited deployments
# - Viewer: Read-only access

# Permission matrix:
# - View environments
# - Deploy to environments
# - Approve deployments
# - Manage variables
# - Configure policies
# - Access cost data
# - Manage users and roles

API et CLI

Installation de l’env0 CLI

Would you like me to continue with the remaining sections?```bash

Install env0 CLI

npm install -g @env0/cli

Alternative installation methods

curl -L https://github.com/env0/env0-cli/releases/latest/download/env0-cli-linux -o env0 chmod +x env0 sudo mv env0 /usr/local/bin/

Verify installation

env0 —version


### CLI Authentication
```bash
# Authenticate with API key
env0 auth login --api-key YOUR_API_KEY

# Authenticate with interactive login
env0 auth login

# Set default organization
env0 config set organization YOUR_ORG_ID

# Verify authentication
env0 auth whoami

CLI Commands

# Project management
env0 projects list
env0 projects create --name "My Project" --repository "https://github.com/user/repo"
env0 projects delete --id PROJECT_ID

# Environment management
env0 environments list --project-id PROJECT_ID
env0 environments create --name "staging" --project-id PROJECT_ID
env0 environments deploy --id ENV_ID
env0 environments destroy --id ENV_ID

# Variable management
env0 variables list --environment-id ENV_ID
env0 variables create --name "AWS_REGION" --value "us-west-2" --environment-id ENV_ID
env0 variables update --id VAR_ID --value "us-east-1"
env0 variables delete --id VAR_ID

# Deployment management
env0 deployments list --environment-id ENV_ID
env0 deployments cancel --id DEPLOYMENT_ID
env0 deployments approve --id DEPLOYMENT_ID

API Integration

# REST API examples
API_BASE="https://api.env0.com"
API_KEY="your-api-key"

# Get organizations
curl -H "Authorization: Bearer $API_KEY" \
     "$API_BASE/organizations"

# Create project
curl -X POST \
     -H "Authorization: Bearer $API_KEY" \
     -H "Content-Type: application/json" \
     -d '{
       "name": "My Project",
       "repository": "https://github.com/user/repo",
       "organizationId": "org-id"
     }' \
     "$API_BASE/projects"

# Trigger deployment
curl -X POST \
     -H "Authorization: Bearer $API_KEY" \
     -H "Content-Type: application/json" \
     -d '{
       "environmentId": "env-id",
       "userRequiresApproval": false
     }' \
     "$API_BASE/deployments"

Integrations

Version Control Systems

# Supported VCS providers:
# - GitHub
# - GitLab
# - Bitbucket
# - Azure DevOps

# Integration features:
# - Automatic webhook setup
# - Branch-based deployments
# - Pull request integration
# - Commit status updates
# - Deployment comments

Cloud Providers

# Supported cloud providers:
# - AWS (IAM roles, access keys)
# - Azure (Service principals, managed identity)
# - Google Cloud (Service accounts)
# - Alibaba Cloud
# - DigitalOcean

# Authentication methods:
# - Static credentials
# - Dynamic credentials (OIDC)
# - Cloud provider IAM roles
# - Cross-account role assumption

Notification Channels

# Notification configuration
notifications:
  slack:
    webhook_url: "https://hooks.slack.com/services/..."
    channels:
      - name: "#deployments"
        events: ["deployment_started", "deployment_completed"]
      - name: "#alerts"
        events: ["deployment_failed", "drift_detected"]
  
  email:
    smtp:
      host: "smtp.company.com"
      port: 587
      username: "notifications@company.com"
    
    recipients:
      - email: "devops@company.com"
        events: ["all"]
      - email: "management@company.com"
        events: ["deployment_failed", "cost_exceeded"]
  
  webhook:
    url: "https://api.company.com/webhooks/env0"
    headers:
      Authorization: "Bearer webhook-token"
    events: ["all"]

Third-Party Tools

# Integration ecosystem:
# - Monitoring: Datadog, New Relic, Grafana
# - Security: Snyk, Aqua Security, Prisma Cloud
# - Cost management: CloudHealth, Cloudability
# - ITSM: ServiceNow, Jira Service Management
# - Communication: Microsoft Teams, Discord

Advanced Features

Custom Workflows

# Custom workflow configuration
workflows:
  pre_deployment:
    - name: "Security Scan"
      type: "script"
      script: |
        #!/bin/bash
        tfsec .
        if [ $? -ne 0 ]; then
          echo "Security scan failed"
          exit 1
        fi
    
    - name: "Cost Validation"
      type: "policy"
      policy: |
        package env0.cost
        deny[msg] {
          input.cost_estimation.monthly_cost > 1000
          msg := "Monthly cost exceeds budget"
        }
  
  post_deployment:
    - name: "Health Check"
      type: "script"
      script: |
        #!/bin/bash
        curl -f http://$(terraform output -raw load_balancer_url)/health
    
    - name: "Update Documentation"
      type: "webhook"
      url: "https://api.company.com/docs/update"
      payload:
        environment: "{{ env.name }}"
        resources: "{{ deployment.resources }}"

Multi-Cloud Management

# Multi-cloud deployment strategies:
# 1. Single project, multiple providers
# 2. Provider-specific projects
# 3. Hybrid cloud architectures
# 4. Cross-cloud resource dependencies

# Example multi-cloud configuration:
# - AWS for compute and storage
# - Azure for AI/ML services
# - GCP for data analytics
# - On-premises for sensitive data

GitOps Integration

# GitOps workflow configuration
gitops:
  enabled: true
  
  pull_request:
    auto_plan: true
    auto_apply: false
    require_approval: true
    
    plan_comment: true
    apply_comment: true
    
  branch_protection:
    required_reviews: 2
    dismiss_stale_reviews: true
    require_code_owner_reviews: true
    
  continuous_deployment:
    branches:
      - name: "main"
        environment: "production"
        auto_apply: false
      
      - name: "develop"
        environment: "development"
        auto_apply: true

Monitoring and Observability

Deployment Monitoring

# Monitoring capabilities:
# - Real-time deployment logs
# - Resource creation tracking
# - Performance metrics
# - Error detection and alerting
# - Deployment duration tracking

# Metrics collected:
# - Deployment success rate
# - Average deployment time
# - Resource provisioning time
# - Cost per deployment
# - Policy violation frequency

Logging and Auditing

# Audit configuration
audit:
  events:
    - user_login
    - deployment_started
    - deployment_completed
    - deployment_failed
    - policy_violation
    - cost_threshold_exceeded
    - drift_detected
    - approval_granted
    - approval_denied
  
  retention: 365  # days
  
  export:
    - type: "s3"
      bucket: "company-audit-logs"
      prefix: "env0/"
    
    - type: "elasticsearch"
      endpoint: "https://logs.company.com"
      index: "env0-audit"

Performance Analytics

# Performance metrics:
# - Infrastructure provisioning time
# - Policy evaluation duration
# - API response times
# - Resource utilization
# - Cost efficiency metrics

# Analytics dashboards:
# - Deployment trends
# - Cost optimization opportunities
# - Security compliance status
# - Team productivity metrics
# - Resource utilization patterns

Troubleshooting

Common Issues

# Deployment failures
# 1. Check deployment logs
env0 deployments logs --id DEPLOYMENT_ID

# 2. Verify credentials
env0 credentials test --environment-id ENV_ID

# 3. Validate Terraform configuration
terraform validate
terraform plan

# 4. Check policy violations
env0 policies evaluate --environment-id ENV_ID

# State file issues
# 1. Check state file location
# 2. Verify state file permissions
# 3. Resolve state conflicts
# 4. Import existing resources if needed

Debug Mode

# Enable debug logging
env0 deployments create --environment-id ENV_ID --debug

# Verbose API responses
env0 --verbose projects list

# Export deployment logs
env0 deployments logs --id DEPLOYMENT_ID --output deployment.log

Support and Diagnostics

# Generate diagnostic report
env0 diagnostics generate --environment-id ENV_ID

# Check system status
env0 status

# Validate configuration
env0 config validate

# Test connectivity
env0 test connection --provider aws

Best Practices

Repository Organization

# Recommended structure:
organization/
├── terraform-modules/          # Reusable modules
   ├── vpc/
   ├── compute/
   └── database/
├── infrastructure/             # Environment-specific configs
   ├── development/
   ├── staging/
   └── production/
└── policies/                   # OPA policies
    ├── security/
    ├── cost/
    └── compliance/

Environment Strategy

# Environment promotion strategy:
# 1. Development: Rapid iteration and testing
# 2. Staging: Production-like validation
# 3. Production: Stable, approved changes only

# Branch mapping:
# - feature/* → development environment
# - develop → staging environment
# - main → production environment

# Approval gates:
# - Development: Auto-approve
# - Staging: Team lead approval
# - Production: Multi-level approval

Security Best Practices

# Security recommendations:
# 1. Use dynamic credentials (OIDC) when possible
# 2. Implement least-privilege access
# 3. Enable audit logging
# 4. Regular policy reviews
# 5. Automated security scanning
# 6. Secrets management integration
# 7. Network security controls
# 8. Regular access reviews

Cost Optimization

# Cost management strategies:
# 1. Set budget alerts and limits
# 2. Regular cost reviews
# 3. Resource rightsizing
# 4. Automated cleanup policies
# 5. Reserved instance planning
# 6. Spot instance utilization
# 7. Resource scheduling
# 8. Cost attribution and chargeback

Migration and Adoption

Migration from Other Tools

# Migration from Terraform Cloud:
# 1. Export Terraform state files
# 2. Import state into env0
# 3. Configure variables and settings
# 4. Set up approval workflows
# 5. Test deployments
# 6. Update CI/CD pipelines

# Migration from Jenkins/GitLab CI:
# 1. Analyze existing pipelines
# 2. Map workflows to env0 features
# 3. Configure environments
# 4. Set up policies and approvals
# 5. Migrate secrets and variables
# 6. Update team processes

Team Onboarding

# Onboarding checklist:
# 1. Account setup and role assignment
# 2. Training on env0 concepts
# 3. Repository access configuration
# 4. First deployment walkthrough
# 5. Policy and approval training
# 6. Cost management overview
# 7. Troubleshooting resources
# 8. Regular check-ins and feedback

Gradual Adoption

# Adoption strategy:
# Phase 1: Pilot with development environments
# Phase 2: Expand to staging environments
# Phase 3: Production environment migration
# Phase 4: Advanced features and optimization

# Success metrics:
# - Deployment frequency
# - Deployment success rate
# - Time to deployment
# - Policy compliance rate
# - Cost optimization achieved
# - Team satisfaction

Resources

Documentation

Community

Training