繁体   English   中英

如何在Ansible Playbook中使用文件行作为变量?

[英]How to use lines of a file as a variables in ansible playbook?

我正在寻找一种使用ansible剧本中的文件行作为变量的方法。 我有一本剧本,使用的变量数量大约为15-20个变量。 因此,对于我来说,在运行时传递这15个变量非常困难。 同样,我将创建一个文件,例如:

**** variables.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 }}"

希望能帮助到你

有几种方法可以执行此操作,但是我将设置Tomcat角色并将vars设置在tomcat_role/default/main.yml 如果您需要更改Tomcat配置,则可以从一个地方轻松完成。

tomcat_role / default / main.yml示例:

---
tomcat_user: tomcat
tomcat_group: tomcat
tomcat_path: "/path/to/tomcat"

当我想调用Tomcat配置时,可以在游戏中这样声明它:

- name: Set up Tomcat
  hosts: your_host_here
  become: yes
  roles:
    - tomcat_role

然后,我可以在剧本中从该角色调用vars,如下所示:

  user: {{tomcat_user}}
  path: {{tomcat_path}}

希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM