func resourceOrSubresourceHCL()

in pkg/tf/serialization/tf_resource.go [47:139]


func resourceOrSubresourceHCL(schema map[string]*tfschema.Schema, attributes map[string]string) (string, error) {
	var hcl strings.Builder
	keys := make([]string, 0, len(schema))
	for k := range schema {
		keys = append(keys, k)
	}
	sort.Strings(keys)
	for _, aname := range keys {
		aschema := schema[aname]
		if !aschema.Optional && !aschema.Required {
			continue
		}
		switch aschema.Type {
		case tfschema.TypeFloat:
			fallthrough
		case tfschema.TypeInt:
			fallthrough
		case tfschema.TypeBool:
			if attributes[aname] == "" {
				continue
			}
			hcl.WriteString(fmt.Sprintf("%s = %s\n", aname, attributes[aname]))
		case tfschema.TypeString:
			if attributes[aname] == "" {
				continue
			}
			hcl.WriteString(fmt.Sprintf("%s = %s\n", aname, stringLitToHCL(attributes[aname])))
		// for each non-primitive, find if there are any values and set them.
		case tfschema.TypeMap:
			if val, ok := attributes[aname+".%"]; !ok || val == "0" {
				continue
			}
			hcl.WriteString(fmt.Sprintf("%s = {\n", aname))
			m, err := mapFromPrefix(attributes, aname)
			if err != nil {
				return "", err
			}
			var keys []string
			for k := range m {
				keys = append(keys, k)
			}
			sort.Strings(keys)
			for _, k := range keys {
				v := m[k]
				hcl.WriteString(fmt.Sprintf("%s = %q\n", k, v))
			}
			hcl.WriteString("}\n")
		case tfschema.TypeSet:
			fallthrough
		case tfschema.TypeList:
			if val, ok := attributes[aname+".#"]; !ok || val == "0" {
				continue
			}
			if subtype, ok := aschema.Elem.(*tfschema.Schema); ok {
				hcl.WriteString(fmt.Sprintf("%s = [", aname))
				l, err := listFromPrefix(attributes, aname, aschema.Type)
				if err != nil {
					return "", err
				}
				for _, v := range l {
					switch subtype.Type {
					case tfschema.TypeFloat:
						fallthrough
					case tfschema.TypeInt:
						fallthrough
					case tfschema.TypeBool:
						hcl.WriteString(fmt.Sprintf("%s, ", v))
					case tfschema.TypeString:
						hcl.WriteString(fmt.Sprintf("%q, ", v))
					}
				}
				hcl.WriteString("]\n")
			} else if subtype, ok := aschema.Elem.(*tfschema.Resource); ok {
				cnt, err := strconv.Atoi(attributes[aname+".#"])
				if err != nil {
					return "", fmt.Errorf("could not parse count of %s, %w", aname, err)
				}
				for i := 0; i < cnt; i++ {
					subAttrs, err := mapsFromPrefix(attributes, fmt.Sprintf("%s.%d", aname, i))
					if err != nil {
						return "", fmt.Errorf("could not get subresource attributes for %s: %w", aname, err)
					}
					subresource, err := resourceOrSubresourceHCL(subtype.Schema, subAttrs)
					if err != nil {
						return "", fmt.Errorf("could not create subresource %s: %w", aname, err)
					}
					hcl.WriteString(fmt.Sprintf("%s {\n%s\n}\n", aname, subresource))
				}
			}
		}
	}
	return hcl.String(), nil
}