如何向 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- 这是基本功能或ADDLOCAL=DB,Agent,Feature_AADDLOCAL=DB,Agent,Feature_A,Feature_B

事情对我来说变得复杂了,因为例如需要额外的参数列表来安装它,Feature_C例如:RABBIT_LOCAL_PORT,,...RABBIT_QUEUE_NAMERABBIT_TTL

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

有没有办法将值添加到 playbook\role 中的现有值中,例如当我选择安装Feature_aand\or 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

相关内容