Post

Ansible deployment with Gitlab CI

Making an Ansible deployment via Gitlab CI is easy but also flexible enough to parameterize the deployment.

Requirements

  • Gitlab Project with CI enabled
  • Gitlab Runner with Ansible, ansible-lint installed
  • CI Trigger added to the Ansible project

Ansible

I will use the alternative directory layout from the ansible best practices:

1
2
3
4
5
6
7
8
9
10
11
12
# inventory
staging/
  hosts
production/
  hosts

playbooks/
  vcs.yml
roles/
  common/
# top level playbook
site.yml

Gitlab

The .gitlab-ci.yml in the Ansible git repository/project:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
---
variables:
  # top level playbook
  TLP: 'site.yml'

stages:
  - test
  - deploy

## STAGING
test:
  stage: test
  script:
    - "ansible-lint $TLP"
  environment:
    name: staging

# run top level playbook
deploy_to_stag:
  stage: deploy
  script:
    - "ansible-playbook -b -D -i staging $TLP"
  environment:
    name: staging
  only:
    - master
  when: manual

# run via api call
deploy_trigger_to_stag:
  stage: deploy
  script:
    - "ansible-playbook -b -D -i staging playbooks/$PLAYBOOK.yml -l $HOSTS"
  environment:
    name: staging
  only:
    - triggers

## PROD
deploy_to_prod:
  stage: deploy
  script:
    - "ansible-playbook -b -D -i production $TLP"
  environment:
    name: production
  only:
    - master
  when: manual

Jobs

test

Everything goes through ansible-lint first.

deploy_to_stag

This is a manual job which starts an Ansible run through all hosts/playbooks for staging env. No other branches then master go through this job.

deploy_trigger_to_stag

This job gets triggered via an API call to Gitlab. 2 variables $PLAYBOOK and $HOSTS are available to limit the Ansible run. It is of course also possible to add Ansible tags as variable to have even more flexibility. All branches including master are allowed.

deploy_to_prod

The same as job deploy_to_stag but for production environment.

Start the pipeline to run Ansible deployment

With following API call we start the deploy_trigger_to_stag job.

You can either use Postman or just a simple curl command.

1
2
curl --request POST --form token=<YOUR_TOKEN> --form ref=master \
--form "variables[PLAYBOOK]=vcs" --form "variables[HOSTS]=srv-vcs-01" https://gitlab.test.at/api/v3/projects/<PROJECT_ID>/trigger/builds

It will execute the playbooks/vcs.yml for host srv-vcs-01 which is configured in the staging/hosts file.

This post is licensed under CC BY 4.0 by the author.