How to set host1
in to group_vars database
from playbook has run?
Thanks
The short answer is: ansible.builtin.add_host
But, it's good to know that this change won't affect the current play. For example, given the inventory
shell> cat hosts
[database]
host2
host3
and the group_vars
shell> cat group_vars/database/main.yml
test_var: database
The below play
- name: Play 1
hosts: database
tasks:
- debug:
var: groups
run_once: true
- debug:
var: test_var
gives as expected (abridged)
TASK [debug] ***
ok: [host2] =>
groups:
all:
- host2
- host3
database:
- host2
- host3
ungrouped: []
TASK [debug] ***
ok: [host2] =>
test_var: database
ok: [host3] =>
test_var: database
If you add the host host1 to the group database
- add_host:
name: host1
groups: database
the added host will be reported in the group immediately
- debug:
var: groups
run_once: true
gives (abridged)
groups:
all:
- host1
- host2
- host3
database:
- host2
- host3
- host1
ungrouped: []
But, the added host won't be included in the execution of the play
- debug:
var: test_var
gives (abridged) the same result as before
ok: [host2] =>
test_var: database
ok: [host3] =>
test_var: database
Refreshing the inventory doesn't help
- meta: refresh_inventory
- debug:
var: test_var
still gives the same result
ok: [host2] =>
test_var: database
ok: [host3] =>
test_var: database
You have to start a new play to include the new host in the group
- name: Play 2
hosts: database
tasks:
- debug:
var: test_var
gives
ok: [host2] =>
test_var: database
ok: [host3] =>
test_var: database
ok: [host1] =>
test_var: database
The addition of the host to the group is not permanent. Only the current playbook is affected.
Example of a complete playbook for testing.
- name: Play 1
hosts: database
tasks:
- debug:
var: groups
run_once: true
- debug:
var: test_var
- add_host:
name: host1
groups: database
- debug:
var: groups
run_once: true
- debug:
var: test_var
- meta: refresh_inventory
- debug:
var: test_var
- name: Play 2
hosts: database
tasks:
- debug:
var: test_var