HiveBrain v1.2.0
Get Started
← Back to all entries
snippetMinor

how to set a variable from an ini file in ansible?

Submitted by: @import:stackexchange-devops··
0
Viewed 0 times
filesethowfromvariableansibleini

Problem

I would like to set a variable value in a playbook reading it from an ini file, possibly failing the play if the file is not found or the value is missing in the file.

I have found the ini lookup plugin to read values from ini files but it is not clear to me how to put that into a variable that I can reuse in other tasks without having to read it again.

I could think of something like:

- name: lookup variable from ini
  ini:
    name: myParam
    section: mySection
    file: /path_to/ini_file
  register: my_variable


But since ini is not a module this does not work.

Moreover, the ini file to be read from is located on the remote system, the ini plugin howhever, seems to look on the control host for it (from the warning "Unable to find '/path_to/ini_file' in expected paths).

Solution

Since the ini lookup plugin only reads files local to the controlling host, the remote file needs to be fetched locally before it can be read and set_fact has to be used to put its content into a variable, which results in the following:

- block:
  - name: "Retrieve remote ini file"
    fetch:
      src: /path_to/ini_file
      dest: /tmp/ansible
  - name: "Read and store my value"
    set_fact:
      my_variable: "{{ lookup( 'ini', 'myParam section=mySection file=/tmp/ansible/{{ inventory_hostname }}/path_to/ini_file' ) }}"


Then the parameter is available as variable and can be used further in the playbook

- debug:
    var: my_variable

Code Snippets

- block:
  - name: "Retrieve remote ini file"
    fetch:
      src: /path_to/ini_file
      dest: /tmp/ansible
  - name: "Read and store my value"
    set_fact:
      my_variable: "{{ lookup( 'ini', 'myParam section=mySection file=/tmp/ansible/{{ inventory_hostname }}/path_to/ini_file' ) }}"
- debug:
    var: my_variable

Context

StackExchange DevOps Q#11967, answer score: 7

Revisions (0)

No revisions yet.