Get current hostname and push it into conf file with ansible
Solution 1:
In general, to look what's inside a variable you can use the debug
module.
- debug:
var: result
This should show you an object and its properties which include stdout
. That is the complete result of the previous command. So to use the output of the first task you would use result.stdout
.
To use any variable you would use Jinja2 expressions: {{ whatever }}
. So your task could look like this:
- name: Set hostname on conf file
lineinfile:
dest: /etc/teste/linux/zabbix_agentd.conf
regexp: ^Hostname=.*
insertafter: ^# Hostname=
line: Hostname={{ result.stdout }}
So much for theory, but here comes the real answer. Don't do it like that. Of course Ansible already knows the hostname.
The hostname as defined in your inventory would be {{ inventory_hostname }}
. The hostname as reported by the server is {{ ansible_hostname }}
. Additionally there is {{ ansible_fqdn }}
. So just use any of these instead of running an additional task:
- name: Set hostname on conf file
lineinfile:
dest: /etc/teste/linux/zabbix_agentd.conf
regexp: ^Hostname=.*
insertafter: ^# Hostname=
line: Hostname={{ ansible_hostname }}
Solution 2:
You should pass variables in the command line.
First, register the variable
---
- hosts: 127.0.0.1
connection: local
vars:
- person: John Snow
- filename: v1.j2
vars_files:
- vars.yml
tasks:
- name: Who I am?
action: command /usr/bin/whoami
register: myname
- name: Run jpprog.sh
action: command ./jpprog.sh
register: v
- name: Populate template
action: template src={{filename}} dest=/tmp/out
This playbook runs two commands: the first stores its output in a variable called myname, and the second in a variable v. The result of whoami is a single string which is made available to the template as variablename.stdout. The result of jpprog.sh is a JSON object represented as a string:
{
"number": 18,
"name": "john"
}
The template follows:
-> I am {{ myname.stdout }}
{% set t = v.stdout|from_json %}
JSON struct T: {{ t }}
name = {{ t.name }}
number = {{ t['number'] }}
and the output is:
-> I am jpm
JSON struct T: {u'number': 18, u'name': u'john'}
name = john
number = 18
Source:Jan-Piet Mens web site.