Reputation: 10910
Supose I have a server that is used to serve one static website (e.g. catpics.com
). Using Ansible, I have a base
role (used to set up firewall, time, user accounts, etc.), a letsencrypt
role (gets TLS certificates for a website), and a webserver
role (creates web root directory for a website).
Now I want to host another website (e.g. snakepics.com
) on this same server. With this new addition, the base
role still needs to be run once, but the letsencrypt
and webserver
roles now need to be run twice. At this point, I have two variable files:
vars/catpics.com
:
---
domain_name: catpics.com
# and other variables...
...
vars/snakepics.com
:
---
domain_name: snakepics.com
# and other variables...
...
Now that I have these two variable files, how do I run both the letsencrypt
and webserver
roles twice? (once using the vars/catpics.com
variables file, and once using the vars/snakepics.com
variables file)
Upvotes: 3
Views: 3315
Reputation: 1447
You can use different Host Groups to make it run for each type and achieve your goal. There are 2 types of variables for hosts.
inventory / hosts file.
[catpics]
catpics.com http_port=301
morecatpics.com http_port=80
[snakepics]
snakepics.com
moresnakepics.com
note the http_port=
is a Host Variable that is inline with the hostname declaration, seperated by a space
then in that same file, using the host:vars
naming format, you define the Group Variables which is for the whole group. So all snakepics
hosts will have those variables and all catpics
hosts will have theirs, but keeping their individual Host Variables ie. http_port=
[snakepics:vars]
FQDN= https://www.snake.com
VAR2= something2
[catpics:vars]
FQDN= https://www.cat.com
VAR2= something2
So great, now we've got the hosts setup, we can define what roles are run for each host. The same role will be run
- hosts: catpics
roles:
- letsencrypt
- webserver
- hosts: snakepics
roles:
- letsencrypt
- webserver
or in this case, hosts could simply look like - hosts: all
and it will get the vars corresponding to each type of host (snake and cat).
To call the variables is like any other ansible variable fetch {{ variable_name }}
when running a task in a role:
-name: Show how variables like this work
domain_name: "{{ FQDN }}"
some_other_task_variable: "{{VAR2}}"
For reference: Host and Group variables
Now that will solve your issue in the quickest way. The current best practice for using group and host variables uses a seperate file in the group_vars/*role_name_file*
directory to automatically fetch all the variables for each Host Group
Upvotes: 1