Search code examples
puppet

Puppet 6 how to split or truncate domian name


I have array of domains like this: 'us1.domain.com', 'us2.domain.com', 'us3.domain.com', 'anotherdomain.com', 'yet.third.com'

I would split or truncate these domain names to:

domain.com
anotherdomain.com
third.com

Could anybody prompt me, please?

This new array will use for certificate file name.

Thanks in advance


Solution

  • You can solve that problem like this:

    $array = [
      'us1.domain.com', 'us2.domain.com', 'us3.domain.com',
      'anotherdomain.com', 'yet.third.com'
    ]
    notice($array.map |$x| { $y=$x.split(/\./); [$y[-2], $y[-1]].join('.') }.unique)
    

    Testing:

    ▶ puppet apply test.pp 
    Notice: Scope(Class[main]): [domain.com, anotherdomain.com, third.com]
    Notice: Compiled catalog for 192-168-1-103.tpgi.com.au in environment production in 0.05 seconds
    Notice: Applied catalog in 0.01 seconds
    

    Key insights there:

    • You can split each element on a period using using the split function.
    • You can take the last and second last elements of an array using $arr[-1] and $arr[-2].
    • You can join it all back together again using the join function.
    • You can transform the list into a new list using the map function.
    • You can remove the duplicates using the unique function.