如何使用Ansible添加Linux环境变量

How to use Ansible to add Linux environment variables

我正在尝试使用如下变量将环境变量添加到 Linux 机器:

vars:
    app_env_variables:
      - key: APP_NAME
        value: App demo
      - key: APP_ENV
        value: demo
      - key: APP_KEY
        value: xxxxx

我正在使用此任务将变量添加到 /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 }}"

但我收到以下错误:

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"}

我在这里错过了什么?

'demo-playbook.yaml':第 423 行,第 7 列,但 may\nbe 位于文件的其他位置,具体取决于确切的语法问题

我认为您的 .yaml 文件中存在一些语法错误

下面的剧本

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 }}"

按预期工作

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   

并创建了文件

shell> cat /tmp/environment 
APP_NAME=App demo
APP_ENV=demo
APP_KEY=xxxxx

为了避免出错,我只加了参数create: true

msg: Destination /tmp/environment does not exist !