Search code examples
postgresqlvagrantpuppet

Initialising a postgresql database via a setup script in a VM using puppet


I want to run the following setup script to configure a postgresql database that's being deployed via a virtual machine, provisioned via vagrant using puppet:

#!/bin/bash -e

sudo su - postgres
createdb testdb

psql -s tm351test -c "create user test password 'test';GRANT ALL PRIVILEGES ON DATABASE testdb TO test;"

touch /root/postgresql.done

My vagrant config takes the form:

package {
  [
    'postgresql',
    'postgresql-client'
  ]: ensure => latest;
}

file {
  '/root/postgresql.setup':
    source => 'puppet:///modules/infinite_interns/root/postgresql.setup',
    owner  => root,
    group  => root,
    mode   => '0744';
}

#TO DO - how do we guarantee the postgresql server is running and tools available?
exec {
  'setup-postgresql':
    cwd     => '/root',
    command => '/root/postgresql.setup',
    creates => '/root/postgresql.done';
}

service {
  'postgresql':
    ensure => running,
    enable => true;
}

Package['postgresql'] -> Service['postgresql']

How do I guarantee that that the postgresql server is installed and running, and the command line tools available, before running the config script?

I'm new to Puppet - does the Exec() not run if the created file postgresql.done exists?

I suspect that the psql command may also expect a confirmatory "return" to execute the command - how would I do that?


Solution

  • There's an official postgresql module that can be easily installed:

    puppet module install puppetlabs-postgresql
    

    or adding following to your Puppetfile:

    mod 'puppetlabs-postgresql'
    

    The configuration might look like this:

      class { 'postgresql::globals':
        encoding => 'UTF-8',
        locale   => 'en_US.UTF-8',
        version  => '9.6',
      }->
      class { 'postgresql::server':
        ip_mask_deny_postgres_user => '0.0.0.0/32',
        ip_mask_allow_all_users    => '0.0.0.0/0',
        listen_addresses           => '*',
        version                    => '9.6',
      }
    
      postgresql::server::db { 'testdb':
        user     => 'test',
        password => postgresql_password('test', 'testpassword'),
      }
    
      postgresql::server::pg_hba_rule { 'allow connection from ...':
        description => "Open up PostgreSQL for access from test domain",
        type        => 'host',
        database    => 'testdb',
        user        => 'test',
        address     => '.testdomain.com',
        auth_method => 'md5',
      }