ansible設定環境變數

anyux發表於2024-08-15

透過~/.profile檔案設定

env01.yaml

---
  - hosts: ubuntu
    tasks:
    # 設定環境變數
    - name: 設定環境變數
      lineinfile:
          dest: ~/.profile
          regexp: ^export ENV_KEY=
          line: export ENV_KEY=env_value

    - name: 獲取環境變數值 #指定bash shell,預設是使用/bin/sh,/bin/sh無法執行source命令
      shell: bash -c 'source ~/.profile && echo $ENV_KEY'
      register: env_key

    - name: 列印環境變數,inventory_hostname 是當前主機在inventory清單檔案中的名稱,預設情況下會在playbook中顯示出來,一般為ip,也可以自定義名稱
      debug:
        msg: "this linux os {{ inventory_hostname }} env_key is {{ env_key.stdout }}"
    - name: 列印環境變數 #ansible_env 變數不包含lineinfile模組設定的變數,不知道為什麼
      debug:
        msg: "{{ ansible_env }}"

透過playbooke檔案硬編碼設定

env02.yaml

---
  - hosts: ubuntu
    tasks:
    - name: 設定環境變數
      get_url:
        url: https://files.pythonhosted.org/packages/fa/de/02b54f42487e3d3c6efb3f89428677074ca7bf43aae402517bc7cca949f3/PyYAML-6.0.2-cp313-cp313-win_amd64.whl
        dest: /tmp
      environment:
        http_proxy: http://1.1.1.1:80/
        https_proxy: https://1.1.1.1:443/

透過playbooke檔案變數設定

env02-1.yaml

---
  - hosts: ubuntu
    vars:
      #為一個下載任務設定http代理
      vars_proxy:
        http_proxy: "http://1.1.1.1:80/"
        https_proxy: "https://1.1.1.1:443/"
    tasks:
     - name: debug環境變數
       debug:
         var: vars_proxy
     - name: 設定環境變數
       get_url:
         url: https://files.pythonhosted.org/packages/fa/de/02b54f42487e3d3c6efb3f89428677074ca7bf43aae402517bc7cca949f3/PyYAML-6.0.2-cp313-cp313-win_amd64.whl
         dest: /tmp
       environment: "{{ vars_proxy }}"

透過proxy_state狀態控制變數狀態

env03.yaml

---
  - hosts: ubuntu
    vars:
      proxy_state: present
    tasks:
      - name: Configure the proxy.
        lineinfile:
          dest: /etc/environment
          regexp: "{{ item.regexp }}"
          line: "{{ item.line }}"
          state: "{{ proxy_state }}"
        with_items:
          - { regexp: "^http_proxy=", line: "http_proxy=http://1.1.1.1:80/" }
          - { regexp: "^https_proxy=", line: "https_proxy=https://1.1.1.1:443/" }
          - { regexp: "^ftp_proxy=", line: "ftp_proxy=http://1.1.1.1:80/" }

在/etc/environment檔案裡配置的變數,再次登入時,會載入到env變數中,可直接透過echo $http_proxy列印出來

ansible ubuntu -m shell -a 'echo $http_proxy '
107.151.199.209 | CHANGED | rc=0 >>
http://1.1.1.1:80/

相關文章