Ansible – Slow Converting Host Vars to Env File with Ansible

ansible

I have the following task in ansible:

- name: Set env vars
  lineinfile:
    path: "~/.env"
    mode: 0600
    create: yes
    line: "{{ item.key|upper }}=\"{{ item.value }}\""
    regexp: "^{{ item.key|upper }}="
  loop: "{{ env_file |dict2items }}"

It's creating the .env file line-by-line but it is REALLY slow. Is there a better way?

The .yml file looks like:

env_file:
  key1: "value1"
  key2: "value2"

The resulting file has the format:

KEY1="value1"
KEY2="value2"

Each line takes about 20 seconds to process and it really adds up.

Best Answer

Try using the template module and writing a Jinja2 file. It tends to be faster than lineinfile when dealing with loops.