How to check in puppet if one of the array items is a sub-string of a given string?

25 Views Asked by At

I have a string (an email address) str = '[email protected]'

I have an array with a list of domains : arr = ['randomain.com', 'test.com', 'support.com']

I need to return true if my string's domain is a part of the array or if its a subdomain of a domain in the array. Return false if the domains are not related.

So far I have tried the in function on the array as a whole and in function while iterating through the elements of the array. Both dont give the right value.

1

There are 1 best solutions below

0
Kai Burghardt On

You need to perform regular expression pattern matching against all array members, like this:

    $email_address = '[email protected]'
    [$user, $host] = $email_address.split('@')
    
    $label = $host.split('\.')
    [$hostname, $domainname] = [$label[0], $label[1, -1].join('.')]
    # Now, $hostname is just 'support', whereas $domainname is 'randomain.com'.
    
    $domains = ['randomain.com', 'test.com', 'support.com']
    
    # Sequentially test 'randomain.com', 'test.com', 'support.com'.
    # The `any` lambda finishes as soon as there is a `true` expression.
    $result = $domains.any |$domain| {
            # The last expression determines the “return value”.
            ($domain =~ $host) or ($domain =~ $domainname)
        }

You need to install measures for case‑insensitive matching, but that’s beside the issue here.