大网数据广告活动
服务器运维问答

Get current hostname and push it into conf file with ansible

· 52CE 我爱测

I'm working into an ansible playbook to get the current hostname of a server and then set it into a configuration file. I cannot figure it out how can I push the shell output using the lineinfile module. - name: Get hostname shel…

问题原文

原帖链接 · pedrocalixto · CC BY-SA 3.0

I'm working into an ansible playbook to get the current hostname of a server and then set it into a configuration file. I cannot figure it out how can I push the shell output using the lineinfile module.

  - name: Get hostname
    shell: echo $HOSTNAME
    register: result

  - name: Set hostname on conf file
    lineinfile: dest=/etc/teste/linux/zabbix_agentd.conf regexp="^Hostname=.*" insertafter="^# Hostname=" line=Hostname=????

已采纳解答

原帖链接 · udondan · CC BY-SA 3.0

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 }}

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2016-03-01)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。