How do I make .gitlab-ci.yml execute different ansible playbooks in different folders/subfolders?

Viewed 287

I just started learning about NetDevOps.

All the examples containing demos of GitLAb + Ansible show how to execute "deploy.yml" from Ansible from the .gitlab-ci.yml.

However, when I see a general network equipment based Ansible tutorial the author executes different Ansible cookbook .yml files, for example sites.yml from the root, deploy.yml from another subfolder, interfaces.yml from another subfolder.

Can someone give me an example of how I would execute the different Ansible playbook .yml files on demand?

I.e. - When it detects changes in .yml in a folder, run that .yml file under that folder?

2 Answers

lets say you have an ansible repo and a .gitlab-ci.yml in the root of it.

.gitlab-ci.yml
ansible/cookbook1
ansible/cookbook2

For each cookbook you could create a Gitlab job

execute_cookbook1:
 script: 
  - ...ANSIBLE COMMANDS...
 ...
 only:
     changes: 
       - ansible/cookbook1/**/*.yml
    
execute_cookbook2:
 script: 
  - ...ANSIBLE COMMANDS...
 ...
 only:
     changes: 
       - ansible/cookbook2/**/*.yml

This way when you push your code to ansible repo, Gitlab will detect which cookbook changed. And run the according job

You can use in your GitLab job complex rules like if, changes, and exists, in the same rule.
The rule evaluates to true only when all included keywords evaluate to true.

For example:

docker build:
 script: docker build -t my-image:$CI_COMMIT_REF_SLUG .
 rules:
   - if: '$VAR == "string value"'
     changes:  # Include the job and set to when:manual if any of the follow paths match a modified file.
       - Dockerfile
       - docker/scripts/*
     when: manual
     allow_failure: true

In your case, keep when: manual and changes: *.yml in order to trigger the job manually, if yml Ansible playbook are changed.

Related