Search code examples
loopsansiblekubernetes-helm

concatenate variables in ansible to pass them as helm flags for deployments


The goal is to pass variables from ansible to helm --set key=value. The following output structure for ansible is available

apps:
- name: proxy
  properties:
  - key: proxy.externalIP
    value: 192.168.178.1
  - key: proxy.service.Type
    value: LoadBalancer
- name: proxylived
  properties:
  - key: proxylived.externalIP
    value: 192.168.178.1
  - key: proxylived.port
    value: 31443

The ansible role should execute the following commands

$ helm install proxy . --set proxy.externalIP=192.168.178.1 --set proxy.service.Type=LoadBalancer 
$ helm install proxylived . --set proxy.externalIP=192.168.178.1 --set proxylived.port=31443

My problem is, I don't know how to iterate over the objects. I tried the following:

main.yml

---
- name: deploy applications
  include_tasks: apps.yml
  loop: "{{ apps }}"
  loop_control:
    loop_var: app

apps.yml

---
- name: deploy application {{ app.name }}
  ansible.builtin.command:
    argv:
    - /usr/bin/helm
    - install
    - {{ app.name }}
    - {{ how to pass here a list of the key value attributes? }}

Solution

  • In a nutshell and not thoroughly tested:

    apps.yml

    ---
    - name: create the list of values to set
      set_fact:
        kvs: "{{ kvs | default([]) + ['--set', item.key ~ '=' ~ item.value] }}"
      loop: "{{ app.properties }}"
    
    - name: deploy application {{ app.name }}
      vars:
        base_cmd:
          - "/usr/bin/helm"
          - "install"
          - "{{ app.name }}"
          - "."
      ansible.builtin.command:
        argv: "{{ base_cmd + kvs }}"