Home > Software engineering >  How to use Ansible to add Linux environment variables
How to use Ansible to add Linux environment variables

Time:04-22

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'\n\nThe error appears to be in 'demo-playbook.yaml': line 423, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n        ssh-add /root/.ssh/id_rsa\n    - name: customize /etc/environment\n      ^ here\n"}

What am I missing here?

CodePudding user response:

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 !

CodePudding user response:

'demo-playbook.yaml': line 423, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem

i think your having some syntax error in your .yaml file

  • Related