Control role inclusion in Ansible

This commit is contained in:
Sam A. 2024-01-02 19:28:06 +01:00
parent f4249ea484
commit 0ba0a6d1c9
Signed by: samsapti
GPG Key ID: CBBBE7371E81C4EA
5 changed files with 33 additions and 68 deletions

View File

@ -2,4 +2,4 @@
# code: language=ansible
---
fqdn: sapt-labx-ctl01.infra.servers.sapti.me
ansible_host: 192.168.23.8
ansible_host: 192.168.17.8

View File

@ -1,5 +0,0 @@
# vim: ft=yaml.ansible
# code: language=ansible
---
fqdn: sapt-labx-pve01.infra.servers.sapti.me
ansible_host: 192.168.23.3

View File

@ -22,11 +22,8 @@ sapt-labr-prx01
# [monitor_shrd]
# sapt-labr-mon01
[proxmox_infra]
sapt-labx-pve01
[control_infra]
sapt-labx-ctl01
# [control_infra]
# sapt-labx-ctl01
[production:children]
app_prod
@ -65,6 +62,5 @@ production
staging
shared
[infrastructure:children]
proxmox_infra
control_infra
# [infrastructure:children]
# control_infra

View File

@ -1,9 +1,34 @@
# vim: ft=yaml.ansible
# code: language=ansible
---
- name: Run playbook against ${HOSTS}
hosts: ${HOSTS}
- name: Run playbook
hosts: all
remote_user: ansible
become: true
gather_facts: true
roles: ${ROLES}
tasks:
- name: Include role 'virt-common'
ansible.builtin.include_role:
name: virt-common
when: hostname in groups['virtualservers']
- name: Include role 'docker'
ansible.builtin.include_role:
name: docker
when: hostname in groups['appservers'] or
hostname in groups['proxyservers']
- name: Include role 'apps'
ansible.builtin.include_role:
name: apps
when: hostname in groups['appservers']
- name: Include role 'postgresql'
ansible.builtin.include_role:
name: postgresql
when: hostname in groups['dbservers']
- name: Include role 'proxy'
ansible.builtin.include_role:
name: proxy
when: hostname in groups['proxyservers']

View File

@ -1,51 +0,0 @@
#!/usr/bin/env bash
HOSTS="$1"
ROLE_LIST=( "virt-common" "docker" "apps" "postgresql" "proxy" )
# Dynamically remove roles that are incompatible with a host
OLDIFS="$IFS"
IFS=:
for target in $HOSTS; do
case $target in
*app*)
ROLE_LIST=( "${ROLE_LIST[@]/postgresql}" )
ROLE_LIST=( "${ROLE_LIST[@]/proxy}" )
;;
*db*)
ROLE_LIST=( "${ROLE_LIST[@]/docker}" )
ROLE_LIST=( "${ROLE_LIST[@]/apps}" )
ROLE_LIST=( "${ROLE_LIST[@]/proxy}" )
;;
*mda*|media*)
ROLE_LIST=( "${ROLE_LIST[@]/apps}" )
ROLE_LIST=( "${ROLE_LIST[@]/postgresql}" )
ROLE_LIST=( "${ROLE_LIST[@]/proxy}" )
;;
*prx*|proxy*)
ROLE_LIST=( "${ROLE_LIST[@]/apps}" )
ROLE_LIST=( "${ROLE_LIST[@]/postgresql}" )
;;
*)
ROLE_LIST=( "virt-common" ) ;;
esac
done
IFS="$OLDIFS"
# Transform role list into JSON array
ROLES="$(jq -c -M -n '$ARGS.positional | map(select(length > 0))' --args -- "${ROLE_LIST[@]}")"
echo "Running roles $ROLES against $HOSTS"
# Export vars for envsubst
export HOSTS
export ROLES
# Execution of temporary envsubst'ed playbook
PLAYBOOK="playbook-$(tr -dc A-Za-z < /dev/urandom | head -c 10).yml"
envsubst < site.yml > "$PLAYBOOK"
ansible-playbook "$PLAYBOOK"
STATUS=$?
# Clean up temporary playbook
rm -f "$PLAYBOOK"
exit $STATUS