0

I want to write hostname and ssh_host under a specific group from an inventory file to a file in my localhost. I have tried this:

my_role

  set_fact:
    hosts: "{{ hosts_list|default({}) | combine( {inventory_hostname: ansible_ssh_host} ) }}"
  when: "'my_group' in group_names"

Playbook

  become: no
  gather_facts: no
  roles:
    - my_role

But now if i try to write this to a file in another task, it will create a file for the hosts in inventory file.

Can you please suggest if there is a better way to create a file containing dictionary with inventory_hostname and ansible_ssh_host as key and value respectively, by running playbook on localhost.

jass
  • 343
  • 3
  • 15
  • FYI, "Ansible 2.0 has deprecated the “ssh” from ansible_ssh_user, ansible_ssh_host, and ansible_ssh_port to become ansible_user, ansible_host, and ansible_port. If you are using a version of Ansible prior to 2.0, you should continue using the older style variables (ansible_ssh_*). These shorter variables are ignored, without warning, in older versions of Ansible." See [Inventory](https://docs.ansible.com/ansible/2.3/intro_inventory.html#hosts-and-groups). – Vladimir Botka Feb 17 '19 at 12:23

2 Answers2

1

An option would be to use lineinfile and delegate_to localhost.

- hosts: test_01
  tasks:
    - set_fact:
        my_inventory_hostname: "{{ ansible_host }}"
    - tempfile:
      delegate_to: localhost
      register: result
    - lineinfile:
        path: "{{ result.path }}"
        line: "inventory_hostname: {{ my_inventory_hostname }}"
      delegate_to: localhost
    - debug:
        msg: "inventory_hostname: {{ ansible_host }}
              stored in {{ result.path }}"

Note: There is no need to quote the conditions. Conditions are expanded by default.

when: my_group in group_names
Vladimir Botka
  • 58,131
  • 4
  • 32
  • 63
  • Thanks a lot, this works great. Also, I am trying to get ansible_host belonging to specific group in inventory, by adding: ```when: "my_group' in group_names" ``` under -set_fact, but that gives me error for hosts which do not belong to the group. Is there a way to skip undefined variables to be written to lineinfile – jass Feb 18 '19 at 10:47
0

Thanks a lot for your answer@Vladimir Botka

I came up with another requirement to write the hosts belonging to a certain group to a file, below code can help with that (adding to @Vladimir's solution).

- hosts: all
  become: no
  gather_facts: no
  tasks:
    - set_fact:
        my_inventory_hostname: "{{ ansible_host }}"
   - lineinfile:
        path: temp/hosts
        line: "inventory_hostname: {{ my_inventory_hostname }}"
      when: inventory_hostname in groups['my_group']
      delegate_to: localhost
    - debug:
        msg: "inventory_hostname: {{ ansible_host }}"
jass
  • 343
  • 3
  • 15