0Pricing
Serverless Backend with AWS Lambda & API Gateway · Урок

CodeCommit и CodeBuild

Интегрируйте AWS CodeCommit для управления исходным кодом и AWS CodeBuild для компиляции и упаковки бессерверного кода

«CodeCommit и CodeBuild» — бесплатный урок Serverless Backend with AWS Lambda & API Gateway на CoddyKit. Это урок 1 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Serverless Backend with AWS Lambda & API Gateway, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Serverless Backend with AWS Lambda & API Gateway содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

CI/CD for Serverless Intro

Welcome to the first lesson in our CI/CD for Serverless Applications course! Continuous Integration and Continuous Delivery (CI/CD) are crucial for modern software development.

In this lesson, we'll dive into two foundational AWS services: AWS CodeCommit for source control and AWS CodeBuild for compiling and packaging your serverless code.

What is AWS CodeCommit?

AWS CodeCommit is a fully managed source control service that hosts secure Git-based repositories. Think of it as AWS's version of GitHub or GitLab, but tightly integrated with other AWS services.

  • It's private: Your code stays within AWS.
  • It's scalable: Handles projects of any size.
  • It's Git-compatible: Use your existing Git tools and workflows.

It acts as the central hub for your application's source code.

Setting Up CodeCommit Repo

To start using CodeCommit, you first need to create a repository. You can do this via the AWS Management Console, AWS CLI, or SDKs.

Once created, you'll configure your local Git client to connect to it. This often involves setting up IAM credentials (HTTPS Git credentials) or SSH keys for authentication.

Cloning & Pushing Code

After setting up your credentials, you can clone your CodeCommit repository to your local machine and push changes just like any other Git repository.

Here's a basic sequence of commands you'd use:

git clone https://git-codecommit.us-east-1.amazonaws.com/v1/repos/MyServerlessRepo
cd MyServerlessRepo
echo "print('Hello CI/CD!')" > app.py
git add app.py
git commit -m "Initial commit for Lambda function"
git push origin main

What is AWS CodeBuild?

AWS CodeBuild is a fully managed continuous integration service that compiles your source code, runs tests, and produces deployable software packages. It eliminates the need to provision, manage, and scale your own build servers.

  • No servers to manage: AWS handles the infrastructure.
  • Scales automatically: Builds run in parallel and scale as needed.
  • Pay-as-you-go: You only pay for the compute time used.

The Buildspec File

The core of a CodeBuild project is the buildspec.yml file. This YAML file defines the commands and actions CodeBuild performs during a build.

It specifies build commands, artifact (output) definitions, and caching instructions. It's placed at the root of your source repository.

Anatomy of a Buildspec

A buildspec.yml is organized into phases:

  • install: Install dependencies.
  • pre_build: Commands before build (e.g., login to Docker).
  • build: Actual build commands (e.g., compile code, run tests).
  • post_build: Commands after build (e.g., package artifacts).

Here's a simple example for a Python Lambda function:

version: 0.2

phases:
  install:
    commands:
      - echo "Installing dependencies..."
      - pip install --upgrade pip
      - pip install -r requirements.txt -t package/
  build:
    commands:
      - echo "Zipping deployment package..."
      - cd package
      - zip -r ../function.zip .
      - cd ..
      - zip -g function.zip app.py
artifacts:
  files:
    - function.zip
  discard-paths: yes

Creating a CodeBuild Project

To use CodeBuild, you create a build project. This involves:

  • Source: Pointing to your source code repository (e.g., CodeCommit).
  • Environment: Selecting an operating system, runtime, and compute type.
  • Buildspec: Specifying the buildspec.yml file.
  • Artifacts: Defining where to store build outputs (e.g., S3 bucket).

You'll also assign an IAM role to CodeBuild, granting it permissions to access your source, S3, and other necessary AWS services.

CodeCommit & CodeBuild Flow

The typical workflow for continuous integration using these services is:

  1. Developer pushes code changes to an AWS CodeCommit repository.
  2. CodeCommit can trigger an AWS CodeBuild project automatically (often via CodePipeline, which we'll cover next).
  3. CodeBuild fetches the latest code, executes the commands in buildspec.yml.
  4. CodeBuild produces artifacts (like a zipped Lambda function) and stores them in an S3 bucket, ready for deployment.

Quick Check

You've just learned about CodeCommit and CodeBuild. Let's test your understanding!

Recap & Next Steps

Great job! In this lesson, you learned about:

  • AWS CodeCommit: A managed Git repository service for secure source control.
  • AWS CodeBuild: A fully managed continuous integration service that compiles and packages your code.
  • The importance of the buildspec.yml file for defining build steps.

These two services form the backbone of your serverless CI/CD pipeline. Next, we'll see how AWS CodePipeline orchestrates these services for automated deployments!

Часто задаваемые вопросы

Урок «CodeCommit и CodeBuild» бесплатный?

Да — полный текст урока «CodeCommit и CodeBuild» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Serverless Backend with AWS Lambda & API Gateway, подпишись на CoddyKit PRO. Курс Serverless Backend with AWS Lambda & API Gateway содержит 4 уроков всего.

Чему я научусь в уроке «CodeCommit и CodeBuild»?

Интегрируйте AWS CodeCommit для управления исходным кодом и AWS CodeBuild для компиляции и упаковки бессерверного кода Ты практикуешь Serverless Backend with AWS Lambda & API Gateway с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Serverless Backend with AWS Lambda & API Gateway?

Предыдущий опыт не требуется. Serverless Backend with AWS Lambda & API Gateway на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 1 из 4.

Сколько времени занимает урок «CodeCommit и CodeBuild»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Serverless Backend with AWS Lambda & API Gateway?

Да. Каждый урок Serverless Backend with AWS Lambda & API Gateway включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. CodeCommit и CodeBuild
  2. CodePipeline для развёртывания
  3. Автоматизация развёртывания бессерверных приложений
  4. Безопасные развёртывания с канареечным выпуском и откатом
← Назад к Serverless Backend with AWS Lambda & API Gateway