Reputation: 13036
Can a playbook load inventory list from variables? So I can easily customize the run based on chosen environment?
tasks:
- name: include environment config variables
include_vars:
file: "{{ item }}"
with_items:
- "../../environments/default.yml"
- "../../environments/{{ env_name }}.yml"
- name: set inventory
set_fact:
inventory.docker_host = " {{ env_docker_host }}"
Upvotes: 1
Views: 978
Reputation: 13036
As I'm in ansible 2.3 I can't use the add_host
module (see Jack's answer and add_host docs) and that would be a superior solution. Therefore, I'll use a different trick to augment an existing ansible inventory file, reload and use it.
[remotehosts]
- hosts: localhost
pre_tasks:
- name: include environment config variables
include_vars:
file: "{{ item }}"
with_items:
- "../environments/default.yml"
- "../environments/{{ env_name }}.yml"
- name: inventory facts
run_once: true
set_fact:
my_host: "{{ env_host_name }}"
- name: update inventory for env
local_action: lineinfile
path=hosts.inv
regexp={{ my_host }}
insertafter="[remotehosts]" line={{ my_host }}
- meta: refresh_inventory
- hosts: remotehosts
...
The pretasks process the environments yml with all the variable replacement etc and use that to populate hosts.inv
prior to reloading via refresh_inventory
Any tasks defined beneath - hosts: remotehosts
would execute on the remote host or hosts.
Upvotes: 1
Reputation: 6168
Yes. Use the add_host
module: https://docs.ansible.com/ansible/latest/modules/add_host_module.html
Upvotes: 1