From d9239c565de4d56658b1e4f4e8cd5c01dd95c525 Mon Sep 17 00:00:00 2001 From: mdefende <mdefende@uab.edu> Date: Mon, 11 Nov 2024 17:07:41 -0600 Subject: [PATCH] wip- instructions on setting up cicd --- README.md | 189 +++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 130 insertions(+), 59 deletions(-) diff --git a/README.md b/README.md index a56aeb5..51eefa7 100644 --- a/README.md +++ b/README.md @@ -1,93 +1,164 @@ -# docker-cicd-test +# CI/CD Example Using Gitlab +## CI/CD +CICD stands for continuous integration and continuous deployment and is a procedure that automates building, testing, distributing, and deploying code in a variety of formats. [RedHat](https://www.redhat.com/en/topics/devops/what-is-ci-cd) has a good summary of CI/CD and why it's useful. Here are a few examples of what CI/CD can automate: -## Getting started +1. Running full test suites on a code base +2. Building source code into a distributable package or compiling it into an executable +3. Building an image containing source code to be used in Docker/Singularity containers +4. Any repetitive tasks that must be done after modifications to source code in order to make that code usable by others -To make it easy for you to get started with GitLab, here's a list of recommended next steps. +Using UAB's self-hosted Gitlab instance and [Cloud](https://docs.rc.uab.edu/uab_cloud/) infrastructure, anyone can implement CI/CD to streamline their code development. -Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! +## How To Use This Repository -## Add your files +This repository is meant to be used as a guide and starting point and will walk through the steps necessary to implement CI/CD in your own projects. This repository can also be cloned or forked by anyone to have as a starting point for a new Gitlab repo so you would not have to start from scratch. -- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files -- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command: +## Prerequisites -``` -cd existing_repo -git remote add origin https://gitlab.rc.uab.edu/mdefende/docker-cicd-test.git -git branch -M main -git push -uf origin main -``` +CI/CD can be implemented using most modern code repositories (ex. Github, Gitlab) and cloud services (ex. AWS, GCP, Azure) so the ideas here are transferrible elsewhere. However, the full guide will be written to use UAB's Gitlab and Cloud platforms specifically. To implement CI/CD as described here, you will need accounts for both Cloud and Gitlab. + +### Create Your Accounts -## Integrate with your tools +- [Request a UAB Cloud account by contacting Research Computing Support](https://docs.rc.uab.edu/#how-to-contact-us) +- [Create a UAB Gitlab account](https://docs.rc.uab.edu/account_management/gitlab_account/#uab-gitlab-registration) -- [ ] [Set up project integrations](https://gitlab.rc.uab.edu/mdefende/docker-cicd-test/-/settings/integrations) +### Learn Account Cloud and Gitlab -## Collaborate with your team +This guide will assume basic understanding of how to use both services. If you do not have any experience with either Cloud or Gitlab, see the following guides on [our docs](https://docs.rc.uab.edu) -- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/) -- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html) -- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically) -- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/) -- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html) +- [Cloud](https://docs.rc.uab.edu/uab_cloud/) +- [Git](https://docs.rc.uab.edu/workflow_solutions/git_collaboration/) -## Test and Deploy +Gitlab is a separate implementation of remote git repositories than Github but functions identically at a basic level. In addition to the guides, our facilitation team would be happy to assist in learning how to use either git or Cloud during our [open office hours on Zoom](https://docs.rc.uab.edu/#how-to-contact-us) -Use the built-in continuous integration in GitLab. +## CI/CD Setup -- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html) -- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/) -- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html) -- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/) -- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html) +Setup can be split into two separate sections, one section for setting up the code repository to use CI/CD and the other section for creating the Cloud VM that will actually run the CI/CD pipeline you create. While most of the steps for each section will not overlap with the other, there will be a couple of steps at the end needed to set the repo to use the VM. -*** +This repository builds Python source code as both a `pip` installable package and a Docker/Singularity image as an example. -# Editing this README +### Gitlab Repo Configuration -When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template. +To implement CI/CD in a Gitlab repo, you will need to create a `.gitlab-ci.yml` file in the repo root as well as specify a runner to execute the CI. The `gitlab-ci` specifies all of the commands to be run to replicate a build and deploy process. These can range from fairly simple to very complicated depending on the pipeline. -## Suggestions for a good README +#### .gitlab-ci.yml + +##### Default Settings + +```yaml +default: + image: python:3.12-slim + rules: + - if: '$CI_COMMIT_BRANCH == "main"' +``` -Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information. +- **image**: Specifies the Docker image to use for all jobs by default. Here, it uses `python:3.12-slim`, which is a lightweight Python environment. +- **rules**: Defines conditions for when the pipeline should run. In this case, it runs only if the branch is `main`. -## Name -Choose a self-explaining name for your project. +##### Variables -## Description -Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors. +```yaml +variables: + PACKAGE_NAME: "pak" + REPO_URL: "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/pypi" + PIP_CACHE_DIR: "${CI_PROJECT_DIR}/.cache/pip" + PIP_INDEX_URL: "https://__token__:${CI_JOB_TOKEN}@gitlab.com/api/v4/projects/${CI_PROJECT_ID}/packages/pypi/simple" + PIP_EXTRA_INDEX_URL: "https://pypi.org/simple" +``` -## Badges -On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge. +- **PACKAGE_NAME**: The name of the package being built. +- **REPO_URL**: The URL for the PyPI repository in GitLab, where the package will be uploaded. +- **PIP_CACHE_DIR**: Directory to cache pip downloads, speeding up subsequent installs. +- **PIP_INDEX_URL**: The primary index URL for pip, using a token for authentication. +- **PIP_EXTRA_INDEX_URL**: An additional index URL for pip, pointing to the public PyPI. -## Visuals -Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method. +##### Stages -## Installation -Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection. +```yaml +stages: + - build + - test + - publish +``` -## Usage -Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README. +Defines the different stages of the CI pipeline: + +- **build**: Compiling or packaging the code. +- **test**: Running tests to ensure the code works as expected. +- **publish**: Publishing the package or Docker image. + +##### Build Package Job + +```yaml +build_package: + stage: build + script: + - pip install --upgrade pip + - pip install setuptools wheel build + - python -m build + artifacts: + paths: + - dist/* + cache: + paths: + - .cache/pip +``` -## Support -Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc. +- **stage**: Specifies that this job is part of the `build` stage. +- **script**: Commands to upgrade pip, install necessary tools, and build the package. +- **artifacts**: Specifies files to be saved after the job completes, in this case, the built package files in the `dist` directory. +- **cache**: Caches the pip downloads to speed up future builds. -## Roadmap -If you have ideas for releases in the future, it is a good idea to list them in the README. +##### Test Package Job -## Contributing -State if you are open to contributions and what your requirements are for accepting them. +```yaml +test_package: + stage: test + script: + - pip install . + - pip install pytest + - pytest +``` -For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self. +- **stage**: Specifies that this job is part of the `test` stage. +- **script**: Commands to install the package, install `pytest`, and run tests. -You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser. +##### Publish to PyPI Job -## Authors and acknowledgment -Show your appreciation to those who have contributed to the project. +```yaml +publish_pip: + stage: publish + script: + - pip install twine + - twine upload -u gitlab-ci-token -p ${CI_JOB_TOKEN} --repository-url ${REPO_URL} dist/* +``` -## License -For open source projects, say how it is licensed. +- **stage**: Specifies that this job is part of the `publish` stage. +- **script**: Commands to install `twine` and upload the built package to the PyPI repository. + +##### Build and Push Docker Image Job + +```yaml +build_and_push_docker_image: + stage: publish + image: docker:latest + services: + - docker:dind + variables: + DOCKER_IMAGE_NAME: ${CI_REGISTRY_IMAGE}/${PACKAGE_NAME} + before_script: + - echo "${CI_REGISTRY_PASSWORD}" | docker login -u "${CI_REGISTRY_USER}" --password-stdin ${CI_REGISTRY} + script: + - docker pull ${DOCKER_IMAGE_NAME}:latest || true + - docker build --build-arg BUILDKIT_INLINE_CACHE=1 --cache-from ${DOCKER_IMAGE_NAME}:latest -t ${DOCKER_IMAGE_NAME}:latest . + - docker push ${DOCKER_IMAGE_NAME}:latest +``` -## Project status -If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers. +- **stage**: Specifies that this job is part of the `publish` stage. +- **image**: Uses the `docker:latest` image for this job. +- **services**: Uses Docker-in-Docker (`docker:dind`) to enable Docker commands within the job. +- **variables**: Defines Docker-related variables. +- **before_script**: Logs into the Docker registry. +- **script**: Commands to pull the latest Docker image, build a new image, and push it to the registry. -- GitLab