{% set profile_name = profile_name|default(service_name) %}
{% set profile_overrides = profile_overrides|default({}) %}
{% set num_subnets = subnetids|length %}
{% set tags = tags|default({}) %}

{{ profile_name }}:
  {% set instance_count = num_instances|default(3) %}
  {% for id_num in range(instance_count) %}
  - {{ service_name }}-{{ environment_name }}-{{ id_num }}:
      network_interfaces:
        - DeviceIndex: 0
          AssociatePublicIpAddress: True
          SubnetId: {{ subnetids[id_num % num_subnets] }}
          SecurityGroupId:
            {% for secgroup in securitygroupid %}
            {% if secgroup and not secgroup.lower() == "none" %}
            - {{ secgroup }}
            {% endif %}
            {% endfor %}
      tag:
        environment: {{ environment_name }}
        role: {{ service_name }}
        {% for tag_name, tag_value in tags.items() %}
        {{ tag_name }}: '{{ tag_value }}'
        {% endfor %}
      grains:
        environment: {{ environment_name }}
        roles: {{ roles|default([service_name])|tojson }}
        {% for tag_name, tag_value in tags.items() %}
        {{ tag_name }}: '{{ tag_value }}'
        {% endfor %}
      {% for profile_setting, profile_value in profile_overrides.items() %}
      {{ profile_setting }}: {{ profile_value }}
      {% endfor %}
  {% endfor %}

{% set profile_name = profile_name|default(service_name) %}
{% set profile_overrides = profile_overrides|default({}) %}
{% set num_subnets = subnetids|length %}
{% set tags = tags|default({}) %}

{{ profile_name }}:
  {% set instance_count = num_instances|default(3) %}
  {% for id_num in range(instance_count) %}
  - {{ service_name }}-{{ environment_name }}-{{ id_num }}:
      network_interfaces:
        - DeviceIndex: 0
          AssociatePublicIpAddress: True
          SubnetId: {{ subnetids[id_num % num_subnets] }}
          SecurityGroupId:
            {% for secgroup in securitygroupid %}
            {% if secgroup and not secgroup.lower() == "none" %}
            - {{ secgroup }}
            {% endif %}
            {% endfor %}
      tag:
        environment: {{ environment_name }}
        role: {{ service_name }}
        {% for tag_name, tag_value in tags.items() %}
        {{ tag_name }}: '{{ tag_value }}'
        {% endfor %}
      grains:
        environment: {{ environment_name }}
        roles: {{ roles|default([service_name])|tojson }}
        {% for tag_name, tag_value in tags.items() %}
        {{ tag_name }}: '{{ tag_value }}'
        {% endfor %}
      {% for profile_setting, profile_value in profile_overrides.items() %}
      {{ profile_setting }}: {{ profile_value|tojson }}
      {% endfor %}
  {% endfor %}

Add |tojson to AWS map template variable
Add |tojson to AWS map template variable
