I’m trying to add environment variables to a Linux machine using vars like below:
vars: app_env_variables: - key: APP_NAME value: App demo - key: APP_ENV value: demo - key: APP_KEY value: xxxxx
I’m using this task to add the variables to /etc/environment
.
- name: customize /etc/environment ansible.builtin.lineinfile: path: /etc/environment state: present regexp: "^{{ item.key }}=" line: "{{ item.key }}={{ item.value }}" with_items: "{{ app_env_variables }}"
But I’m getting the error below:
TASK [customize /etc/environment] ********************************************** fatal: [default]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'ansible.utils.unsafe_proxy.AnsibleUnsafeText object' has no attribute 'key'nnThe error appears to be in 'demo-playbook.yaml': line 423, column 7, but maynbe elsewhere in the file depending on the exact syntax problem.nnThe offending line appears to be:nn ssh-add /root/.ssh/id_rsan - name: customize /etc/environmentn ^ heren"}
What am I missing here?
Advertisement
Answer
The playbook below
shell> cat playbook.yml - hosts: localhost vars: app_env_variables: - key: APP_NAME value: App demo - key: APP_ENV value: demo - key: APP_KEY value: xxxxx tasks: - name: customize /tmp/environment ansible.builtin.lineinfile: create: true path: /tmp/environment state: present regexp: "^{{ item.key }}=" line: "{{ item.key }}={{ item.value }}" with_items: "{{ app_env_variables }}"
works as expected
shell> ansible-playbook playbook.yml PLAY [localhost] ***************************************************************************** TASK [customize /tmp/environment] ************************************************************ changed: [localhost] => (item={'key': 'APP_NAME', 'value': 'App demo'}) changed: [localhost] => (item={'key': 'APP_ENV', 'value': 'demo'}) changed: [localhost] => (item={'key': 'APP_KEY', 'value': 'xxxxx'}) PLAY RECAP *********************************************************************************** localhost : ok=1 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
and created the file
shell> cat /tmp/environment APP_NAME=App demo APP_ENV=demo APP_KEY=xxxxx
I only added the parameter create: true
to avoid error
msg: Destination /tmp/environment does not exist !