ansible - 如何在ansible playbook中使用文件的行作为变量?
问题描述
我正在寻找一种在 ansible playbook 中使用文件行作为变量的方法。我有一本使用大约 15-20 个变量的变量数的剧本。所以我很难在运行时传递这 15 个变量。同样,我将创建一个文件,例如:
**** 变量.txt *****
Tomcat8
192.168.0.67
8080
8081
8082
8084
剧本样本:
---
- hosts: tomcat_server
vars:
tomcat_instances:
- name: foo
user: tomcatfoo
group: tomcatfoo
path: /srv/tomcatfoo
home: /home/tomcatfoo
service_name: foo@tomcat
service_file: foo@.service
port_ajp: 18009
port_connector: 18080
port_redirect: 18443
port_shutdown: 18005
因此,如果有任何方法可以调用行号来传递剧本中变量的值,那将非常有帮助。
提前致谢!
解决方案
我建议使用结构化的方式来管理变量,例如:
tomcat:
p_port: 8080
s_port: 8081
ip : 192.168.0.1
然后读取变量,如
- name: Read all variables
block:
- name: Get All Variables
stat:
path: "{{item}}"
with_fileglob:
- "/myansiblehome/vars/common/tomcat1.yml"
- "/myansiblehome/vars/common/tomcat2.yml"
register: _variables_stat
- name: Include Variables when found
include_vars : "{{item.stat.path}}"
when : item.stat.exists
with_items : "{{_variables_stat.results}}"
no_log : true
delegate_to: localhost
become: false
之后,像这样使用:
- name: My Tomcat install
mymodule:
myaction1: "{{ tomcat.p_port }}"
myaction2: "{{ tomcat.s_port }}"
myaction3: "{{ tomcat.ip }}"
希望能帮助到你
推荐阅读
- arrays - Adding Property to Documents Where Target Property is an Array Not Working as Expected
- c# - Calling a private function from another class in C#
- mysql - MySQL - 用逗号将两列合并为一列
- sql-server - 如果每条记录有多个单词,则选择不同的单词列表
- python - 从 Python 中的分隔字符串中删除元素
- mingw - 如何将 libcurl 与 MinGW 一起使用?
- python - 避免在 Windows 路径中使用双反斜杠
- python - pandoc过滤器隐藏某个类的div
- api - identityserver4 保护公共 api
- r - 如何在 rmarkdown 中缩进 word 文档输出?