0

I'm new in ansible, but I've been trying to arrange properly my inventory (100 servers give or take) by environment, something like:

[dev]
server1
server2

[qa]
server3
server4

[prod]
server5
server6

There's nothing on the name of these servers to identify what environment these belong to: (dev/qa/prod) but to connect to each one of these and retrieve a file /foo/var/file present in each server that shows the environment of the server

so far, I've created this

---
- hosts: ALL
  gather_facts: no
  tasks:
     - name: return environment to registered var
       shell: 'cat /foo/var/file'
       register: environment
     
     - template:
          src: template.csv.j2
          dest: list.csv
       delegate_to: localhost
       with_items: {{ environment }}

template is:

{% for x in environment %}
['x']
{{ host }}
{% endfor %}

So I'm just trying to retrieve these values to be able to create some sort of inventory with these

what would be the best way to create this inventory?

1
  • Welcome to SE! See mcve and update the question. Make it complete, i.e. example of /foo/var/file is missing and an example of expected result is missing. Make it minimal. Commented Oct 2, 2020 at 20:35

1 Answer 1

0

Use ansible_play_hosts and hostvars to iterate the registered values. For example, the inventory, playbook, and template below

shell> cat hosts
test_01
test_02
test_03
shell> cat pb.yml
- hosts: all
  tasks:
    - command: uptime
      register: environment
    - template:
        src: template.csv.j2
        dest: list.csv
      delegate_to: localhost
shell> cat template.csv.j2
{% for host in ansible_play_hosts %}
{{ host }}, {{ hostvars[host]['environment']['stdout'] }}
{% endfor %}

give

shell> cat list.csv
test_01, 12:02AM  up 62 days,  3:21, 2 users, load averages: 0.51, 0.65, 0.40
test_02, 12:02AM  up 62 days,  3:21, 1 user, load averages: 0.51, 0.65, 0.40
test_03, 10:02PM  up 62 days,  3:21, 1 user, load averages: 0.55, 0.65, 0.41

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .