Ansible-如何在lineinfile模块中使用三元函数? [英] Ansible - how to use ternary function with lineinfile module?
问题描述
如果主机名中没有该行,我们需要添加行.
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模板还是在剧本中定义逻辑?
请同时提出建议.
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屋!