Skip to content

GitLab CI/CD Integration

Overview

Configure GitLab CI/CD pipelines for Ansible automation.

Pipeline Configuration

Basic Pipeline

image: python:3.9

variables:
  ANSIBLE_FORCE_COLOR: "1"

stages:
  - lint
  - test
  - deploy

before_script:
  - pip install ansible ansible-lint molecule

lint:
  stage: lint
  script:
    - ansible-lint

test:
  stage: test
  services:
    - docker:dind
  script:
    - molecule test

deploy_staging:
  stage: deploy
  script:
    - echo "$VAULT_PASS" > .vault_pass
    - ansible-playbook -i inventory/staging site.yml
  environment:
    name: staging
  only:
    - develop

deploy_production:
  stage: deploy
  script:
    - echo "$VAULT_PASS" > .vault_pass
    - ansible-playbook -i inventory/production site.yml
  environment:
    name: production
  rules:
    - if: $CI_COMMIT_BRANCH == "main"
      when: manual
  needs:
    - test

Environment Configuration

Multi-Environment Setup

.deploy_template: &deploy_definition
  script:
    - |
      echo "$VAULT_PASS" > .vault_pass
      ansible-playbook \
        -i inventory/${CI_ENVIRONMENT_NAME} \
        --vault-password-file .vault_pass \
        site.yml

deploy_dev:
  <<: *deploy_definition
  environment:
    name: dev
  rules:
    - if: $CI_COMMIT_BRANCH == "develop"

deploy_staging:
  <<: *deploy_definition
  environment:
    name: staging
  rules:
    - if: $CI_COMMIT_BRANCH == "staging"

deploy_production:
  <<: *deploy_definition
  environment:
    name: production
  rules:
    - if: $CI_COMMIT_BRANCH == "main"
      when: manual

Testing Integration

Molecule Testing

molecule_test:
  image: python:3.9
  services:
    - docker:dind
  variables:
    DOCKER_HOST: "tcp://docker:2375"
  script:
    - pip install molecule[docker]
    - cd roles/myapp
    - molecule test

Parallel Testing

test:
  parallel:
    matrix:
      - DISTRO: [ubuntu2004, centos8]
        PYTHON: ['3.8', '3.9']
  script:
    - molecule test

Artifacts and Caching

Cache Configuration

cache:
  paths:
    - .pip-cache/
    - venv/
  key: ${CI_COMMIT_REF_SLUG}

before_script:
  - python -m venv venv
  - source venv/bin/activate
  - pip install -r requirements.txt

Artifact Management

create_artifacts:
  stage: build
  script:
    - tar -czf playbooks.tar.gz .
  artifacts:
    paths:
      - playbooks.tar.gz
    expire_in: 1 week