Exemple #1
0
// ShadowVariables shadows the given variables with the given holder. Variables
// need to be in interpolation form, i.e: ${var.foo}
func (t *Template) ShadowVariables(holder string, vars ...string) error {
	replace := func(s string) string {
		variables := ReadVariables(s)
		if len(variables) == 0 {
			return ""
		}

		var matching []Variable

	lookup:
		for _, variable := range variables {
			for _, name := range vars {
				if variable.Name == name {
					matching = append(matching, variable)
					continue lookup
				}
			}
		}

		if len(matching) == 0 {
			return ""
		}

		return ReplaceVariables(s, matching, holder)
	}

	return object.ReplaceFunc(t.Resource, replace)
}
Exemple #2
0
func TestReplace(t *testing.T) {
	v := map[string]interface{}{
		"key": "secret",
		"m": map[string]interface{}{
			"key": "secret",
			"secret": &Secret{
				Field: "secret",
				M: map[string]interface{}{
					"key": "secret",
					"keys": []string{
						"secret",
						"secret",
						"secret",
					},
				},
			},
			"secrets": []*Secret{
				{Field: "secret"},
				{Field: "secret"},
				{M: map[string]interface{}{"key": "secret"}},
			},
			"ms": []interface{}{
				map[string]interface{}{"key": "secret"},
				&Secret{Field: "secret"},
				"secret",
			},
		},
	}

	want := map[string]interface{}{
		"key": "***",
		"m": map[string]interface{}{
			"key": "***",
			"secret": &Secret{
				Field: "***",
				M: map[string]interface{}{
					"key": "***",
					"keys": []string{
						"***",
						"***",
						"***",
					},
				},
			},
			"secrets": []*Secret{
				{Field: "***"},
				{Field: "***"},
				{M: map[string]interface{}{"key": "***"}},
			},
			"ms": []interface{}{
				map[string]interface{}{"key": "***"},
				&Secret{Field: "***"},
				"***",
			},
		},
	}

	fn := func(s string) string {
		if s == "secret" {
			return "***"
		}
		return ""
	}

	if err := object.ReplaceFunc(v, fn); err != nil {
		t.Fatalf("Walk()=%s", err)
	}

	if !reflect.DeepEqual(v, want) {
		t.Fatalf("got %+v, want %+v", v, want)
	}
}