首页 > 解决方案 > 如何在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

因此,如果有任何方法可以调用行号来传递剧本中变量的值,那将非常有帮助。

提前致谢!

标签: ansibleansible-2.xansible-inventory

解决方案


我建议使用结构化的方式来管理变量,例如:

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

希望能帮助到你


推荐阅读