Ansible syntax for outputing information

Hello,

I have ansible code that works quite well - logs on to the server I want and so forth.

The way it is designed, system asks for your username and password, then logs into the host.
Using ansible code, I would like to gather information after I login and then output the results.

The information that I would like to gather:
hostname
ip address

So I would like output that says:

<>–> <>

I would only like this information to be outputted to screen. Nothing else.

I am close as I have the following:


  • name: “Output test”
    shell: |
    ip=$(ifconfig)
    hostn=$(hostname)
    echo “$hostn → $ip”
    register: out
  • debug:
    msg: hostn ip

The output is not exactly in the format I am looking for. It is messy

I thought maybe msg parameter might work, but have not been able to figure out appropriate syntax

Can anyone guide me so I can just output

hostname —> IP address

Thanks!

Mark

Welcome to the Ansible forum, @Budman .

Is it messy because $ip has extra content, or because the output of an Ansible job is an Ansible job log? I’m not sure what benefit you get by involving Ansible in the process. It seems like it would be simpler to say

$ ssh yourhost 'printf "%s --> %s\n" "$(hostname)" "$(ifconfig)"'

If the point is to make the output of Ansible look like something other than an Ansible job log, then I think a re-evaluation of the technique is in order.

1 Like

You might want to look at a callback plugin, i’m not sure an existing one matches exactly what you want, but you can probably modify them to do so.

https://docs.ansible.com/ansible/latest/plugins/callback.html
https://docs.ansible.com/ansible/latest/collections/index_callback.html

1 Like

It is unclear to me why you are using shell at all? Isn’t this information available as an Ansible Fact, so you should be able to use those to echo (debug-msg) however you want?

https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_vars_facts.html

2 Likes

As @jrglynn2 suggested, take advantage of the facts that Ansible gathers by default.

The following will display the short hostname, fully qualified domain name, as well as the default ipv4 and ipv6 addresses. It’s possible for IPv4/IPv6 to be undefined, so this snippet sets a default message instead of failing the debug task whenever that’s the case.

---
- hosts: all
  gather_facts: true
  tasks:
    - name: show desired facts
      debug:
        msg:
          - "{{ ansible_hostname }}"
          - "{{ ansible_fqdn }}"
          - "{{ ansible_default_ipv4.address | default('No IPv4 address found') }}"
          - "{{ ansible_default_ipv6.address | default('No IPv6 address found') }}"

Based on what it seems you want in your original post, msg: "{{ ansible_fqdn | default(ansible_hostname) }} --> {{ ansible_default_ipv4.address }}" is probably what you’re looking for.

1 Like