Ask Your Question
0

How to generate files based on array contents?

asked 2015-04-24 00:12:37 -0500

red-cricket gravatar image

Hi,

I'd like to be able to create files based on the contents of an array. Here is what I have tried:

class make_files (
    $servers = ['server-1','server-2','server-3'],
) {
    file { $servers :
        path    => '/tmp',
        content => $servers,
    }
}

... but when I execute this like so ...

# puppet apply --modulepath=/root/modules -e 'include make_files'

... I get this output:

Notice: Compiled catalog for host-001 in environment production in 0.13 seconds
Error: Cannot alias File[server-2] to ["/tmp"] at /root/modules/make_files/manifests/init.pp:9; resource ["File", "/tmp"] already declared at /root/modules/make_files/manifests/init.pp:9

I was hoping to have three files ...

# ls /tmp/server-?
/tmp/server-1  /tmp/server-2  /tmp/server-3
# cat /tmp/server-?
server-1
server-2
server-3

Any help is appreciated thanks!

edit retag flag offensive close merge delete

2 answers

Sort by ยป oldest newest most voted
1

answered 2015-04-24 01:05:13 -0500

You could use a defined type and the std lib join function:

class make_files (
    $servers = ['server-1','server-2','server-3'],
) {
    define my_file ($content) {
        $file_name = "/tmp/$name"
        file { $file_name:
          ensure  => file,
          content => $content,
        }
    }
    include stdlib
    $content = join($servers, ',')
    my_file { $servers: content => $content }
}

This should be easier in Puppet 4, which supports loops.

edit flag offensive delete link more

Comments

Thanks alexharv074, that works perfectly. I do not completely understand it though. where does $name come from?

red-cricket gravatar imagered-cricket ( 2015-04-24 10:51:27 -0500 )edit

The character limit here is preventing me from explaining, so I'll just point you to the docs: https://docs.puppetlabs.com/puppet/latest/reference/lang_defined_types.html#title-and-name.

Alex Harvey gravatar imageAlex Harvey ( 2015-04-25 09:08:37 -0500 )edit
1

answered 2015-04-24 01:20:27 -0500

JohnsonEarls gravatar image

I'm not at my puppet system right now, but try this:

class make_files (
    $servers = ['server-1','server-2','server-3'],
) {
    file { regsubst($servers, '^', '/tmp/'):
        ensure => file,
        content => $servers,
    }
}
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2015-04-24 00:12:37 -0500

Seen: 734 times

Last updated: Apr 24 '15