如何為 ansible-playbook 添加值而不是覆蓋它?

如何為 ansible-playbook 添加值而不是覆蓋它?

截至今天,我具有以下角色,該角色模擬產品的基本安裝:

- name: Install Server.msi primary_appserver
  ansible.windows.win_package:
    path: C:\product.msi
    log_path: C:\InstallProduct.log
    arguments:
     ADDLOCAL=DB,Agent
    state: present
  become: true
  become_method: runas
  vars:
    ansible_become_user: "{{ ansible_user }}"
    ansible_become_password: "{{ ansible_password }}"
  when: "'primary_appservers' in group_names"

我想模擬“高級”安裝,我在安裝精靈中選擇附加功能

在安裝精靈中,我可以選擇一個或多個功能,意思是ADDLOCAL參數可以是:ADDLOCAL=DB,Agent- 這是基本的 OR ADDLOCAL=DB,Agent,Feature_AORADDLOCAL=DB,Agent,Feature_A,Feature_B

事情對我來說變得複雜,因為Feature_C例如需要額外的參數列表來安裝它,例如:RABBIT_LOCAL_PORT, RABBIT_QUEUE_NAME, RABBIT_TTL...

vars在 Ansible 或Jenkins 中使用extraVars- 覆寫 playbook\role 中的值

有沒有辦法將該值新增至 playbook\role 中的現有值中,例如當我選擇安裝Feature_a和\或Feature_b- ADDLOCAL 角色中的值將變更為ADDLOCAL=DB,Agent,Feature_A,Feature_B?或者在第二種情況下,當我添加時Feature_CADDLOCAL角色中的值將更改為ADDLOCAL=DB,Agent,Feature_C並且arguments鍵將另外包含:RABBIT_LOCAL_PORTRABBIT_QUEUE_NAMERABBIT_TTL參數?

答案1

有兩個選項可以實現所需的行為:

將參數變數視為列表

生成參數時將它們視為結構(在我的範例中為列表映射)。您可以根據您的用例新增或刪除任何功能/參數。但這種方法增加了一些複雜性:

- name: set default arguments
  set_fact:
    arguments_map:
      ADDLOCAL:
      - feature1
      - feature2
- name: set feature3
  set_fact:
    arguments_map: "{{ arguments_map | combine({'ADDLOCAL':['feature3']}, recursive=True, list_merge='append') }}"
- name: set feature4
  set_fact:
    arguments_map: "{{ arguments_map | combine({'ADDLOCAL':['feature4'], 'RABBIT_LOCAL_PORT':5672, 'RABBIT_QUEUE_NAME':'test'}, recursive=True, list_merge='append') }}"
- name: generate arguments string
  set_fact:
    arguments: "{% for argument in arguments_map | dict2items %}{{ argument['key'] }}={{ (argument['value'] | join(',')) if (argument['value'] | type_debug == 'list') else (argument['value']) }} {% endfor %}"
- debug:
    var: arguments

這會產生以下字串:

ADDLOCAL=feature1,feature2,feature3,feature4 RABBIT_LOCAL_PORT=5672 RABBIT_QUEUE_NAME=test 

您可以將所有預定義集移至 var 檔案以提高可讀性。

逐漸連接到參數字串

更直接但不太靈活:

- name: set default arguments
  set_fact:
    arguments: 'ADDLOCAL=DB,Agent'
- name: set feature1
  set_fact:
    arguments: "{{ arguments + ',feature1' }}"
- name: set feature2
  set_fact:
    arguments: "{{ arguments + ',feature2' }}"
- name: set additional arguments
  set_fact:
    arguments: "{{ arguments + ' RABBIT_LOCAL_PORT=5672 RABBIT_QUEUE_NAME=test' }}"
  when: arguments is search('feature2')
- debug:
    var: arguments

產生以下字串:

ADDLOCAL=DB,Agent,feature1,feature2 RABBIT_LOCAL_PORT=5672 RABBIT_QUEUE_NAME=test

相關內容