0

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

1

You need to use set_fact when setting a variable (instead of register the outcome of a task):

- name: Set myParam from ini
  set_fact:
    myParam: "{{ lookup('ini', 'section=mySection, file=/path_to/ini_file') }}"

In the lookup:

  • ini specifies what lookup plugin we are using
  • section and file are arguments passed to the lookup, according to its documentation
| improve this answer | |
  • The ini lookup seems to look for the ini_file only on the control host, but I want to look up a file on the remote host giving its full path, would that be possible? – a1an Jul 6 at 12:34
  • This may be possible if you use the delegate_to keyword - this should run the task on the delegated host, where the file is present. Else, you can slurp the file into a variable and read it from memory. – Bruce Becker Jul 6 at 12:55
  • As far as I understood, the delegate_to should be used the other way around (to run tasks on the local/controller machine or others) but the default for a task should be to run on the target controlled host so something seems not to be working as I would expect. is slurping the file compatible with the ini lookup (which expects a file)? – a1an Jul 6 at 13:35
1

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
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.