func flattenPhase()

in internal/elasticsearch/index/ilm.go [681:742]


func flattenPhase(phaseName string, p models.Phase, d *schema.ResourceData) (interface{}, diag.Diagnostics) {
	var diags diag.Diagnostics
	out := make([]interface{}, 1)
	phase := make(map[string]interface{})
	enabled := make(map[string]interface{})
	ns := make(map[string]interface{})

	_, new := d.GetChange(phaseName)

	if new != nil && len(new.([]interface{})) > 0 {
		ns = new.([]interface{})[0].(map[string]interface{})
	}

	existsAndNotEmpty := func(key string, m map[string]interface{}) bool {
		if v, ok := m[key]; ok && len(v.([]interface{})) > 0 {
			return true
		}
		return false
	}
	for _, aCase := range []string{"readonly", "freeze", "unfollow"} {
		if existsAndNotEmpty(aCase, ns) {
			enabled["enabled"] = false
			phase[aCase] = []interface{}{enabled}
		}
	}

	if p.MinAge != "" {
		phase["min_age"] = p.MinAge
	}
	for actionName, action := range p.Actions {
		switch actionName {
		case "readonly", "freeze", "unfollow":
			enabled["enabled"] = true
			phase[actionName] = []interface{}{enabled}
		case "allocate":
			allocateAction := make(map[string]interface{})
			if v, ok := action["number_of_replicas"]; ok {
				allocateAction["number_of_replicas"] = v
			}
			if v, ok := action["total_shards_per_node"]; ok {
				allocateAction["total_shards_per_node"] = v
			} else {
				// Specify the default for total_shards_per_node. This avoids an endless diff loop for ES 7.15 or lower which don't support this setting
				allocateAction["total_shards_per_node"] = -1
			}
			for _, f := range []string{"include", "require", "exclude"} {
				if v, ok := action[f]; ok {
					res, err := json.Marshal(v)
					if err != nil {
						return nil, diag.FromErr(err)
					}
					allocateAction[f] = string(res)
				}
			}
			phase[actionName] = []interface{}{allocateAction}
		default:
			phase[actionName] = []interface{}{action}
		}
	}
	out[0] = phase
	return out, diags
}