---
- name: Customize a given TOML file
  hosts: all
  vars:
    toml_base: >
      {{
        lookup('ansible.builtin.file', 'initial.toml')
        | sivel.toiletwater.from_toml
      }}
    toml_overrides:
      concurrent: 10
      listen_address: '0.0.0.0:9090'
      runners:
        - name: gitlab-runner-1
          limit: 10
          executor: docker+machine
          machine:
            IdleCount: 1
            IdleCountMin: 0
            IdleTime: 60
            MachineDriver: amazonec2
            MachineName: gitlab-runner-%s
            MachineOptions:
              # See https://gitlab.com/gitlab-org/ci-cd/docker-machine/-/blob/main/docs/drivers/aws.md.
              - 'amazonec2-iam-instance-profile=GitlabRunnerRole'
              - 'amazonec2-instance-type=m7g.medium'
              - 'amazonec2-vpc-id=vpc-01234567890abcdef'
              - 'amazonec2-subnet-id=subnet-01234567890abcdef'
              - 'amazonec2-tags=Application,gitlab_runner'
              - 'amazonec2-use-private-address=true'
              - 'amazonec2-private-address-only=true'
            MaxBuilds: 150
            MaxGrowthRate: 2
    toml_final:
      # There is no filter to automagically merge the objects in the 'runners'
      # list. This updates the base with the overrides at top level only,
      # (notice 'recursive=false'), then updates the result's list with a merged
      # version of it.
      # Merging lists requires an attribute to merge the correct element. Using
      # the 'name' attribute for this.
      >
      {{
        toml_base
        | ansible.builtin.combine(
          toml_overrides,
          {
            "runners": (
              toml_base.runners
              | community.general.lists_mergeby(
                  toml_overrides.runners,
                  'name'
                )
            )
          },
          recursive=false
        )
      }}
  tasks:
    - name: Show changes
      ansible.builtin.debug:
        var: item
      with_items:
        - "{{ toml_base }}"
        - "{{ toml_overrides }}"
        - "{{ toml_final }}"
        - "{{ toml_final | sivel.toiletwater.to_toml }}"
