I have a requirement to setup environment on multiple hosts. I need to read variables from a file and I want them to execute on a particular hosts or a set of hosts. I am unable to make out how can I use single task to achieve this?
Assuming I have a file which contains variables in a following format:
container_name: java1
container_hostname: java-mc1
script_location: /tmp
execute_on_hosts: host1,host2,host3
container_name: java2
container_hostname: java-mc2
script_location: /tmp
execute_on_hosts: host1
I want my task to read from this file and execute the task on specified hosts only by matching hostname in hosts section (provided in playbook).
You should read the Ansible Variables docs. Whilst you can probably get something to work, you are not really using Ansible the way it was intended.
Ansible fundamentally is built around the concept of 'plays'. Each play represents one or more tasks, that should be targetted at a host or group of hosts. Those plays are then packaged up into a 'playbook'. Ansible provides methods to organise variables in the 'Inventory'. A common approach would be to do something like:
/some/ansible/dir/hosts
[mc1_hosts]
host1
host2
host3
[mc2_hosts]
host1
/some/ansible/dir/group_vars/mc1_hosts
---
mc1_container_data:
container_name: java1
container_hostname: java-mc1
script_location: /tmp
/some/ansible/dir/group_vars/mc2_hosts
---
mc2_container_data:
container_name: java2
container_hostname: java-mc2
script_location: /tmp
/some/ansible/dir/playbook.yml
---
- hosts: mc1_hosts
tasks:
- name: Display variables
debug:
msg: "{{ mc1_container_data }}"
- name: Display container_name
msg: "{{ mc1_container_data.container_name }}"
- hosts: mc2_hosts
tasks:
- name: Display variables
debug:
msg: "{{ mc2_container_data }}"
- name: Display container_name
msg: "{{ mc2_container_data.container_name }}"
And finally ansible-playbook playbook.yml
to run those tasks.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.