Ansible - 如何在 lineinfile 模块中使用三元函数? [英] Ansible - how to use ternary function with lineinfile module?

查看:25
本文介绍了Ansible - 如何在 lineinfile 模块中使用三元函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果基于主机名不在该文件中,我们需要添加行.

We have requirement to add line if it is not in that file on basis of hostname.

意思是:

  • 如果主机名是 abc 然后行 "ABC" 转到 /etc/app.conf
  • 否则行 "XYZ" 转到 /etc/app.conf 文件.
  • if hostname is abc then line "ABC" goes to /etc/app.conf
  • otherwise line "XYZ" goes to /etc/app.conf file.

对此有什么更好的方法?
我们是使用 jinja2 模板还是在 playbook 中定义逻辑?
请对两者提出建议.

What would be better approach for this?
Do we use jinja2 template or define logic in playbook?
Please suggest on both.

推荐答案

这确实是一个偏好问题,以及您想在输出中登录什么.我想对于这样一个简单的任务,使用以下方法是最简单的:

It's really a matter of preference and what you want to log in the output. I guess for such an easy task using the following would be easiest:

- name: Ensure line ABC is configured for host ABC
  lineinfile:
    dest: /etc/abc.conf
    line: "ABC"
  when: inventory_hostname == "abc"

- name: Ensure line XYZ is configured for hosts other than ABC
  lineinfile:
    dest: /etc/abc.conf
    line: "XYZ"
  when: inventory_hostname != "abc"

或者在一项任务中使用三元过滤器:

Or use the ternary filter in one task:

- lineinfile:
    dest: /etc/abc.conf
    line: "{{ ( inventory_hostname == 'abc' ) | ternary ('ABC','XYZ') }}"

如果配置文件需要更多更改,或者您想确保配置完全符合您的要求,模板文件会更合适.

If the configuration file required more changes or you'd want to ensure the configuration is exactly as you want, a template file would be a better fit.

这篇关于Ansible - 如何在 lineinfile 模块中使用三元函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆