stages:
  - build
  - setup-cluster
  - install-apps
  - test
  - cleanup

ci_test_image:
  stage: build
  variables:
    DOCKER_DRIVER: overlay2
  image: docker:stable
  services:
    - docker:dind
  before_script:
    - docker info
  script:
    - docker login -u gitlab-ci-token -p $CI_JOB_TOKEN $CI_REGISTRY
    - docker build -t ${CI_REGISTRY_IMAGE}/bootstrap-ci test/
    - docker push ${CI_REGISTRY_IMAGE}/bootstrap-ci
  only:
    changes:
      - test/Dockerfile
      - test/requirements.txt

bootstrap:
  stage: setup-cluster
  image: "${CI_REGISTRY_IMAGE}/bootstrap-ci"
  script:
    # Ensure test/ is not world-writable otherwise ansible-playbook refuses to run, see
    # https://docs.ansible.com/ansible/devel/reference_appendices/config.html#cfg-in-world-writable-dir
    - chmod 755 test/
    - cd test/
    - eval $(ssh-agent -s)
    - echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add - > /dev/null
    - ANSIBLE_HOST_KEY_CHECKING=False python3 -u ./ci-bootstrap.py --create-droplet --create-domain-records --run-ansible --ansible-param skip-tags=helmfile
  artifacts:
    paths:
    - ansible/rke.log
    - test/inventory.yml
    - test/group_vars/all.yml
    expire_in: 1 month
    when: always

install:
  stage: install-apps
  image: "${CI_REGISTRY_IMAGE}/bootstrap-ci"
  script:
    - cd test/
    - eval $(ssh-agent -s)
    - echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add - > /dev/null
    - ANSIBLE_HOST_KEY_CHECKING=False python3 -u ./ci-bootstrap.py --use-existing-inventory --run-ansible --ansible-param tags=helmfile --write-behave-config
  artifacts:
    paths:
    - test/behave/behave.ini
    expire_in: 1 month

testinfra:
  stage: test
  image: "${CI_REGISTRY_IMAGE}/bootstrap-ci"
  script:
    - eval $(ssh-agent -s)
    - echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add - > /dev/null
    - cd test/
    - py.test -v --connection=ansible --ansible-inventory=./inventory.yml --hosts='ansible://*'

terminate:
  stage: cleanup
  image: "${CI_REGISTRY_IMAGE}/bootstrap-ci"
  script:
    # Remove droplet after successful tests
    - cd test/
    # - python3 -c "import cosmos; cosmos.terminate_droplets_by_name(\"^ci-${CI_PIPELINE_ID}\$\")"
    - python3 -u ./ci-bootstrap.py --use-existing-inventory --terminate