heat_template_version: 2015-10-15

description: >
  Configure os-net-config mappings for specific nodes
  Your environment file needs to look like:
    parameter_defaults:
      NetConfigDataLookup:
        node1:
          nic1: "00:c8:7c:e6:f0:2e"
        node2:
          nic1: "00:18:7d:99:0c:b6"
  This will result in the first nodeN entry where a mac matches a
  local device being written as a mapping file for os-net-config in
  /etc/os-net-config/mapping.yaml

parameters:
  # Note this requires a liberty heat or newer in the undercloud due to
  # the 2015-10-15 (which is required to enable str_replace serializing
  # the json parameter to json, another approch with a string parameter
  # will be required for older heat versions)
  NetConfigDataLookup:
    type: json
    default: {}
    description: per-node configuration map

resources:
  userdata:
    type: OS::Heat::MultipartMime
    properties:
      parts:
      - config: {get_resource: OsNetConfigMappings}

  OsNetConfigMappings:
    type: OS::Heat::SoftwareConfig
    properties:
      group: ungrouped
      config:
        str_replace:
          template: |
            #!/bin/sh
            eth_addr=$(/sbin/ifconfig eth0 | grep ether | awk '{print $2}')
            mkdir -p /etc/os-net-config

            # Create an os-net-config mapping file, note this defaults to
            # /etc/os-net-config/mapping.yaml, so we use that name despite
            # rendering the result as json
            echo '$node_lookup' | python -c "
            import json
            import sys
            import yaml
            input = sys.stdin.readline() or '{}'
            data = json.loads(input)
            for node in data:
              if '${eth_addr}' in data[node].values():
                interface_mapping = {'interface_mapping': data[node]}
                with open('/etc/os-net-config/mapping.yaml', 'w') as f:
                  yaml.safe_dump(interface_mapping, f, default_flow_style=False)
                break
            "
          params:
            $node_lookup: {get_param: NetConfigDataLookup}

outputs:
  OS::stack_id:
    value: {get_resource: userdata}
