简体   繁体   中英

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

I am looking for a way that uses lines of file as variable in ansible playbook. I have a playbook which uses number of variables approximate 15-20 variables. So it is very difficult for me to pass these 15 variables during runtime. For the same I will create one file like:

**** variables.txt *****

Tomcat8
192.168.0.67
8080
8081
8082
8084

Playbook Sample:

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

So if there is any way where I can call the line number to pass the value of the variable in playbook it will be very helpful.

Thanks in advance!

I recommend using a structured way of managing variables like:

tomcat:
  p_port: 8080 
  s_port: 8081
  ip  : 192.168.0.1

Then read the variables like

  - 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

After that, use like:

- name: My Tomcat install
  mymodule:
    myaction1: "{{ tomcat.p_port }}"
    myaction2: "{{ tomcat.s_port }}"
    myaction3: "{{ tomcat.ip }}"

Hope it helps

There are a few ways of doing it, but I would set up a Tomcat role and set the vars in tomcat_role/default/main.yml . If you ever need to change your Tomcat config it's done neatly from one place.

tomcat_role/default/main.yml example:

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

When I want to call the Tomcat config I would declare it in my play like this:

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

I can then call the vars from that role in my play like this:

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

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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