diff --git a/docs/network.md b/docs/network.md new file mode 100644 index 00000000..ea6cfd7f --- /dev/null +++ b/docs/network.md @@ -0,0 +1,11 @@ +# Network Functions + +Sprig network manipulation functions. + +## getHostByName + +The `getHostByName` receives a domain name and returns the ip address. + +``` +getHostByName "www.google.com" would return the corresponding ip address of www.google.com +``` diff --git a/functions.go b/functions.go index 45e9d5ae..2823282d 100644 --- a/functions.go +++ b/functions.go @@ -85,6 +85,9 @@ var nonhermeticFunctions = []string{ // OS "env", "expandenv", + + // Network + "getHostByName", } var genericMap = map[string]interface{}{ @@ -224,6 +227,9 @@ var genericMap = map[string]interface{}{ "env": func(s string) string { return os.Getenv(s) }, "expandenv": func(s string) string { return os.ExpandEnv(s) }, + // Network: + "getHostByName": getHostByName, + // File Paths: "base": path.Base, "dir": path.Dir, diff --git a/network.go b/network.go new file mode 100644 index 00000000..d786cc73 --- /dev/null +++ b/network.go @@ -0,0 +1,12 @@ +package sprig + +import ( + "math/rand" + "net" +) + +func getHostByName(name string) string { + addrs, _ := net.LookupHost(name) + //TODO: add error handing when release v3 cames out + return addrs[rand.Intn(len(addrs))] +} diff --git a/network_test.go b/network_test.go new file mode 100644 index 00000000..9c153f0a --- /dev/null +++ b/network_test.go @@ -0,0 +1,18 @@ +package sprig + +import ( + "net" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestGetHostByName(t *testing.T) { + tpl := `{{"www.google.com" | getHostByName}}` + + resolvedIP, _ := runRaw(tpl, nil) + + ip := net.ParseIP(resolvedIP) + assert.NotNil(t, ip) + assert.NotEmpty(t, ip) +}