diff --git a/.gitignore b/.gitignore index f6e8b46..a102277 100644 --- a/.gitignore +++ b/.gitignore @@ -1,24 +1,23 @@ -#This file is generated by ModuleSync, do not edit. -pkg/ -Gemfile.lock -Gemfile.local -vendor/ -spec/fixtures/manifests/ -spec/fixtures/modules/ -log/ -junit/ -.vagrant/ +# This file is generated by ModuleSync, do not edit. +*.iml +.*.sw[op] +.DS_Store .bundle/ -coverage/ -log/ .idea/ .metadata -*.iml -.*.sw[op] +.vagrant/ .yardoc .yardwarns -.DS_Store +Gemfile.local +Gemfile.lock +bin/ +coverage/ +doc/ +junit/ +log/ +pkg/ +spec/fixtures/manifests/ +spec/fixtures/modules/ tmp/ vendor/ -doc/ diff --git a/.rubocop.yml b/.rubocop.yml index 5aadd1b..515ef63 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -1,508 +1,98 @@ -require: rubocop-rspec +--- +require: + - rubocop-rspec AllCops: - TargetRubyVersion: 1.9 + TargetRubyVersion: '2.1' Include: - - ./**/*.rb + - "./**/*.rb" Exclude: - - vendor/**/* - - .vendor/**/* - - pkg/**/* - - spec/fixtures/**/* -Lint/ConditionPosition: - Enabled: True - -Lint/ElseLayout: - Enabled: True - -Lint/UnreachableCode: - Enabled: True - -Lint/UselessComparison: - Enabled: True - -Lint/EnsureReturn: - Enabled: True - -Lint/HandleExceptions: - Enabled: True - -Lint/LiteralInCondition: - Enabled: True - -Lint/ShadowingOuterLocalVariable: - Enabled: True - -Lint/LiteralInInterpolation: - Enabled: True - -Style/HashSyntax: - Enabled: True - -Style/RedundantReturn: - Enabled: True - -Lint/AmbiguousOperator: - Enabled: True - -Lint/AssignmentInCondition: - Enabled: True - -Style/SpaceBeforeComment: - Enabled: True - -Style/AndOr: - Enabled: True - -Style/RedundantSelf: - Enabled: True - -# Method length is not necessarily an indicator of code quality -Metrics/MethodLength: - Enabled: False - -# Module length is not necessarily an indicator of code quality -Metrics/ModuleLength: - Enabled: False - -Style/WhileUntilModifier: - Enabled: True - -Lint/AmbiguousRegexpLiteral: - Enabled: True - -Lint/Eval: - Enabled: True - -Lint/BlockAlignment: - Enabled: True - -Lint/DefEndAlignment: - Enabled: True - -Lint/EndAlignment: - Enabled: True - -Lint/DeprecatedClassMethods: - Enabled: True - -Lint/Loop: - Enabled: True - -Lint/ParenthesesAsGroupedExpression: - Enabled: True - -Lint/RescueException: - Enabled: True - -Lint/StringConversionInInterpolation: - Enabled: True - -Lint/UnusedBlockArgument: - Enabled: True - -Lint/UnusedMethodArgument: - Enabled: True - -Lint/UselessAccessModifier: - Enabled: True - -Lint/UselessAssignment: - Enabled: True - -Lint/Void: - Enabled: True - -Style/AccessModifierIndentation: - Enabled: True - -Style/AccessorMethodName: - Enabled: True - -Style/Alias: - Enabled: True - -Style/AlignArray: - Enabled: True - -Style/AlignHash: - Enabled: True - -Style/AlignParameters: - Enabled: True - -Metrics/BlockNesting: - Enabled: True - -Style/AsciiComments: - Enabled: True - -Style/Attr: - Enabled: True - -Style/BracesAroundHashParameters: - Enabled: True - -Style/CaseEquality: - Enabled: True - -Style/CaseIndentation: - Enabled: True - -Style/CharacterLiteral: - Enabled: True - -Style/ClassAndModuleCamelCase: - Enabled: True - -Style/ClassAndModuleChildren: - Enabled: False - -Style/ClassCheck: - Enabled: True - -# Class length is not necessarily an indicator of code quality -Metrics/ClassLength: - Enabled: False - -Style/ClassMethods: - Enabled: True - -Style/ClassVars: - Enabled: True - -Style/WhenThen: - Enabled: True - -Style/WordArray: - Enabled: True - -Style/UnneededPercentQ: - Enabled: True - -Style/Tab: - Enabled: True - -Style/SpaceBeforeSemicolon: - Enabled: True - -Style/TrailingBlankLines: - Enabled: True - -Style/SpaceInsideBlockBraces: - Enabled: True - -Style/SpaceInsideBrackets: - Enabled: True - -Style/SpaceInsideHashLiteralBraces: - Enabled: True - -Style/SpaceInsideParens: - Enabled: True - -Style/LeadingCommentSpace: - Enabled: True - -Style/SpaceBeforeFirstArg: - Enabled: True - -Style/SpaceAfterColon: - Enabled: True - -Style/SpaceAfterComma: - Enabled: True - -Style/SpaceAfterMethodName: - Enabled: True - -Style/SpaceAfterNot: - Enabled: True - -Style/SpaceAfterSemicolon: - Enabled: True - -Style/SpaceAroundEqualsInParameterDefault: - Enabled: True - -Style/SpaceAroundOperators: - Enabled: True - -Style/SpaceBeforeBlockBraces: - Enabled: True - -Style/SpaceBeforeComma: - Enabled: True - -Style/CollectionMethods: - Enabled: True - -Style/CommentIndentation: - Enabled: True - -Style/ColonMethodCall: - Enabled: True - -Style/CommentAnnotation: - Enabled: True - -# 'Complexity' is very relative -Metrics/CyclomaticComplexity: - Enabled: False - -Style/ConstantName: - Enabled: True - -Style/Documentation: - Enabled: False - -Style/DefWithParentheses: - Enabled: True - -Style/PreferredHashMethods: - Enabled: True - -Style/DotPosition: - EnforcedStyle: trailing - -Style/DoubleNegation: - Enabled: True - -Style/EachWithObject: - Enabled: True - -Style/EmptyLineBetweenDefs: - Enabled: True - -Style/IndentArray: - Enabled: True - -Style/IndentHash: - Enabled: True - -Style/IndentationConsistency: - Enabled: True - -Style/IndentationWidth: - Enabled: True - -Style/EmptyLines: - Enabled: True - -Style/EmptyLinesAroundAccessModifier: - Enabled: True - -Style/EmptyLiteral: - Enabled: True - -# Configuration parameters: AllowURI, URISchemes. + - bin/* + - ".vendor/**/*" + - Gemfile + - Rakefile + - pkg/**/* + - spec/fixtures/**/* + - vendor/**/* +inherit_from: .rubocop_todo.yml Metrics/LineLength: - Enabled: False - -Style/MethodCallParentheses: - Enabled: True - -Style/MethodDefParentheses: - Enabled: True - -Style/LineEndConcatenation: - Enabled: True - -Style/TrailingWhitespace: - Enabled: True - -Style/StringLiterals: - Enabled: True - -Style/TrailingCommaInArguments: - Enabled: True - -Style/TrailingCommaInLiteral: - Enabled: True - -Style/GlobalVars: - Enabled: True - -Style/GuardClause: - Enabled: True - -Style/IfUnlessModifier: - Enabled: True - -Style/MultilineIfThen: - Enabled: True - -Style/NegatedIf: - Enabled: True - -Style/NegatedWhile: - Enabled: True - -Style/Next: - Enabled: True - -Style/SingleLineBlockParams: - Enabled: True - -Style/SingleLineMethods: - Enabled: True - -Style/SpecialGlobalVars: - Enabled: True - -Style/TrivialAccessors: - Enabled: True - -Style/UnlessElse: - Enabled: True - -Style/VariableInterpolation: - Enabled: True - -Style/VariableName: - Enabled: True - -Style/WhileUntilDo: - Enabled: True - -Style/EvenOdd: - Enabled: True - -Style/FileName: - Enabled: True - -Style/For: - Enabled: True - -Style/Lambda: - Enabled: True - -Style/MethodName: - Enabled: True - -Style/MultilineTernaryOperator: - Enabled: True - -Style/NestedTernaryOperator: - Enabled: True - -Style/NilComparison: - Enabled: True - + Description: People have wide screens, use them. + Max: 200 +RSpec/BeforeAfterAll: + Description: Beware of using after(:all) as it may cause state to leak between tests. + A necessary evil in acceptance testing. + Exclude: + - spec/acceptance/**/*.rb +RSpec/HookArgument: + Description: Prefer explicit :each argument, matching existing module's style + EnforcedStyle: each +Style/BlockDelimiters: + Description: Prefer braces for chaining. Mostly an aesthetical choice. Better to + be consistent then. + EnforcedStyle: braces_for_chaining +Style/ClassAndModuleChildren: + Description: Compact style reduces the required amount of indentation. + EnforcedStyle: compact +Style/EmptyElse: + Description: Enforce against empty else clauses, but allow `nil` for clarity. + EnforcedStyle: empty Style/FormatString: - Enabled: True - -Style/MultilineBlockChain: - Enabled: True - -Style/Semicolon: - Enabled: True - -Style/SignalException: - Enabled: True - -Style/NonNilCheck: - Enabled: True - -Style/Not: - Enabled: True - -Style/NumericLiterals: - Enabled: True - -Style/OneLineConditional: - Enabled: True - -Style/OpMethod: - Enabled: True - -Style/ParenthesesAroundCondition: - Enabled: True - -Style/PercentLiteralDelimiters: - Enabled: True - -Style/PerlBackrefs: - Enabled: True - -Style/PredicateName: - Enabled: True - -Style/RedundantException: - Enabled: True - -Style/SelfAssignment: - Enabled: True - -Style/Proc: - Enabled: True - -Style/RaiseArgs: - Enabled: True - -Style/RedundantBegin: - Enabled: True - -Style/RescueModifier: - Enabled: True - -# based on https://github.com/voxpupuli/modulesync_config/issues/168 + Description: Following the main puppet project's style, prefer the % format format. + EnforcedStyle: percent +Style/FormatStringToken: + Description: Following the main puppet project's style, prefer the simpler template + tokens over annotated ones. + EnforcedStyle: template +Style/Lambda: + Description: Prefer the keyword for easier discoverability. + EnforcedStyle: literal Style/RegexpLiteral: + Description: Community preference. See https://github.com/voxpupuli/modulesync_config/issues/168 EnforcedStyle: percent_r - Enabled: True - -Lint/UnderscorePrefixedVariableName: - Enabled: True - -Metrics/ParameterLists: - Enabled: False - -Lint/RequireParentheses: - Enabled: True - -Style/SpaceBeforeFirstArg: - Enabled: True - -Style/ModuleFunction: - Enabled: True - -Lint/Debugger: - Enabled: True - -Style/IfWithSemicolon: - Enabled: True - -Style/Encoding: - Enabled: True - -Style/BlockDelimiters: - Enabled: True - -Style/MultilineBlockLayout: - Enabled: True - -# 'Complexity' is very relative +Style/TernaryParentheses: + Description: Checks for use of parentheses around ternary conditions. Enforce parentheses + on complex expressions for better readability, but seriously consider breaking + it up. + EnforcedStyle: require_parentheses_when_complex +Style/TrailingCommaInArguments: + Description: Prefer always trailing comma on multiline argument lists. This makes + diffs, and re-ordering nicer. + EnforcedStyleForMultiline: comma +Style/TrailingCommaInLiteral: + Description: Prefer always trailing comma on multiline literals. This makes diffs, + and re-ordering nicer. + EnforcedStyleForMultiline: comma +Style/SymbolArray: + Description: Using percent style obscures symbolic intent of array's contents. + EnforcedStyle: brackets +Style/CollectionMethods: + Enabled: true +Style/MethodCalledOnDoEndBlock: + Enabled: true +Style/StringMethods: + Enabled: true Metrics/AbcSize: - Enabled: False - -# 'Complexity' is very relative + Enabled: false +Metrics/BlockLength: + Enabled: false +Metrics/ClassLength: + Enabled: false +Metrics/CyclomaticComplexity: + Enabled: false +Metrics/MethodLength: + Enabled: false +Metrics/ModuleLength: + Enabled: false +Metrics/ParameterLists: + Enabled: false Metrics/PerceivedComplexity: - Enabled: False - -Lint/UselessAssignment: - Enabled: True - -Style/ClosingParenthesisIndentation: - Enabled: False - -# RSpec - -# We don't use rspec in this way + Enabled: false RSpec/DescribeClass: - Enabled: False - -# Example length is not necessarily an indicator of code quality -RSpec/ExampleLength: - Enabled: False - -RSpec/NamedSubject: - Enabled: False + Enabled: false +RSpec/MessageExpectation: + Enabled: false +Style/AsciiComments: + Enabled: false +Style/IfUnlessModifier: + Enabled: false +Style/SymbolProc: + Enabled: false diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml new file mode 100644 index 0000000..e69de29 diff --git a/.sync.yml b/.sync.yml index 5850fed..436f1c4 100644 --- a/.sync.yml +++ b/.sync.yml @@ -1,7 +1,11 @@ --- NOTICE: unmanaged: true appveyor.yml: delete: true spec/spec_helper.rb: allow_deprecations: true +.travis.yml: + extras: + - rvm: 2.1.9 + script: bundle exec rake rubocop diff --git a/.travis.yml b/.travis.yml index 38d2263..47c6d8d 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,32 +1,31 @@ #This file is generated by ModuleSync, do not edit. --- sudo: false language: ruby cache: bundler script: "bundle exec rake release_checks" -#Inserting below due to the following issue: https://github.com/travis-ci/travis-ci/issues/3531#issuecomment-88311203 -before_install: - - gem update bundler matrix: fast_finish: true include: - rvm: 2.3.1 dist: trusty env: PUPPET_INSTALL_TYPE=agent BEAKER_debug=true BEAKER_set=docker/ubuntu-14.04 script: bundle exec rake beaker services: docker sudo: required - rvm: 2.3.1 dist: trusty env: PUPPET_INSTALL_TYPE=agent BEAKER_debug=true BEAKER_set=docker/centos-7 script: bundle exec rake beaker services: docker sudo: required - rvm: 2.4.1 bundler_args: --without system_tests env: PUPPET_GEM_VERSION="~> 5.0" - rvm: 2.1.9 bundler_args: --without system_tests env: PUPPET_GEM_VERSION="~> 4.0" + - rvm: 2.1.9 + script: bundle exec rake rubocop notifications: email: false diff --git a/Gemfile b/Gemfile index 8bd07c7..84b23f2 100644 --- a/Gemfile +++ b/Gemfile @@ -1,77 +1,84 @@ #This file is generated by ModuleSync, do not edit. source ENV['GEM_SOURCE'] || "https://rubygems.org" # Determines what type of gem is requested based on place_or_version. def gem_type(place_or_version) if place_or_version =~ /^git:/ :git elsif place_or_version =~ /^file:/ :file else :gem end end # Find a location or specific version for a gem. place_or_version can be a # version, which is most often used. It can also be git, which is specified as # `git://somewhere.git#branch`. You can also use a file source location, which # is specified as `file://some/location/on/disk`. def location_for(place_or_version, fake_version = nil) if place_or_version =~ /^(git[:@][^#]*)#(.*)/ [fake_version, { :git => $1, :branch => $2, :require => false }].compact elsif place_or_version =~ /^file:\/\/(.*)/ ['>= 0', { :path => File.expand_path($1), :require => false }] else [place_or_version, { :require => false }] end end # Used for gem conditionals -supports_windows = false ruby_version_segments = Gem::Version.new(RUBY_VERSION.dup).segments minor_version = "#{ruby_version_segments[0]}.#{ruby_version_segments[1]}" +# The following gems are not included by default as they require DevKit on Windows. +# You should probably include them in a Gemfile.local or a ~/.gemfile +#gem 'pry' #this may already be included in the gemfile +#gem 'pry-stack_explorer', :require => false +#if RUBY_VERSION =~ /^2/ +# gem 'pry-byebug' +#else +# gem 'pry-debugger' +#end + group :development do gem "puppet-module-posix-default-r#{minor_version}", :require => false, :platforms => "ruby" gem "puppet-module-win-default-r#{minor_version}", :require => false, :platforms => ["mswin", "mingw", "x64_mingw"] gem "puppet-module-posix-dev-r#{minor_version}", :require => false, :platforms => "ruby" gem "puppet-module-win-dev-r#{minor_version}", '0.0.7', :require => false, :platforms => ["mswin", "mingw", "x64_mingw"] gem "json_pure", '<= 2.0.1', :require => false if Gem::Version.new(RUBY_VERSION.dup) < Gem::Version.new('2.0.0') gem "fast_gettext", '1.1.0', :require => false if Gem::Version.new(RUBY_VERSION.dup) < Gem::Version.new('2.1.0') gem "fast_gettext", :require => false if Gem::Version.new(RUBY_VERSION.dup) >= Gem::Version.new('2.1.0') end group :system_tests do gem "puppet-module-posix-system-r#{minor_version}", :require => false, :platforms => "ruby" gem "puppet-module-win-system-r#{minor_version}", :require => false, :platforms => ["mswin", "mingw", "x64_mingw"] gem "beaker", *location_for(ENV['BEAKER_VERSION'] || '>= 3') gem "beaker-pe", :require => false gem "beaker-rspec", *location_for(ENV['BEAKER_RSPEC_VERSION']) gem "beaker-hostgenerator", *location_for(ENV['BEAKER_HOSTGENERATOR_VERSION']) gem "beaker-abs", *location_for(ENV['BEAKER_ABS_VERSION'] || '~> 0.1') gem "puppet-blacksmith", '~> 3.4', :require => false - gem "beaker-task_helper" end gem 'puppet', *location_for(ENV['PUPPET_GEM_VERSION']) # Only explicitly specify Facter/Hiera if a version has been specified. # Otherwise it can lead to strange bundler behavior. If you are seeing weird # gem resolution behavior, try setting `DEBUG_RESOLVER` environment variable # to `1` and then run bundle install. gem 'facter', *location_for(ENV['FACTER_GEM_VERSION']) if ENV['FACTER_GEM_VERSION'] gem 'hiera', *location_for(ENV['HIERA_GEM_VERSION']) if ENV['HIERA_GEM_VERSION'] - # Evaluate Gemfile.local if it exists if File.exists? "#{__FILE__}.local" eval(File.read("#{__FILE__}.local"), binding) end # Evaluate ~/.gemfile if it exists if File.exists?(File.join(Dir.home, '.gemfile')) eval(File.read(File.join(Dir.home, '.gemfile')), binding) end # vim:ft=ruby diff --git a/README.md b/README.md index 9b1fb64..90efb58 100644 --- a/README.md +++ b/README.md @@ -1,1942 +1,2189 @@ # postgresql #### Table of Contents 1. [Module Description - What does the module do?](#module-description) 2. [Setup - The basics of getting started with postgresql module](#setup) * [What postgresql affects](#what-postgresql-affects) * [Getting started with postgresql](#getting-started-with-postgresql) 3. [Usage - Configuration options and additional functionality](#usage) * [Configure a server](#configure-a-server) * [Create a database](#create-a-database) * [Manage users, roles, and permissions](#manage-users-roles-and-permissions) * [Manage ownership of DB objects](#manage-ownership-of-db-objects) * [Override defaults](#override-defaults) * [Create an access rule for pg_hba.conf](#create-an-access-rule-for-pg_hbaconf) * [Create user name maps for pg_ident.conf](#create-user-name-maps-for-pg_identconf) * [Validate connectivity](#validate-connectivity) 4. [Reference - An under-the-hood peek at what the module is doing and how](#reference) * [Classes](#classes) * [Defined Types](#defined-types) * [Types](#types) * [Functions](#functions) * [Tasks](#tasks) 5. [Limitations - OS compatibility, etc.](#limitations) 6. [Development - Guide for contributing to the module](#development) * [Contributors - List of module contributors](#contributors) 7. [Tests](#tests) 8. [Contributors - List of module contributors](#contributors) ## Module description The postgresql module allows you to manage PostgreSQL databases with Puppet. -PostgreSQL is a high-performance, free, open-source relational database server. The postgresql module allows you to manage packages, services, databases, users, and common security settings in PostgreSQL. +PostgreSQL is a high-performance, free, open-source relational database server. +The postgresql module allows you to manage packages, services, databases, +users, and common security settings in PostgreSQL. ## Setup ### What postgresql affects * Package, service, and configuration files for PostgreSQL * Listened-to ports * IP and mask (optional) ### Getting started with postgresql -To configure a basic default PostgreSQL server, declare the `postgresql::server` class. +To configure a basic default PostgreSQL server, declare +the `postgresql::server` class. ```puppet class { 'postgresql::server': } ``` ## Usage ### Configure a server -For default settings, declare the `postgresql::server` class as above. To customize PostgreSQL server settings, specify the [parameters](#postgresqlserver) you want to change: +For default settings, declare the `postgresql::server` class as above. +To customize PostgreSQL server settings, specify +[the parameters](#postgresqlserver) you want to change: ```puppet class { 'postgresql::server': ip_mask_deny_postgres_user => '0.0.0.0/32', ip_mask_allow_all_users => '0.0.0.0/0', ipv4acls => ['hostssl all johndoe 192.168.0.0/24 cert'], postgres_password => 'TPSrep0rt!', } ``` After configuration, test your settings from the command line: ```shell psql -h localhost -U postgres psql -h my.postgres.server -U ``` -If you get an error message from these commands, your permission settings restrict access from the location you're trying to connect from. Depending on whether you want to allow connections from that location, you might need to adjust your permissions. +If you get an error message from these commands, your permission settings +restrict access from the location you're trying to connect from. Depending +on whether you want to allow connections from that location, you might need +to adjust your permissions. -For more details about server configuration parameters, consult the [PostgreSQL Runtime Configuration documentation](http://www.postgresql.org/docs/current/static/runtime-config.html). +For more details about server configuration parameters, consult +[the PostgreSQL Runtime Configuration documentation](http://www.postgresql.org/docs/current/static/runtime-config.html). ### Create a database -You can set up a variety of PostgreSQL databases with the `postgresql::server::db` defined type. For instance, to set up a database for PuppetDB: +You can set up a variety of PostgreSQL databases with +the `postgresql::server::db` defined type. For instance, to set up a database +for PuppetDB: ```puppet class { 'postgresql::server': } postgresql::server::db { 'mydatabasename': user => 'mydatabaseuser', password => postgresql_password('mydatabaseuser', 'mypassword'), } ``` ### Manage users, roles, and permissions To manage users, roles, and permissions: ```puppet class { 'postgresql::server': } postgresql::server::role { 'marmot': password_hash => postgresql_password('marmot', 'mypasswd'), } postgresql::server::database_grant { 'test1': privilege => 'ALL', db => 'test1', role => 'marmot', } postgresql::server::table_grant { 'my_table of test2': privilege => 'ALL', table => 'my_table', db => 'test2', role => 'marmot', } ``` -This example grants **all** privileges on the test1 database and on the `my_table` table of the test2 database to the specified user or group. After the values are added into the PuppetDB config file, this database would be ready for use. +This example grants **all** privileges on the `test1` database and on +the `my_table` table of the `test2` database to the specified user or group. +After the values are added into the PuppetDB config file, this database would +be ready for use. ### Manage ownership of DB objects -To change the ownership of all objects within a database using REASSIGN OWNED: +To change the ownership of all objects within a database using +`REASSIGN OWNED`: ```puppet postgresql::server::reassign_owned_by { 'new owner is meerkat': db => 'test_db', old_owner => 'marmot', new_owner => 'meerkat', } ``` -This would run the PostgreSQL statement 'REASSIGN OWNED' to update to ownership of all tables, sequences, functions and views currently owned by the role 'marmot' to be owned by the role 'meerkat' instead. +This would run the PostgreSQL statement `REASSIGN OWNED` to update to ownership +of all tables, sequences, functions and views currently owned by +the role `marmot` to be owned by the role `meerkat` instead. -This applies to objects within the nominated database, 'test_db' only. +This applies to objects within the nominated database, `test_db` only. -For Postgresql >= 9.3, the ownership of the database is also updated. +For PostgreSQL >= 9.3, the ownership of the database is also updated. ### Override defaults -The `postgresql::globals` class allows you to configure the main settings for this module globally, so that other classes and defined resources can use them. By itself, it does nothing. +The `postgresql::globals` class allows you to configure the main settings +for this module globally, so that other classes and defined resources can use +them. By itself, it does nothing. -For example, to overwrite the default `locale` and `encoding` for all classes, use the following: +For example, to overwrite the default `locale` and `encoding` for all classes, +use the following: ```puppet class { 'postgresql::globals': encoding => 'UTF-8', locale => 'en_US.UTF-8', } class { 'postgresql::server': } ``` To use a specific version of the PostgreSQL package: ```puppet class { 'postgresql::globals': manage_package_repo => true, version => '9.2', } class { 'postgresql::server': } ``` ### Manage remote users, roles, and permissions -Remote SQL objects are managed using the same Puppet resources as local SQL objects, along with a [`connect_settings`](#connect_settings) hash. This provides control over how Puppet connects to the remote Postgres instances and which version is used for generating SQL commands. +Remote SQL objects are managed using the same Puppet resources as local +SQL objects, along with a [`connect_settings`](#connect_settings) hash. +This provides control over how Puppet connects to the remote PostgreSQL +instances and which version is used for generating SQL commands. -The `connect_settings` hash can contain environment variables to control Postgres client connections, such as 'PGHOST', 'PGPORT', 'PGPASSWORD', and 'PGSSLKEY'. See the [PostgreSQL Environment Variables](http://www.postgresql.org/docs/9.4/static/libpq-envars.html) documentation for a complete list of variables. +The `connect_settings` hash can contain environment variables to control +PostgreSQL client connections, such as `PGHOST`, `PGPORT`, `PGPASSWORD`, +and `PGSSLKEY`. See +[the PostgreSQL Environment Variables documentation](http://www.postgresql.org/docs/9.4/static/libpq-envars.html) +for a complete list of variables. -Additionally, you can specify the target database version with the special value of 'DBVERSION'. If the `connect_settings` hash is omitted or empty, then Puppet connects to the local PostgreSQL instance. +Additionally, you can specify the target database version with the special +value of `DBVERSION`. If the `connect_settings` hash is omitted or empty, +then Puppet connects to the local PostgreSQL instance. -You can provide a `connect_settings` hash for each of the Puppet resources, or you can set a default `connect_settings` hash in `postgresql::globals`. Configuring `connect_settings` per resource allows SQL objects to be created on multiple databases by multiple users. +You can provide a `connect_settings` hash for each of the Puppet resources, +or you can set a default `connect_settings` hash in `postgresql::globals`. +Configuring `connect_settings` per resource allows SQL objects to be created +on multiple databases by multiple users. ```puppet $connection_settings_super2 = { 'PGUSER' => 'super2', 'PGPASSWORD' => 'foobar2', 'PGHOST' => '127.0.0.1', 'PGPORT' => '5432', 'PGDATABASE' => 'postgres', } include postgresql::server # Connect with no special settings, i.e domain sockets, user postgres postgresql::server::role { 'super2': password_hash => 'foobar2', superuser => true, connect_settings => {}, } # Now using this new user connect via TCP postgresql::server::database { 'db1': connect_settings => $connection_settings_super2, require => Postgresql::Server::Role['super2'], } ``` ### Create an access rule for pg_hba.conf To create an access rule for `pg_hba.conf`: ```puppet postgresql::server::pg_hba_rule { 'allow application network to access app database': description => 'Open up PostgreSQL for access from 200.1.2.0/24', type => 'host', database => 'app', user => 'app', address => '200.1.2.0/24', auth_method => 'md5', } ``` This would create a ruleset in `pg_hba.conf` similar to: ``` # Rule Name: allow application network to access app database # Description: Open up PostgreSQL for access from 200.1.2.0/24 # Order: 150 host app app 200.1.2.0/24 md5 ``` -By default, `pg_hba_rule` requires that you include `postgresql::server`. However, you can override that behavior by setting target and postgresql_version when declaring your rule. That might look like the following: +By default, `pg_hba_rule` requires that you include `postgresql::server`. +However, you can override that behavior by setting target and +postgresql_version when declaring your rule. That might look like +the following: ```puppet postgresql::server::pg_hba_rule { 'allow application network to access app database': description => 'Open up postgresql for access from 200.1.2.0/24', type => 'host', database => 'app', user => 'app', address => '200.1.2.0/24', auth_method => 'md5', target => '/path/to/pg_hba.conf', postgresql_version => '9.4', } ``` ### Create user name maps for pg_ident.conf To create a user name map for the pg_ident.conf: ```puppet postgresql::server::pg_ident_rule { 'Map the SSL certificate of the backup server as a replication user': map_name => 'sslrepli', system_username => 'repli1.example.com', database_username => 'replication', } ``` This would create a user name map in `pg_ident.conf` similar to: ``` #Rule Name: Map the SSL certificate of the backup server as a replication user #Description: none #Order: 150 sslrepli repli1.example.com replication ``` ### Create recovery configuration To create the recovery configuration file (`recovery.conf`): ```puppet postgresql::server::recovery { 'Create a recovery.conf file with the following defined parameters': restore_command => 'cp /mnt/server/archivedir/%f %p', archive_cleanup_command => undef, recovery_end_command => undef, recovery_target_name => 'daily backup 2015-01-26', recovery_target_time => '2015-02-08 22:39:00 EST', recovery_target_xid => undef, recovery_target_inclusive => true, recovery_target => 'immediate', recovery_target_timeline => 'latest', pause_at_recovery_target => true, standby_mode => 'on', primary_conninfo => 'host=localhost port=5432', primary_slot_name => undef, trigger_file => undef, recovery_min_apply_delay => 0, } ``` The above creates this `recovery.conf` config file: ``` restore_command = 'cp /mnt/server/archivedir/%f %p' recovery_target_name = 'daily backup 2015-01-26' recovery_target_time = '2015-02-08 22:39:00 EST' recovery_target_inclusive = true recovery_target = 'immediate' recovery_target_timeline = 'latest' pause_at_recovery_target = true standby_mode = 'on' primary_conninfo = 'host=localhost port=5432' recovery_min_apply_delay = 0 ``` -Only the specified parameters are recognized in the template. The `recovery.conf` is only be created if at least one parameter is set **and** [manage_recovery_conf](#manage_recovery_conf) is set to true. +Only the specified parameters are recognized in the template. +The `recovery.conf` is only be created if at least one parameter is set +**and** [manage_recovery_conf](#manage_recovery_conf) is set to true. ### Validate connectivity -To validate client connections to a remote PostgreSQL database before starting dependent tasks, use the `postgresql_conn_validator` resource. You can use this on any node where the PostgreSQL client software is installed. It is often chained to other tasks such as starting an application server or performing a database migration. +To validate client connections to a remote PostgreSQL database before starting +dependent tasks, use the `postgresql_conn_validator` resource. You can use +this on any node where the PostgreSQL client package is installed. It is +often chained to other tasks such as starting an application server or +performing a database migration. Example usage: ```puppet postgresql_conn_validator { 'validate my postgres connection': host => 'my.postgres.host', db_username => 'mydbuser', db_password => 'mydbpassword', db_name => 'mydbname', }-> exec { 'rake db:migrate': cwd => '/opt/myrubyapp', } ``` ## Reference -The postgresql module comes with many options for configuring the server. While you are unlikely to use all of the settings below, they provide a decent amount of control over your security settings. +The postgresql module comes with many options for configuring the server. +While you are unlikely to use all of the settings below, they provide a decent +amount of control over your security settings. **Classes:** * [postgresql::client](#postgresqlclient) * [postgresql::globals](#postgresqlglobals) * [postgresql::lib::devel](#postgresqllibdevel) * [postgresql::lib::java](#postgresqllibjava) * [postgresql::lib::perl](#postgresqllibperl) * [postgresql::lib::python](#postgresqllibpython) * [postgresql::server](#postgresqlserver) * [postgresql::server::plperl](#postgresqlserverplperl) * [postgresql::server::contrib](#postgresqlservercontrib) * [postgresql::server::postgis](#postgresqlserverpostgis) **Defined Types:** * [postgresql::server::config_entry](#postgresqlserverconfig_entry) * [postgresql::server::database](#postgresqlserverdatabase) * [postgresql::server::database_grant](#postgresqlserverdatabase_grant) * [postgresql::server::db](#postgresqlserverdb) * [postgresql::server::extension](#postgresqlserverextension) * [postgresql::server::grant](#postgresqlservergrant) * [postgresql::server::grant_role](#postgresqlservergrant_role) * [postgresql::server::pg_hba_rule](#postgresqlserverpg_hba_rule) * [postgresql::server::pg_ident_rule](#postgresqlserverpg_ident_rule) * [postgresql::server::reassign_owned_by](#postgresqlserverreassign_owned_by) * [postgresql::server::recovery](#postgresqlserverrecovery) * [postgresql::server::role](#postgresqlserverrole) * [postgresql::server::schema](#postgresqlserverschema) * [postgresql::server::table_grant](#postgresqlservertable_grant) * [postgresql::server::tablespace](#postgresqlservertablespace) **Types:** * [postgresql_psql](#custom-resource-postgresql_psql) * [postgresql_replication_slot](#custom-resource-postgresql_replication_slot) * [postgresql_conf](#custom-resource-postgresql_conf) * [postgresql_conn_validator](#custom-resource-postgresql_conn_validator) **Functions:** * [postgresql_password](#function-postgresql_password) * [postgresql_acls_to_resources_hash](#function-postgresql_acls_to_resources_hashacl_array-id-order_offset) **Tasks:** ### Classes #### postgresql::client -Installs PostgreSQL client software. Set the following parameters if you have a custom version you would like to install. +Installs PostgreSQL client package. Set the following parameters if you have +a custom version you would like to install. ->**Note:** Make sure to add any necessary yum or apt repositories if specifying a custom version. +**Note:** Make sure to add any necessary yum or apt repositories if specifying +a custom version. ##### `package_ensure` Whether the PostgreSQL client package resource should be present. -Valid values: 'present', 'absent'. +Valid values: `present`, `absent`. -Default value: 'present'. +Default value: `present`. ##### `package_name` Sets the name of the PostgreSQL client package. -Default value: 'file'. +Default value: `file`. #### postgresql::lib::docs -Installs PostgreSQL bindings for Postgres-Docs. Set the following parameters if you have a custom version you would like to install. +Installs PostgreSQL documentation package. Set the following parameters +if you have a custom version you would like to install. -**Note:** Make sure to add any necessary yum or apt repositories if specifying a custom version. +**Note:** Make sure to add any necessary yum or apt repositories if specifying +a custom version. ##### `package_name` Specifies the name of the PostgreSQL docs package. ##### `package_ensure` Whether the PostgreSQL docs package resource should be present. -Valid values: 'present', 'absent'. +Valid values: `present`, `absent`. -Default value: 'present'. +Default value: `present`. #### postgresql::globals -**Note:** Most server-specific defaults should be overridden in the `postgresql::server` class. This class should be used only if you are using a non-standard OS, or if you are changing elements that can only be changed here, such as `version` or `manage_package_repo`. +**Note:** Most server-specific defaults should be overridden in +the `postgresql::server` class. This class should be used only if you are +using a non-standard OS, or if you are changing elements that can only be +changed here, such as `version` or `manage_package_repo`. ##### `bindir` Overrides the default PostgreSQL binaries directory for the target platform. Default value: OS dependent. ##### `client_package_name` Overrides the default PostgreSQL client package name. Default value: OS dependent. ##### `confdir` -Overrides the default PostgreSQL configuration directory for the target platform. +Overrides the default PostgreSQL configuration directory for the target +platform. Default value: OS dependent. ##### `contrib_package_name` Overrides the default PostgreSQL contrib package name. Default value: OS dependent. ##### `createdb_path` -**Deprecated.** Path to the `createdb` command. +**Deprecated.** + +Path to the `createdb` command. -Default value: '${bindir}/createdb'. +Default value: `${bindir}/createdb`. ##### `datadir` Overrides the default PostgreSQL data directory for the target platform. Default value: OS dependent. -**Note:** Changing the datadir after installation causes the server to come to a full stop before making the change. For Red Hat systems, the data directory must be labeled appropriately for SELinux. On Ubuntu, you must explicitly set `needs_initdb = true` to allow Puppet to initialize the database in the new datadir (`needs_initdb` defaults to true on other systems). +**Note:** Changing the `datadir` after installation causes the server to come +to a full stop before making the change. For Red Hat systems, the data +directory must be labeled appropriately for SELinux. On Ubuntu, you must +explicitly set `needs_initdb = true` to allow Puppet to initialize the database +in the new `datadir` (`needs_initdb` defaults to true on other systems). -**Warning:** If datadir is changed from the default, Puppet does not manage purging of the original data directory, which causes it to fail if the data directory is changed back to the original. +**Warning:** If `datadir` is changed from the default, Puppet does not manage +purging of the original data directory, which causes it to fail if the data +directory is changed back to the original. ##### `data_checksums` Optional. -Data type: Boolean. - -Use checksums on data pages to help detect corruption by the I/O system that would otherwise be silent. +Use checksums on data pages to help detect corruption by the I/O system that +would otherwise be silent. Valid values: `true` or `false`. -Default: initdb's default (`false`). +Default: `initdb`'s default (`false`). -**Warning:** This option is used during initialization by initdb, and cannot be changed later. If set, checksums are calculated for all objects, in all databases. +**Warning:** This option is used during initialization by `initdb`, and cannot +be changed later. If set, checksums are calculated for all objects, in all +databases. ##### `default_database` Specifies the name of the default database to connect with. -Default value: 'postgres' (for most systems). +Default value: `postgres` (for most systems). ##### `devel_package_name` Overrides the default PostgreSQL devel package name. Default value: OS dependent. ##### `docs_package_name` Optional. Overrides the default PostgreSQL docs package name. Default value: OS dependent. ##### `encoding` -Sets the default encoding for all databases created with this module. On certain operating systems, this is also used during the `template1` initialization, so it becomes a default outside of the module as well. +Sets the default encoding for all databases created with this module. +On certain operating systems, this is also used during the `template1` +initialization, so it becomes a default outside of the module as well. -Default value: Dependent on the operating system's default encoding. +Default value: dependent on the operating system's default encoding. ##### `group` -Overrides the default postgres user group to be used for related files in the file system. +Overrides the default postgres user group to be used for related files in +the file system. -Default value: 'postgres'. +Default value: `postgres`. ##### `initdb_path` Path to the `initdb` command. ##### `java_package_name` -Overrides the default PostgreSQL java package name. +Overrides the default PostgreSQL Java package name. Default value: OS dependent. ##### `locale` -Sets the default database locale for all databases created with this module. On certain operating systems, this is also used during the `template1` initialization, so it becomes a default outside of the module as well. +Sets the default database locale for all databases created with this module. +On certain operating systems, this is also used during the `template1` +initialization, so it becomes a default outside of the module as well. -Default value: `undef`, which is effectively 'C'. +Default value: `undef`, which is effectively `"C"`. -**On Debian, you'll need to ensure that the 'locales-all' package is installed for full functionality of PostgreSQL.** +**Warning:** On Debian, you'll need to ensure that the `locales-all` package is +installed for full functionality of PostgreSQL. ##### `timezone` -Sets the default timezone of the postgresql server. The postgresql built-in default is taking the systems timezone information. +Sets the default timezone of the postgresql server. The postgresql built-in +default is taking the systems timezone information. ##### `logdir` Overrides the default PostgreSQL log directory. -Default value: initdb's default path. +Default value: `initdb`'s default path. ##### `manage_package_repo` Sets up official PostgreSQL repositories on your host if set to `true`. Default value: `false`. ##### `module_workdir` -Specifies working directory under which the psql command should be executed. May need to specify if '/tmp' is on volume mounted with noexec option. +Specifies working directory under which the `psql` command should be executed. +May need to specify if `/tmp` is on volume mounted with `noexec` option. -Default value: '/tmp'. +Default value: `/tmp`. ##### `needs_initdb` -Explicitly calls the initdb operation after the server package is installed and before the PostgreSQL service is started. +Explicitly calls the `initdb` operation after the server package is installed +and before the PostgreSQL service is started. Default value: OS dependent. ##### `perl_package_name` Overrides the default PostgreSQL Perl package name. Default value: OS dependent. ##### `pg_hba_conf_defaults` -Disables the defaults supplied with the module for `pg_hba.conf` if set to `false`. This is useful if you want to override the defaults. Be sure that your changes align with the rest of the module, as some access is required to perform some operations, such as basic `psql` operations. +Disables the defaults supplied with the module for `pg_hba.conf` if set to +`false`. This is useful if you want to override the defaults. Be sure that +your changes align with the rest of the module, as some access is required +to perform some operations, such as basic `psql` operations. -Default value: The globals value set in `postgresql::globals::manage_pg_hba_conf` which defaults to `true`. +Default value: the globals value set in `postgresql::globals::manage_pg_hba_conf` +which defaults to `true`. ##### `pg_hba_conf_path` Specifies the path to your `pg_hba.conf` file. -Default value: '${confdir}/pg_hba.conf'. +Default value: `${confdir}/pg_hba.conf`. ##### `pg_ident_conf_path` Specifies the path to your `pg_ident.conf` file. -Default value: '${confdir}/pg_ident.conf'. +Default value: `${confdir}/pg_ident.conf`. ##### `plperl_package_name` Overrides the default PostgreSQL PL/Perl package name. Default value: OS dependent. ##### `plpython_package_name` Overrides the default PostgreSQL PL/Python package name. Default value: OS dependent. ##### `postgis_version` Defines the version of PostGIS to install, if you install PostGIS. -Default value: The lowest available with the version of PostgreSQL to be installed. +Default value: the lowest available with the version of PostgreSQL to be +installed. ##### `postgresql_conf_path` Sets the path to your `postgresql.conf` file. -Default value: '${confdir}/postgresql.conf'. +Default value: `${confdir}/postgresql.conf`. ##### `psql_path` Sets the path to the `psql` command. ##### `python_package_name` Overrides the default PostgreSQL Python package name. Default value: OS dependent. ##### `recovery_conf_path` Path to your `recovery.conf` file. ##### `repo_proxy` -Sets the proxy option for the official PostgreSQL yum-repositories only. This is useful if your server is behind a corporate firewall and needs to use proxy servers for outside connectivity. +Sets the proxy option for the official PostgreSQL yum-repositories only. +This is useful if your server is behind a corporate firewall and needs to use +proxy servers for outside connectivity. Debian is currently not supported. ##### `repo_baseurl` -Sets the baseurl for the PostgreSQL repository. Useful if you host your own mirror of the repository. +Sets the baseurl for the PostgreSQL repository. Useful if you host your own +mirror of the repository. -Default value: The official PostgreSQL repository. +Default value: the official PostgreSQL repository. ##### `server_package_name` Overrides the default PostgreSQL server package name. Default value: OS dependent. ##### `service_name` Overrides the default PostgreSQL service name. Default value: OS dependent. ##### `service_provider` Overrides the default PostgreSQL service provider. Default value: OS dependent. ##### `service_status` Overrides the default status check command for your PostgreSQL service. Default value: OS dependent. ##### `user` -Overrides the default PostgreSQL super user and owner of PostgreSQL related files in the file system. +Overrides the default PostgreSQL super user and owner of PostgreSQL related +files in the file system. -Default value: 'postgres'. +Default value: `postgres`. ##### `version` The version of PostgreSQL to install and manage. Default value: OS system default. ##### `xlogdir` Overrides the default PostgreSQL xlog directory. Default value: initdb's default path. #### postgresql::lib::devel -Installs the packages containing the development libraries for PostgreSQL and symlinks `pg_config` into `/usr/bin` (if not in `/usr/bin` or `/usr/local/bin`). +Installs the packages containing the development libraries for PostgreSQL and +symlinks `pg_config` into `/usr/bin` (if not in `/usr/bin` or `/usr/local/bin`). ##### `link_pg_config` -If the bin directory used by the PostgreSQL page is not `/usr/bin` or `/usr/local/bin`, symlinks `pg_config` from the package's bin dir into `usr/bin` (not applicable to Debian systems). Set to `false` to disable this behavior. +If the bin directory used by the PostgreSQL page is not `/usr/bin` or +`/usr/local/bin`, symlinks `pg_config` from the package's bin directory into +`usr/bin` (not applicable to Debian systems). Set to `false` to disable +this behavior. Valid values: `true`, `false`. Default value: `true`. ##### `package_ensure` -Overrides the 'ensure' parameter during package installation. +Overrides the `ensure` parameter during package installation. -Default value: 'present'. +Default value: `present`. ##### `package_name` Overrides the default package name for the distribution you are installing to. -Default value: 'postgresql-devel' or 'postgresql-devel' depending on your distro. +Default value: `postgresql-devel` or `postgresql-devel` depending on +your OS. #### postgresql::lib::java -Installs PostgreSQL bindings for Java (JDBC). Set the following parameters if you have a custom version you would like to install. +Installs PostgreSQL bindings for Java (JDBC). Set the following parameters +if you have a custom version you would like to install. -**Note:** Make sure to add any necessary yum or apt repositories if specifying a custom version. +**Note:** Make sure to add any necessary yum or apt repositories if specifying +a custom version. ##### `package_ensure` Specifies whether the package is present. -Valid values: 'present', 'absent'. +Valid values: `present`, `absent`. -Default value: 'present'. +Default value: `present`. ##### `package_name` Specifies the name of the PostgreSQL java package. #### postgresql::lib::perl Installs the PostgreSQL Perl libraries. ##### `package_ensure` Specifies whether the package is present. -Valid values: 'present', 'absent'. +Valid values: `present`, `absent`. -Default value: 'present'. +Default value: `present`. ##### `package_name` Specifies the name of the PostgreSQL perl package to install. #### postgresql::server::plpython Installs the PL/Python procedural language for PostgreSQL. ##### `package_name` Specifies the name of the postgresql PL/Python package. ##### `package_ensure` Specifies whether the package is present. -Valid values: 'present', 'absent'. +Valid values: `present`, `absent`. -Default value: 'present'. +Default value: `present`. #### postgresql::lib::python Installs PostgreSQL Python libraries. ##### `package_ensure` Specifies whether the package is present. -Valid values: 'present', 'absent'. +Valid values: `present`, `absent`. -Default value: 'present'. +Default value: `present`. ##### `package_name` The name of the PostgreSQL Python package. #### postgresql::server ##### `createdb_path` -**Deprecated.** Specifies the path to the `createdb` command. +**Deprecated.** + +Specifies the path to the `createdb` command. -Default value: '${bindir}/createdb'. +Default value: `${bindir}/createdb`. ##### `data_checksums` Optional. -Data type: Boolean. - -Use checksums on data pages to help detect corruption by the I/O system that would otherwise be silent. +Use checksums on data pages to help detect corruption by the I/O system that +would otherwise be silent. Valid values: `true` or `false`. -Default value: initdb's default (`false`). +Default value: `initdb`'s default (`false`). -**Warning:** This option is used during initialization by initdb, and cannot be changed later. If set, checksums are calculated for all objects, in all databases. +**Warning:** This option is used during initialization by `initdb`, and cannot +be changed later. If set, checksums are calculated for all objects, in all +databases. ##### `default_database` -Specifies the name of the default database to connect with. On most systems this is 'postgres'. +Specifies the name of the default database to connect with. On most systems +this is `postgres`. ##### `default_connect_settings` -Specifies a hash of environment variables used when connecting to a remote server. Becomes the default for other defined types, such as `postgresql::server::role`. +Specifies a hash of environment variables used when connecting to a remote +server. Becomes the default for other defined types, such as +`postgresql::server::role`. ##### `encoding` -Sets the default encoding for all databases created with this module. On certain operating systems this is also used during the `template1` initialization, so it becomes a default outside of the module as well. +Sets the default encoding for all databases created with this module. On +certain operating systems this is also used during the `template1` +initialization, so it becomes a default outside of the module as well. Default value: `undef`. ##### `group` -Overrides the default postgres user group to be used for related files in the file system. +Overrides the default postgres user group to be used for related files in +the file system. -Default value: OS dependent default. +Default value: OS dependent. ##### `initdb_path` Specifies the path to the `initdb` command. -Default value: '${bindir}/initdb'. +Default value: `${bindir}/initdb`. ##### `ipv4acls` -Lists strings for access control for connection method, users, databases, IPv4 addresses; - -see [PostgreSQL documentation](http://www.postgresql.org/docs/current/static/auth-pg-hba-conf.html) on `pg_hba.conf` for information. +Lists strings for access control for connection method, users, databases, IPv4 +addresses. See +[the PostgreSQL HBA documentation](http://www.postgresql.org/docs/current/static/auth-pg-hba-conf.html) +for information. ##### `ipv6acls` -Lists strings for access control for connection method, users, databases, IPv6 addresses. - -see [PostgreSQL documentation](http://www.postgresql.org/docs/current/static/auth-pg-hba-conf.html) on `pg_hba.conf` for information. +Lists strings for access control for connection method, users, databases, IPv6 +addresses. See +[the PostgreSQL HBA documentation](http://www.postgresql.org/docs/current/static/auth-pg-hba-conf.html) +for information. ##### `ip_mask_allow_all_users` -Overrides PostgreSQL defaults for remote connections. By default, PostgreSQL does not allow database user accounts to connect via TCP from remote machines. If you'd like to allow this, you can override this setting. +Overrides PostgreSQL defaults for remote connections. By default, PostgreSQL +does not allow database user accounts to connect via TCP from remote machines. +If you'd like to allow this, you can override this setting. -Set to '0.0.0.0/0' to allow database users to connect from any remote machine, or '192.168.0.0/1' to allow connections from any machine on your local '192.168' subnet. +Set to `0.0.0.0/0` to allow database users to connect from any remote machine, +or `192.168.0.0/1` to allow connections from any machine on your local +`192.168` subnet. -Default value: '127.0.0.1/32'. +Default value: `127.0.0.1/32`. ##### `ip_mask_deny_postgres_user` -Specifies the IP mask from which remote connections should be denied for the postgres superuser. +Specifies the IP mask from which remote connections should be denied for +the postgres superuser. -Default value: '0.0.0.0/0', which denies any remote connection. +Default value: `0.0.0.0/0`, which denies any remote connection. ##### `locale` -Sets the default database locale for all databases created with this module. On certain operating systems this is used during the `template1` initialization as well, so it becomes a default outside of the module. +Sets the default database locale for all databases created with this module. +On certain operating systems this is used during the `template1` initialization +as well, so it becomes a default outside of the module. -Default value: `undef`, which is effectively 'C'. +Default value: `undef`, which is effectively `"C"`. -**On Debian, you must ensure that the 'locales-all' package is installed for full functionality of PostgreSQL.** +**Warning:** On Debian, you'll need to ensure that the `locales-all` package is +installed for full functionality of PostgreSQL. ##### `manage_pg_hba_conf` Whether to manage the `pg_hba.conf`. If set to `true`, Puppet overwrites this file. If set to `false`, Puppet does not modify the file. Valid values: `true`, `false`. Default value: `true` ##### `manage_pg_ident_conf` Overwrites the pg_ident.conf file. If set to `true`, Puppet overwrites the file. If set to `false`, Puppet does not modify the file. Valid values: `true`, `false`. Default value: `true`. ##### `manage_recovery_conf` Specifies whether or not manage the `recovery.conf`. If set to `true`, Puppet overwrites this file. Valid values: `true`, `false`. Default value: `false`. ##### `needs_initdb` -Explicitly calls the `initdb` operation after server package is installed, and before the PostgreSQL service is started. +Explicitly calls the `initdb` operation after server package is installed, and +before the PostgreSQL service is started. Default value: OS dependent. ##### `package_ensure` -Passes a value through to the `package` resource when creating the server instance. +Passes a value through to the `package` resource when creating the server +instance. Default value: `undef`. ##### `package_name` -Specifies the name of the package to use for installing the server software. +Specifies the name of the package to use for installing the PostgreSQL server. Default value: OS dependent. ##### `pg_hba_conf_defaults` -If `false`, disables the defaults supplied with the module for `pg_hba.conf`. This is useful if you disagree with the defaults and wish to override them yourself. Be sure that your changes of course align with the rest of the module, as some access is required to perform basic `psql` operations for example. +If `false`, disables the defaults supplied with the module for `pg_hba.conf`. +This is useful if you disagree with the defaults and wish to override them +yourself. Be sure that your changes of course align with the rest of +the module, as some access is required to perform basic `psql` operations +for example. ##### `pg_hba_conf_path` Specifies the path to your `pg_hba.conf` file. ##### `pg_ident_conf_path` Specifies the path to your `pg_ident.conf` file. -Default value: '${confdir}/pg_ident.conf'. +Default value: `${confdir}/pg_ident.conf`. ##### `plperl_package_name` Sets the default package name for the PL/Perl extension. Default value: OS dependent. ##### `plpython_package_name` Sets the default package name for the PL/Python extension. Default value: OS dependent. ##### `port` -Specifies the port for the PostgreSQL server to listen on. **Note:** The same port number is used for all IP addresses the server listens on. Also, for Red Hat systems and early Debian systems, changing the port causes the server to come to a full stop before being able to make the change. +Specifies the port for the PostgreSQL server to listen on. + +**Note:** The same +port number is used for all IP addresses the server listens on. Also, +for Red Hat systems and early Debian systems, changing the port causes +the server to come to a full stop before being able to make the change. -Default value: 5432. Meaning the Postgres server listens on TCP port 5432. +Default value: 5432 ##### `postgres_password` -Sets the password for the postgres user to your specified value. By default, this setting uses the superuser account in the Postgres database, with a user called `postgres` and no password. +Sets the password for the postgres user to your specified value. By default, +this setting uses the superuser account. Default value: `undef`. ##### `postgresql_conf_path` -Specifies the path to your `postgresql.conf` file. +Specifies the path to your `postgresql.conf` file. -Default value: '${confdir}/postgresql.conf'. +Default value: `${confdir}/postgresql.conf`. ##### `psql_path` -Specifies the path to the `psql` command. +Specifies the path to the `psql` command. Default value: OS dependent. ##### `service_manage` -Defines whether or not Puppet should manage the service. +Defines whether or not Puppet should manage the service. Default value: `true`. ##### `service_name` -Overrides the default PostgreSQL service name. +Overrides the default PostgreSQL service name. Default value: OS dependent. ##### `service_provider` -Overrides the default PostgreSQL service provider. +Overrides the default PostgreSQL service provider. Default value: `undef`. ##### `service_reload` -Overrides the default reload command for your PostgreSQL service. +Overrides the default reload command for your PostgreSQL service. Default value: OS dependent. ##### `service_restart_on_change` -Overrides the default behavior to restart your PostgreSQL service when a config entry has been changed that requires a service restart to become active. +Overrides the default behavior to restart your PostgreSQL service when a config +entry has been changed that requires a service restart to become active. Default value: `true`. ##### `service_status` -Overrides the default status check command for your PostgreSQL service. +Overrides the default status check command for your PostgreSQL service. Default value: OS dependent. ##### `user` -Overrides the default PostgreSQL super user and owner of PostgreSQL related files in the file system. +Overrides the default PostgreSQL super user and owner of PostgreSQL related +files in the file system. -Default value: 'postgres'. +Default value: `postgres`. #### postgresql::server::contrib Installs the PostgreSQL contrib package. ##### `package_ensure` Sets the ensure parameter passed on to PostgreSQL contrib package resource. ##### `package_name` The name of the PostgreSQL contrib package. #### postgresql::server::plperl Installs the PL/Perl procedural language for postgresql. ##### `package_ensure` The ensure parameter passed on to PostgreSQL PL/Perl package resource. ##### `package_name` The name of the PostgreSQL PL/Perl package. #### postgresql::server::postgis Installs the PostgreSQL postgis packages. ### Defined Types #### postgresql::server::config_entry Modifies your `postgresql.conf` configuration file. Each resource maps to a line inside the file, for example: ```puppet postgresql::server::config_entry { 'check_function_bodies': value => 'off', } ``` ##### `ensure` -Removes an entry if set to 'absent'. +Removes an entry when set to `absent`. -Valid values: 'present', 'absent'. +Valid values: `present`, `absent`. -Default value: 'present'. +Default value: `present`. ##### `value` Defines the value for the setting. #### postgresql::server::db Creates a local database, user, and assigns necessary permissions. ##### `comment` -Defines a comment to be stored about the database using the PostgreSQL COMMENT command. +Defines a comment to be stored about the database using the PostgreSQL COMMENT +command. ##### `connect_settings` -Specifies a hash of environment variables used when connecting to a remote server. +Specifies a hash of environment variables used when connecting to a remote +server. -Default value: Connects to the local Postgres instance. +Default value: local PostgreSQL instance. ##### `dbname` -Sets the name of the database to be created. +Sets the name of the database to be created. Default value: the namevar. ##### `encoding` -Overrides the character set during creation of the database. +Overrides the character set during creation of the database. -Default value: The default defined during installation. +Default value: the default defined during installation. ##### `grant` -Specifies the permissions to grant during creation. +Specifies the permissions to grant during creation. -Default value: 'ALL'. +Default value: `ALL`. ##### `istemplate` -Specifies that the database is a template, if set to `true`. +Specifies that the database is a template, if set to `true`. Default value: `false`. ##### `locale` -Overrides the locale during creation of the database. +Overrides the locale during creation of the database. -Default value: The default defined during installation. +Default value: the default defined during installation. ##### `owner` -Sets a user as the owner of the database. +Sets a user as the owner of the database. -Default value: '$user' variable set in `postgresql::server` or `postgresql::globals`. +Default value: `$user` variable set in `postgresql::server` or +`postgresql::globals`. ##### `password` -**Required** Sets the password for the created user. +Required. + +Sets the password for the created user. ##### `tablespace` -Defines the name of the tablespace to allocate the created database to. +Defines the name of the tablespace to allocate the created database to. Default value: PostgreSQL default. ##### `template` -Specifies the name of the template database from which to build this database. +Specifies the name of the template database from which to build this database. -Defaults value: `template0`. +Default value: `template0`. ##### `user` -User to create and assign access to the database upon creation. Mandatory. +Required. + +User to create and assign access to the database upon creation. #### postgresql::server::database Creates a database with no users and no permissions. ##### `dbname` -Sets the name of the database. +Sets the name of the database. -Defaults value: The namevar. +Default value: the namevar. ##### `encoding` -Overrides the character set during creation of the database. +Overrides the character set during creation of the database. -Default value: The default defined during installation. +Default value: the default defined during installation. ##### `istemplate` Defines the database as a template if set to `true`. Default value: `false`. ##### `locale` Overrides the locale during creation of the database. -Default value: The default defined during installation. +Default value: the default defined during installation. ##### `owner` Sets name of the database owner. -Default value: The '$user' variable set in `postgresql::server` or `postgresql::globals`. +Default value: the `$user` variable set in `postgresql::server` or +`postgresql::globals`. ##### `tablespace` -Sets tablespace for where to create this database. +Sets tablespace for where to create this database. -Default value: The default defined during installation. +Default value: the default defined during installation. ##### `template` -Specifies the name of the template database from which to build this database. +Specifies the name of the template database from which to build this database. -Default value: 'template0'. +Default value: `template0`. #### postgresql::server::database_grant -Manages grant-based access privileges for users, wrapping the `postgresql::server::database_grant` for database specific permissions. Consult the [PostgreSQL documentation for `grant`](http://www.postgresql.org/docs/current/static/sql-grant.html) for more information. +Manages grant-based access privileges for users, wrapping +the `postgresql::server::database_grant` for database specific permissions. +Consult +[the PostgreSQL documentation for `GRANT`](http://www.postgresql.org/docs/current/static/sql-grant.html) +for more information. ##### `ensure` Specifies whether to grant or revoke the privilege. Default is to grant the privilege. Valid values: 'present', 'absent'. * 'present' to grant the privilege * 'absent' to revoke the privilege Default value: 'present'. #### `connect_settings` -Specifies a hash of environment variables used when connecting to a remote server. +Specifies a hash of environment variables used when connecting to a remote +server. -Default value: Connects to the local Postgres instance. +Default value: local PostgreSQL instance. ##### `db` Specifies the database to which you are granting access. ##### `privilege` -Specifies comma-separated list of privileges to grant. +Specifies comma-separated list of privileges to grant. -Valid options: 'ALL', 'CREATE', 'CONNECT', 'TEMPORARY', 'TEMP'. +Valid values: `ALL`, `CREATE`, `CONNECT`, `TEMPORARY`, `TEMP`. ##### `psql_db` -Defines the database to execute the grant against. +Defines the database to execute the grant against. -**This should not ordinarily be changed from the default** +**Warning:** This should not ordinarily be changed from the default. -Default value: 'postgres'. +Default value: `postgres`. ##### `psql_user` -Specifies the OS user for running `psql`. +Specifies the OS user for running `psql`. -Default value: The default user for the module, usually 'postgres'. +Default value: the default user for the module, usually `postgres`. ##### `role` Specifies the role or user whom you are granting access to. #### postgresql::server::extension Manages a PostgreSQL extension. ##### `database` Specifies the database on which to activate the extension. +##### `schema` + +Specifies the schema on which to activate the extension. + ##### `ensure` Specifies whether to activate or deactivate the extension. -Valid options: 'present' or 'absent'. +Valid values: `present` or `absent`. -#### `extension` +##### `extension` -Specifies the extension to activate. If left blank, uses the name of the resource. +Specifies the extension to activate. If left blank, uses the name of +the resource. -#### `version` +##### `version` Specifies the version of the extension which the database uses. -When an extension package is updated, this does not automatically change the effective version in each database. +When an extension package is updated, this does not automatically change +the effective version in each database. This needs be updated using the PostgreSQL-specific SQL `ALTER EXTENSION...` -`version` may be set to `latest`, in which case the SQL `ALTER EXTENSION "extension" UPDATE` is applied to this database (only). +`version` may be set to `latest`, in which case the SQL +`ALTER EXTENSION "extension" UPDATE` is applied to this database (only). -`version` may be set to a specific version, in which case the extension is updated using `ALTER EXTENSION "extension" UPDATE TO 'version'` +`version` may be set to a specific version, in which case the extension is +updated using `ALTER EXTENSION "extension" UPDATE TO 'version'` -eg. If extension is set to `postgis` and version is set to `2.3.3`, this will apply the SQL `ALTER EXTENSION "postgis" UPDATE TO '2.3.3'` to this database only. +For example, if extension is set to `postgis` and version is set to `2.3.3`, +this will only apply the SQL `ALTER EXTENSION "postgis" UPDATE TO '2.3.3'` to +the database. -`version` may be omitted, in which case no `ALTER EXTENSION...` SQL is applied, and the version will be left unchanged. +`version` may be omitted, in which case no `ALTER EXTENSION...` SQL is applied, +and the version will be left unchanged. ##### `package_name` Specifies a package to install prior to activating the extension. ##### `package_ensure` Overrides default package deletion behavior. -By default, the package specified with `package_name` is installed when the extension is activated and removed when the extension is deactivated. To override this behavior, set the `ensure` value for the package. +By default, the package specified with `package_name` is installed when +the extension is activated and removed when the extension is deactivated. +To override this behavior, set the `ensure` value for the package. #### postgresql::server::grant -Manages grant-based access privileges for roles. See [PostgreSQL documentation for `grant`](http://www.postgresql.org/docs/current/static/sql-grant.html) for more information. +Manages grant-based access privileges for roles. See +[PostgreSQL documentation for `grant`](http://www.postgresql.org/docs/current/static/sql-grant.html) +for more information. ##### `ensure` Specifies whether to grant or revoke the privilege. Default is to grant the privilege. Valid values: 'present', 'absent'. * 'present' to grant the privilege * 'absent' to revoke the privilege Default value: 'present'. ##### `db` Specifies the database to which you are granting access. ##### `object_type` Specifies the type of object to which you are granting privileges. -Valid options: 'DATABASE', 'SCHEMA', 'SEQUENCE', 'ALL SEQUENCES IN SCHEMA', 'TABLE' or 'ALL TABLES IN SCHEMA'. +Valid values: 'DATABASE', 'SCHEMA', 'SEQUENCE', 'ALL SEQUENCES IN SCHEMA', +'TABLE' or 'ALL TABLES IN SCHEMA'. ##### `object_name` -Specifies name of `object_type` to which to grant access, can be either a string or a two element array. - -String: 'object_name' -Array: ['schema_name', 'object_name'] +Specifies name of `object_type` to which to grant access, can be either +a string or a two element array. When it is an array then the first element +must be the `object_type` and the second actual `object_name`. ##### `port` Port to use when connecting. -Default value: `undef`, which generally defaults to port 5432 depending on your PostgreSQL packaging. +Default value: `undef`, which generally defaults to port 5432 depending on your +PostgreSQL packaging. ##### `privilege` Specifies the privilege to grant. -Valid options: 'ALL', 'ALL PRIVILEGES' or 'object_type' dependent string. +Valid values: `ALL`, `ALL PRIVILEGES` or `object_type` dependent string. ##### `psql_db` Specifies the database to execute the grant against. -**This should not ordinarily be changed from the default** +**Warning:** This should not ordinarily be changed from the default. -Default value: 'postgres'. +Default value: `postgres`. ##### `psql_user` Sets the OS user to run `psql`. -Default value: the default user for the module, usually 'postgres'. +Default value: the default user for the module, usually `postgres`. ##### `role` Specifies the role or user whom you are granting access to. #### postgresql::server::grant_role -Allows you to assign a role to a (group) role. See [PostgreSQL documentation for `Role Membership`](http://www.postgresql.org/docs/current/static/role-membership.html) for more information. +Allows you to assign a role to a (group) role. See +[PostgreSQL documentation for `Role Membership`](http://www.postgresql.org/docs/current/static/role-membership.html) +for more information. ##### `group` Specifies the group role to which you are assigning a role. ##### `role` -Specifies the role you want to assign to a group. If left blank, uses the name of the resource. +Specifies the role you want to assign to a group. If left blank, uses the name +of the resource. ##### `ensure` Specifies whether to grant or revoke the membership. -Valid options: 'present' or 'absent'. +Valid values: `present` or `absent`. -Default value: 'present'. +Default value: `present`. ##### `port` Port to use when connecting. -Default value: `undef`, which generally defaults to port 5432 depending on your PostgreSQL packaging. +Default value: `undef`, which generally defaults to port 5432 depending on your +PostgreSQL packaging. ##### `psql_db` Specifies the database to execute the grant against. -**This should not ordinarily be changed from the default** +**Warning:** This should not ordinarily be changed from the default. -Default value: 'postgres'. +Default value: `postgres`. ##### `psql_user` Sets the OS user to run `psql`. Default value: the default user for the module, usually `postgres`. ##### `connect_settings` -Specifies a hash of environment variables used when connecting to a remote server. +Specifies a hash of environment variables used when connecting to a remote +server. -Default value: Connects to the local Postgres instance. +Default value: local PostgreSQL instance. #### postgresql::server::pg_hba_rule -Allows you to create an access rule for `pg_hba.conf`. For more details see the [usage example](#create-an-access-rule-for-pghba.conf) and the [PostgreSQL documentation](http://www.postgresql.org/docs/current/static/auth-pg-hba-conf.html). +Allows you to create an access rule for `pg_hba.conf`. For more details see +[the usage example](#create-an-access-rule-for-pghba.conf) and +[the PostgreSQL HBA documentation](http://www.postgresql.org/docs/current/static/auth-pg-hba-conf.html). ##### `address` -Sets a CIDR based address for this rule matching when the type is not 'local'. +Sets a CIDR based address for this rule matching when the type is not `local`. ##### `auth_method` -Provides the method that is used for authentication for the connection that this rule matches. Described further in the PostgreSQL `pg_hba.conf` documentation. +Provides the method that is used for authentication for the connection that +this rule matches. ##### `auth_option` -For certain `auth_method` settings there are extra options that can be passed. Consult the PostgreSQL `pg_hba.conf` documentation for further details. +For certain `auth_method` settings there are extra options that can be passed. ##### `database` Sets a comma-separated list of databases that this rule matches. ##### `description` -Defines a longer description for this rule, if required. This description is placed in the comments above the rule in `pg_hba.conf`. +Defines a longer description for this rule, if required. This description is +placed in the comments above the rule in `pg_hba.conf`. -Default value: 'none'. +Default value: `none`. -Specifies a way to uniquely identify this resource, but functionally does nothing. +Specifies a way to uniquely identify this resource, but functionally does +nothing. ##### `order` Sets an order for placing the rule in `pg_hba.conf`. Default value: 150. #### `postgresql_version` Manages `pg_hba.conf` without managing the entire PostgreSQL instance. Default value: the version set in `postgresql::server`. ##### `target` Provides the target for the rule, and is generally an internal only property. -**Use with caution.** +**Warning:** Use with caution. ##### `type` Sets the type of rule. -Valid options: 'local', 'host', 'hostssl' or 'hostnossl'. +Valid values: `local`, `host`, `hostssl` or `hostnossl`. ##### `user` Sets a comma-separated list of users that this rule matches. - #### postgresql::server::pg_ident_rule -Allows you to create user name maps for `pg_ident.conf`. For more details see the [usage example](#create-user-name-maps-for-pgidentconf) above and the [PostgreSQL documentation](http://www.postgresql.org/docs/current/static/auth-username-maps.html). +Allows you to create user name maps for `pg_ident.conf`. For more details see +[the usage example](#create-user-name-maps-for-pgidentconf) above and +[the PostgreSQL User Name Maps documentation](http://www.postgresql.org/docs/current/static/auth-username-maps.html). ##### `database_username` -Specifies the user name of the database user. The `system_username` is mapped to this user name. +Specifies the user name of the database user. The `system_username` is mapped +to this user name. ##### `description` -Sets a longer description for this rule if required. This description is placed in the comments above the rule in `pg_ident.conf`. +Sets a longer description for this rule if required. This description is +placed in the comments above the rule in `pg_ident.conf`. -Default value: 'none'. +Default value: `none`. ##### `map_name` -Sets the name of the user map that is used to refer to this mapping in `pg_hba.conf`. +Sets the name of the user map that is used to refer to this mapping +in `pg_hba.conf`. ##### `order` Defines an order for placing the mapping in `pg_ident.conf`. Default value: 150. ##### `system_username` -Specifies the operating system user name (the user name used to connect to the database). +Specifies the operating system user name (the user name used to connect to +the database). ##### `target` Provides the target for the rule and is generally an internal only property. -**Use with caution.** +**Warning:** Use with caution. #### postgresql::server::reassign_owned_by -Runs the PostgreSQL command 'REASSIGN OWNED' on a database, to transfer the ownership of existing objects between database roles +Runs the PostgreSQL command `REASSIGN OWNED` on a database, to transfer +the ownership of existing objects between database roles ##### `db` -Specifies the database to which the 'REASSIGN OWNED' will be applied +Specifies the database to which the `REASSIGN OWNED` will be applied. ##### `old_role` -Specifies the role or user who is the current owner of the objects in the specified db +Specifies the role or user who is the current owner of the objects in +the specified db. ##### `new_role` -Specifies the role or user who will be the new owner of these objects +Specifies the role or user who will be the new owner of these objects. ##### `psql_user` Specifies the OS user for running `psql`. -Default value: The default user for the module, usually 'postgres'. +Default value: the default user for the module, usually `postgres`. ##### `port` Port to use when connecting. -Default value: `undef`, which generally defaults to port 5432 depending on your PostgreSQL packaging. +Default value: `undef`, which generally defaults to port 5432 depending on +your PostgreSQL packaging. ##### `connect_settings` -Specifies a hash of environment variables used when connecting to a remote server. +Specifies a hash of environment variables used when connecting to a remote +server. -Default value: Connects to the local Postgres instance. +Default value: local PostgreSQL instance. #### postgresql::server::recovery -Allows you to create the content for `recovery.conf`. For more details see the [usage example](#create-recovery-configuration) and the [PostgreSQL documentation](http://www.postgresql.org/docs/current/static/recovery-config.html). +Allows you to create the content for `recovery.conf`. For more details see +[the usage example](#create-recovery-configuration) and +[the PostgreSQL Recovery Configuration documentation](http://www.postgresql.org/docs/current/static/recovery-config.html). -Every parameter value is a string set in the template except `recovery_target_inclusive`, `pause_at_recovery_target`, `standby_mode` and `recovery_min_apply_delay`. +Every parameter value is a string set in the template except +`recovery_target_inclusive`, `pause_at_recovery_target`, `standby_mode` and +`recovery_min_apply_delay`. -A detailed description of all listed parameters can be found in the [PostgreSQL documentation](http://www.postgresql.org/docs/current/static/recovery-config.html). +A detailed description of all listed parameters can be found in +[the PostgreSQL documentation](http://www.postgresql.org/docs/current/static/recovery-config.html). The parameters are grouped into these three sections: ##### [Archive Recovery Parameters](http://www.postgresql.org/docs/current/static/archive-recovery-settings.html) * `restore_command` * `archive_cleanup_command` * `recovery_end_command` ##### [Recovery Target Settings](http://www.postgresql.org/docs/current/static/recovery-target-settings.html) + * `recovery_target_name` * `recovery_target_time` * `recovery_target_xid` * `recovery_target_inclusive` * `recovery_target` * `recovery_target_timeline` * `pause_at_recovery_target` ##### [Standby Server Settings](http://www.postgresql.org/docs/current/static/standby-settings.html) -* `standby_mode`: Can be specified with the string ('on'/'off'), or by using a Boolean value (`true`/`false`). + +* `standby_mode`: Can be specified with the string (`on`/`off`), or by using a `Boolean` value (`true`/`false`). * `primary_conninfo` * `primary_slot_name` * `trigger_file` * `recovery_min_apply_delay` ##### `target` + Provides the target for the rule, and is generally an internal only property. - -**Use with caution.** + +**Warning:** Use with caution. #### postgresql::server::role -Creates a role or user in PostgreSQL. + +Creates or drops a role or user in PostgreSQL. + +##### `ensure` + +Specify whether to create or drop the role. + +Specifying `present` will create the role. +Specifying `absent` will drop the role. + +Default value: `present`. ##### `connection_limit` + Specifies how many concurrent connections the role can make. -Default value: '-1', meaning no limit. +Default value: `-1`, meaning no limit. ##### `connect_settings` -Specifies a hash of environment variables used when connecting to a remote server. -Default value: Connects to the local Postgres instance. +Specifies a hash of environment variables used when connecting to a remote +server. + +Default value: local PostgreSQL instance. ##### `createdb` + Specifies whether to grant the ability to create new databases with this role. Default value: `false`. ##### `createrole` + Specifies whether to grant the ability to create new roles with this role. Default value: `false`. ##### `inherit` + Specifies whether to grant inherit capability for the new role. Default value: `true`. ##### `login` + Specifies whether to grant login capability for the new role. Default value: `true`. ##### `password_hash` -Sets the hash to use during password creation. If the password is not already pre-encrypted in a format that PostgreSQL supports, use the `postgresql_password` function to provide an MD5 hash here, for example: + +Sets the hash to use during password creation. If the password is not already +pre-encrypted in a format that PostgreSQL supports, use +the `postgresql_password` function to provide an MD5 hash here, for example: ##### `update_password` -If set to true, updates the password on changes. Set this to false to not modify the role's password after creation. + +If set to true, updates the password on changes. Set this to false to not +modify the role's password after creation. ```puppet postgresql::server::role { 'myusername': password_hash => postgresql_password('myusername', 'mypassword'), } ``` ##### `replication` Provides provides replication capabilities for this role if set to `true`. Default value: `false`. ##### `superuser` Specifies whether to grant super user capability for the new role. Default value: `false`. ##### `username` Defines the username of the role to create. Default value: the namevar. #### postgresql::server::schema Creates a schema. ##### `connect_settings` -Specifies a hash of environment variables used when connecting to a remote server. +Specifies a hash of environment variables used when connecting to a remote +server. -Default value: Connects to the local Postgres instance. +Default value: local PostgreSQL instance. ##### `db` Required. Sets the name of the database in which to create this schema. ##### `owner` Sets the default owner of the schema. ##### `schema` Sets the name of the schema. Default value: the namevar. #### postgresql::server::table_grant -Manages grant-based access privileges for users. Consult the PostgreSQL documentation for `grant` for more information. +Manages grant-based access privileges for users. Consult +[the PostgreSQL documentation for `GRANT`](http://www.postgresql.org/docs/current/static/sql-grant.html) +for more information. ##### `ensure` Specifies whether to grant or revoke the privilege. Default is to grant the privilege. Valid values: 'present', 'absent'. * 'present' to grant the privilege * 'absent' to revoke the privilege Default value: 'present'. ##### `connect_settings` -Specifies a hash of environment variables used when connecting to a remote server. +Specifies a hash of environment variables used when connecting to a remote +server. -Default value: Connects to the local Postgres instance. +Default value: local PostgreSQL instance. ##### `db` Specifies which database the table is in. ##### `privilege` -Specifies comma-separated list of privileges to grant. Valid options: 'ALL', 'SELECT', 'INSERT', 'UPDATE', 'DELETE', 'TRUNCATE', 'REFERENCES', 'TRIGGER'. +Specifies comma-separated list of privileges to grant. + +Valid values: `ALL`, `SELECT`, `INSERT`, `UPDATE`, `DELETE`, `TRUNCATE`, +`REFERENCES`, `TRIGGER`. ##### `psql_db` Specifies the database to execute the grant against. -This should not ordinarily be changed from the default. +**Warning:** This should not ordinarily be changed from the default. -Default value: 'postgres'. +Default value: `postgres`. ##### `psql_user` Specifies the OS user for running `psql`. -Default value: The default user for the module, usually 'postgres'. +Default value: the default user for the module, usually `postgres`. ##### `role` Specifies the role or user to whom you are granting access. ##### `table` Specifies the table to which you are granting access. #### postgresql::server::tablespace -Creates a tablespace. If necessary, also creates the location and assigns the same permissions as the PostgreSQL server. +Creates a tablespace. If necessary, also creates the location and assigns +the same permissions as the PostgreSQL server. ##### `connect_settings` -Specifies a hash of environment variables used when connecting to a remote server. +Specifies a hash of environment variables used when connecting to a remote +server. -Default value: Connects to the local Postgres instance. +Default value: local PostgreSQL instance. ##### `location` Specifies the path to locate this tablespace. ##### `owner` Specifies the default owner of the tablespace. ##### `spcname` Specifies the name of the tablespace. Default value: the namevar. ### Types #### postgresql_psql -Enables Puppet to run psql statements. +Enables Puppet to run `psql` statements. ##### `command` Required. -Specifies the SQL command to execute via psql. +Specifies the SQL command to execute via `psql`. ##### `cwd` -Specifies the working directory under which the psql command should be executed. +Specifies the working directory under which the `psql` command should be +executed. -Default value: '/tmp'. +Default value: `/tmp`. ##### `db` Specifies the name of the database to execute the SQL command against. ##### `environment` -Specifies any additional environment variables you want to set for a SQL command. Multiple environment variables should be specified as an array. +Specifies any additional environment variables you want to set for a SQL +command. Multiple environment variables should be specified as an array. ##### `name` -Sets an arbitrary tag for your own reference; the name of the message. This is the namevar. +Sets an arbitrary tag for your own reference; the name of the message. +This is the namevar. ##### `onlyif` -Sets an optional SQL command to execute prior to the main command. This is generally intended to be used for idempotency, to check for the existence of an object in the database to determine whether or not the main SQL command needs to be executed at all. +Sets an optional SQL command to execute prior to the main command. This is +generally intended to be used for idempotency, to check for the existence of +an object in the database to determine whether or not the main SQL command +needs to be executed at all. ##### `port` Specifies the port of the database server to execute the SQL command against. ##### `psql_group` -Specifies the system user group account under which the psql command should be executed. +Specifies the system user group account under which the `psql` command should +be executed. -Default value: 'postgres'. +Default value: `postgres`. ##### `psql_path` -Specifies the path to psql executable. +Specifies the path to `psql` executable. -Default value: 'psql'. +Default value: `psql`. ##### `psql_user` -Specifies the system user account under which the psql command should be executed. +Specifies the system user account under which the `psql` command should be +executed. -Default value: 'postgres'. +Default value: `postgres`. ##### `refreshonly` -Specifies whether to execute the SQL only if there is a notify or subscribe event. +Specifies whether to execute the SQL only if there is a notify or subscribe +event. Valid values: `true`, `false`. Default value: `false`. ##### `search_path` Defines the schema search path to use when executing the SQL command. ##### `unless` The inverse of `onlyif`. #### postgresql_conf Allows Puppet to manage `postgresql.conf` parameters. ##### `name` Specifies the PostgreSQL parameter name to manage. This is the namevar. ##### `target` Specifies the path to `postgresql.conf`. -Default value: '/etc/postgresql.conf'. +Default value: `/etc/postgresql.conf`. ##### `value` Specifies the value to set for this parameter. #### postgresql_replication_slot -Allows you to create and destroy replication slots to register warm standby replication on a PostgreSQL master server. +Allows you to create and destroy replication slots to register warm standby +replication on a PostgreSQL master server. ##### `name` -Specifies the name of the slot to create. Must be a valid replication slot name. +Specifies the name of the slot to create. Must be a valid replication slot +name. This is the namevar. ##### `ensure` Required. -Specifies the action to create or destroy named slot. +Specifies the action to create or destroy named slot. -Valid values: 'present', 'absent'. +Valid values: `present`, `absent`. -Default value: 'present'. +Default value: `present`. #### postgresql_conn_validator -Validate the connection to a local or remote PostgreSQL database using this type. +Validate the connection to a local or remote PostgreSQL database using this +type. ##### `connect_settings` -Specifies a hash of environment variables used when connecting to a remote server. This is an alternative to providing individual parameters (`host`, etc). If provided, the individual parameters take precedence. +Specifies a hash of environment variables used when connecting to a remote +server. This is an alternative to providing individual parameters +(`host`, etc). If provided, the individual parameters take precedence. -Default value: {} +Default value: `{}` ##### `db_name` Specifies the name of the database you wish to test. -Default value: '' +Default value: `''` ##### `db_password` -Specifies the password to connect with. Can be left blank if `.pgpass` is being used, otherwise not recommended. +Specifies the password to connect with. Can be left blank if `.pgpass` is +being used, otherwise not recommended. -Default value: '' +Default value: `''` ##### `db_username` Specifies the username to connect with. -Default value: '' +Default value: `''` When using a Unix socket and ident auth, this is the user you are running as. ##### `command` This is the command run against the target database to verify connectivity. -Default value: 'SELECT 1' +Default value: `SELECT 1` ##### `host` Sets the hostname of the database you wish to test. -Default value: '', which generally uses the designated local Unix socket. +Default value: `''`, which generally uses the designated local Unix socket. -**If the host is remote you must provide a username.** +**Warning:** If the host is remote you must provide a username. ##### `port` Defines the port to use when connecting. -Default value: '' +Default value: `''` ##### `run_as` -Specifies the user to run the `psql` command as. This is important when trying to connect to a database locally using Unix sockets and `ident` authentication. Not needed for remote testing. +Specifies the user to run the `psql` command as. This is important when trying +to connect to a database locally using Unix sockets and `ident` authentication. +Not needed for remote testing. ##### `sleep` Sets the number of seconds to sleep for before trying again after a failure. ##### `tries` -Sets the number of attempts after failure before giving up and failing the resource. +Sets the number of attempts after failure before giving up and failing +the resource. ### Functions #### postgresql_password -Generates a PostgreSQL encrypted password, use `postgresql_password`. Call it from the command line and then copy and paste the encrypted password into your manifest: +Generates a PostgreSQL encrypted password, use `postgresql_password`. Call it +from the command line and then copy and paste the encrypted password into your +manifest: ```shell puppet apply --execute 'notify { 'test': message => postgresql_password('username', 'password') }' ``` -Alternatively, you can call this from your production manifests, but the manifests will then contain a clear text version of your passwords. +Alternatively, you can call this from your production manifests, but +the manifests will then contain a clear text version of your passwords. #### postgresql_acls_to_resources_hash(acl_array, id, order_offset) -This internal function converts a list of `pg_hba.conf` based ACLs (passed in as an array of strings) to a format compatible with the `postgresql::pg_hba_rule` resource. +This internal function converts a list of `pg_hba.conf` based ACLs (passed in +as an array of strings) to a format compatible with +the `postgresql::pg_hba_rule` resource. -**This function should only be used internally by the module**. +**Warning:** This function should only be used internally by the module. ### Tasks -The Postgresql module has an example task that allows a user to execute arbitary SQL against a database. Please refer to to the [PE documentation](https://puppet.com/docs/pe/2017.3/orchestrator/running_tasks.html) or [Bolt documentation](https://puppet.com/docs/bolt/latest/bolt.html) on how to execute a task. +The postgresql module has an example task that allows a user to execute +arbitrary SQL against a database. Please refer to to +[the PE documentation](https://puppet.com/docs/pe/2017.3/orchestrator/running_tasks.html) or +[the Bolt documentation](https://puppet.com/docs/bolt/latest/bolt.html) on how +to execute a task. ## Limitations Works with versions of PostgreSQL from 8.1 through 9.5. Currently, the postgresql module is tested on the following operating systems: * Debian 6.x, 7.x, 8.x. * CentOS 5.x, 6.x, and 7.x. * Ubuntu 10.04 and 12.04, 14.04. Other systems might be compatible, but are not being actively tested. ### Apt module support -While this module supports both 1.x and 2.x versions of the 'puppetlabs-apt' module, it does not support 'puppetlabs-apt' 2.0.0 or 2.0.1. +While this module supports both 1.x and 2.x versions of the puppetlabs-apt +module, it does not support puppetlabs-apt 2.0.0 or 2.0.1. ### PostGIS support -PostGIS is currently considered an unsupported feature, as it doesn't work on all platforms correctly. +PostGIS is currently considered an unsupported feature, as it doesn't work on +all platforms correctly. ### All versions of RHEL/CentOS -If you have SELinux enabled you must add any custom ports you use to the `postgresql_port_t` context. You can do this as follows: +If you have SELinux enabled you must add any custom ports you use to +the `postgresql_port_t` context. You can do this as follows: ```shell semanage port -a -t postgresql_port_t -p tcp $customport ``` ## Development -Puppet Labs modules on the Puppet Forge are open projects, and community contributions are essential for keeping them great. We can’t access the huge number of platforms and myriad hardware, software, and deployment configurations that Puppet is intended to serve. We want to keep it as easy as possible to contribute changes so that our modules work in your environment. There are a few guidelines that we need contributors to follow so that we can have a chance of keeping on top of things. For more information, see our [module contribution guide](https://docs.puppetlabs.com/forge/contributing.html). +Puppet Labs modules on the Puppet Forge are open projects, and community +contributions are essential for keeping them great. We can't access the huge +number of platforms and myriad hardware, software, and deployment +configurations that Puppet is intended to serve. We want to keep it as easy +as possible to contribute changes so that our modules work in your environment. +There are a few guidelines that we need contributors to follow so that we can +have a chance of keeping on top of things. For more information, see our +[module contribution guide](https://docs.puppetlabs.com/forge/contributing.html). ### Tests -There are two types of tests distributed with this module. Unit tests with `rspec-puppet` and system tests using `rspec-system`. +There are two types of tests distributed with this module. Unit tests with +`rspec-puppet` and system tests using `rspec-system`. For unit testing, make sure you have: * rake * bundler Install the necessary gems: ```shell bundle install --path=vendor ``` And then run the unit tests: ```shell bundle exec rake spec ``` -The unit tests are run in Travis-CI as well. If you want to see the results of your own tests, register the service hook through Travis-CI via the accounts section for your GitHub clone of this project. +The unit tests are run in Travis-CI as well. If you want to see the results of +your own tests, register the service hook through Travis-CI via the accounts +section for your GitHub clone of this project. To run the system tests, make sure you also have: * Vagrant > 1.2.x * VirtualBox > 4.2.10 Then run the tests using: ```shell bundle exec rspec spec/acceptance ``` -To run the tests on different operating systems, see the sets available in `.nodeset.yml` and run the specific set with the following syntax: +To run the tests on different operating systems, see the sets available +in `.nodeset.yml` and run the specific set with the following syntax: ```shell RSPEC_SET=debian-607-x64 bundle exec rspec spec/acceptance ``` ### Contributors -View the full list of contributors on [Github](https://github.com/puppetlabs/puppetlabs-postgresql/graphs/contributors). +View the full list of contributors on +[GitHub](https://github.com/puppetlabs/puppetlabs-postgresql/graphs/contributors). diff --git a/lib/puppet/parser/functions/postgresql_acls_to_resources_hash.rb b/lib/puppet/parser/functions/postgresql_acls_to_resources_hash.rb index 2508f85..e9112ca 100644 --- a/lib/puppet/parser/functions/postgresql_acls_to_resources_hash.rb +++ b/lib/puppet/parser/functions/postgresql_acls_to_resources_hash.rb @@ -1,76 +1,75 @@ +# postgresql_acls_to_resources_hash.rb module Puppet::Parser::Functions - newfunction(:postgresql_acls_to_resources_hash, :type => :rvalue, :doc => <<-EOS + newfunction(:postgresql_acls_to_resources_hash, type: :rvalue, doc: <<-EOS This internal function translates the ipv(4|6)acls format into a resource suitable for create_resources. It is not intended to be used outside of the postgresql internal classes/defined resources. This function accepts an array of strings that are pg_hba.conf rules. It will return a hash that can be fed into create_resources to create multiple individual pg_hba_rule resources. The second parameter is an identifier that will be included in the namevar to provide uniqueness. It must be a string. The third parameter is an order offset, so you can start the order at an arbitrary starting point. EOS - ) do |args| - func_name = "postgresql_acls_to_resources_hash()" + ) do |args| + func_name = 'postgresql_acls_to_resources_hash()' - raise(Puppet::ParseError, "#{func_name}: Wrong number of arguments " + - "given (#{args.size} for 3)") if args.size != 3 + if args.size != 3 + raise(Puppet::ParseError, "#{func_name}: Wrong number of arguments " \ + "given (#{args.size} for 3)") + end acls = args[0] raise(Puppet::ParseError, "#{func_name}: first argument must be an array") \ unless acls.instance_of? Array id = args[1] raise(Puppet::ParseError, "#{func_name}: second argument must be a string") \ unless id.instance_of? String offset = args[2].to_i raise(Puppet::ParseError, "#{func_name}: third argument must be a number") \ unless offset.is_a? Integer resources = {} acls.each do |acl| index = acls.index(acl) parts = acl.split - raise(Puppet::ParseError, "#{func_name}: acl line #{index} does not " + - "have enough parts") unless parts.length >= 4 + unless parts.length >= 4 + raise(Puppet::ParseError, "#{func_name}: acl line #{index} does not " \ + 'have enough parts') + end resource = { 'type' => parts[0], 'database' => parts[1], 'user' => parts[2], - 'order' => format('%03d', offset + index), + 'order' => format('%03d', offset + index), # rubocop:disable Style/FormatString } - if parts[0] == 'local' then + if parts[0] == 'local' resource['auth_method'] = parts[3] - if parts.length > 4 then - resource['auth_option'] = parts.last(parts.length - 4).join(" ") + if parts.length > 4 + resource['auth_option'] = parts.last(parts.length - 4).join(' ') end - else - if parts[4] =~ /^\d/ - resource['address'] = parts[3] + ' ' + parts[4] - resource['auth_method'] = parts[5] + elsif parts[4] =~ %r{^\d} + resource['address'] = parts[3] + ' ' + parts[4] + resource['auth_method'] = parts[5] - if parts.length > 6 then - resource['auth_option'] = parts.last(parts.length - 6).join(" ") - end - else - resource['address'] = parts[3] - resource['auth_method'] = parts[4] + resource['auth_option'] = parts.last(parts.length - 6).join(' ') if parts.length > 6 + else + resource['address'] = parts[3] + resource['auth_method'] = parts[4] - if parts.length > 5 then - resource['auth_option'] = parts.last(parts.length - 5).join(" ") - end - end + resource['auth_option'] = parts.last(parts.length - 5).join(' ') if parts.length > 5 end resources["postgresql class generated rule #{id} #{index}"] = resource end resources end end diff --git a/lib/puppet/parser/functions/postgresql_escape.rb b/lib/puppet/parser/functions/postgresql_escape.rb index 1ec11b8..49d6d7e 100644 --- a/lib/puppet/parser/functions/postgresql_escape.rb +++ b/lib/puppet/parser/functions/postgresql_escape.rb @@ -1,25 +1,28 @@ require 'digest/md5' +# postgresql_escape.rb module Puppet::Parser::Functions - newfunction(:postgresql_escape, :type => :rvalue, :doc => <<-EOS + newfunction(:postgresql_escape, type: :rvalue, doc: <<-EOS Safely escapes a string using $$ using a random tag which should be consistent EOS - ) do |args| + ) do |args| - raise(Puppet::ParseError, "postgresql_escape(): Wrong number of arguments " + - "given (#{args.size} for 1)") if args.size != 1 + if args.size != 1 + raise(Puppet::ParseError, 'postgresql_escape(): Wrong number of arguments ' \ + "given (#{args.size} for 1)") + end password = args[0] - if password !~ /\$\$/ and password[-1] != '$' + if password !~ %r{\$\$} && password[-1] != '$' retval = "$$#{password}$$" else - escape = Digest::MD5.hexdigest(password)[0..5].gsub(/\d/,'') - until password !~ /#{escape}/ - escape = Digest::MD5.hexdigest(escape)[0..5].gsub(/\d/,'') + escape = Digest::MD5.hexdigest(password)[0..5].gsub(%r{\d}, '') + until password !~ %r{#{escape}} + escape = Digest::MD5.hexdigest(escape)[0..5].gsub(%r{\d}, '') end retval = "$#{escape}$#{password}$#{escape}$" end retval end end diff --git a/lib/puppet/parser/functions/postgresql_password.rb b/lib/puppet/parser/functions/postgresql_password.rb index e5d2620..e53e5f9 100644 --- a/lib/puppet/parser/functions/postgresql_password.rb +++ b/lib/puppet/parser/functions/postgresql_password.rb @@ -1,18 +1,21 @@ # hash a string as mysql's "PASSWORD()" function would do it require 'digest/md5' +# postgresql_password.rb module Puppet::Parser::Functions - newfunction(:postgresql_password, :type => :rvalue, :doc => <<-EOS + newfunction(:postgresql_password, type: :rvalue, doc: <<-EOS Returns the postgresql password hash from the clear text username / password. EOS - ) do |args| + ) do |args| - raise(Puppet::ParseError, "postgresql_password(): Wrong number of arguments " + - "given (#{args.size} for 2)") if args.size != 2 + if args.size != 2 + raise(Puppet::ParseError, 'postgresql_password(): Wrong number of arguments ' \ + "given (#{args.size} for 2)") + end username = args[0] password = args[1] 'md5' + Digest::MD5.hexdigest(password.to_s + username.to_s) end end diff --git a/lib/puppet/provider/postgresql_conf/parsed.rb b/lib/puppet/provider/postgresql_conf/parsed.rb index 88bd303..40a9cd4 100644 --- a/lib/puppet/provider/postgresql_conf/parsed.rb +++ b/lib/puppet/provider/postgresql_conf/parsed.rb @@ -1,42 +1,40 @@ require 'puppet/provider/parsedfile' Puppet::Type.type(:postgresql_conf).provide( :parsed, - :parent => Puppet::Provider::ParsedFile, - :default_target => '/etc/postgresql.conf', - :filetype => :flat + parent: Puppet::Provider::ParsedFile, + default_target: '/etc/postgresql.conf', + filetype: :flat, ) do - desc "Set key/values in postgresql.conf." + desc 'Set key/values in postgresql.conf.' - text_line :comment, :match => /^\s*#/ - text_line :blank, :match => /^\s*$/ + text_line :comment, match: %r{^\s*#} + text_line :blank, match: %r{^\s*$} record_line :parsed, - :fields => %w{name value comment}, - :optional => %w{comment}, - :match => /^\s*([\w\.]+)\s*=?\s*(.*?)(?:\s*#\s*(.*))?\s*$/, - :to_line => proc { |h| - - # simple string and numeric values don't need to be enclosed in quotes - if h[:value].is_a?(Numeric) - val = h[:value].to_s - else - val = h[:value] - end - dontneedquote = val.match(/^(\d+.?\d+|\w+)$/) - dontneedequal = h[:name].match(/^(include|include_if_exists)$/i) - - str = h[:name].downcase # normalize case - str += dontneedequal ? ' ' : ' = ' - str += "'" unless dontneedquote && !dontneedequal - str += val - str += "'" unless dontneedquote && !dontneedequal - str += " # #{h[:comment]}" unless (h[:comment].nil? or h[:comment] == :absent) - str - }, - :post_parse => proc { |h| - h[:name].downcase! # normalize case - h[:value].gsub!(/(^'|'$)/, '') # strip out quotes - } + fields: %w[name value comment], + optional: %w[comment], + match: %r{^\s*([\w\.]+)\s*=?\s*(.*?)(?:\s*#\s*(.*))?\s*$}, + to_line: proc { |h| + # simple string and numeric values don't need to be enclosed in quotes + val = if h[:value].is_a?(Numeric) + h[:value].to_s + else + h[:value] + end + dontneedquote = val.match(%r{^(\d+.?\d+|\w+)$}) + dontneedequal = h[:name].match(%r{^(include|include_if_exists)$}i) + str = h[:name].downcase # normalize case + str += dontneedequal ? ' ' : ' = ' + str += "'" unless dontneedquote && !dontneedequal + str += val + str += "'" unless dontneedquote && !dontneedequal + str += " # #{h[:comment]}" unless h[:comment].nil? || h[:comment] == :absent + str + }, + post_parse: proc { |h| + h[:name].downcase! # normalize case + h[:value].gsub!(%r{(^'|'$)}, '') # strip out quotes + } end diff --git a/lib/puppet/provider/postgresql_conn_validator/ruby.rb b/lib/puppet/provider/postgresql_conn_validator/ruby.rb index f31b8b9..6e26e52 100644 --- a/lib/puppet/provider/postgresql_conn_validator/ruby.rb +++ b/lib/puppet/provider/postgresql_conn_validator/ruby.rb @@ -1,43 +1,41 @@ -$LOAD_PATH.unshift(File.join(File.dirname(__FILE__),"..","..","..")) +$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', '..', '..')) require 'puppet/util/postgresql_validator' # This file contains a provider for the resource type `postgresql_conn_validator`, # which validates the puppetdb connection by attempting an https connection. Puppet::Type.type(:postgresql_conn_validator).provide(:ruby) do desc "A provider for the resource type `postgresql_conn_validator`, which validates the PostgreSQL connection by attempting a query to the target PostgreSQL server." # Test to see if the resource exists, returns true if it does, false if it # does not. # # Here we simply monopolize the resource API, to execute a test to see if the # database is connectable. When we return a state of `false` it triggers the # create method where we can return an error message. # # @return [bool] did the test succeed? def exists? validator.attempt_connection(resource[:sleep], resource[:tries]) end # This method is called when the exists? method returns false. # # @return [void] def create # If `#create` is called, that means that `#exists?` returned false, which # means that the connection could not be established... so we need to # cause a failure here. raise Puppet::Error, "Unable to connect to PostgreSQL server! (#{resource[:host]}:#{resource[:port]})" end # Returns the existing validator, if one exists otherwise creates a new object # from the class. # # @api private def validator @validator ||= Puppet::Util::PostgresqlValidator.new(resource) end - end - diff --git a/lib/puppet/provider/postgresql_psql/ruby.rb b/lib/puppet/provider/postgresql_psql/ruby.rb index 166c8bc..45e7b07 100644 --- a/lib/puppet/provider/postgresql_psql/ruby.rb +++ b/lib/puppet/provider/postgresql_psql/ruby.rb @@ -1,80 +1,77 @@ Puppet::Type.type(:postgresql_psql).provide(:ruby) do - def run_unless_sql_command(sql) # for the 'unless' queries, we wrap the user's query in a 'SELECT COUNT', # which makes it easier to parse and process the output. - run_sql_command('SELECT COUNT(*) FROM (' << sql << ') count') + run_sql_command('SELECT COUNT(*) FROM (' << sql << ') count') end def run_sql_command(sql) if resource[:search_path] sql = "set search_path to #{Array(resource[:search_path]).join(',')}; #{sql}" end command = [resource[:psql_path]] - command.push("-d", resource[:db]) if resource[:db] - command.push("-p", resource[:port]) if resource[:port] - command.push("-t", "-c", '"' + sql.gsub('"', '\"') + '"') + command.push('-d', resource[:db]) if resource[:db] + command.push('-p', resource[:port]) if resource[:port] + command.push('-t', '-c', '"' + sql.gsub('"', '\"') + '"') environment = get_environment if resource[:cwd] Dir.chdir resource[:cwd] do run_command(command, resource[:psql_user], resource[:psql_group], environment) end else run_command(command, resource[:psql_user], resource[:psql_group], environment) end end private - def get_environment + def get_environment # rubocop:disable Style/AccessorMethodName : Refactor does not work correctly environment = (resource[:connect_settings] || {}).dup - if envlist = resource[:environment] - envlist = [envlist] unless envlist.is_a? Array - envlist.each do |setting| - if setting =~ /^(\w+)=((.|\n)+)$/ - env_name = $1 - value = $2 - if environment.include?(env_name) || environment.include?(env_name.to_sym) - if env_name == 'NEWPGPASSWD' - warning "Overriding environment setting '#{env_name}' with '****'" - else - warning "Overriding environment setting '#{env_name}' with '#{value}'" - end + envlist = resource[:environment] + return environment unless envlist + + envlist = [envlist] unless envlist.is_a? Array + envlist.each do |setting| + if setting =~ %r{^(\w+)=((.|\n)+)$} + env_name = Regexp.last_match(1) + value = Regexp.last_match(2) + if environment.include?(env_name) || environment.include?(env_name.to_sym) + if env_name == 'NEWPGPASSWD' + warning "Overriding environment setting '#{env_name}' with '****'" + else + warning "Overriding environment setting '#{env_name}' with '#{value}'" end - environment[env_name] = value - else - warning "Cannot understand environment setting #{setting.inspect}" end + environment[env_name] = value + else + warning "Cannot understand environment setting #{setting.inspect}" end end - return environment + environment end def run_command(command, user, group, environment) command = command.join ' ' if Puppet::PUPPETVERSION.to_f < 3.0 require 'puppet/util/execution' Puppet::Util::Execution.withenv environment do Puppet::Util::SUIDManager.run_and_capture(command, user, group) end elsif Puppet::PUPPETVERSION.to_f < 3.4 Puppet::Util.withenv environment do Puppet::Util::SUIDManager.run_and_capture(command, user, group) end else - output = Puppet::Util::Execution.execute(command, { - :uid => user, - :gid => group, - :failonfail => false, - :combine => true, - :override_locale => true, - :custom_environment => environment, - }) + output = Puppet::Util::Execution.execute(command, uid: user, + gid: group, + failonfail: false, + combine: true, + override_locale: true, + custom_environment: environment) [output, $CHILD_STATUS.dup] end end - end diff --git a/lib/puppet/provider/postgresql_replication_slot/ruby.rb b/lib/puppet/provider/postgresql_replication_slot/ruby.rb index cc49f7b..b120038 100644 --- a/lib/puppet/provider/postgresql_replication_slot/ruby.rb +++ b/lib/puppet/provider/postgresql_replication_slot/ruby.rb @@ -1,68 +1,59 @@ Puppet::Type.type(:postgresql_replication_slot).provide(:ruby) do # For confinement - commands :psql => 'psql' + commands psql: 'psql' def self.instances - run_sql_command('SELECT * FROM pg_replication_slots;')[0].split("\n").select { |l| l =~ /\|/ }.map do |l| - name, *others = l.strip.split(/\s+\|\s+/) - new({ - :name => name, - :ensure => :present, - }) + run_sql_command('SELECT * FROM pg_replication_slots;')[0].split("\n").select { |l| l =~ %r{\|} }.map do |l| + name, *_others = l.strip.split(%r{\s+\|\s+}) + new(name: name, + ensure: :present) end end def self.prefetch(resources) instances.each do |i| - if slot = resources[i.name] + slot = resources[i.name] + if slot slot.provider = i end end end def exists? @property_hash[:ensure] == :present end def create output = self.class.run_sql_command("SELECT * FROM pg_create_physical_replication_slot('#{resource[:name]}');") - if output[1].success? - @property_hash[:ensure] = :present - else - raise Puppet::Error, "Failed to create replication slot #{resource[:name]}:\n#{output[0]}" - end + raise Puppet::Error, "Failed to create replication slot #{resource[:name]}:\n#{output[0]}" unless output[1].success? + @property_hash[:ensure] = :present end def destroy output = self.class.run_sql_command("SELECT pg_drop_replication_slot('#{resource[:name]}');") - if output[1].success? - @property_hash[:ensure] = :absent - else - raise Puppet::Error, "Failed to destroy replication slot #{resource[:name]}:\n#{output[0]}" - end + raise Puppet::Error, "Failed to destroy replication slot #{resource[:name]}:\n#{output[0]}" unless output[1].success? + @property_hash[:ensure] = :absent end private def self.run_sql_command(sql) command = ['psql', '-t', '-c', sql] - self.run_command(command, 'postgres', 'postgres') + run_command(command, 'postgres', 'postgres') end def self.run_command(command, user, group) if Puppet::PUPPETVERSION.to_f < 3.4 Puppet::Util::SUIDManager.run_and_capture(command, user, group) else - output = Puppet::Util::Execution.execute(command, { - :uid => user, - :gid => group, - :failonfail => false, - :combine => true, - :override_locale => true, - :custom_environment => {} - }) + output = Puppet::Util::Execution.execute(command, uid: user, + gid: group, + failonfail: false, + combine: true, + override_locale: true, + custom_environment: {}) [output, $CHILD_STATUS.dup] end end end diff --git a/lib/puppet/type/postgresql_conf.rb b/lib/puppet/type/postgresql_conf.rb index 6dbaaee..bef52c2 100644 --- a/lib/puppet/type/postgresql_conf.rb +++ b/lib/puppet/type/postgresql_conf.rb @@ -1,29 +1,27 @@ Puppet::Type.newtype(:postgresql_conf) do - - @doc = "This type allows puppet to manage postgresql.conf parameters." + @doc = 'This type allows puppet to manage postgresql.conf parameters.' ensurable newparam(:name) do - desc "The postgresql parameter name to manage." + desc 'The postgresql parameter name to manage.' isnamevar - newvalues(/^[\w\.]+$/) + newvalues(%r{^[\w\.]+$}) end newproperty(:value) do - desc "The value to set for this parameter." + desc 'The value to set for this parameter.' end newproperty(:target) do - desc "The path to postgresql.conf" - defaultto { + desc 'The path to postgresql.conf' + defaultto do if @resource.class.defaultprovider.ancestors.include?(Puppet::Provider::ParsedFile) @resource.class.defaultprovider.default_target else nil end - } + end end - end diff --git a/lib/puppet/type/postgresql_conn_validator.rb b/lib/puppet/type/postgresql_conn_validator.rb index b9dc64e..8a07c6c 100644 --- a/lib/puppet/type/postgresql_conn_validator.rb +++ b/lib/puppet/type/postgresql_conn_validator.rb @@ -1,88 +1,87 @@ Puppet::Type.newtype(:postgresql_conn_validator) do - @doc = "Verify that a connection can be successfully established between a node and the PostgreSQL server. Its primary use is as a precondition to prevent configuration changes from being applied if the PostgreSQL server cannot be reached, but it could potentially be used for other purposes such as monitoring." ensurable do defaultvalues defaultto :present end - newparam(:name, :namevar => true) do + newparam(:name, namevar: true) do desc 'An arbitrary name used as the identity of the resource.' end newparam(:db_name) do - desc "The name of the database you are trying to validate a connection with." + desc 'The name of the database you are trying to validate a connection with.' end newparam(:db_username) do - desc "A user that has access to the target PostgreSQL database." + desc 'A user that has access to the target PostgreSQL database.' end newparam(:db_password) do - desc "The password required to access the target PostgreSQL database." + desc 'The password required to access the target PostgreSQL database.' end newparam(:host) do desc 'The DNS name or IP address of the server where PostgreSQL should be running.' end newparam(:port) do desc 'The port that the PostgreSQL server should be listening on.' validate do |value| Integer(value) end munge do |value| Integer(value) end end newparam(:connect_settings) do desc 'Hash of environment variables for connection to a db.' end newparam(:sleep) do - desc "The length of sleep time between connection tries." + desc 'The length of sleep time between connection tries.' validate do |value| Integer(value) end munge do |value| Integer(value) end defaultto 2 end newparam(:tries) do - desc "The number of tries to validate the connection to the target PostgreSQL database." + desc 'The number of tries to validate the connection to the target PostgreSQL database.' validate do |value| Integer(value) end munge do |value| Integer(value) end defaultto 10 end newparam(:psql_path) do - desc "Path to the psql command." + desc 'Path to the psql command.' end newparam(:run_as) do - desc "System user that will run the psql command." + desc 'System user that will run the psql command.' end newparam(:command) do - desc "Command to run against target database." + desc 'Command to run against target database.' - defaultto "SELECT 1" + defaultto 'SELECT 1' end end diff --git a/lib/puppet/type/postgresql_psql.rb b/lib/puppet/type/postgresql_psql.rb index 5b2702c..1e7b2c4 100644 --- a/lib/puppet/type/postgresql_psql.rb +++ b/lib/puppet/type/postgresql_psql.rb @@ -1,135 +1,135 @@ Puppet::Type.newtype(:postgresql_psql) do - newparam(:name) do - desc "An arbitrary tag for your own reference; the name of the message." + desc 'An arbitrary tag for your own reference; the name of the message.' isnamevar end newproperty(:command) do desc 'The SQL command to execute via psql.' defaultto { @resource[:name] } # If needing to run the SQL command, return a fake value that will trigger # a sync, else return the expected SQL command so no sync takes place def retrieve if @resource.should_run_sql - return :notrun + :notrun else - return self.should + should end end def sync output, status = provider.run_sql_command(value) - self.fail("Error executing SQL; psql returned #{status}: '#{output}'") unless status == 0 + raise("Error executing SQL; psql returned #{status}: '#{output}'") unless status == 0 # rubocop:disable Style/NumericPredicate end end newparam(:unless) do - desc "An optional SQL command to execute prior to the main :command; " + - "this is generally intended to be used for idempotency, to check " + - "for the existence of an object in the database to determine whether " + - "or not the main SQL command needs to be executed at all." + desc 'An optional SQL command to execute prior to the main :command; ' \ + 'this is generally intended to be used for idempotency, to check ' \ + 'for the existence of an object in the database to determine whether ' \ + 'or not the main SQL command needs to be executed at all.' # Return true if a matching row is found def matches(value) output, status = provider.run_unless_sql_command(value) - self.fail("Error evaluating 'unless' clause, returned #{status}: '#{output}'") unless status == 0 + # rubocop:disable Style/NumericPredicate + fail("Error evaluating 'unless' clause, returned #{status}: '#{output}'") unless status == 0 # rubocop:disable Style/SignalException + # rubocop:enable Style/NumericPredicate result_count = output.strip.to_i - self.debug("Found #{result_count} row(s) executing 'unless' clause") + debug("Found #{result_count} row(s) executing 'unless' clause") result_count > 0 end end newparam(:onlyif) do - desc "An optional SQL command to execute prior to the main :command; " + - "this is generally intended to be used for idempotency, to check " + - "for the existence of an object in the database to determine whether " + - "or not the main SQL command needs to be executed at all." + desc 'An optional SQL command to execute prior to the main :command; ' \ + 'this is generally intended to be used for idempotency, to check ' \ + 'for the existence of an object in the database to determine whether ' \ + 'or not the main SQL command needs to be executed at all.' # Return true if a matching row is found def matches(value) output, status = provider.run_unless_sql_command(value) status = output.exitcode if status.nil? - self.fail("Error evaluating 'onlyif' clause, returned #{status}: '#{output}'") unless status == 0 + raise("Error evaluating 'onlyif' clause, returned #{status}: '#{output}'") unless status == 0 # rubocop:disable Style/NumericPredicate result_count = output.strip.to_i - self.debug("Found #{result_count} row(s) executing 'onlyif' clause") + debug("Found #{result_count} row(s) executing 'onlyif' clause") result_count > 0 end end newparam(:connect_settings) do - desc "Connection settings that will be used when connecting to postgres" + desc 'Connection settings that will be used when connecting to postgres' end newparam(:db) do - desc "The name of the database to execute the SQL command against, this overrides any PGDATABASE value in connect_settings" + desc 'The name of the database to execute the SQL command against, this overrides any PGDATABASE value in connect_settings' end newparam(:port) do - desc "The port of the database server to execute the SQL command against, this overrides any PGPORT value in connect_settings." + desc 'The port of the database server to execute the SQL command against, this overrides any PGPORT value in connect_settings.' end newparam(:search_path) do - desc "The schema search path to use when executing the SQL command" + desc 'The schema search path to use when executing the SQL command' end newparam(:psql_path) do - desc "The path to psql executable." - defaultto("psql") + desc 'The path to psql executable.' + defaultto('psql') end newparam(:psql_user) do - desc "The system user account under which the psql command should be executed." - defaultto("postgres") + desc 'The system user account under which the psql command should be executed.' + defaultto('postgres') end newparam(:psql_group) do - desc "The system user group account under which the psql command should be executed." - defaultto("postgres") + desc 'The system user group account under which the psql command should be executed.' + defaultto('postgres') end - newparam(:cwd, :parent => Puppet::Parameter::Path) do - desc "The working directory under which the psql command should be executed." - defaultto("/tmp") + newparam(:cwd, parent: Puppet::Parameter::Path) do + desc 'The working directory under which the psql command should be executed.' + defaultto('/tmp') end newparam(:environment) do desc "Any additional environment variables you want to set for a SQL command. Multiple environment variables should be specified as an array." validate do |values| Array(values).each do |value| - unless value =~ /\w+=/ + unless value =~ %r{\w+=} raise ArgumentError, "Invalid environment setting '#{value}'" end end end end - newparam(:refreshonly, :boolean => true) do + newparam(:refreshonly, boolean: true) do desc "If 'true', then the SQL will only be executed via a notify/subscribe event." defaultto(:false) newvalues(:true, :false) end def should_run_sql(refreshing = false) onlyif_param = @parameters[:onlyif] unless_param = @parameters[:unless] return false if !onlyif_param.nil? && !onlyif_param.value.nil? && !onlyif_param.matches(onlyif_param.value) return false if !unless_param.nil? && !unless_param.value.nil? && unless_param.matches(unless_param.value) return false if !refreshing && @parameters[:refreshonly].value == :true true end def refresh - self.property(:command).sync if self.should_run_sql(true) + property(:command).sync if should_run_sql(true) end - end diff --git a/lib/puppet/type/postgresql_replication_slot.rb b/lib/puppet/type/postgresql_replication_slot.rb index b5b317c..c489cc3 100644 --- a/lib/puppet/type/postgresql_replication_slot.rb +++ b/lib/puppet/type/postgresql_replication_slot.rb @@ -1,16 +1,16 @@ Puppet::Type.newtype(:postgresql_replication_slot) do @doc = "Manages Postgresql replication slots. This type allows to create and destroy replication slots to register warm standby replication on a Postgresql master server. " ensurable newparam(:name) do - desc "The name of the slot to create. Must be a valid replication slot name." + desc 'The name of the slot to create. Must be a valid replication slot name.' isnamevar - newvalues /^[a-z0-9_]+$/ + newvalues %r{^[a-z0-9_]+$} end end diff --git a/lib/puppet/util/postgresql_validator.rb b/lib/puppet/util/postgresql_validator.rb index d737f12..972f936 100644 --- a/lib/puppet/util/postgresql_validator.rb +++ b/lib/puppet/util/postgresql_validator.rb @@ -1,65 +1,64 @@ -module Puppet - module Util - class PostgresqlValidator - attr_reader :resource +module Puppet::Util + # postgresql_validator.rb + class PostgresqlValidator + attr_reader :resource - def initialize(resource) - @resource = resource - end - - def build_psql_cmd - final_cmd = [] + def initialize(resource) + @resource = resource + end - cmd_init = "#{@resource[:psql_path]} --tuples-only --quiet --no-psqlrc" + def build_psql_cmd + final_cmd = [] - final_cmd.push cmd_init + cmd_init = "#{@resource[:psql_path]} --tuples-only --quiet --no-psqlrc" - cmd_parts = { - :host => "--host #{@resource[:host]}", - :port => "--port #{@resource[:port]}", - :db_username => "--username #{@resource[:db_username]}", - :db_name => "--dbname #{@resource[:db_name]}", - :command => "--command '#{@resource[:command]}'" - } + final_cmd.push cmd_init - cmd_parts.each do |k,v| - final_cmd.push v if @resource[k] - end + cmd_parts = { + host: "--host #{@resource[:host]}", + port: "--port #{@resource[:port]}", + db_username: "--username #{@resource[:db_username]}", + db_name: "--dbname #{@resource[:db_name]}", + command: "--command '#{@resource[:command]}'", + } - final_cmd.join ' ' + cmd_parts.each do |k, v| + final_cmd.push v if @resource[k] end - def parse_connect_settings - c_settings = @resource[:connect_settings] || {} - c_settings.merge! ({ 'PGPASSWORD' => @resource[:db_password] }) if @resource[:db_password] - return c_settings.map { |k,v| "#{k}=#{v}" } - end + final_cmd.join ' ' + end - def attempt_connection(sleep_length, tries) - (0..tries-1).each do |try| - Puppet.debug "PostgresqlValidator.attempt_connection: Attempting connection to #{@resource[:db_name]}" - Puppet.debug "PostgresqlValidator.attempt_connection: #{build_validate_cmd}" - result = execute_command - if result && result.length > 0 - Puppet.debug "PostgresqlValidator.attempt_connection: Connection to #{@resource[:db_name] || parse_connect_settings.select { |elem| elem.match /PGDATABASE/ }} successful!" - return true - else - Puppet.warning "PostgresqlValidator.attempt_connection: Sleeping for #{sleep_length} seconds" - sleep sleep_length - end + def parse_connect_settings + c_settings = @resource[:connect_settings] || {} + c_settings['PGPASSWORD'] = @resource[:db_password] if @resource[:db_password] + c_settings.map { |k, v| "#{k}=#{v}" } + end + + def attempt_connection(sleep_length, tries) + (0..tries - 1).each do |_try| + Puppet.debug "PostgresqlValidator.attempt_connection: Attempting connection to #{@resource[:db_name]}" + Puppet.debug "PostgresqlValidator.attempt_connection: #{build_validate_cmd}" + result = execute_command + if result && !result.empty? + Puppet.debug "PostgresqlValidator.attempt_connection: Connection to #{@resource[:db_name] || parse_connect_settings.select { |elem| elem.match %r{PGDATABASE} }} successful!" + return true + else + Puppet.warning "PostgresqlValidator.attempt_connection: Sleeping for #{sleep_length} seconds" + sleep sleep_length end - false end + false + end - private + private - def execute_command - Execution.execute(build_validate_cmd, :uid => @resource[:run_as]) - end + def execute_command + Execution.execute(build_validate_cmd, uid: @resource[:run_as]) + end - def build_validate_cmd - "#{parse_connect_settings.join(' ')} #{build_psql_cmd} " - end + def build_validate_cmd + "#{parse_connect_settings.join(' ')} #{build_psql_cmd} " end end end diff --git a/manifests/params.pp b/manifests/params.pp index 44ff664..4f6d285 100644 --- a/manifests/params.pp +++ b/manifests/params.pp @@ -1,324 +1,324 @@ # PRIVATE CLASS: do not use directly class postgresql::params inherits postgresql::globals { $version = $postgresql::globals::globals_version $postgis_version = $postgresql::globals::globals_postgis_version $listen_addresses = undef $port = 5432 $log_line_prefix = undef $ip_mask_deny_postgres_user = '0.0.0.0/0' $ip_mask_allow_all_users = '127.0.0.1/32' $ipv4acls = [] $ipv6acls = [] $encoding = $postgresql::globals::encoding $locale = $postgresql::globals::locale $data_checksums = $postgresql::globals::data_checksums $timezone = $postgresql::globals::timezone $service_ensure = 'running' $service_enable = true $service_manage = true $service_restart_on_change = true $service_provider = $postgresql::globals::service_provider $manage_pg_hba_conf = pick($manage_pg_hba_conf, true) $manage_pg_ident_conf = pick($manage_pg_ident_conf, true) $manage_recovery_conf = pick($manage_recovery_conf, false) $package_ensure = 'present' $module_workdir = pick($module_workdir,'/tmp') # Amazon Linux's OS Family is 'Linux', operating system 'Amazon'. case $::osfamily { 'RedHat', 'Linux': { $link_pg_config = true $user = pick($user, 'postgres') $group = pick($group, 'postgres') $needs_initdb = pick($needs_initdb, true) $version_parts = split($version, '[.]') $package_version = "${version_parts[0]}${version_parts[1]}" if $version == $postgresql::globals::default_version and $::operatingsystem != 'Amazon' { $client_package_name = pick($client_package_name, 'postgresql') $server_package_name = pick($server_package_name, 'postgresql-server') $contrib_package_name = pick($contrib_package_name,'postgresql-contrib') $devel_package_name = pick($devel_package_name, 'postgresql-devel') $java_package_name = pick($java_package_name, 'postgresql-jdbc') $docs_package_name = pick($docs_package_name, 'postgresql-docs') $plperl_package_name = pick($plperl_package_name, 'postgresql-plperl') $plpython_package_name = pick($plpython_package_name, 'postgresql-plpython') $service_name = pick($service_name, 'postgresql') $bindir = pick($bindir, '/usr/bin') $datadir = $::operatingsystem ? { 'Amazon' => pick($datadir, "/var/lib/pgsql${package_version}/data"), default => pick($datadir, '/var/lib/pgsql/data'), } $confdir = pick($confdir, $datadir) } else { $client_package_name = pick($client_package_name, "postgresql${package_version}") $server_package_name = pick($server_package_name, "postgresql${package_version}-server") $contrib_package_name = pick($contrib_package_name,"postgresql${package_version}-contrib") $devel_package_name = pick($devel_package_name, "postgresql${package_version}-devel") $java_package_name = pick($java_package_name, "postgresql${package_version}-jdbc") $docs_package_name = pick($docs_package_name, "postgresql${package_version}-docs") $plperl_package_name = pick($plperl_package_name, "postgresql${package_version}-plperl") $plpython_package_name = pick($plpython_package_name, "postgresql${package_version}-plpython") $service_name = $::operatingsystem ? { 'Amazon' => pick($service_name, "postgresql${version_parts[0]}${version_parts[1]}"), default => pick($service_name, "postgresql-${version}"), } $bindir = $::operatingsystem ? { 'Amazon' => pick($bindir, '/usr/bin'), default => pick($bindir, "/usr/pgsql-${version}/bin"), } $datadir = $::operatingsystem ? { 'Amazon' => pick($datadir, "/var/lib/pgsql${package_version}/data"), default => pick($datadir, "/var/lib/pgsql/${version}/data"), } $confdir = pick($confdir, $datadir) } $psql_path = pick($psql_path, "${bindir}/psql") $service_status = $service_status $service_reload = "service ${service_name} reload" $perl_package_name = pick($perl_package_name, 'perl-DBD-Pg') $python_package_name = pick($python_package_name, 'python-psycopg2') if $postgresql::globals::postgis_package_name { $postgis_package_name = $postgresql::globals::postgis_package_name } elsif $::operatingsystemrelease =~ /^5\./ { $postgis_package_name = 'postgis' } elsif $postgis_version and versioncmp($postgis_version, '2') < 0 { $postgis_package_name = "postgis${package_version}" } else { $postgis_package_name = "postgis2_${package_version}" } } 'Archlinux': { $link_pg_config = true $needs_initdb = pick($needs_initdb, true) $user = pick($user, 'postgres') $group = pick($group, 'postgres') # Archlinux doesn't have a client-package but has a libs package which # pulls in postgresql server $client_package_name = pick($client_package_name, 'postgresql') $server_package_name = pick($server_package_name, 'postgresql-libs') $java_package_name = pick($java_package_name, 'postgresql-jdbc') # Archlinux doesn't have develop packages $devel_package_name = pick($devel_package_name, 'postgresql-devel') # Archlinux does have postgresql-contrib but it isn't maintained $contrib_package_name = pick($contrib_package_name,'undef') # Archlinux postgresql package provides plperl $plperl_package_name = pick($plperl_package_name, 'undef') $plpython_package_name = pick($plpython_package_name, 'undef') $service_name = pick($service_name, 'postgresql') $bindir = pick($bindir, '/usr/bin') $datadir = pick($datadir, '/var/lib/postgres/data') $confdir = pick($confdir, $datadir) $psql_path = pick($psql_path, "${bindir}/psql") $service_status = $service_status $service_reload = "systemctl reload ${service_name}" $python_package_name = pick($python_package_name, 'python-psycopg2') # Archlinux does not have a perl::DBD::Pg package $perl_package_name = pick($perl_package_name, 'undef') } 'Debian': { $link_pg_config = false $user = pick($user, 'postgres') $group = pick($group, 'postgres') if $postgresql::globals::manage_package_repo == true { $needs_initdb = pick($needs_initdb, true) $service_name = pick($service_name, 'postgresql') } else { $needs_initdb = pick($needs_initdb, false) $service_name = $::operatingsystem ? { 'Debian' => pick($service_name, 'postgresql'), 'Ubuntu' => $::lsbmajdistrelease ? { /^10/ => pick($service_name, "postgresql-${version}"), default => pick($service_name, 'postgresql'), }, default => undef } } $client_package_name = pick($client_package_name, "postgresql-client-${version}") $server_package_name = pick($server_package_name, "postgresql-${version}") $contrib_package_name = pick($contrib_package_name, "postgresql-contrib-${version}") if $postgis_version and versioncmp($postgis_version, '2') < 0 { $postgis_package_name = pick($postgis_package_name, "postgresql-${version}-postgis") } else { $postgis_package_name = pick($postgis_package_name, "postgresql-${version}-postgis-${postgis_version}") } $devel_package_name = pick($devel_package_name, 'libpq-dev') $java_package_name = $::operatingsystem ? { 'Debian' => $::operatingsystemrelease ? { /^6/ => pick($java_package_name, 'libpg-java'), default => pick($java_package_name, 'libpostgresql-jdbc-java'), }, default => pick($java_package_name, 'libpostgresql-jdbc-java'), } $perl_package_name = pick($perl_package_name, 'libdbd-pg-perl') $plperl_package_name = pick($plperl_package_name, "postgresql-plperl-${version}") $plpython_package_name = pick($plpython_package_name, "postgresql-plpython-${version}") $python_package_name = pick($python_package_name, 'python-psycopg2') $bindir = pick($bindir, "/usr/lib/postgresql/${version}/bin") $datadir = pick($datadir, "/var/lib/postgresql/${version}/main") $confdir = pick($confdir, "/etc/postgresql/${version}/main") if $::operatingsystem == 'Debian' and versioncmp($::operatingsystemrelease, '8.0') >= 0 { # Jessie uses systemd $service_status = pick($service_status, "/usr/sbin/service ${service_name}@*-main status") } elsif $::operatingsystem == 'Ubuntu' and versioncmp($::operatingsystemrelease, '15.04') >= 0 { # Ubuntu releases since vivid use systemd $service_status = pick($service_status, "/usr/sbin/service ${service_name} status") } else { $service_status = pick($service_status, "/etc/init.d/${service_name} status | /bin/egrep -q 'Running clusters: .+|online'") } $service_reload = "service ${service_name} reload" $psql_path = pick($psql_path, '/usr/bin/psql') } 'Gentoo': { $user = pick($user, 'postgres') $group = pick($group, 'postgres') $client_package_name = pick($client_package_name, 'UNSET') $server_package_name = pick($server_package_name, 'postgresql') $contrib_package_name = pick_default($contrib_package_name, undef) $devel_package_name = pick_default($devel_package_name, undef) $java_package_name = pick($java_package_name, 'jdbc-postgresql') $perl_package_name = pick($perl_package_name, 'DBD-Pg') $plperl_package_name = undef $python_package_name = pick($python_package_name, 'psycopg') $service_name = pick($service_name, "postgresql-${version}") $bindir = pick($bindir, "/usr/lib/postgresql-${version}/bin") $datadir = pick($datadir, "/var/lib/postgresql/${version}_data") $confdir = pick($confdir, "/etc/postgresql-${version}") $service_status = pick($service_status, "systemctl status ${service_name}") $service_reload = "systemctl reload ${service_name}" $psql_path = pick($psql_path, "${bindir}/psql") $needs_initdb = pick($needs_initdb, true) } 'FreeBSD': { case $version { - '96': { + '96', '10': { $user = pick($user, 'postgres') $group = pick($group, 'postgres') $datadir = pick($datadir, "/var/db/postgres/data${version}") } default: { $user = pick($user, 'pgsql') $group = pick($group, 'pgsql') $datadir = pick($datadir, '/usr/local/pgsql/data') } } $link_pg_config = true $client_package_name = pick($client_package_name, "databases/postgresql${version}-client") $server_package_name = pick($server_package_name, "databases/postgresql${version}-server") $contrib_package_name = pick($contrib_package_name, "databases/postgresql${version}-contrib") $devel_package_name = pick($devel_package_name, 'databases/postgresql-libpqxx3') $java_package_name = pick($java_package_name, 'databases/postgresql-jdbc') $perl_package_name = pick($plperl_package_name, 'databases/p5-DBD-Pg') $plperl_package_name = pick($plperl_package_name, "databases/postgresql${version}-plperl") $python_package_name = pick($python_package_name, 'databases/py-psycopg2') $service_name = pick($service_name, 'postgresql') $bindir = pick($bindir, '/usr/local/bin') $confdir = pick($confdir, $datadir) $service_status = pick($service_status, "/usr/local/etc/rc.d/${service_name} onestatus") $service_reload = "service ${service_name} reload" $psql_path = pick($psql_path, "${bindir}/psql") $needs_initdb = pick($needs_initdb, true) } 'OpenBSD': { $user = pick($user, '_postgresql') $group = pick($group, '_postgresql') $client_package_name = pick($client_package_name, 'postgresql-client') $server_package_name = pick($server_package_name, 'postgresql-server') $contrib_package_name = pick($contrib_package_name, 'postgresql-contrib') $devel_package_name = pick($devel_package_name, 'postgresql-client') $java_package_name = pick($java_package_name, 'postgresql-jdbc') $perl_package_name = pick($perl_package_name, 'databases/p5-DBD-Pg') $plperl_package_name = undef $python_package_name = pick($python_package_name, 'py-psycopg2') $service_name = pick($service_name, 'postgresql') $bindir = pick($bindir, '/usr/local/bin') $datadir = pick($datadir, '/var/postgresql/data') $confdir = pick($confdir, $datadir) $service_status = pick($service_status, "/etc/rc.d/${service_name} check") $service_reload = "/etc/rc.d/${service_name} reload" $psql_path = pick($psql_path, "${bindir}/psql") $needs_initdb = pick($needs_initdb, true) } 'Suse': { $link_pg_config = true $user = pick($user, 'postgres') $group = pick($group, 'postgres') $client_package_name = pick($client_package_name, "postgresql${version}") $server_package_name = pick($server_package_name, "postgresql${version}-server") $contrib_package_name = pick($contrib_package_name, "postgresql${version}-contrib") $devel_package_name = pick($devel_package_name, "postgresql${version}-devel") $java_package_name = pick($java_package_name, "postgresql${version}-jdbc") $perl_package_name = pick($plperl_package_name, 'perl-DBD-Pg') $plperl_package_name = pick($plperl_package_name, "postgresql${version}-plperl") $python_package_name = pick($python_package_name, 'python-psycopg2') $service_name = pick($service_name, 'postgresql') $bindir = pick($bindir, "/usr/lib/postgresql${version}/bin") $datadir = pick($datadir, '/var/lib/pgsql/data') $confdir = pick($confdir, $datadir) if $::operatingsystem == 'SLES' and versioncmp($::operatingsystemrelease, '11.4') <= 0 { $service_status = pick($service_status, "/etc/init.d/${service_name} status") $service_reload = "/etc/init.d/${service_name} reload" } else { $service_status = pick($service_status, "systemctl status ${service_name}") $service_reload = "systemctl reload ${service_name}" } $psql_path = pick($psql_path, "${bindir}/psql") $needs_initdb = pick($needs_initdb, true) } default: { $link_pg_config = true $psql_path = pick($psql_path, "${bindir}/psql") # Since we can't determine defaults on our own, we rely on users setting # parameters with the postgresql::globals class. Here we are checking # that the mandatory minimum is set for the module to operate. $err_prefix = "Module ${module_name} does not provide defaults for osfamily: ${::osfamily} operatingsystem: ${::operatingsystem}; please specify a value for ${module_name}::globals::" if ($needs_initdb == undef) { fail("${err_prefix}needs_initdb") } if ($service_name == undef) { fail("${err_prefix}service_name") } if ($client_package_name == undef) { fail("${err_prefix}client_package_name") } if ($server_package_name == undef) { fail("${err_prefix}server_package_name") } if ($bindir == undef) { fail("${err_prefix}bindir") } if ($datadir == undef) { fail("${err_prefix}datadir") } if ($confdir == undef) { fail("${err_prefix}confdir") } } } if($data_checksums and versioncmp($version, '9.3') < 0) { fail('data_checksums require version 9.3 or greater') } $validcon_script_path = pick($validcon_script_path, '/usr/local/bin/validate_postgresql_connection.sh') $initdb_path = pick($initdb_path, "${bindir}/initdb") $pg_hba_conf_path = pick($pg_hba_conf_path, "${confdir}/pg_hba.conf") $pg_hba_conf_defaults = pick($pg_hba_conf_defaults, true) $pg_ident_conf_path = pick($pg_ident_conf_path, "${confdir}/pg_ident.conf") $postgresql_conf_path = pick($postgresql_conf_path, "${confdir}/postgresql.conf") $recovery_conf_path = pick($recovery_conf_path, "${datadir}/recovery.conf") $default_database = pick($default_database, 'postgres') } diff --git a/manifests/server/config_entry.pp b/manifests/server/config_entry.pp index 3e37f00..5a4f83a 100644 --- a/manifests/server/config_entry.pp +++ b/manifests/server/config_entry.pp @@ -1,173 +1,173 @@ # Manage a postgresql.conf entry. See README.md for more details. define postgresql::server::config_entry ( $ensure = 'present', $value = undef, $path = false ) { $postgresql_conf_path = $postgresql::server::postgresql_conf_path $target = $path ? { false => $postgresql_conf_path, default => $path, } # Those are the variables that are marked as "(change requires restart)" # on postgresql.conf. Items are ordered as on postgresql.conf. # # XXX: This resource supports setting other variables without knowing # their names. Do not add them here. $requires_restart_until = { 'data_directory' => undef, 'hba_file' => undef, 'ident_file' => undef, 'external_pid_file' => undef, 'listen_addresses' => undef, 'port' => undef, 'max_connections' => undef, 'superuser_reserved_connections' => undef, 'unix_socket_directory' => '9.3', # Turned into "unix_socket_directories" 'unix_socket_directories' => undef, 'unix_socket_group' => undef, 'unix_socket_permissions' => undef, 'bonjour' => undef, 'bonjour_name' => undef, 'ssl' => '10', 'ssl_ciphers' => '10', 'ssl_prefer_server_ciphers' => '10', # New on 9.4 'ssl_ecdh_curve' => '10', # New on 9.4 'ssl_cert_file' => '10', # New on 9.2 'ssl_key_file' => '10', # New on 9.2 'ssl_ca_file' => '10', # New on 9.2 'ssl_crl_file' => '10', # New on 9.2 'shared_buffers' => undef, 'huge_pages' => undef, # New on 9.4 'max_prepared_transactions' => undef, 'max_files_per_process' => undef, 'shared_preload_libraries' => undef, 'max_worker_processes' => undef, # New on 9.4 'old_snapshot_threshold' => undef, # New on 9.6 'wal_level' => undef, 'wal_log_hints' => undef, # New on 9.4 'wal_buffers' => undef, 'archive_mode' => undef, 'max_wal_senders' => undef, 'max_replication_slots' => undef, # New on 9.4 'track_commit_timestamp' => undef, # New on 9.5 'hot_standby' => undef, 'logging_collector' => undef, 'cluster_name' => undef, # New on 9.5 'silent_mode' => '9.2', # Removed 'track_activity_query_size' => undef, 'autovacuum_max_workers' => undef, 'autovacuum_freeze_max_age' => undef, 'autovacuum_multixact_freeze_max_age' => undef, # New on 9.5 'max_locks_per_transaction' => undef, 'max_pred_locks_per_transaction' => undef, } Exec { logoutput => 'on_failure', } if ! ($name in $requires_restart_until and ( ! $requires_restart_until[$name] or versioncmp($postgresql::server::_version, $requires_restart_until[$name]) < 0 )) { Postgresql_conf { notify => Class['postgresql::server::reload'], } } elsif $postgresql::server::service_restart_on_change { Postgresql_conf { notify => Class['postgresql::server::service'], } } else { Postgresql_conf { before => Class['postgresql::server::service'], } } # We have to handle ports and the data directory in a weird and # special way. On early Debian and Ubuntu and RHEL we have to ensure # we stop the service completely. On RHEL 7 we either have to create # a systemd override for the port or update the sysconfig file, but this # is managed for us in postgresql::server::config. if $::operatingsystem == 'Debian' or $::operatingsystem == 'Ubuntu' { if $name == 'port' and ( $::operatingsystemrelease =~ /^6/ or $::operatingsystemrelease =~ /^10\.04/ ) { exec { "postgresql_stop_${name}": command => "service ${::postgresql::server::service_name} stop", onlyif => "service ${::postgresql::server::service_name} status", unless => "grep 'port = ${value}' ${::postgresql::server::postgresql_conf_path}", path => '/usr/sbin:/sbin:/bin:/usr/bin:/usr/local/bin', before => Postgresql_conf[$name], } } elsif $name == 'data_directory' { exec { "postgresql_stop_${name}": command => "service ${::postgresql::server::service_name} stop", onlyif => "service ${::postgresql::server::service_name} status", unless => "grep \"data_directory = '${value}'\" ${::postgresql::server::postgresql_conf_path}", path => '/usr/sbin:/sbin:/bin:/usr/bin:/usr/local/bin', before => Postgresql_conf[$name], } } } if $::osfamily == 'RedHat' { if ! ($::operatingsystemrelease =~ /^7/ or $::operatingsystem == 'Fedora') { if $name == 'port' { # We need to force postgresql to stop before updating the port # because puppet becomes confused and is unable to manage the # service appropriately. exec { "postgresql_stop_${name}": command => "service ${::postgresql::server::service_name} stop", onlyif => "service ${::postgresql::server::service_name} status", unless => "grep 'PGPORT=${value}' /etc/sysconfig/pgsql/postgresql", path => '/sbin:/bin:/usr/bin:/usr/local/bin', require => File['/etc/sysconfig/pgsql/postgresql'], } -> augeas { 'override PGPORT in /etc/sysconfig/pgsql/postgresql': lens => 'Shellvars.lns', - incl => '/etc/sysconfig/pgsql/*', + incl => '/etc/sysconfig/pgsql/postgresql', context => '/files/etc/sysconfig/pgsql/postgresql', changes => "set PGPORT ${value}", require => File['/etc/sysconfig/pgsql/postgresql'], notify => Class['postgresql::server::service'], before => Class['postgresql::server::reload'], } } elsif $name == 'data_directory' { # We need to force postgresql to stop before updating the data directory # otherwise init script breaks exec { "postgresql_${name}": command => "service ${::postgresql::server::service_name} stop", onlyif => "service ${::postgresql::server::service_name} status", unless => "grep 'PGDATA=${value}' /etc/sysconfig/pgsql/postgresql", path => '/sbin:/bin:/usr/bin:/usr/local/bin', require => File['/etc/sysconfig/pgsql/postgresql'], } -> augeas { 'override PGDATA in /etc/sysconfig/pgsql/postgresql': lens => 'Shellvars.lns', - incl => '/etc/sysconfig/pgsql/*', + incl => '/etc/sysconfig/pgsql/postgresql', context => '/files/etc/sysconfig/pgsql/postgresql', changes => "set PGDATA ${value}", require => File['/etc/sysconfig/pgsql/postgresql'], notify => Class['postgresql::server::service'], before => Class['postgresql::server::reload'], } } } } case $ensure { /present|absent/: { postgresql_conf { $name: ensure => $ensure, target => $target, value => $value, require => Class['postgresql::server::initdb'], } } default: { fail("Unknown value for ensure '${ensure}'.") } } } diff --git a/manifests/server/extension.pp b/manifests/server/extension.pp index 86f2f9d..9fb100c 100644 --- a/manifests/server/extension.pp +++ b/manifests/server/extension.pp @@ -1,85 +1,113 @@ # Activate an extension on a postgresql database define postgresql::server::extension ( $database, $extension = $name, + Optional[String[1]] $schema = undef, Optional[String[1]] $version = undef, String[1] $ensure = 'present', $package_name = undef, $package_ensure = undef, $connect_settings = $postgresql::server::default_connect_settings, ) { $user = $postgresql::server::user $group = $postgresql::server::group $psql_path = $postgresql::server::psql_path case $ensure { 'present': { $command = "CREATE EXTENSION \"${extension}\"" - $unless_comp = '=' + $unless_mod = '' $package_require = [] - $package_before = Postgresql_psql["Add ${extension} extension to ${database}"] + $package_before = Postgresql_psql["${database}: ${command}"] } 'absent': { $command = "DROP EXTENSION \"${extension}\"" - $unless_comp = '!=' - $package_require = Postgresql_psql["Add ${extension} extension to ${database}"] + $unless_mod = 'NOT ' + $package_require = Postgresql_psql["${database}: ${command}"] $package_before = [] } default: { fail("Unknown value for ensure '${ensure}'.") } } if( $database != 'postgres' ) { # The database postgres cannot managed by this module, so it is exempt from this dependency Postgresql_psql { require => Postgresql::Server::Database[$database], } } - postgresql_psql {"Add ${extension} extension to ${database}": + postgresql_psql { "${database}: ${command}": psql_user => $user, psql_group => $group, psql_path => $psql_path, connect_settings => $connect_settings, db => $database, command => $command, - unless => "SELECT t.count FROM (SELECT count(extname) FROM pg_extension WHERE extname = '${extension}') as t WHERE t.count ${unless_comp} 1", + unless => "SELECT 1 WHERE ${unless_mod}EXISTS (SELECT 1 FROM pg_extension WHERE extname = '${extension}')", + } + + if $ensure == 'present' and $schema { + $set_schema_command = "ALTER EXTENSION \"${extension}\" SET SCHEMA \"${schema}\"" + + postgresql_psql { "${database}: ${set_schema_command}": + command => $set_schema_command, + unless => @("END") + SELECT 1 + WHERE EXISTS ( + SELECT 1 + FROM pg_extension e + JOIN pg_namespace n ON e.extnamespace = n.oid + WHERE e.extname = '${extension}' AND + n.nspname = '${schema}' + ) + |-END + , + psql_user => $user, + psql_group => $group, + psql_path => $psql_path, + connect_settings => $connect_settings, + db => $database, + require => Postgresql_psql["${database}: ${command}"], + } + + Postgresql::Server::Schema <| db == $database and schema == $schema |> -> Postgresql_psql["${database}: ${set_schema_command}"] } if $package_name { $_package_ensure = $package_ensure ? { undef => $ensure, default => $package_ensure, } ensure_packages($package_name, { ensure => $_package_ensure, tag => 'postgresql', require => $package_require, before => $package_before, }) } if $version { if $version == 'latest' { $alter_extension_sql = "ALTER EXTENSION \"${extension}\" UPDATE" $update_unless = "SELECT 1 FROM pg_available_extensions WHERE name = '${extension}' AND default_version = installed_version" } else { $alter_extension_sql = "ALTER EXTENSION \"${extension}\" UPDATE TO '${version}'" $update_unless = "SELECT 1 FROM pg_extension WHERE extname='${extension}' AND extversion='${version}'" } postgresql_psql { "${database}: ${alter_extension_sql}": db => $database, psql_user => $user, psql_group => $group, psql_path => $psql_path, connect_settings => $connect_settings, command => $alter_extension_sql, unless => $update_unless, } } } diff --git a/manifests/server/grant.pp b/manifests/server/grant.pp index 579acab..4817326 100644 --- a/manifests/server/grant.pp +++ b/manifests/server/grant.pp @@ -1,426 +1,426 @@ # Define for granting permissions to roles. See README.md for more details. define postgresql::server::grant ( String $role, String $db, Optional[String] $privilege = undef, Pattern[#/(?i:^COLUMN$)/, /(?i:^ALL SEQUENCES IN SCHEMA$)/, /(?i:^ALL TABLES IN SCHEMA$)/, /(?i:^DATABASE$)/, #/(?i:^FOREIGN DATA WRAPPER$)/, #/(?i:^FOREIGN SERVER$)/, #/(?i:^FUNCTION$)/, /(?i:^LANGUAGE$)/, #/(?i:^PROCEDURAL LANGUAGE$)/, /(?i:^TABLE$)/, #/(?i:^TABLESPACE$)/, /(?i:^SCHEMA$)/, /(?i:^SEQUENCE$)/ #/(?i:^VIEW$)/ ] $object_type = 'database', Optional[Variant[ Array[String,2,2], String[1]] ] $object_name = undef, String $psql_db = $postgresql::server::default_database, String $psql_user = $postgresql::server::user, Integer $port = $postgresql::server::port, Boolean $onlyif_exists = false, Hash $connect_settings = $postgresql::server::default_connect_settings, Enum['present', 'absent' ] $ensure = 'present', ) { case $ensure { default: { # default is 'present' $sql_command = 'GRANT %s ON %s "%s" TO "%s"' $unless_is = true } 'absent': { $sql_command = 'REVOKE %s ON %s "%s" FROM "%s"' $unless_is = false } } $group = $postgresql::server::group $psql_path = $postgresql::server::psql_path if ! $object_name { $_object_name = $db } else { $_object_name = $object_name } # # Port, order of precedence: $port parameter, $connect_settings[PGPORT], $postgresql::server::port # if $port != undef { $port_override = $port } elsif $connect_settings != undef and has_key( $connect_settings, 'PGPORT') { $port_override = undef } else { $port_override = $postgresql::server::port } ## Munge the input values $_object_type = upcase($object_type) $_privilege = upcase($privilege) # You can use ALL TABLES IN SCHEMA by passing schema_name to object_name # You can use ALL SEQUENCES IN SCHEMA by passing schema_name to object_name ## Validate that the object type's privilege is acceptable # TODO: this is a terrible hack; if they pass "ALL" as the desired privilege, # we need a way to test for it--and has_database_privilege does not # recognize 'ALL' as a valid privilege name. So we probably need to # hard-code a mapping between 'ALL' and the list of actual privileges that # it entails, and loop over them to check them. That sort of thing will # probably need to wait until we port this over to ruby, so, for now, we're # just going to assume that if they have "CREATE" privileges on a database, # then they have "ALL". (I told you that it was terrible!) case $_object_type { 'DATABASE': { $unless_privilege = $_privilege ? { 'ALL' => 'CREATE', 'ALL PRIVILEGES' => 'CREATE', Pattern[ - '^$', - '^CONNECT$', - '^CREATE$', - '^TEMP$', - '^TEMPORARY$' + /^$/, + /^CONNECT$/, + /^CREATE$/, + /^TEMP$/, + /^TEMPORARY$/ ] => $_privilege, default => fail('Illegal value for $privilege parameter'), } $unless_function = 'has_database_privilege' $on_db = $psql_db $onlyif_function = $ensure ? { default => undef, 'absent' => 'role_exists', } } 'SCHEMA': { $unless_privilege = $_privilege ? { 'ALL' => 'CREATE', 'ALL PRIVILEGES' => 'CREATE', Pattern[ - '^$', - '^CREATE$', - '^USAGE$' + /^$/, + /^CREATE$/, + /^USAGE$/ ] => $_privilege, default => fail('Illegal value for $privilege parameter'), } $unless_function = 'has_schema_privilege' $on_db = $db $onlyif_function = undef } 'SEQUENCE': { $unless_privilege = $_privilege ? { 'ALL' => 'USAGE', Pattern[ - '^$', - '^ALL PRIVILEGES$', - '^SELECT$', - '^UPDATE$', - '^USAGE$' + /^$/, + /^ALL PRIVILEGES$/, + /^SELECT$/, + /^UPDATE$/, + /^USAGE$/ ] => $_privilege, default => fail('Illegal value for $privilege parameter'), } $unless_function = 'has_sequence_privilege' $on_db = $db $onlyif_function = undef } 'ALL SEQUENCES IN SCHEMA': { case $_privilege { Pattern[ - '^$', - '^ALL$', - '^ALL PRIVILEGES$', - '^SELECT$', - '^UPDATE$', - '^USAGE$' + /^$/, + /^ALL$/, + /^ALL PRIVILEGES$/, + /^SELECT$/, + /^UPDATE$/, + /^USAGE$/ ]: { } default: { fail('Illegal value for $privilege parameter') } } $unless_function = 'custom' $on_db = $db $onlyif_function = undef $schema = $object_name $custom_privilege = $_privilege ? { 'ALL' => 'USAGE', 'ALL PRIVILEGES' => 'USAGE', default => $_privilege, } # This checks if there is a difference between the sequences in the # specified schema and the sequences for which the role has the specified # privilege. It uses the EXCEPT clause which computes the set of rows # that are in the result of the first SELECT statement but not in the # result of the second one. It then counts the number of rows from this # operation. If this number is zero then the role has the specified # privilege for all sequences in the schema and the whole query returns a # single row, which satisfies the `unless` parameter of Postgresql_psql. # If this number is not zero then there is at least one sequence for which # the role does not have the specified privilege, making it necessary to # execute the GRANT statement. if $ensure == 'present' { $custom_unless = "SELECT 1 WHERE NOT EXISTS ( SELECT sequence_name FROM information_schema.sequences WHERE sequence_schema='${schema}' EXCEPT DISTINCT SELECT object_name as sequence_name FROM ( SELECT object_schema, object_name, grantee, CASE privs_split WHEN 'r' THEN 'SELECT' WHEN 'w' THEN 'UPDATE' WHEN 'U' THEN 'USAGE' END AS privilege_type FROM ( SELECT DISTINCT object_schema, object_name, (regexp_split_to_array(regexp_replace(privs,E'/.*',''),'='))[1] AS grantee, regexp_split_to_table((regexp_split_to_array(regexp_replace(privs,E'/.*',''),'='))[2],E'\\s*') AS privs_split FROM ( SELECT n.nspname as object_schema, c.relname as object_name, regexp_split_to_table(array_to_string(c.relacl,','),',') AS privs FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON c.relnamespace = n.oid WHERE c.relkind = 'S' AND n.nspname NOT IN ( 'pg_catalog', 'information_schema' ) ) P1 ) P2 ) P3 WHERE grantee='${role}' AND object_schema='${schema}' AND privilege_type='${custom_privilege}' )" } else { # ensure == absent $custom_unless = "SELECT 1 WHERE NOT EXISTS ( SELECT object_name as sequence_name FROM ( SELECT object_schema, object_name, grantee, CASE privs_split WHEN 'r' THEN 'SELECT' WHEN 'w' THEN 'UPDATE' WHEN 'U' THEN 'USAGE' END AS privilege_type FROM ( SELECT DISTINCT object_schema, object_name, (regexp_split_to_array(regexp_replace(privs,E'/.*',''),'='))[1] AS grantee, regexp_split_to_table((regexp_split_to_array(regexp_replace(privs,E'/.*',''),'='))[2],E'\\s*') AS privs_split FROM ( SELECT n.nspname as object_schema, c.relname as object_name, regexp_split_to_table(array_to_string(c.relacl,','),',') AS privs FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON c.relnamespace = n.oid WHERE c.relkind = 'S' AND n.nspname NOT IN ( 'pg_catalog', 'information_schema' ) ) P1 ) P2 ) P3 WHERE grantee='${role}' AND object_schema='${schema}' AND privilege_type='${custom_privilege}' )" } } 'TABLE': { $unless_privilege = $_privilege ? { 'ALL' => 'INSERT', Pattern[ - '^$', - '^ALL$', - '^ALL PRIVILEGES$', - '^DELETE$', - '^REFERENCES$', - '^SELECT$', - '^TRIGGER$', - '^TRUNCATE$', - '^UPDATE$' + /^$/, + /^ALL$/, + /^ALL PRIVILEGES$/, + /^DELETE$/, + /^REFERENCES$/, + /^SELECT$/, + /^TRIGGER$/, + /^TRUNCATE$/, + /^UPDATE$/ ] => $_privilege, default => fail('Illegal value for $privilege parameter'), } $unless_function = 'has_table_privilege' $on_db = $db $onlyif_function = $onlyif_exists ? { true => 'table_exists', default => undef, } } 'ALL TABLES IN SCHEMA': { case $_privilege { Pattern[ - '^$', - '^ALL$', - '^ALL PRIVILEGES$', - '^DELETE$', - '^INSERT$', - '^REFERENCES$', - '^SELECT$', - '^TRIGGER$', - '^TRUNCATE$', - '^UPDATE$' + /^$/, + /^ALL$/, + /^ALL PRIVILEGES$/, + /^DELETE$/, + /^INSERT$/, + /^REFERENCES$/, + /^SELECT$/, + /^TRIGGER$/, + /^TRUNCATE$/, + /^UPDATE$/ ]: { } default: { fail('Illegal value for $privilege parameter') } } $unless_function = 'custom' $on_db = $db $onlyif_function = undef $schema = $object_name # Again there seems to be no easy way in plain SQL to check if ALL # PRIVILEGES are granted on a table. # There are currently 7 possible priviliges: # ('SELECT','UPDATE','INSERT','DELETE','TRIGGER','REFERENCES','TRUNCATE') # This list is consistant from Postgresql 8.0 # # There are 4 cases to cover, each with it's own distinct unless clause: # grant ALL # grant SELECT (or INSERT or DELETE ...) # revoke ALL # revoke SELECT (or INSERT or DELETE ...) if $ensure == 'present' { if $_privilege == 'ALL' or $_privilege == 'ALL PRIVILEGES' { # GRANT ALL $custom_unless = "SELECT 1 WHERE NOT EXISTS ( SELECT 1 FROM pg_catalog.pg_tables AS t, (VALUES ('SELECT'), ('UPDATE'), ('INSERT'), ('DELETE'), ('TRIGGER'), ('REFERENCES'), ('TRUNCATE')) AS p(privilege_type) WHERE t.schemaname = '${schema}' AND NOT EXISTS ( SELECT 1 FROM information_schema.role_table_grants AS g WHERE g.grantee = '${role}' AND g.table_schema = '${schema}' AND g.privilege_type = p.privilege_type ) )" } else { # GRANT $_privilege $custom_unless = "SELECT 1 WHERE NOT EXISTS ( SELECT 1 FROM pg_catalog.pg_tables AS t WHERE t.schemaname = '${schema}' AND NOT EXISTS ( SELECT 1 FROM information_schema.role_table_grants AS g WHERE g.grantee = '${role}' AND g.table_schema = '${schema}' AND g.privilege_type = '${_privilege}' ) )" } } else { if $_privilege == 'ALL' or $_privilege == 'ALL PRIVILEGES' { # REVOKE ALL $custom_unless = "SELECT 1 WHERE NOT EXISTS ( SELECT table_name FROM information_schema.role_table_grants WHERE grantee = '${role}' AND table_schema ='${schema}' )" } else { # REVOKE $_privilege $custom_unless = "SELECT 1 WHERE NOT EXISTS ( SELECT table_name FROM information_schema.role_table_grants WHERE grantee = '${role}' AND table_schema ='${schema}' AND privilege_type = '${_privilege}' )" } } } 'LANGUAGE': { $unless_privilege = $_privilege ? { 'ALL' => 'USAGE', 'ALL PRIVILEGES' => 'USAGE', Pattern[ - '^$', - '^CREATE$', - '^USAGE$' + /^$/, + /^CREATE$/, + /^USAGE$/ ] => $_privilege, default => fail('Illegal value for $privilege parameter'), } $unless_function = 'has_language_privilege' $on_db = $db $onlyif_function = $onlyif_exists ? { true => 'language_exists', default => undef, } } default: { fail("Missing privilege validation for object type ${_object_type}") } } # This is used to give grant to "schemaname"."tablename" # If you need such grant, use: # postgresql::grant { 'table:foo': # role => 'joe', # ... # object_type => 'TABLE', # object_name => [$schema, $table], # } case $_object_name { Array: { $_togrant_object = join($_object_name, '"."') # Never put double quotes into has_*_privilege function $_granted_object = join($_object_name, '.') } default: { $_granted_object = $_object_name $_togrant_object = $_object_name } } $_unless = $unless_function ? { false => undef, 'custom' => $custom_unless, default => "SELECT 1 WHERE ${unless_function}('${role}', '${_granted_object}', '${unless_privilege}') = ${unless_is}", } $_onlyif = $onlyif_function ? { 'table_exists' => "SELECT true FROM pg_tables WHERE tablename = '${_togrant_object}'", 'language_exists' => "SELECT true from pg_language WHERE lanname = '${_togrant_object}'", 'role_exists' => "SELECT 1 FROM pg_roles WHERE rolname = '${role}'", default => undef, } $grant_cmd = sprintf($sql_command, $_privilege, $_object_type, $_togrant_object, $role) postgresql_psql { "grant:${name}": command => $grant_cmd, db => $on_db, port => $port_override, connect_settings => $connect_settings, psql_user => $psql_user, psql_group => $group, psql_path => $psql_path, unless => $_unless, onlyif => $_onlyif, require => Class['postgresql::server'] } if($role != undef and defined(Postgresql::Server::Role[$role])) { Postgresql::Server::Role[$role]->Postgresql_psql["grant:${name}"] } if($db != undef and defined(Postgresql::Server::Database[$db])) { Postgresql::Server::Database[$db]->Postgresql_psql["grant:${name}"] } } diff --git a/manifests/server/role.pp b/manifests/server/role.pp index a0bc7ef..daef482 100644 --- a/manifests/server/role.pp +++ b/manifests/server/role.pp @@ -1,125 +1,134 @@ # Define for creating a database role. See README.md for more information define postgresql::server::role( $update_password = true, $password_hash = false, $createdb = false, $createrole = false, $db = $postgresql::server::default_database, $port = undef, $login = true, $inherit = true, $superuser = false, $replication = false, $connection_limit = '-1', $username = $title, $connect_settings = $postgresql::server::default_connect_settings, + Enum['present', 'absent'] $ensure = 'present', ) { $psql_user = $postgresql::server::user $psql_group = $postgresql::server::group $psql_path = $postgresql::server::psql_path $module_workdir = $postgresql::server::module_workdir # # Port, order of precedence: $port parameter, $connect_settings[PGPORT], $postgresql::server::port # if $port != undef { $port_override = $port } elsif $connect_settings != undef and has_key( $connect_settings, 'PGPORT') { $port_override = undef } else { $port_override = $postgresql::server::port } # If possible use the version of the remote database, otherwise # fallback to our local DB version if $connect_settings != undef and has_key( $connect_settings, 'DBVERSION') { $version = $connect_settings['DBVERSION'] } else { $version = $postgresql::server::_version } - $login_sql = $login ? { true => 'LOGIN', default => 'NOLOGIN' } - $inherit_sql = $inherit ? { true => 'INHERIT', default => 'NOINHERIT' } - $createrole_sql = $createrole ? { true => 'CREATEROLE', default => 'NOCREATEROLE' } - $createdb_sql = $createdb ? { true => 'CREATEDB', default => 'NOCREATEDB' } - $superuser_sql = $superuser ? { true => 'SUPERUSER', default => 'NOSUPERUSER' } - $replication_sql = $replication ? { true => 'REPLICATION', default => '' } - if ($password_hash != false) { - $environment = "NEWPGPASSWD=${password_hash}" - $password_sql = "ENCRYPTED PASSWORD '\$NEWPGPASSWD'" - } else { - $password_sql = '' - $environment = [] - } - Postgresql_psql { db => $db, port => $port_override, psql_user => $psql_user, psql_group => $psql_group, psql_path => $psql_path, connect_settings => $connect_settings, cwd => $module_workdir, require => [ Postgresql_psql["CREATE ROLE ${username} ENCRYPTED PASSWORD ****"], Class['postgresql::server'], ], } - postgresql_psql { "CREATE ROLE ${username} ENCRYPTED PASSWORD ****": - command => "CREATE ROLE \"${username}\" ${password_sql} ${login_sql} ${createrole_sql} ${createdb_sql} ${superuser_sql} ${replication_sql} CONNECTION LIMIT ${connection_limit}", - unless => "SELECT 1 FROM pg_roles WHERE rolname = '${username}'", - environment => $environment, - require => Class['Postgresql::Server'], - } + if $ensure == 'present' { + $login_sql = $login ? { true => 'LOGIN', default => 'NOLOGIN' } + $inherit_sql = $inherit ? { true => 'INHERIT', default => 'NOINHERIT' } + $createrole_sql = $createrole ? { true => 'CREATEROLE', default => 'NOCREATEROLE' } + $createdb_sql = $createdb ? { true => 'CREATEDB', default => 'NOCREATEDB' } + $superuser_sql = $superuser ? { true => 'SUPERUSER', default => 'NOSUPERUSER' } + $replication_sql = $replication ? { true => 'REPLICATION', default => '' } + if ($password_hash != false) { + $environment = "NEWPGPASSWD=${password_hash}" + $password_sql = "ENCRYPTED PASSWORD '\$NEWPGPASSWD'" + } else { + $password_sql = '' + $environment = [] + } - postgresql_psql {"ALTER ROLE \"${username}\" ${superuser_sql}": - unless => "SELECT 1 FROM pg_roles WHERE rolname = '${username}' AND rolsuper = ${superuser}", - } + postgresql_psql { "CREATE ROLE ${username} ENCRYPTED PASSWORD ****": + command => "CREATE ROLE \"${username}\" ${password_sql} ${login_sql} ${createrole_sql} ${createdb_sql} ${superuser_sql} ${replication_sql} CONNECTION LIMIT ${connection_limit}", + unless => "SELECT 1 FROM pg_roles WHERE rolname = '${username}'", + environment => $environment, + require => Class['Postgresql::Server'], + } - postgresql_psql {"ALTER ROLE \"${username}\" ${createdb_sql}": - unless => "SELECT 1 FROM pg_roles WHERE rolname = '${username}' AND rolcreatedb = ${createdb}", - } + postgresql_psql {"ALTER ROLE \"${username}\" ${superuser_sql}": + unless => "SELECT 1 FROM pg_roles WHERE rolname = '${username}' AND rolsuper = ${superuser}", + } - postgresql_psql {"ALTER ROLE \"${username}\" ${createrole_sql}": - unless => "SELECT 1 FROM pg_roles WHERE rolname = '${username}' AND rolcreaterole = ${createrole}", - } + postgresql_psql {"ALTER ROLE \"${username}\" ${createdb_sql}": + unless => "SELECT 1 FROM pg_roles WHERE rolname = '${username}' AND rolcreatedb = ${createdb}", + } - postgresql_psql {"ALTER ROLE \"${username}\" ${login_sql}": - unless => "SELECT 1 FROM pg_roles WHERE rolname = '${username}' AND rolcanlogin = ${login}", - } + postgresql_psql {"ALTER ROLE \"${username}\" ${createrole_sql}": + unless => "SELECT 1 FROM pg_roles WHERE rolname = '${username}' AND rolcreaterole = ${createrole}", + } - postgresql_psql {"ALTER ROLE \"${username}\" ${inherit_sql}": - unless => "SELECT 1 FROM pg_roles WHERE rolname = '${username}' AND rolinherit = ${inherit}", - } + postgresql_psql {"ALTER ROLE \"${username}\" ${login_sql}": + unless => "SELECT 1 FROM pg_roles WHERE rolname = '${username}' AND rolcanlogin = ${login}", + } - if(versioncmp($version, '9.1') >= 0) { - if $replication_sql == '' { - postgresql_psql {"ALTER ROLE \"${username}\" NOREPLICATION": - unless => "SELECT 1 FROM pg_roles WHERE rolname = '${username}' AND rolreplication = ${replication}", - } - } else { - postgresql_psql {"ALTER ROLE \"${username}\" ${replication_sql}": - unless => "SELECT 1 FROM pg_roles WHERE rolname = '${username}' AND rolreplication = ${replication}", + postgresql_psql {"ALTER ROLE \"${username}\" ${inherit_sql}": + unless => "SELECT 1 FROM pg_roles WHERE rolname = '${username}' AND rolinherit = ${inherit}", + } + + if(versioncmp($version, '9.1') >= 0) { + if $replication_sql == '' { + postgresql_psql {"ALTER ROLE \"${username}\" NOREPLICATION": + unless => "SELECT 1 FROM pg_roles WHERE rolname = '${username}' AND rolreplication = ${replication}", + } + } else { + postgresql_psql {"ALTER ROLE \"${username}\" ${replication_sql}": + unless => "SELECT 1 FROM pg_roles WHERE rolname = '${username}' AND rolreplication = ${replication}", + } } } - } - postgresql_psql {"ALTER ROLE \"${username}\" CONNECTION LIMIT ${connection_limit}": - unless => "SELECT 1 FROM pg_roles WHERE rolname = '${username}' AND rolconnlimit = ${connection_limit}", - } + postgresql_psql {"ALTER ROLE \"${username}\" CONNECTION LIMIT ${connection_limit}": + unless => "SELECT 1 FROM pg_roles WHERE rolname = '${username}' AND rolconnlimit = ${connection_limit}", + } - if $password_hash and $update_password { - if($password_hash =~ /^md5.+/) { - $pwd_hash_sql = $password_hash - } else { - $pwd_md5 = md5("${password_hash}${username}") - $pwd_hash_sql = "md5${pwd_md5}" + if $password_hash and $update_password { + if($password_hash =~ /^md5.+/) { + $pwd_hash_sql = $password_hash + } else { + $pwd_md5 = md5("${password_hash}${username}") + $pwd_hash_sql = "md5${pwd_md5}" + } + postgresql_psql { "ALTER ROLE ${username} ENCRYPTED PASSWORD ****": + command => "ALTER ROLE \"${username}\" ${password_sql}", + unless => "SELECT 1 FROM pg_shadow WHERE usename = '${username}' AND passwd = '${pwd_hash_sql}'", + environment => $environment, + } } - postgresql_psql { "ALTER ROLE ${username} ENCRYPTED PASSWORD ****": - command => "ALTER ROLE \"${username}\" ${password_sql}", - unless => "SELECT 1 FROM pg_shadow WHERE usename = '${username}' AND passwd = '${pwd_hash_sql}'", - environment => $environment, + } else { + # ensure == absent + postgresql_psql { "DROP ROLE \"${username}\"": + onlyif => "SELECT 1 FROM pg_roles WHERE rolname = '${username}'", + require => Class['Postgresql::Server'], } } } diff --git a/manifests/server/service.pp b/manifests/server/service.pp index 9342b07..b421325 100644 --- a/manifests/server/service.pp +++ b/manifests/server/service.pp @@ -1,50 +1,50 @@ # PRIVATE CLASS: do not call directly class postgresql::server::service { $service_ensure = $postgresql::server::service_ensure $service_enable = $postgresql::server::service_enable $service_manage = $postgresql::server::service_manage $service_name = $postgresql::server::service_name $service_provider = $postgresql::server::service_provider $service_status = $postgresql::server::service_status $user = $postgresql::server::user $port = $postgresql::server::port $default_database = $postgresql::server::default_database - $psql_path = $postgresql::params::psql_path + $psql_path = $postgresql::server::psql_path $connect_settings = $postgresql::server::default_connect_settings anchor { 'postgresql::server::service::begin': } if $service_manage { service { 'postgresqld': ensure => $service_ensure, enable => $service_enable, name => $service_name, provider => $service_provider, hasstatus => true, status => $service_status, } if $service_ensure == 'running' { # This blocks the class before continuing if chained correctly, making # sure the service really is 'up' before continuing. # # Without it, we may continue doing more work before the database is # prepared leading to a nasty race condition. postgresql_conn_validator{ 'validate_service_is_running': run_as => $user, db_name => $default_database, port => $port, connect_settings => $connect_settings, sleep => 1, tries => 60, psql_path => $psql_path, require => Service['postgresqld'], before => Anchor['postgresql::server::service::end'] } Postgresql::Server::Database <| title == $default_database |> -> Postgresql_conn_validator['validate_service_is_running'] } } anchor { 'postgresql::server::service::end': } } diff --git a/readmes/README_ja_JP.md b/readmes/README_ja_JP.md index de69428..e079ed5 100644 --- a/readmes/README_ja_JP.md +++ b/readmes/README_ja_JP.md @@ -1,1905 +1,1905 @@ # postgresql #### 目次 1. [モジュールの概要 - モジュールの機能](#module-description) 2. [セットアップ - postgresqlモジュール導入の基本](#setup) * [postgresqlの影響](#what-postgresql-affects) * [postgresqlの導入](#getting-started-with-postgresql) 3. [使用方法 - 設定オプションと追加機能](#usage) * [サーバーの設定](#configure-a-server) * [データベースの作成](#create-a-database) * [ユーザ、ロール、パーミッションの管理](#manage-users-roles-and-permissions) * [DBオブジェクトの所有権の管理](#manage-ownership-of-db-objects) * [デフォルトのオーバーライド](#override-defaults) * [pg_hba.confのアクセスルールの作成](#create-an-access-rule-for-pg_hbaconf) * [pg_ident.confのユーザ名マップの作成](#create-user-name-maps-for-pg_identconf) * [接続の検証](#validate-connectivity) 4. [参考 - モジュールの機能と動作について](#reference) * [クラス](#classes) * [定義できるタイプ](#defined-types) * [タイプ](#types) * [関数](#functions) 5. [制約事項 - OSの互換性など](#limitations) 6. [開発 - モジュール貢献についてのガイド](#development) * [コントリビュータ - モジュール貢献者の一覧](#contributors) 7. [テスト](#tests) 8. [コントリビュータ - モジュール貢献者の一覧](#contributors) ## モジュールの概要 postgresqlモジュールを使用すると、PuppetでPostgreSQLを管理できます。 PostgreSQLは、高性能な無償のオープンソースリレーショナルデータベースサーバーです。postgresqlモジュールを使用すると、PostgreSQLのパッケージ、サービス、データベース、ユーザ、一般的なセキュリティ設定を管理できるようになります。 ## セットアップ ### postgresqlの影響 * PostgreSQLのパッケージ、サービス、設定ファイル * リッスンするポート * IPおよびマスク(オプション) ### postgresqlの導入 基本的なデフォルトのPostgreSQLサーバーを設定するには、`postgresql::server`クラスを宣言します。 ```puppet class { 'postgresql::server': } ``` ## 使用方法 ### サーバーの設定 デフォルト設定を使用する場合は、上記のように`postgresql::server`クラスを宣言します。PostgreSQLサーバーの設定をカスタマイズするには、次のように、変更する[パラメータ](#postgresqlserver)を指定します。 ```puppet class { 'postgresql::server': ip_mask_deny_postgres_user => '0.0.0.0/32', ip_mask_allow_all_users => '0.0.0.0/0', ipv4acls => ['hostssl all johndoe 192.168.0.0/24 cert'], postgres_password => 'TPSrep0rt!', } ``` 設定後、コマンドラインで設定をテストします。 ```shell psql -h localhost -U postgres psql -h my.postgres.server -U ``` 上記のコマンドでエラーメッセージが返ってくる場合は、パーミッションの設定によって現在の接続元からのアクセスが制限されています。その場所からの接続を許可するかどうかに応じて、パーミッション設定の変更が必要な場合があります。 サーバー設定パラメータの詳細については、[PostgreSQLランタイム設定マニュアル](http://www.postgresql.org/docs/current/static/runtime-config.html)を参照してください。 ### データベースの作成 さまざまなPostgreSQLデータベースを定義タイプ`postgresql::server::db`を使用してセットアップできます。例えば、PuppetDBのデータベースをセットアップするには、次のように記述します。 ```puppet class { 'postgresql::server': } postgresql::server::db { 'mydatabasename': user => 'mydatabaseuser', password => postgresql_password('mydatabaseuser', 'mypassword'), } ``` ### ユーザ、ロール、パーミッションの管理 ユーザ、ロール、パーミッションを管理するには、次のようにします。 ```puppet class { 'postgresql::server': } postgresql::server::role { 'marmot': password_hash => postgresql_password('marmot', 'mypasswd'), } postgresql::server::database_grant { 'test1': privilege => 'ALL', db => 'test1', role => 'marmot', } postgresql::server::table_grant { 'my_table of test2': privilege => 'ALL', table => 'my_table', db => 'test2', role => 'marmot', } ``` この例では、test1データベース上とtest2データベースの`my_table`テーブル上の**すべての**権限を、指定したユーザまたはグループに付与します。値がPuppetDB設定ファイルに追加されると、このデータベースは使用可能になります。 ### DBオブジェクトの所有権の管理 REASSIGN OWNEDを使用して、データベース内にあるすべてのオブジェクトの所有権を変更するには、次のようにします。 ```puppet postgresql::server::reassign_owned_by { 'new owner is meerkat': db => 'test_db', old_owner => 'marmot', new_owner => 'meerkat', } ``` この例では、PostgreSQLの'REASSIGN OWNED'ステートメントを実行して所有権を更新し、現在、ロール'marmot'が所有しているすべてのテーブル、シーケンス、関数、ビューが、ロール'meerkat'に所有されるようにします。 これは、指定された'test_db'内のオブジェクトに対してのみ適用されます。 バージョン9.3以上のPostgresqlでは、データベースの所有権も更新されます。 ### デフォルトのオーバーライド `postgresql::globals`クラスを使用すると、このモジュールの主な設定をグローバルに構成できます。この設定は、他のクラスや定義済みリソースから使用できます。単独では機能しません。 例えば、すべてのクラスのデフォルトの`locale`と`encoding`をオーバーライドするには、次のように記述します。 ```puppet class { 'postgresql::globals': encoding => 'UTF-8', locale => 'en_US.UTF-8', } class { 'postgresql::server': } ``` 特定のバージョンのPostgreSQLパッケージを使用するには、次のように記述します。 ```puppet class { 'postgresql::globals': manage_package_repo => true, version => '9.2', } class { 'postgresql::server': } ``` ### リモートのユーザ、ロール、パーミッションの管理 リモートのSQLオブジェクトは、ローカルのSQLオブジェクトと同じPuppetリソースと、[`connect_settings`](#connect_settings)ハッシュを使用して管理します。これは、PuppetがリモートのPostgresインスタンスに接続する方法と、SQLコマンドの生成に使用されるバージョンを制御します。 `connect_settings`ハッシュには、'PGHOST'、'PGPORT'、'PGPASSWORD'、'PGSSLKEY'など、Postgresクライアント接続を制御する環境変数を含めることができます。変数の全リストについては、[PostgreSQL環境変数](http://www.postgresql.org/docs/9.4/static/libpq-envars.html)マニュアルを参照してください。 さらに、特殊値の'DBVERSION'により、ターゲットデータベースのバージョンを指定できます。`connect_settings`ハッシュが省略されているか空の場合、PuppetはローカルのPostgreSQLインスタンスに接続します。 Puppetリソースごとに`connect_settings`ハッシュを設定するか、`postgresql::globals`にデフォルトの`connect_settings`ハッシュを設定できます。リソースごとに`connect_settings`を設定すると、SQLオブジェクトが複数のユーザによって複数のデータベース上に作成できるようになります。 ```puppet $connection_settings_super2 = { 'PGUSER' => 'super2', 'PGPASSWORD' => 'foobar2', 'PGHOST' => '127.0.0.1', 'PGPORT' => '5432', 'PGDATABASE' => 'postgres', } include postgresql::server # Connect with no special settings, i.e domain sockets, user postgres postgresql::server::role { 'super2': password_hash => 'foobar2', superuser => true, connect_settings => {}, } # Now using this new user connect via TCP postgresql::server::database { 'db1': connect_settings => $connection_settings_super2, require => Postgresql::Server::Role['super2'], } ``` ### pg_hba.confのアクセスルールの作成 `pg_hba.conf`のアクセスルールを作成するには、次のように記述します。 ```puppet postgresql::server::pg_hba_rule { 'allow application network to access app database': description => 'Open up PostgreSQL for access from 200.1.2.0/24', type => 'host', database => 'app', user => 'app', address => '200.1.2.0/24', auth_method => 'md5', } ``` これにより、以下のようなルールセットが`pg_hba.conf`内に作成されます。 ``` # Rule Name: allow application network to access app database # Description: Open up PostgreSQL for access from 200.1.2.0/24 # Order: 150 host app app 200.1.2.0/24 md5 ``` デフォルトでは、`pg_hba_rule`に`postgresql::server`を含める必要がありますが、ルールを宣言する際にtargetおよびpostgresql_versionを設定することで、その動作をオーバーライドできます。例えば次のようになります。 ```puppet postgresql::server::pg_hba_rule { 'allow application network to access app database': description => 'Open up postgresql for access from 200.1.2.0/24', type => 'host', database => 'app', user => 'app', address => '200.1.2.0/24', auth_method => 'md5', target => '/path/to/pg_hba.conf', postgresql_version => '9.4', } ``` ### pg_ident.confのユーザ名マップの作成 pg_ident.confのユーザ名マップを作成するには、次のように記述します。 ```puppet postgresql::server::pg_ident_rule { 'Map the SSL certificate of the backup server as a replication user': map_name => 'sslrepli', system_username => 'repli1.example.com', database_username => 'replication', } ``` これにより、次のようなユーザ名マップが`pg_ident.conf`に作成されます。 ``` #Rule Name: Map the SSL certificate of the backup server as a replication user #Description: none #Order: 150 sslrepli repli1.example.com replication ``` ### リカバリ設定の作成 リカバリ設定ファイル(`recovery.conf`)を作成するには、次のように記述します。 ```puppet postgresql::server::recovery { 'Create a recovery.conf file with the following defined parameters': restore_command => 'cp /mnt/server/archivedir/%f %p', archive_cleanup_command => undef, recovery_end_command => undef, recovery_target_name => 'daily backup 2015-01-26', recovery_target_time => '2015-02-08 22:39:00 EST', recovery_target_xid => undef, recovery_target_inclusive => true, recovery_target => 'immediate', recovery_target_timeline => 'latest', pause_at_recovery_target => true, standby_mode => 'on', primary_conninfo => 'host=localhost port=5432', primary_slot_name => undef, trigger_file => undef, recovery_min_apply_delay => 0, } ``` これにより、次の`recovery.conf`設定ファイルが作成されます。 ``` restore_command = 'cp /mnt/server/archivedir/%f %p' recovery_target_name = 'daily backup 2015-01-26' recovery_target_time = '2015-02-08 22:39:00 EST' recovery_target_inclusive = true recovery_target = 'immediate' recovery_target_timeline = 'latest' pause_at_recovery_target = true standby_mode = 'on' primary_conninfo = 'host=localhost port=5432' recovery_min_apply_delay = 0 ``` テンプレートでは、指定されたパラメータのみが認識されます。`recovery.conf`は、少なくとも1つのパラメータが設定済みで、**かつ**、[manage_recovery_conf](#manage_recovery_conf)がtrueの場合のみ作成されます。 ### 接続の検証 従属タスクを開始する前に、リモートのPostgreSQLデータベースへのクライアント接続を検証するには、`postgresql_conn_validator`リソースを使用します。このリソースは、PostgreSQLクライアントソフトウェアがインストールされている任意のノード上で使用できます。アプリケーションサーバーの起動や、データベース移行の実行など、他のタスクと結合されることがよくあります。 使用例: ```puppet postgresql_conn_validator { 'validate my postgres connection': host => 'my.postgres.host', db_username => 'mydbuser', db_password => 'mydbpassword', db_name => 'mydbname', }-> exec { 'rake db:migrate': cwd => '/opt/myrubyapp', } ``` ## 参考 postgresqlモジュールには、サーバー設定用に多数のオプションがあります。以下の設定をすべて使うことはないかもしれませんが、これらを使用することで、セキュリティ設定をかなり制御することができます。 **クラス:** * [postgresql::client](#postgresqlclient) * [postgresql::globals](#postgresqlglobals) * [postgresql::lib::devel](#postgresqllibdevel) * [postgresql::lib::java](#postgresqllibjava) * [postgresql::lib::perl](#postgresqllibperl) * [postgresql::lib::python](#postgresqllibpython) * [postgresql::server](#postgresqlserver) * [postgresql::server::plperl](#postgresqlserverplperl) * [postgresql::server::contrib](#postgresqlservercontrib) * [postgresql::server::postgis](#postgresqlserverpostgis) **定義できるタイプ:** * [postgresql::server::config_entry](#postgresqlserverconfig_entry) * [postgresql::server::database](#postgresqlserverdatabase) * [postgresql::server::database_grant](#postgresqlserverdatabase_grant) * [postgresql::server::db](#postgresqlserverdb) * [postgresql::server::extension](#postgresqlserverextension) * [postgresql::server::grant](#postgresqlservergrant) * [postgresql::server::grant_role](#postgresqlservergrant_role) * [postgresql::server::pg_hba_rule](#postgresqlserverpg_hba_rule) * [postgresql::server::pg_ident_rule](#postgresqlserverpg_ident_rule) * [postgresql::server::reassign_owned_by](#postgresqlserverreassign_owned_by) * [postgresql::server::recovery](#postgresqlserverrecovery) * [postgresql::server::role](#postgresqlserverrole) * [postgresql::server::schema](#postgresqlserverschema) * [postgresql::server::table_grant](#postgresqlservertable_grant) * [postgresql::server::tablespace](#postgresqlservertablespace) **タイプ:** * [postgresql_psql](#custom-resource-postgresql_psql) * [postgresql_replication_slot](#custom-resource-postgresql_replication_slot) * [postgresql_conf](#custom-resource-postgresql_conf) * [postgresql_conn_validator](#custom-resource-postgresql_conn_validator) **関数:** * [postgresql_password](#function-postgresql_password) * [postgresql_acls_to_resources_hash](#function-postgresql_acls_to_resources_hashacl_array-id-order_offset) ### クラス #### postgresql::client PostgreSQLクライアントソフトウェアをインストールします。カスタムのバージョンをインストールするには、次のパラメータを設定します。 >**注意:** カスタムのバージョンを指定する場合、必要なyumまたはaptリポジトリを忘れずに追加してください。 ##### `package_ensure` PostgreSQLクライアントパッケージリソースが存在する必要があるかどうかを指定します。 有効な値: 'present'、'absent'。 デフォルト値: 'present'。 ##### `package_name` PostgreSQLクライアントパッケージの名前を設定します。 デフォルト値: 'file'。 #### postgresql::lib::docs Postgres-Docs向けのPostgreSQLバインディングをインストールします。カスタムのバージョンをインストールするには、次のパラメータを設定します。 **注意:** カスタムのバージョンを指定する場合、必要なyumまたはaptリポジトリを忘れずに追加してください。 ##### `package_name` PostgreSQL docsパッケージの名前を指定します。 ##### `package_ensure` PostgreSQL docsパッケージリソースが存在する必要があるかどうかを指定します。 有効な値: 'present'、'absent'。 デフォルト値: 'present'。 #### postgresql::globals **注意:** ほとんどのサーバー固有のデフォルト値は、`postgresql::server`クラスでオーバーライドする必要があります。このクラスは、標準以外のOSを使用している場合か、ここでしか変更できない要素(`version`や`manage_package_repo`)を変更する場合のみ使用します。 ##### `bindir` ターゲットプラットフォームのデフォルトのPostgreSQLバイナリディレクトリをオーバーライドします。 デフォルト値: OSによって異なります。 ##### `client_package_name` デフォルトのPostgreSQLクライアントパッケージ名をオーバーライドします。 デフォルト値: OSによって異なります。 ##### `confdir` ターゲットプラットフォームのデフォルトのPostgreSQL設定ディレクトリをオーバーライドします。 デフォルト値: OSによって異なります。 ##### `contrib_package_name` デフォルトのPostgreSQL contribパッケージ名をオーバーライドします。 デフォルト値: OSによって異なります。 ##### `createdb_path` **非推奨** `createdb`コマンドへのパス。 デフォルト値: '${bindir}/createdb'。 ##### `datadir` ターゲットプラットフォームのデフォルトのPostgreSQLデータディレクトリをオーバーライドします。 デフォルト値: OSによって異なります。 **注意:** インストール後にdatadirを変更すると、変更が実行される前にサーバーが完全に停止します。Red Hatシステムでは、データディレクトリはSELinuxに適切にラベル付けする必要があります。Ubuntuでは、明示的に`needs_initdb = true`に設定して、Puppetが新しいdatadir内のデータベースを初期化できるようにする必要があります(他のシステムでは、`needs_initdb`はデフォルトでtrueになっています)。 **警告:** datadirがデフォルトから変更された場合、Puppetは元のデータディレクトリのパージを管理しません。そのため、データディレクトリが元のディレクトリに戻ったときにエラーが発生します。 ##### `data_checksums` オプションです。 データタイプ: 真偽値(boolean) データページに対してチェックサムを使用すると、その他の方法では発見の難しいI/Oシステムによる破損を検出するのに役立ちます。 有効な値: `true`、`false`。 デフォルト値: initdbのデフォルト値(`false`)。 **警告:** このオプションは、initdbによって初期化中に使用され、後から変更することはできません。設定された時点で、すべてのデータベース内のすべてのオブジェクトに対してチェックサムが計算されます。 ##### `default_database` 接続するデフォルトのデータベースの名前を指定します。 デフォルト値: (ほとんどのシステムにおいて) 'postgres'。 ##### `devel_package_name` デフォルトのPostgreSQL develパッケージ名をオーバーライドします。 デフォルト値: OSによって異なります。 ##### `docs_package_name` オプションです。 デフォルトのPostgreSQL docsパッケージ名をオーバーライドします。 デフォルト値: OSによって異なります。 ##### `encoding` このモジュールで作成されるすべてのデータベースのデフォルトエンコーディングを設定します。オペレーティングシステムによっては、`template1` の初期化にも使用されます。その場合、モジュール外部のデフォルトにもなります。 デフォルト値: オペレーティングシステムのデフォルトエンコーディングによって決まります。 ##### `group` ファイルシステムの関連ファイルに使用されるデフォルトのpostgresユーザグループをオーバーライドします。 デフォルト値: 'postgres'。 ##### `initdb_path` `initdb`コマンドへのパス。 ##### `java_package_name` デフォルトのPostgreSQL javaパッケージ名をオーバーライドします。 デフォルト値: OSによって異なります。 ##### `locale` このモジュールで作成されるすべてのデータベースのデフォルトのデータベースロケールを設定します。オペレーティングシステムによっては、`template1` の初期化にも使用されます。その場合、モジュール外部のデフォルトにもなります。 デフォルト値: `undef`、実質的には'C'。 **Debianでは、PostgreSQLのフル機能が使用できるように'locales-all'パッケージがインストールされていることを確認する必要があります。** ##### `timezone` postgresqlサーバーのデフォルトタイムゾーンを設定します。postgresqlのビルトインのデフォルト値は、システムのタイムゾーン情報を取得しています。 ##### `logdir` デフォルトのPostgreSQL logディレクトリをオーバーライドします。 デフォルト値: initdbのデフォルトパス。 ##### `manage_package_repo` `true`に設定されている場合、お使いのホスト上に公式なPostgreSQLリポジトリをセットアップします。 デフォルト値: `false`。 ##### `module_workdir` psqlコマンドを実行する作業ディレクトリを指定します。'/tmp'がnoexecオプションでマウントされたボリューム上にあるときに、指定が必要になる場合があります。 デフォルト値: '/tmp'。 ##### `needs_initdb` サーバーパッケージをインストール後、PostgreSQLサービスを開始する前に、initdb動作を明示的に呼び出します。 デフォルト値: OSによって異なります。 ##### `perl_package_name` デフォルトのPostgreSQL Perlパッケージ名をオーバーライドします。 デフォルト値: OSによって異なります。 ##### `pg_hba_conf_defaults` `false`に設定すると、`pg_hba.conf`についてモジュールに設定されたデフォルト値を無効にします。デフォルト値をオーバーライドするときに役立ちます。ただし、基本的な`psql`動作など、一定の動作を行うためには一定のアクセスが要求されるので、ここでの変更内容がその他のモジュールと矛盾しないように注意してください。 デフォルト値: `postgresql::globals::manage_pg_hba_conf`に設定されたグローバル値。デフォルトは`true`。 ##### `pg_hba_conf_path` `pg_hba.conf`ファイルへのパスを指定します。 デフォルト値: '${confdir}/pg_hba.conf'。 ##### `pg_ident_conf_path` `pg_ident.conf`ファイルへのパスを指定します。 デフォルト値: '${confdir}/pg_ident.conf'。 ##### `plperl_package_name` デフォルトのPostgreSQL PL/Perlパッケージ名をオーバーライドします。 デフォルト値: OSによって異なります。 ##### `plpython_package_name` デフォルトのPostgreSQL PL/Pythonパッケージ名をオーバーライドします。 デフォルト値: OSによって異なります。 ##### `postgis_version` PostGISをインストールする場合に、インストールするPostGISのバージョンを定義します。 デフォルト値: インストールするPostgreSQLで利用可能な最下位のバージョン。 ##### `postgresql_conf_path` `postgresql.conf`ファイルへのパスを設定します。 デフォルト値: '${confdir}/postgresql.conf'。 ##### `psql_path` `psql`コマンドへのパスを設定します。 ##### `python_package_name` デフォルトのPostgreSQL Pythonパッケージ名をオーバーライドします。 デフォルト値: OSによって異なります。 ##### `recovery_conf_path` `recovery.conf`ファイルへのパス。 ##### `repo_proxy` 公式のPostgreSQL yumリポジトリのみのプロキシオプションを設定します。これは、サーバーが企業のファイアウォール内にあり、外部への接続にプロキシを使用する必要がある場合に役立ちます。 Debianは現在サポートされていません。 ##### `repo_baseurl` PostgreSQLリポジトリのbaseurlを設定します。リポジトリのミラーを所有している場合に便利です。 デフォルト値: 公式なPostgreSQLリポジトリ。 ##### `server_package_name` デフォルトのPostgreSQLサーバーパッケージ名をオーバーライドします。 デフォルト値: OSによって異なります。 ##### `service_name` デフォルトのPostgreSQLサービス名をオーバーライドします。 デフォルト値: OSによって異なります。 ##### `service_provider` デフォルトのPostgreSQLサービスプロバイダをオーバーライドします。 デフォルト値: OSによって異なります。 ##### `service_status` PostgreSQLサービスのデフォルトのステータスチェックコマンドをオーバーライドします。 デフォルト値: OSによって異なります。 ##### `user` ファイルシステム内のPostgreSQL関連ファイルのデフォルトのPostgreSQLスーパーユーザおよび所有者をオーバーライドします。 デフォルト値: 'postgres'。 ##### `version` インストールおよび管理するPostgreSQLのバージョン。 デフォルト値: OSシステムのデフォルト値。 ##### `xlogdir` デフォルトのPostgreSQL xlogディレクトリをオーバーライドします。 デフォルト値: initdbのデフォルトパス。 #### postgresql::lib::devel PostgreSQLの開発ライブラリとシンボリックリンク`pg_config`を含むパッケージを`/usr/bin`にインストールします(`/usr/bin`または`/usr/local/bin`に存在しない場合)。 ##### `link_pg_config` PostgreSQLページが使用するbinディレクトリが`/usr/bin`でも`/usr/local/bin`でもない場合、パッケージのbinディレクトリから`usr/bin`に`pg_config`をシンボリックリンクします(Debianシステムには適用されません)。この動作を無効にするには、`false`に設定します。 有効な値: `true`、`false`。 デフォルト値: `true`。 ##### `package_ensure` パッケージのインストール中に'ensure'パラメータをオーバーライドします。 デフォルト値: 'present'。 ##### `package_name` インストール先のディストリビューションのデフォルトパッケージ名をオーバーライドします。 デフォルト値: ディストリビューションに応じて、'postgresql-devel'または'postgresql-devel'。 #### postgresql::lib::java Java (JDBC)向けのPostgreSQLバインディングをインストールします。カスタムのバージョンをインストールするには、次のパラメータを設定します。 **注意:** カスタムのバージョンを指定する場合、必要なyumまたはaptリポジトリを忘れずに追加してください。 ##### `package_ensure` パッケージが存在するかどうかを指定します。 有効な値: 'present'、'absent'。 デフォルト値: 'present'。 ##### `package_name` PostgreSQL javaパッケージの名前を指定します。 #### postgresql::lib::perl PostgreSQL Perlライブラリをインストールします。 ##### `package_ensure` パッケージが存在するかどうかを指定します。 有効な値: 'present'、'absent'。 デフォルト値: 'present'。 ##### `package_name` インストールするPostgreSQL perlパッケージの名前を指定します。 #### postgresql::server::plpython PostgreSQLのPL/Python手続き型言語をインストールします。 ##### `package_name` postgresql PL/Pythonパッケージの名前を指定します。 ##### `package_ensure` パッケージが存在するかどうかを指定します。 有効な値: 'present'、'absent'。 デフォルト値: 'present'。 #### postgresql::lib::python PostgreSQL Pythonライブラリをインストールします。 ##### `package_ensure` パッケージが存在するかどうかを指定します。 有効な値: 'present'、'absent'。 デフォルト値: 'present'。 ##### `package_name` PostgreSQL Pythonパッケージの名前。 #### postgresql::server ##### `createdb_path` **非推奨** `createdb`コマンドへのパスを指定します。 デフォルト値: '${bindir}/createdb'。 ##### `data_checksums` オプションです。 データタイプ: 真偽値(boolean) データページに対してチェックサムを使用すると、その他の方法では発見の難しいI/Oシステムによる破損を検出するのに役立ちます。 有効な値: `true`、`false`。 デフォルト値: initdbのデフォルト値(`false`)。 **警告:** このオプションは、initdbによって初期化中に使用され、後から変更することはできません。設定された時点で、すべてのデータベース内のすべてのオブジェクトに対してチェックサムが計算されます。 ##### `default_database` 接続するデフォルトのデータベースの名前を指定します。ほとんどのシステムで、'postgres'になります。 ##### `default_connect_settings` リモートサーバーに接続する際に使用される環境変数のハッシュを指定します。他の定義タイプのデフォルトとして使用されます(`postgresql::server::role`など)。 ##### `encoding` このモジュールで作成されるすべてのデータベースのデフォルトエンコーディングを設定します。オペレーティングシステムによっては、`template1` の初期化にも使用されます。その場合、モジュール外部のデフォルトにもなります。 デフォルト値: `undef`。 ##### `group` ファイルシステムの関連ファイルに使用されるデフォルトのpostgresユーザグループをオーバーライドします。 デフォルト値: OSによって異なります。 ##### `initdb_path` `initdb`コマンドへのパスを指定します。 デフォルト値: '${bindir}/initdb'。 ##### `ipv4acls` 接続方法、ユーザ、データベース、IPv4アドレスのアクセス制御のための文字列を一覧表示します。 詳細については、[PostgreSQLマニュアル](http://www.postgresql.org/docs/current/static/auth-pg-hba-conf.html)の`pg_hba.conf`の項を参照してください。 ##### `ipv6acls` 接続方法、ユーザ、データベース、IPv6アドレスのアクセス制御のための文字列を一覧表示します。 詳細については、[PostgreSQLマニュアル](http://www.postgresql.org/docs/current/static/auth-pg-hba-conf.html)の`pg_hba.conf`の項を参照してください。 ##### `ip_mask_allow_all_users` リモート接続に関するPostgreSQLのデフォルト動作をオーバーライドします。デフォルトでは、PostgreSQLは、データベースユーザアカウントがリモートマシンからTCP経由で接続することを許可しません。許可するには、この設定をオーバーライドします。 データベースユーザによる任意のリモートマシンからの接続を許可するには、'0.0.0.0/0'に設定します。ローカルの'192.168'サブネット内の任意のマシンからの接続を許可するには、'192.168.0.0/1'に設定します。 デフォルト値: '127.0.0.1/32'。 ##### `ip_mask_deny_postgres_user` postgresスーパーユーザについて、リモート接続を拒否するためのIPマスクを指定します。 デフォルト値: '0.0.0.0/0'。デフォルト値ではリモート接続はすべて拒否されます。 ##### `locale` このモジュールで作成されるすべてのデータベースのデフォルトのデータベースロケールを設定します。オペレーティングシステムによっては、`template1` の初期化にも使用されます。その場合、モジュール外部のデフォルトになります。 デフォルト値: `undef`、実質的には'C'。 **Debianでは、PostgreSQLの全機能を使用できるよう、'locales-all'パッケージがインストールされていることを確認してください。** ##### `manage_pg_hba_conf` `pg_hba.conf`を管理するかどうかを指定します。 `true`に設定すると、Puppetはこのファイルを上書きします。 `false`に設定すると、Puppetはこのファイルに変更を加えません。 有効な値: `true`、`false`。 デフォルト値: `true` ##### `manage_pg_ident_conf` pg_ident.confファイルを上書きします。 `true`に設定すると、Puppetはこのファイルを上書きします。 `false`に設定すると、Puppetはこのファイルに変更を加えません。 有効な値: `true`、`false`。 デフォルト値: `true`。 ##### `manage_recovery_conf` `recovery.conf`を管理するかどうかを指定します。 `true`に設定すると、Puppetはこのファイルを上書きします。 有効な値: `true`、`false`。 デフォルト値: `false`。 ##### `needs_initdb` サーバーパッケージをインストール後、PostgreSQLサービスを開始する前に、`initdb`動作を明示的に呼び出します。 デフォルト値: OSによって異なります。 ##### `package_ensure` サーバーインスタンスを作成するときに、`package`リソースに値を受け渡します。 デフォルト値: `undef`。 ##### `package_name` サーバーソフトウェアをインストールするときに使用するパッケージの名前を指定します。 デフォルト値: OSによって異なります。 ##### `pg_hba_conf_defaults` `false`に設定すると、`pg_hba.conf`についてモジュールに設定されたデフォルト値を無効にします。これは、デフォルト値を使用せずにオーバーライドするときに役立ちます。だし、基本的な`psql`動作などを実行するには一定のアクセスが要求されるので、ここでの変更内容がその他のモジュールと矛盾しないように注意してください。 ##### `pg_hba_conf_path` `pg_hba.conf`ファイルへのパスを指定します。 ##### `pg_ident_conf_path` `pg_ident.conf`ファイルへのパスを指定します。 デフォルト値: '${confdir}/pg_ident.conf'。 ##### `plperl_package_name` PL/Perl拡張のデフォルトパッケージ名を設定します。 デフォルト値: OSによって異なります。 ##### `plpython_package_name` PL/Python拡張のデフォルトパッケージ名を設定します。 デフォルト値: OSによって異なります。 ##### `port` PostgreSQLサーバーがリッスンするポートを指定します。**注意:** サーバーがリッスンする全IPアドレスで、同一のポート番号が使用されます。また、Red Hatシステムと初期のDebianシステムでは、ポート番号を変更するとき、変更実行前にサーバーが完全停止します。 デフォルト値: 5432。これは、PostgresサーバーがTCPポート5432をリッスンすることを意味します。 ##### `postgres_password` postgresユーザのパスワードを特定の値に設定します。デフォルトでは、この設定はPostgresデータベース内のスーパーユーザアカウント(ユーザ名`postgres`、パスワードなし)を使用します。 デフォルト値: `undef`。 ##### `postgresql_conf_path` `postgresql.conf`ファイルへのパスを指定します。 デフォルト値: '${confdir}/postgresql.conf'。 ##### `psql_path` `psql`コマンドへのパスを指定します。 デフォルト値: OSによって異なります。 ##### `service_manage` Puppetがサービスを管理するかどうかを定義します。 デフォルト値: `true`。 ##### `service_name` デフォルトのPostgreSQLサービス名をオーバーライドします。 デフォルト値: OSによって異なります。 ##### `service_provider` デフォルトのPostgreSQLサービスプロバイダをオーバーライドします。 デフォルト値: `undef`。 ##### `service_reload` PostgreSQLサービスのデフォルトのリロードコマンドをオーバーライドします。 デフォルト値: OSによって異なります。 ##### `service_restart_on_change` 設定変更をアクティブにするにはサービスの再起動が必要な設定エントリが変更された場合に、PostgreSQLサービスを再起動する際のデフォルト動作をオーバーライドします。 デフォルト値: `true`。 ##### `service_status` PostgreSQLサービスのデフォルトのステータスチェックコマンドをオーバーライドします。 デフォルト値: OSによって異なります。 ##### `user` ファイルシステム内のPostgreSQL関連ファイルのデフォルトのPostgreSQLスーパーユーザおよびオーナーをオーバーライドします。 デフォルト値: 'postgres'。 #### postgresql::server::contrib PostgreSQL contribパッケージをインストールします。 ##### `package_ensure` PostgreSQL contribパッケージリソースに受け渡されたensureパラメータを設定します。 ##### `package_name` PostgreSQL contribパッケージの名前。 #### postgresql::server::plperl postgresqlのPL/Perl手続き型言語をインストールします。 ##### `package_ensure` PostgreSQL PL/Perlパッケージリソースに受け渡されたensureパラメータ。 ##### `package_name` PostgreSQL PL/Perlパッケージの名前。 #### postgresql::server::postgis PostgreSQL postgisパッケージをインストールします。 ### 定義できるタイプ #### postgresql::server::config_entry `postgresql.conf`設定ファイルを変更します。 各リソースは、次の例のようにファイル内の各行にマッピングされています。 ```puppet postgresql::server::config_entry { 'check_function_bodies': value => 'off', } ``` ##### `ensure` 'absent'に設定した場合、エントリを削除します。 有効な値: 'present'、'absent'。 デフォルト値: 'present'。 ##### `value` 設定の値を定義します。 #### postgresql::server::db ローカルのデータベース、ユーザを作成し、必要なパーミッションを割り当てます。 ##### `comment` PostgreSQLのCOMMENTコマンドを使用して、データベースについて保存するコメントを定義します。 ##### `connect_settings` リモートサーバーに接続する際に使用される環境変数のハッシュを指定します。 デフォルト値: ローカルのPostgresインスタンスに接続します。 ##### `dbname` 作成するデータベースの名前を設定します。 デフォルト値: namevar。 ##### `encoding` データベースの作成中の文字セットをオーバーライドします。 デフォルト値: インストール時に定義されたデフォルト値。 ##### `grant` 作成中に付与するパーミッションを指定します。 デフォルト値: 'ALL'。 ##### `istemplate` -`true`に設定すると、そのデータベースをテンプレートとして指定します。 +`true`に設定すると、そのデータベースをテンプレートとして指定します。 デフォルト値: `false`。 ##### `locale` データベース作成中にロケールをオーバーライドします。 デフォルト値: インストール時に定義されたデフォルト値。 ##### `owner` ユーザをデータベースの所有者として設定します。 デフォルト値: `postgresql::server`または`postgresql::globals`で設定された'$user'変数。 ##### `password` **必須** 作成されたユーザのパスワードを設定します。 ##### `tablespace` 作成したデータベースを割り当てるテーブル空間の名前を定義します。 デフォルト値: PostgreSQLのデフォルト値。 ##### `template` このデータベースを構築する際にテンプレートとして使用するデータベースの名前を指定します。 デフォルト値: `template0`。 ##### `user` データベースを作成し、作成後にデータベースへのアクセスを割り当てるユーザ。必須指定です。 #### postgresql::server::database ユーザなし、パーミッションなしのデータベースを作成します。 ##### `dbname` データベースの名前を設定します。 デフォルト値: namevar。 ##### `encoding` データベースの作成中の文字セットをオーバーライドします。 デフォルト値: インストール時に定義されたデフォルト値。 ##### `istemplate` `true`に設定すると、そのデータベースをテンプレートとして定義します。 デフォルト値: `false`。 ##### `locale` データベース作成中にロケールをオーバーライドします。 デフォルト値: インストール時に定義されたデフォルト値。 ##### `owner` データベース所有者の名前を設定します。 デフォルト値: `postgresql::server`または`postgresql::globals`で設定された'$user'変数。 ##### `tablespace` このデータベースを作成するテーブル空間を設定します。 デフォルト値: インストール時に定義されたデフォルト値。 ##### `template` このデータベースを構築する際にテンプレートとして使用するデータベースの名前を指定します。 デフォルト値: 'template0'。 #### postgresql::server::database_grant データベース固有のパーミッションについて`postgresql::server::database_grant`をラッピングして、grantベースのユーザアクセス権を管理します。詳細については、[PostgreSQLマニュアルの`grant`](http://www.postgresql.org/docs/current/static/sql-grant.html)を参照してください。 #### `connect_settings` リモートサーバーに接続する際に使用される環境変数のハッシュを指定します。 デフォルト値: ローカルのPostgresインスタンスに接続します。 ##### `db` アクセス権を付与するデータベースを指定します。 ##### `privilege` 付与する権限のコンマ区切りリストを指定します。 有効なオプション: 'ALL'、'CREATE'、'CONNECT'、'TEMPORARY'、'TEMP'。 ##### `psql_db` 権限付与を実行するデータベースを定義します。 **通常、デフォルトを変更しないでください。** デフォルト値: 'postgres'。 ##### `psql_user` `psql`を実行するOSユーザを指定します。 デフォルト値: モジュールのデフォルトユーザ。通常、'postgres'。 ##### `role` アクセスを付与するロールまたはユーザを指定します。 #### postgresql::server::extension PostgreSQL拡張を管理します。 ##### `database` 拡張を有効化するデータベースを指定します。 ##### `ensure` 拡張を有効化するか無効化するかを指定します。 有効なオプション: 'present'または'absent'。 #### `extension` 有効化する拡張を指定します。空欄にした場合、リソースの名前が使用されます。 #### `version` データベースが使用するエクステンションのバージョンを指定します。 拡張パッケージが更新された場合、各データベースで有効なバージョンを自動的に変更することはありません。 そのためには、PostgreSQLに固有のSQL `ALTER EXTENSION...`を使用して更新する必要があります `version`は`latest`に設定できます。この場合、SQL `ALTER EXTENSION "extension" UPDATE`がこのデータベースのみに適用されます。 `version`は特定のバージョンに設定できます。この場合、拡張は`ALTER EXTENSION "extension" UPDATE TO 'version'`を使用して更新されます 例えば、拡張を`postgis`、バージョンを`2.3.3`に設定した場合、SQL `ALTER EXTENSION "postgis" UPDATE TO '2.3.3'`がこのデータベースのみに適用されます。 `version`は省略される場合もあります。この場合、SQL `ALTER EXTENSION...`は適用されません。バージョンは変更されず、そのままになります。 ##### `package_name` 拡張を有効化する前にインストールするパッケージを指定します。 ##### `package_ensure` デフォルトのパッケージ削除動作をオーバーライドします。 デフォルトでは、`package_name`で指定されたパッケージが、拡張が有効のときインストールされ、拡張が無効のとき削除されます。この動作をオーバーライドするには、そのパッケージに`ensure`の値を設定してください。 #### postgresql::server::grant ロールのgrantベースのアクセス権を管理します。詳細については、[PostgreSQLマニュアルの`grant`](http://www.postgresql.org/docs/current/static/sql-grant.html)を参照してください。 ##### `db` アクセス権を付与するデータベースを指定します。 ##### `object_type` 権限を付与するオブジェクトのタイプを指定します。 有効なオプション: 'DATABASE'、'SCHEMA'、'SEQUENCE'、'ALL SEQUENCES IN SCHEMA'、'TABLE'、または'ALL TABLES IN SCHEMA'。 ##### `object_name` アクセス権を付与する`object_type`の名前を、文字列または2要素の配列で指定します。 String: 'object_name' Array: ['schema_name', 'object_name'] ##### `port` 接続に使用するポート。 デフォルト値: `undef`。PostgreSQLのパッケージングに応じて、通常、デフォルトでポート5432になります。 ##### `privilege` 付与する権限を指定します。 有効なオプション: 'ALL'、'ALL PRIVILEGES'、または'object_type'依存の文字列。 ##### `psql_db` 権限付与を実行するデータベースを指定します。 **通常、デフォルトを変更しないでください。** デフォルト値: 'postgres'。 ##### `psql_user` `psql`を実行するOSユーザを設定します。 デフォルト値: モジュールのデフォルトユーザ。通常、'postgres'。 ##### `role` アクセスを付与するロールまたはユーザを指定します。 #### postgresql::server::grant_role ロールを(グループ)ロールに割り当てられるようにします。詳細については、[PostgreSQLマニュアルの`Role Membership`](http://www.postgresql.org/docs/current/static/role-membership.html)を参照してください。 ##### `group` ロールを割り当てるグループロールを指定します。 ##### `role` グループに割り当てるロールを指定します。空欄にした場合、リソースの名前が使用されます。 ##### `ensure` メンバーシップを付与するか、無効化するかを指定します。 有効なオプション: 'present'または'absent'。 デフォルト値: 'present'。 ##### `port` 接続に使用するポート。 デフォルト値: `undef`。PostgreSQLのパッケージングに応じて、通常、デフォルトでポート5432になります。 ##### `psql_db` 権限付与を実行するデータベースを指定します。 **通常、デフォルトを変更しないでください。** デフォルト値: 'postgres'。 ##### `psql_user` `psql`を実行するOSユーザを設定します。 デフォルト値: モジュールのデフォルトユーザ。通常、`postgres`。 ##### `connect_settings` リモートサーバーへの接続時に使用する環境変数のハッシュを指定します。 デフォルト値: ローカルのPostgresインスタンスに接続します。 #### postgresql::server::pg_hba_rule `pg_hba.conf`のアクセスルールを作成できるようにします。詳細については、[使用例](#create-an-access-rule-for-pghba.conf)および[PostgreSQLマニュアル](http://www.postgresql.org/docs/current/static/auth-pg-hba-conf.html)を参照してください。 ##### `address` タイプが'local'ではないとき、このルール一致に対するCIDRベースのアドレスを設定します。 ##### `auth_method` このルールが一致する接続の認証に使用される方法を提供します。詳細な説明は、PostgreSQL `pg_hba.conf`のマニュアルに記載されています。 ##### `auth_option` 特定の`auth_method`設定については、受け渡し可能な追加オプションがあります。詳細については、PostgreSQL `pg_hba.conf`マニュアルを参照してください。 ##### `database` このルールが一致するデータベースのコンマ区切りリストを設定します。 ##### `description` 必要に応じて、このルールの長めの説明を定義します。この説明は、`pg_hba.conf`のルール上部のコメント内に挿入されます。 デフォルト値: 'none'。 そのリソースを一意に識別するための方法を指定しますが、機能的には何も実行しません。 ##### `order` `pg_hba.conf`にルールを配置する順序を設定します。 デフォルト値: 150。 #### `postgresql_version` PostgreSQLインスタンス全体を管理することなく、`pg_hba.conf`を管理します。 デフォルト値: `postgresql::server`に設定されたバージョン。 ##### `target` ルールのターゲットを提供します。通常、内部使用のみのプロパティです。 **注意して使用してください。** ##### `type` ルールのタイプを設定します。 有効なオプション: 'local'、'host'、'hostssl'、または'hostnossl'。 ##### `user` このルールが一致するユーザのコンマ区切りリストを設定します。 #### postgresql::server::pg_ident_rule `pg_ident.conf`のユーザ名マップを作成可能にします。詳細については、上述の[使用例](#create-user-name-maps-for-pgidentconf)および[PostgreSQLマニュアル](http://www.postgresql.org/docs/current/static/auth-username-maps.html)を参照してください。 ##### `database_username` データベースユーザのユーザ名を指定します。このユーザ名には`system_username`がマッピングされています。 ##### `description` 必要に応じて、このルールの長めの説明を設定します。この説明は、`pg_ident.conf`のルール上部のコメント内に挿入されます。 デフォルト値: 'none'。 ##### `map_name` `pg_hba.conf`でこのマッピングを参照するために使用されるユーザマップの名前を設定します。 ##### `order` `pg_ident.conf`にマッピングを配置する際の順序を定義します。 デフォルト値: 150。 ##### `system_username` オペレーティングシステムのユーザ名(データベースへの接続に使用するユーザ名)を指定します。 ##### `target` ルールのターゲットを提供します。通常、内部使用のみのプロパティです。 **注意して使用してください。** #### postgresql::server::reassign_owned_by PostgreSQLコマンド'REASSIGN OWNED'をデータベースに対して実行し、既存オブジェクトの所有権を別のデータベースロールに移します。 ##### `db`  'REASSIGN OWNED'コマンドを適用するデータベースを指定します。 ##### `old_role` 指定したデータベース内のオブジェクトを現在所有しているロールまたはユーザを指定します。 ##### `new_role` 対象オブジェクトの新しい所有者となるロールまたはユーザを指定します。 ##### `psql_user` `psql`を実行するOSユーザを指定します。 デフォルト値: モジュールのデフォルトユーザ。通常、'postgres'。 ##### `port` 接続に使用するポート。 デフォルト値: `undef`。PostgreSQLのパッケージングに応じて、通常、デフォルトでポート5432になります。 ##### `connect_settings` リモートサーバーへの接続時に使用する環境変数のハッシュを指定します。 デフォルト値: ローカルのPostgresインスタンスに接続します。 #### postgresql::server::recovery `recovery.conf`の内容を作成可能にします。詳細については、[使用例](#create-recovery-configuration)および[PostgreSQLマニュアル](http://www.postgresql.org/docs/current/static/recovery-config.html)を参照してください。 `recovery_target_inclusive`、 `pause_at_recovery_target`、`standby_mode`、`recovery_min_apply_delay`を除くすべてのパラメータ値は、テンプレートに含まれる文字列セットです。 全パラメータリストの詳細な説明は、[PostgreSQLマニュアル](http://www.postgresql.org/docs/current/static/recovery-config.html)にあります。 パラメータは、次の3つのセクションにグループ分けされています。 ##### [アーカイブリカバリパラメータ](http://www.postgresql.org/docs/current/static/archive-recovery-settings.html) * `restore_command` * `archive_cleanup_command` * `recovery_end_command` ##### [Recovery Target Settings](http://www.postgresql.org/docs/current/static/recovery-target-settings.html) * `recovery_target_name` * `recovery_target_time` * `recovery_target_xid` * `recovery_target_inclusive` * `recovery_target` * `recovery_target_timeline` * `pause_at_recovery_target` ##### [Standby Server Settings](http://www.postgresql.org/docs/current/static/standby-settings.html) * `standby_mode`: 文字列('on'/'off')またはブール値(`true`/`false`)で指定できます。 * `primary_conninfo` * `primary_slot_name` * `trigger_file` * `recovery_min_apply_delay` ##### `target` ルールのターゲットを提供します。通常、内部使用のみのプロパティです。 **注意して使用してください。** #### postgresql::server::role PostgreSQLのロールまたはユーザを作成します。 ##### `connection_limit` ロールが同時に接続可能な数を指定します。 デフォルト値: '-1'。これは、無制限を意味します。 ##### `connect_settings` リモートサーバーへの接続時に使用する環境変数のハッシュを指定します。 デフォルト値: ローカルのPostgresインスタンスに接続します。 ##### `createdb` このロールに新しいデータベースを作成する能力を付与するかどうかを指定します。 デフォルト値: `false`。 ##### `createrole` このロールに新しいロールを作成する権限を付与するかどうかを指定します。 デフォルト値: `false`。 ##### `inherit` 新しいロールに継承権限を付与するかどうかを指定します。 デフォルト値: `true`。 ##### `login` 新しいロールにログイン権限を付与するかどうかを指定します。 デフォルト値: `true`。 ##### `password_hash` パスワード作成中に使用するハッシュを設定します。PostgreSQLがサポートする形式でパスワードが暗号化されていない場合、ここで、`postgresql_password`関数を使用して、MD5ハッシュを提供します。例は次のとおりです。 ##### `update_password` trueに設定すると、変更時にパスワードが更新されます。作成後にロールのパスワードを変更しない場合は、falseに設定してください。 ```puppet postgresql::server::role { 'myusername': password_hash => postgresql_password('myusername', 'mypassword'), } ``` ##### `replication` `true`に設定すると、このロールにレプリケーション機能が提供されます。 デフォルト値: `false`。 ##### `superuser` 新しいロールにスーパーユーザ権限を付与するかどうかを指定します。 デフォルト値: `false`。 ##### `username` 作成するロールのユーザ名を定義します。 デフォルト値: namevar。 #### postgresql::server::schema スキーマを作成します。 ##### `connect_settings` リモートサーバーへの接続時に使用する環境変数のハッシュを指定します。 デフォルト値: ローカルのPostgresインスタンスに接続します。 ##### `db` 必須。 このスキーマを作成するデータベースの名前を設定します。 ##### `owner` スキーマのデフォルト所有者を設定します。 ##### `schema` スキーマの名前を設定します。 デフォルト値: namevar。 #### postgresql::server::table_grant ユーザのgrantベースのアクセス権を管理します。詳細については、PostgreSQLマニュアルの`grant`の項を参照してください。 ##### `connect_settings` リモートサーバーへの接続時に使用する環境変数のハッシュを指定します。 デフォルト値: ローカルのPostgresインスタンスに接続します。 ##### `db` そのテーブルが存在するデータベースを指定します。 ##### `privilege` 付与する権限のコンマ区切りリストを指定します。有効なオプション: 'ALL'、'SELECT'、'INSERT'、'UPDATE'、'DELETE'、'TRUNCATE'、'REFERENCES'、'TRIGGER'。 ##### `psql_db` 権限付与を実行するデータベースを指定します。 通常、デフォルトを変更しないでください。 デフォルト値: 'postgres'。 ##### `psql_user` `psql`を実行するOSユーザを指定します。 デフォルト値: モジュールのデフォルトユーザ。通常、'postgres'。 ##### `role` アクセスを付与するロールまたはユーザを指定します。 ##### `table` アクセス権を付与するテーブルを指定します。 #### postgresql::server::tablespace テーブル空間を作成します。必要な場合、場所も作成し、PostgreSQLサーバーと同じパーミッションを割り当てます。 ##### `connect_settings` リモートサーバーへの接続時に使用する環境変数のハッシュを指定します。 デフォルト値: ローカルのPostgresインスタンスに接続します。 ##### `location` このテーブル空間へのパスを指定します。 ##### `owner` そのテーブル空間のデフォルト所有者を指定します。 ##### `spcname` テーブル空間の名前を指定します。 デフォルト値: namevar。 ### タイプ #### postgresql_psql Puppetがpsqlステートメントを実行できるようにします。 ##### `command` 必須。 psqlを介して実行するSQLコマンドを指定します。 ##### `cwd` psqlコマンドが実行される作業ディレクトリを指定します。 デフォルト値: '/tmp'。 ##### `db` SQLコマンドを実行するデータベースの名前を指定します。 ##### `environment` SQLコマンドに対して追加の環境変数を設定する場合に指定します。複数の環境変数を使用する場合は、配列として指定します。 ##### `name` 自身の参考用の任意のタグ、すなわちメッセージの名前を設定します。これはnamevarです。 ##### `onlyif` メインのコマンドの前に実行するオプションのSQLコマンドを設定します。通常、これはべき等性に基づいて、データベース内のオブジェクトの存在を確認し、メインのSQLコマンドを実行する必要があるかどうかを判断するため使用されます。 ##### `port` SQLコマンドを実行するデータベースサーバーのポートを指定します。 ##### `psql_group` psqlコマンドを実行するシステムユーザグループアカウントを指定します。 デフォルト値: 'postgres'。 ##### `psql_path` psql実行ファイルへのパスを指定します。 デフォルト値: 'psql'。 ##### `psql_user` psqlコマンドを実行するシステムユーザアカウントを指定します。 デフォルト値: 'postgres'。 ##### `refreshonly` notifyイベントまたはsubscribeイベントが発生したときのみSQLを実行するかどうかを指定します。 有効な値: `true`、`false`。 デフォルト値: `false`。 ##### `search_path` SQLコマンドを実行するときに使用するスキーマ検索パスを定義します。 ##### `unless` `onlyif`の逆です。 #### postgresql_conf Puppetが`postgresql.conf`パラメータを管理できるようにします。 ##### `name` 管理するPostgreSQLパラメータ名を指定します。 これはnamevarです。 ##### `target` `postgresql.conf`へのパスを指定します。 デフォルト値: '/etc/postgresql.conf'。 ##### `value` このパラメータに設定する値を指定します。 #### postgresql_replication_slot PostgreSQLマスターサーバー上でウォームスタンバイレプリケーションを登録するためのレプリケーションスロットを作成および消去できるようにします。 ##### `name` 作成するスロットの名前を指定します。有効なレプリケーションスロット名である必要があります。 これはnamevarです。 ##### `ensure` 必須。 指定されたスロットに対して、作成または消去のいずれかのアクションを指定します。 有効な値: 'present'、'absent'。 デフォルト値: 'present'。 #### postgresql_conn_validator このタイプを使用するローカルまたはリモートのPostgreSQLデータベースへの接続を検証します。 ##### `connect_settings` リモートサーバーへの接続時に使用する環境変数のハッシュを指定します。個々のパラメータ(`host`など)を設定する代わりに使用されますが、個々のパラメータが設定されている場合は個々のパラメータが優先されます。 デフォルト値: {} ##### `db_name` テストするデータベースの名前を指定します。Specifies the name of the database you wish to test. デフォルト値: '' ##### `db_password` 接続するパスワードを指定します。`.pgpass`が使用されている場合は空欄にできます。それ以外の場合、空欄にすることは推奨されません。 デフォルト値: '' ##### `db_username` 接続するユーザ名を指定します。 デフォルト値: '' Unixソケットとident認証を使用するとき、このユーザとして実行されます。 ##### `command` 接続性を検証するためにターゲットデータベースで実行されるコマンドです。 デフォルト値: 'SELECT 1' ##### `host` テストするデータベースのホスト名を設定します。 デフォルト値: ''。これは、通常指定されたローカルUnixソケットを使用します。 **ホストがリモートの場合、ユーザ名を指定する必要があります。** ##### `port` 接続するときに使用するポートを定義します。 -デフォルト値: '' +デフォルト値: '' ##### `run_as` `psql`コマンドの実行ユーザを指定します。これは、Unixソケットと`ident`認証を使用してローカルにデータベースに接続するときに重要です。リモートテストには必要ありません。 ##### `sleep` 失敗した後、再試行する前にスリープする時間を秒単位で設定します。 ##### `tries` 失敗した後、リソースを失敗とみなすまで再試行する回数を設定します。 ### 関数 #### postgresql_password PostgreSQL暗号化パスワードを生成します。次のように、`postgresql_password`をコマンドラインから呼び出し、暗号化されたパスワードをマニフェストにコピーペーストします。 ```shell puppet apply --execute 'notify { 'test': message => postgresql_password('username', 'password') }' ``` 本番マニフェストからこの関数を呼び出すことも可能ですが、その場合、マニフェストには暗号化していない平文のパスワードを含める必要があります。 #### postgresql_acls_to_resources_hash(acl_array, id, order_offset) この内部関数は、`pg_hba.conf`ベースのACLのリスト(文字列の配列として受け渡されたもの)を`postgresql::pg_hba_rule`リソースと互換性のある形式に変換します。 **この関数は、モジュールによる内部的な使用のみ可能です。** ## 制約事項 PostgreSQLのバージョン8.1~9.5で動作します。 現在、postgresqlモジュールは次のオペレーティングシステムでテスト済みです。 * Debian 6.x, 7.x, 8.x. * CentOS 5.x、6.x、7.x。 * Ubuntu 10.04および12.04、14.04。 その他のシステムとも互換性がある可能性がありますが、積極的なテストは行っておりません。 ### Aptモジュールのサポート このモジュールは1.xと2.x両方のバージョンの'puppetlabs-apt'モジュールをサポートしていますが、'puppetlabs-apt'の2.0.0と2.0.1はサポートしていません。 ### PostGISのサポート PostGISは、現時点ではすべてのプラットフォームで正常に動作するわけではないため、サポート対象外の機能とみなします。 ### すべてのバージョンのRHEL/CentOS SELinuxが有効化されている場合、次の方法で`postgresql_port_t`コンテキストに使用中のカスタムポートを追加する必要があります。 ```shell semanage port -a -t postgresql_port_t -p tcp $customport ``` ## 開発 Puppet Forgeに公開されているPuppet Labsモジュールはオープンプロジェクトのため、維持するにはコミュニティの貢献が不可欠です。Puppetは、現在私たちがアクセスできない無数のプラットフォームやハードウェア、ソフトウェア、デプロイ構成にも利用されることを目的としています。私たちの目標は、できる限り簡単に変更に貢献し、みなさまの環境で私たちのモジュールが機能できるようにすることです。最高の状態を維持するため、コントリビュータにはいくつかのガイドラインを守っていただく必要があります。詳細については、[モジュールコントリビューションガイド](https://docs.puppetlabs.com/forge/contributing.html)を参照してください。 ### テスト このモジュールには、2種類のテストが配布されています。`rspec-puppet`のユニットテストと、`rspec-system`を使用したシステムテストです。 ユニットテストを実行するには、以下がインストールされていることを確認してください。 * rake * bundler 次のように、必要なgemをインストールします。 ```shell bundle install --path=vendor ``` そして、次のように記述して、ユニットテストを実行します。 ```shell bundle exec rake spec ``` ユニットテストは、Travis-CIでも実行されます。自身のテスト結果を確認するには、このプロジェクトのご自身のGitHubクローンのアカウントセクションから、Travis-CIを介してサービスフックを登録してください。 システムテストを実行するには、以下のツールもインストールされていることを確認してください。 * Vagrant > 1.2.x * VirtualBox > 4.2.10 次の記述を使用してテストを実行します。 ```shell bundle exec rspec spec/acceptance ``` 異なるオペレーティングシステムでテストを実行するには、`.nodeset.yml`で利用可能なセットを確認して、次の構文で特定のセットを実行します。 ```shell RSPEC_SET=debian-607-x64 bundle exec rspec spec/acceptance ``` ### コントリビュータ -貢献してくださった方々の一覧を[Github](https://github.com/puppetlabs/puppetlabs-postgresql/graphs/contributors)でご覧いただけます。 +貢献してくださった方々の一覧を[GitHub](https://github.com/puppetlabs/puppetlabs-postgresql/graphs/contributors)でご覧いただけます。 diff --git a/spec/acceptance/00-utf8_encoding_spec.rb b/spec/acceptance/00-utf8_encoding_spec.rb index 2e7770b..e98762c 100644 --- a/spec/acceptance/00-utf8_encoding_spec.rb +++ b/spec/acceptance/00-utf8_encoding_spec.rb @@ -1,37 +1,33 @@ -require 'spec_helper_acceptance' +require 'spec_helper_acceptance' # rubocop:disable Style/FileName # These tests are designed to ensure that the module, when ran with defaults, # sets up everything correctly and allows us to connect to Postgres. -describe 'postgresql::server', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do - it 'with defaults' do - pp = <<-EOS +describe 'postgresql::server', unless: UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + pp = <<-MANIFEST class { 'postgresql::globals': encoding => 'UTF8', locale => 'en_NG', } -> class { 'postgresql::server': } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => true) + MANIFEST + it 'with defaults' do + apply_manifest(pp, catch_failures: true) + apply_manifest(pp, catch_changes: true) end describe port(5432) do it { is_expected.to be_listening } end it 'can connect with psql' do psql('--command="\l" postgres', 'postgres') do |r| - expect(r.stdout).to match(/List of databases/) + expect(r.stdout).to match(%r{List of databases}) end end it 'must set UTF8 as template1 encoding' do psql('--command="SELECT pg_encoding_to_char(encoding) FROM pg_database WHERE datname=\'template1\'"') do |r| - expect(r.stdout).to match(/UTF8/) + expect(r.stdout).to match(%r{UTF8}) end end end - - - diff --git a/spec/acceptance/alternative_port_spec.rb b/spec/acceptance/alternative_port_spec.rb index 11094d3..6bf56b7 100644 --- a/spec/acceptance/alternative_port_spec.rb +++ b/spec/acceptance/alternative_port_spec.rb @@ -1,28 +1,24 @@ require 'spec_helper_acceptance' # These tests ensure that postgres can change itself to an alternative port # properly. -describe 'postgresql::server', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do +describe 'postgresql::server', unless: UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do it 'on an alternative port' do - pp = <<-EOS + pp = <<-MANIFEST class { 'postgresql::server': port => '55433' } - EOS + MANIFEST - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => true) + apply_manifest(pp, catch_failures: true) + apply_manifest(pp, catch_changes: true) end - describe port(55433) do + describe port(55433) do # rubocop:disable Style/NumericLiterals it { is_expected.to be_listening } end it 'can connect with psql' do psql('-p 55433 --command="\l" postgres', 'postgres') do |r| - expect(r.stdout).to match(/List of databases/) + expect(r.stdout).to match(%r{List of databases}) end end - end - - - diff --git a/spec/acceptance/db_spec.rb b/spec/acceptance/db_spec.rb index 0285c3f..2e89d32 100644 --- a/spec/acceptance/db_spec.rb +++ b/spec/acceptance/db_spec.rb @@ -1,54 +1,57 @@ require 'spec_helper_acceptance' -describe 'postgresql::server::db', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do +describe 'postgresql::server::db', unless: UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + # rubocop:disable RSpec/ExampleLength + # rubocop:disable RSpec/MultipleExpectations + # rubocop:disable Metrics/LineLength it 'creates a database' do begin tmpdir = default.tmpdir('postgresql') - pp = <<-EOS + pp = <<-MANIFEST class { 'postgresql::server': postgres_password => 'space password', } postgresql::server::tablespace { 'postgresql-test-db': location => '#{tmpdir}', } -> postgresql::server::db { 'postgresql-test-db': comment => 'testcomment', user => 'test-user', password => 'test1', tablespace => 'postgresql-test-db', } - EOS + MANIFEST - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => true) + apply_manifest(pp, catch_failures: true) + apply_manifest(pp, catch_changes: true) # Verify that the postgres password works shell("echo 'localhost:*:*:postgres:\'space password\'' > /root/.pgpass") - shell("chmod 600 /root/.pgpass") + shell('chmod 600 /root/.pgpass') shell("psql -U postgres -h localhost --command='\\l'") psql('--command="select datname from pg_database" "postgresql-test-db"') do |r| - expect(r.stdout).to match(/postgresql-test-db/) + expect(r.stdout).to match(%r{postgresql-test-db}) expect(r.stderr).to eq('') end psql('--command="SELECT 1 FROM pg_roles WHERE rolname=\'test-user\'"') do |r| - expect(r.stdout).to match(/\(1 row\)/) + expect(r.stdout).to match(%r{\(1 row\)}) end result = shell('psql --version') version = result.stdout.match(%r{\s(\d\.\d)})[1] - if version > "8.1" - comment_information_function = "shobj_description" - else - comment_information_function = "obj_description" - end + comment_information_function = if version > '8.1' + 'shobj_description' + else + 'obj_description' + end psql("--dbname postgresql-test-db --command=\"SELECT pg_catalog.#{comment_information_function}(d.oid, 'pg_database') FROM pg_catalog.pg_database d WHERE datname = 'postgresql-test-db' AND pg_catalog.#{comment_information_function}(d.oid, 'pg_database') = 'testcomment'\"") do |r| - expect(r.stdout).to match(/\(1 row\)/) + expect(r.stdout).to match(%r{\(1 row\)}) end ensure psql('--command=\'drop database "postgresql-test-db" postgres\'') psql('--command="DROP USER test"') end end end diff --git a/spec/acceptance/default_parameters_spec.rb b/spec/acceptance/default_parameters_spec.rb index 4763482..eb132e4 100644 --- a/spec/acceptance/default_parameters_spec.rb +++ b/spec/acceptance/default_parameters_spec.rb @@ -1,28 +1,24 @@ require 'spec_helper_acceptance' # These tests are designed to ensure that the module, when ran with defaults, # sets up everything correctly and allows us to connect to Postgres. -describe 'postgresql::server', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do +describe 'postgresql::server', unless: UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do it 'with defaults' do - pp = <<-EOS + pp = <<-MANIFEST class { 'postgresql::server': } - EOS + MANIFEST - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => true) + apply_manifest(pp, catch_failures: true) + apply_manifest(pp, catch_changes: true) end describe port(5432) do it { is_expected.to be_listening } end it 'can connect with psql' do psql('--command="\l" postgres', 'postgres') do |r| - expect(r.stdout).to match(/List of databases/) + expect(r.stdout).to match(%r{List of databases}) end end - end - - - diff --git a/spec/acceptance/postgresql_conn_validator_spec.rb b/spec/acceptance/postgresql_conn_validator_spec.rb index 20d8422..dfc116e 100644 --- a/spec/acceptance/postgresql_conn_validator_spec.rb +++ b/spec/acceptance/postgresql_conn_validator_spec.rb @@ -1,76 +1,73 @@ require 'spec_helper_acceptance' -describe 'postgresql_conn_validator', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do - - let(:install_pp) { <<-EOS - class { 'postgresql::server': - postgres_password => 'space password', - }-> - postgresql::server::role { 'testuser': - password_hash => postgresql_password('testuser','test1'), - }-> - postgresql::server::database { 'testdb': - owner => 'testuser', - require => Postgresql::Server::Role['testuser'] - }-> - postgresql::server::database_grant { 'allow connect for testuser': - privilege => 'ALL', - db => 'testdb', - role => 'testuser', - } - - EOS - - } +describe 'postgresql_conn_validator', unless: UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + let(:install_pp) do + <<-MANIFEST + class { 'postgresql::server': + postgres_password => 'space password', + }-> + postgresql::server::role { 'testuser': + password_hash => postgresql_password('testuser','test1'), + }-> + postgresql::server::database { 'testdb': + owner => 'testuser', + require => Postgresql::Server::Role['testuser'] + }-> + postgresql::server::database_grant { 'allow connect for testuser': + privilege => 'ALL', + db => 'testdb', + role => 'testuser', + } + MANIFEST + end context 'local connection' do - it 'validates successfully with defaults' do - pp = <<-EOS + it 'validates successfully with defaults' do # rubocop:disable RSpec/ExampleLength + pp = <<-MANIFEST #{install_pp}-> postgresql_conn_validator { 'validate this': db_name => 'testdb', db_username => 'testuser', db_password => 'test1', host => 'localhost', psql_path => '/usr/bin/psql', } - EOS + MANIFEST - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => true) + apply_manifest(pp, catch_failures: true) + apply_manifest(pp, catch_changes: true) end - it 'works with connect settings hash' do - pp = <<-EOS + it 'works with connect settings hash' do # rubocop:disable RSpec/ExampleLength + pp = <<-MANIFEST #{install_pp}-> postgresql_conn_validator { 'validate this': connect_settings => { 'PGDATABASE' => 'testdb', 'PGPORT' => '5432', 'PGUSER' => 'testuser', 'PGPASSWORD' => 'test1', 'PGHOST' => 'localhost' }, psql_path => '/usr/bin/psql' } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => true) + MANIFEST + apply_manifest(pp, catch_failures: true) + apply_manifest(pp, catch_changes: true) end - it 'fails gracefully' do - pp = <<-EOS + it 'fails gracefully' do # rubocop:disable RSpec/ExampleLength + pp = <<-MANIFEST #{install_pp}-> postgresql_conn_validator { 'validate this': psql_path => '/usr/bin/psql', tries => 3 } - EOS + MANIFEST result = apply_manifest(pp) - expect(result.stderr).to match /Unable to connect to PostgreSQL server/ + expect(result.stderr).to match %r{Unable to connect to PostgreSQL server} end end end diff --git a/spec/acceptance/postgresql_psql_spec.rb b/spec/acceptance/postgresql_psql_spec.rb index 34a258c..6362bc9 100644 --- a/spec/acceptance/postgresql_psql_spec.rb +++ b/spec/acceptance/postgresql_psql_spec.rb @@ -1,183 +1,173 @@ require 'spec_helper_acceptance' -describe 'postgresql_psql', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do - - it 'should always run SQL' do - pp = <<-EOS - class { 'postgresql::server': } -> - postgresql_psql { 'foobar': - db => 'postgres', - psql_user => 'postgres', - command => 'select 1', - } - EOS +describe 'postgresql_psql', unless: UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + pp_one = <<-MANIFEST + class { 'postgresql::server': } -> + postgresql_psql { 'foobar': + db => 'postgres', + psql_user => 'postgres', + command => 'select 1', + } + MANIFEST + it 'alwayses run SQL' do + apply_manifest(pp_one, catch_failures: true) + apply_manifest(pp_one, expect_changes: true) + end - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :expect_changes => true) + pp_two = <<-MANIFEST + class { 'postgresql::server': } -> + postgresql_psql { 'foobar': + db => 'postgres', + psql_user => 'postgres', + command => 'select 1', + unless => 'select 1 where 1=2', + } + MANIFEST + it 'runs some SQL when the unless query returns no rows' do + apply_manifest(pp_two, catch_failures: true) + apply_manifest(pp_two, expect_changes: true) end - it 'should run some SQL when the unless query returns no rows' do - pp = <<-EOS - class { 'postgresql::server': } -> - postgresql_psql { 'foobar': - db => 'postgres', - psql_user => 'postgres', - command => 'select 1', - unless => 'select 1 where 1=2', - } - EOS + pp_three = <<-MANIFEST + class { 'postgresql::server': } -> + postgresql_psql { 'foobar': + db => 'postgres', + psql_user => 'postgres', + command => 'select * from pg_database limit 1', + unless => 'select 1 where 1=1', + } + MANIFEST + it 'does not run SQL when the unless query returns rows' do + apply_manifest(pp_three, catch_failures: true) + apply_manifest(pp_three, catch_changes: true) + end - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :expect_changes => true) + pp_four = <<-MANIFEST + class { 'postgresql::server': } -> + notify { 'trigger': } ~> + postgresql_psql { 'foobar': + db => 'postgres', + psql_user => 'postgres', + command => 'invalid sql statement', + unless => 'select 1 where 1=1', + } + MANIFEST + it 'does not run SQL when refreshed and the unless query returns rows' do + apply_manifest(pp_four, catch_failures: true) + apply_manifest(pp_four, expect_changes: true) end - it 'should not run SQL when the unless query returns rows' do - pp = <<-EOS + context 'with refreshonly' do + pp_five = <<-MANIFEST class { 'postgresql::server': } -> postgresql_psql { 'foobar': - db => 'postgres', - psql_user => 'postgres', - command => 'select * from pg_database limit 1', - unless => 'select 1 where 1=1', + db => 'postgres', + psql_user => 'postgres', + command => 'select 1', + unless => 'select 1 where 1=2', + refreshonly => true, } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => true) - end + MANIFEST + it 'does not run SQL when the unless query returns no rows' do + apply_manifest(pp_five, catch_failures: true) + apply_manifest(pp_five, catch_changes: true) + end - it 'should not run SQL when refreshed and the unless query returns rows' do - pp = <<-EOS + pp_six = <<-MANIFEST.unindent class { 'postgresql::server': } -> notify { 'trigger': } ~> postgresql_psql { 'foobar': - db => 'postgres', - psql_user => 'postgres', - command => 'invalid sql statement', - unless => 'select 1 where 1=1', + db => 'postgres', + psql_user => 'postgres', + command => 'select 1', + unless => 'select 1 where 1=2', + refreshonly => true, } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :expect_changes => true) - end - - context 'with refreshonly' do - it 'should not run SQL when the unless query returns no rows' do - pp = <<-EOS - class { 'postgresql::server': } -> - postgresql_psql { 'foobar': - db => 'postgres', - psql_user => 'postgres', - command => 'select 1', - unless => 'select 1 where 1=2', - refreshonly => true, - } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => true) + MANIFEST + it 'runs SQL when refreshed and the unless query returns no rows' do + apply_manifest(pp_six, catch_failures: true) + apply_manifest(pp_six, expect_changes: true) end - it 'should run SQL when refreshed and the unless query returns no rows' do - pp = <<-EOS.unindent - class { 'postgresql::server': } -> - notify { 'trigger': } ~> - postgresql_psql { 'foobar': - db => 'postgres', - psql_user => 'postgres', - command => 'select 1', - unless => 'select 1 where 1=2', - refreshonly => true, - } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :expect_changes => true) - end - - it 'should not run SQL when refreshed and the unless query returns rows' do - pp = <<-EOS.unindent - class { 'postgresql::server': } -> - notify { 'trigger': } ~> - postgresql_psql { 'foobar': - db => 'postgres', - psql_user => 'postgres', - command => 'invalid sql query', - unless => 'select 1 where 1=1', - refreshonly => true, - } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :expect_changes => true) - end - end - - it 'should not run some SQL when the onlyif query returns no rows' do - pp = <<-EOS + pp_seven = <<-MANIFEST.unindent class { 'postgresql::server': } -> + notify { 'trigger': } ~> postgresql_psql { 'foobar': - db => 'postgres', - psql_user => 'postgres', - command => 'select 1', - onlyif => 'select 1 where 1=2', + db => 'postgres', + psql_user => 'postgres', + command => 'invalid sql query', + unless => 'select 1 where 1=1', + refreshonly => true, } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => true) + MANIFEST + it 'does not run SQL when refreshed and the unless query returns rows' do + apply_manifest(pp_seven, catch_failures: true) + apply_manifest(pp_seven, expect_changes: true) + end end - it 'should run SQL when the onlyif query returns rows' do - pp = <<-EOS - class { 'postgresql::server': } -> - postgresql_psql { 'foobar': - db => 'postgres', - psql_user => 'postgres', - command => 'select * from pg_database limit 1', - onlyif => 'select 1 where 1=1', - } - EOS + pp_eight = <<-MANIFEST + class { 'postgresql::server': } -> + postgresql_psql { 'foobar': + db => 'postgres', + psql_user => 'postgres', + command => 'select 1', + onlyif => 'select 1 where 1=2', + } + MANIFEST + it 'does not run some SQL when the onlyif query returns no rows' do + apply_manifest(pp_eight, catch_failures: true) + apply_manifest(pp_eight, catch_changes: true) + end - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :expect_changes => true) + pp_nine = <<-MANIFEST + class { 'postgresql::server': } -> + postgresql_psql { 'foobar': + db => 'postgres', + psql_user => 'postgres', + command => 'select * from pg_database limit 1', + onlyif => 'select 1 where 1=1', + } + MANIFEST + it 'runs SQL when the onlyif query returns rows' do + apply_manifest(pp_nine, catch_failures: true) + apply_manifest(pp_nine, expect_changes: true) end context 'with secure password passing by environment' do - it 'should run SQL that contanins password passed by environment' do + it 'runs SQL that contanins password passed by environment' do # rubocop:disable RSpec/ExampleLength select = "select \\'$PASS_TO_EMBED\\'" - pp = <<-EOS.unindent + pp = <<-MANIFEST.unindent class { 'postgresql::server': } -> postgresql_psql { 'password embedded by environment: #{select}': db => 'postgres', psql_user => 'postgres', command => '#{select}', environment => [ 'PASS_TO_EMBED=pa$swD', ], } - EOS - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :expect_changes => false) + MANIFEST + apply_manifest(pp, catch_failures: true) + apply_manifest(pp, expect_changes: false) end - it 'should run SQL that contanins password passed by environment in check' do + it 'runs SQL that contanins password passed by environment in check' do # rubocop:disable RSpec/ExampleLength select = "select 1 where \\'$PASS_TO_EMBED\\'=\\'passwD\\'" - pp = <<-EOS.unindent + pp = <<-MANIFEST.unindent class { 'postgresql::server': } -> postgresql_psql { 'password embedded by environment in check: #{select}': db => 'postgres', psql_user => 'postgres', command => 'invalid sql query', unless => '#{select}', environment => [ 'PASS_TO_EMBED=passwD', ], } - EOS + MANIFEST - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :expect_changes => false) + apply_manifest(pp, catch_failures: true) + apply_manifest(pp, expect_changes: false) end end end diff --git a/spec/acceptance/remote_access_spec.rb b/spec/acceptance/remote_access_spec.rb index 9dd31de..f801f37 100644 --- a/spec/acceptance/remote_access_spec.rb +++ b/spec/acceptance/remote_access_spec.rb @@ -1,72 +1,71 @@ require 'spec_helper_acceptance' -describe 'remote-access', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do - before do - skip "These tests require the spec/acceptance/nodesets/centos-64-x64-2-hosts nodeset" +describe 'remote-access', unless: UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + before(:each) do + skip 'These tests require the spec/acceptance/nodesets/centos-64-x64-2-hosts nodeset' end - describe "configuring multi-node postgresql" do - + describe 'configuring multi-node postgresql' do # Get the database's IP to connect to from the database let(:database_ip_address) do - hosts_as('database').inject({}) do |memo,host| - fact_on host, "ipaddress_eth1" + hosts_as('database').reduce({}) do |_memo, host| + fact_on host, 'ipaddress_eth1' end end hosts_as('database').each do |host| - it "should be able to configure a host as database on #{host}" do - pp = <<-EOS + pp_one = <<-MANIFEST # Stop firewall so we can easily connect service {'iptables': ensure => 'stopped', } class { 'postgresql::server': ip_mask_allow_all_users => '0.0.0.0/0', listen_addresses => '*', } postgresql::server::db { 'puppet': user => 'puppet', password => postgresql_password('puppet', 'puppet'), } postgresql::server::pg_hba_rule { 'allow full yolo access password': type => 'host', database => 'all', user => 'all', address => '0.0.0.0/0', auth_method => 'password', order => '002', } - EOS - apply_manifest_on(host, pp, :catch_failures => true) + MANIFEST + it "should be able to configure a host as database on #{host}" do + apply_manifest_on(host, pp_one, catch_failures: true) end end hosts_as('client').each do |host| - it "should be able to configure a host as client on #{host} and then access database" do - pp = <<-EOS + pp_two = <<-MANIFEST class { 'postgresql::client':} $connection_settings = { 'PGUSER' => "puppet", 'PGPASSWORD' => "puppet", 'PGHOST' => "#{database_ip_address}", 'PGPORT' => "5432", 'PGDATABASE' => "puppet", } postgresql_psql { 'run using connection_settings': command => 'select 1', psql_user => 'root', psql_group => 'root', connect_settings => $connection_settings, } - EOS - apply_manifest_on(host, pp, :catch_failures => true) + MANIFEST + it "should be able to configure a host as client on #{host} and then access database" do + apply_manifest_on(host, pp_two, catch_failures: true) end end end end diff --git a/spec/acceptance/server/config_entry_spec.rb b/spec/acceptance/server/config_entry_spec.rb index 6e56259..c606a0d 100644 --- a/spec/acceptance/server/config_entry_spec.rb +++ b/spec/acceptance/server/config_entry_spec.rb @@ -1,38 +1,39 @@ require 'spec_helper_acceptance' describe 'postgresql::server::config_entry' do - - let(:pp_setup) { <<-EOS + let(:pp_setup) do + <<-MANIFEST class { 'postgresql::server': postgresql_conf_path => '/tmp/postgresql.conf', } - EOS - } + MANIFEST + end context 'unix_socket_directories' do - let(:pp_test) { pp_setup + <<-EOS + let(:pp_test) do + pp_setup + <<-MANIFEST postgresql::server::config_entry { 'unix_socket_directories': value => '/var/socket/, /root/' } - EOS - } + MANIFEST + end - #get postgresql version + # get postgresql version apply_manifest("class { 'postgresql::server': }") result = shell('psql --version') version = result.stdout.match(%r{\s(\d\.\d)})[1] if version >= '9.3' it 'is expected to run idempotently' do - apply_manifest(pp_test, :catch_failures => true) - apply_manifest(pp_test, :catch_changes => true) + apply_manifest(pp_test, catch_failures: true) + apply_manifest(pp_test, catch_changes: true) end it 'is expected to contain directories' do shell('cat /tmp/postgresql.conf') do |output| expect(output.stdout).to contain("unix_socket_directories = '/var/socket/, /root/'") end end end end end diff --git a/spec/acceptance/server/grant_role_spec.rb b/spec/acceptance/server/grant_role_spec.rb index 552c2f5..90d62ab 100644 --- a/spec/acceptance/server/grant_role_spec.rb +++ b/spec/acceptance/server/grant_role_spec.rb @@ -1,259 +1,263 @@ require 'spec_helper_acceptance' -describe 'postgresql::server::grant_role:', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do - +describe 'postgresql::server::grant_role:', unless: UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do let(:db) { 'grant_role_test' } let(:user) { 'psql_grant_role_tester' } let(:group) { 'test_group' } let(:password) { 'psql_grant_role_pw' } let(:version) do - if fact('osfamily') == 'RedHat' and fact('operatingsystemrelease') =~ /5/ + if fact('osfamily') == 'RedHat' && fact('operatingsystemrelease') =~ %r{5} '8.1' end end + let(:pp_one) do + <<-MANIFEST.unindent + $db = #{db} + $user = #{user} + $group = #{group} + $password = #{password} + $version = '#{version}' + + class { 'postgresql::server': } + + # Since we are not testing pg_hba or any of that, make a local user for ident auth + user { $user: + ensure => present, + } + + postgresql::server::role { $user: + password_hash => postgresql_password($user, $password), + } + + postgresql::server::database { $db: + owner => $user, + require => Postgresql::Server::Role[$user], + } + + # Lets setup the base rules + $local_auth_option = $version ? { + '8.1' => 'sameuser', + default => undef, + } + + # Create a rule for the user + postgresql::server::pg_hba_rule { "allow ${user}": + type => 'local', + database => $db, + user => $user, + auth_method => 'ident', + auth_option => $local_auth_option, + order => 1, + } + + # Create a role to grant to the user + postgresql::server::role { $group: + db => $db, + login => false, + require => Postgresql::Server::Database[$db], + } + + # Grant the role to the user + postgresql::server::grant_role { "grant_role ${group} to ${user}": + role => $user, + group => $group, + } + MANIFEST + end + let(:pp_two) do + <<-MANIFEST.unindent + $db = #{db} + $user = #{user} + $group = #{group} + $password = #{password} + $version = '#{version}' + + class { 'postgresql::server': } + + # Since we are not testing pg_hba or any of that, make a local user for ident auth + user { $user: + ensure => present, + } + + postgresql::server::role { $user: + password_hash => postgresql_password($user, $password), + } + + postgresql::server::database { $db: + owner => $user, + require => Postgresql::Server::Role[$user], + } + + # Lets setup the base rules + $local_auth_option = $version ? { + '8.1' => 'sameuser', + default => undef, + } + + # Create a rule for the user + postgresql::server::pg_hba_rule { "allow ${user}": + type => 'local', + database => $db, + user => $user, + auth_method => 'ident', + auth_option => $local_auth_option, + order => 1, + } + + # Create a role to grant to the user + postgresql::server::role { $group: + db => $db, + login => false, + require => Postgresql::Server::Database[$db], + } + + # Grant the role to the user + postgresql::server::grant_role { "grant_role ${group} to ${user}": + role => $user, + group => $group, + } + MANIFEST + end + let(:pp_three) do + <<-MANIFEST + $db = "#{db}" + $user = "#{user}" + $group = "#{group}" + $password = #{password} + $version = '#{version}' + + class { 'postgresql::server': } + + # Since we are not testing pg_hba or any of that, make a local user for ident auth + user { $user: + ensure => present, + } + + postgresql::server::role { $user: + password_hash => postgresql_password($user, $password), + } + + postgresql::server::database { $db: + owner => $user, + require => Postgresql::Server::Role[$user], + } + + # Lets setup the base rules + $local_auth_option = $version ? { + '8.1' => 'sameuser', + default => undef, + } + + # Create a rule for the user + postgresql::server::pg_hba_rule { "allow ${user}": + type => 'local', + database => $db, + user => $user, + auth_method => 'ident', + auth_option => $local_auth_option, + order => 1, + } + + # Create a role to grant to the user + postgresql::server::role { $group: + db => $db, + login => false, + require => Postgresql::Server::Database[$db], + } + + # Grant the role to the user + postgresql::server::grant_role { "grant_role ${group} to ${user}": + role => $user, + group => $group, + } + + postgresql::server::grant_role {"revoke ${group} from ${user}": + ensure => absent, + role => $user, + group => $group, + } + MANIFEST + end + let(:pp_four) do + <<-MANIFEST + $db = "#{db}" + $user = "#{user}" + $group = "#{group}" + $password = #{password} + + class { 'postgresql::server': } + + # Since we are not testing pg_hba or any of that, make a local user for ident auth + user { $user: + ensure => absent, + } + + postgresql::server::database { $db: + } + + # Create a role to grant to the nonexistent user + postgresql::server::role { $group: + db => $db, + login => false, + require => Postgresql::Server::Database[$db], + } + + # Grant the role to the nonexistent user + postgresql::server::grant_role { "grant_role ${group} to ${user}": + role => $user + group => $group, + } + MANIFEST + end - it 'should grant a role to a user' do + # rubocop:disable RSpec/ExampleLength + # rubocop:disable RSpec/MultipleExpectations + it 'grants a role to a user' do begin - pp = <<-EOS.unindent - $db = #{db} - $user = #{user} - $group = #{group} - $password = #{password} - $version = '#{version}' - - class { 'postgresql::server': } - - # Since we are not testing pg_hba or any of that, make a local user for ident auth - user { $user: - ensure => present, - } - - postgresql::server::role { $user: - password_hash => postgresql_password($user, $password), - } - - postgresql::server::database { $db: - owner => $user, - require => Postgresql::Server::Role[$user], - } - - # Lets setup the base rules - $local_auth_option = $version ? { - '8.1' => 'sameuser', - default => undef, - } - - # Create a rule for the user - postgresql::server::pg_hba_rule { "allow ${user}": - type => 'local', - database => $db, - user => $user, - auth_method => 'ident', - auth_option => $local_auth_option, - order => 1, - } - - # Create a role to grant to the user - postgresql::server::role { $group: - db => $db, - login => false, - require => Postgresql::Server::Database[$db], - } - - # Grant the role to the user - postgresql::server::grant_role { "grant_role ${group} to ${user}": - role => $user, - group => $group, - } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => true) + apply_manifest(pp_one, catch_failures: true) + apply_manifest(pp_one, catch_changes: true) ## Check that the role was granted to the user psql('--command="SELECT 1 WHERE pg_has_role(\'psql_grant_role_tester\', \'test_group\', \'MEMBER\') = true" grant_role_test', 'psql_grant_role_tester') do |r| - expect(r.stdout).to match(/\(1 row\)/) + expect(r.stdout).to match(%r{\(1 row\)}) expect(r.stderr).to eq('') end end end - it 'should grant a role to a superuser' do + it 'grants a role to a superuser' do begin - pp = <<-EOS.unindent - $db = "#{db}" - $user = "#{user}" - $group = "#{group}" - $password = #{password} - $version = '#{version}' - - class { 'postgresql::server': } - - # Since we are not testing pg_hba or any of that, make a local user for ident auth - user { $user: - ensure => present, - } - - postgresql::server::role { $user: - password_hash => postgresql_password($user, $password), - superuser => true, - } - - postgresql::server::database { $db: - owner => $user, - require => Postgresql::Server::Role[$user], - } - - # Lets setup the base rules - $local_auth_option = $version ? { - '8.1' => 'sameuser', - default => undef, - } - - # Create a rule for the user - postgresql::server::pg_hba_rule { "allow ${user}": - type => 'local', - database => $db, - user => $user, - auth_method => 'ident', - auth_option => $local_auth_option, - order => 1, - } - - # Create a role to grant to the user - postgresql::server::role { $group: - db => $db, - login => false, - require => Postgresql::Server::Database[$db], - } - - # Grant the role to the user - postgresql::server::grant_role { "grant_role ${group} to ${user}": - role => $user, - group => $group, - } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => true) + apply_manifest(pp_two, catch_failures: true) + apply_manifest(pp_two, catch_changes: true) ## Check that the role was granted to the user - psql('--command="SELECT 1 FROM pg_roles AS r_role JOIN pg_auth_members AS am ON r_role.oid = am.member JOIN pg_roles AS r_group ON r_group.oid = am.roleid WHERE r_group.rolname = \'test_group\' AND r_role.rolname = \'psql_grant_role_tester\'" grant_role_test', 'psql_grant_role_tester') do |r| - expect(r.stdout).to match(/\(1 row\)/) + psql('--command="SELECT 1 FROM pg_roles AS r_role JOIN pg_auth_members AS am ON r_role.oid = am.member JOIN pg_roles AS r_group ON r_group.oid = am.roleid WHERE r_group.rolname = \'test_group\' AND r_role.rolname = \'psql_grant_role_tester\'" grant_role_test', 'psql_grant_role_tester') do |r| # rubocop:disable Metrics/LineLength + expect(r.stdout).to match(%r{\(1 row\)}) expect(r.stderr).to eq('') end end end - it 'should revoke a role from a user' do + it 'revokes a role from a user' do begin - pp = <<-EOS - - $db = "#{db}" - $user = "#{user}" - $group = "#{group}" - $password = #{password} - $version = '#{version}' - - class { 'postgresql::server': } - - # Since we are not testing pg_hba or any of that, make a local user for ident auth - user { $user: - ensure => present, - } - - postgresql::server::role { $user: - password_hash => postgresql_password($user, $password), - } - - postgresql::server::database { $db: - owner => $user, - require => Postgresql::Server::Role[$user], - } - - # Lets setup the base rules - $local_auth_option = $version ? { - '8.1' => 'sameuser', - default => undef, - } - - # Create a rule for the user - postgresql::server::pg_hba_rule { "allow ${user}": - type => 'local', - database => $db, - user => $user, - auth_method => 'ident', - auth_option => $local_auth_option, - order => 1, - } - - # Create a role to grant to the user - postgresql::server::role { $group: - db => $db, - login => false, - require => Postgresql::Server::Database[$db], - } - - # Grant the role to the user - postgresql::server::grant_role { "grant_role ${group} to ${user}": - role => $user, - group => $group, - } - - postgresql::server::grant_role {"revoke ${group} from ${user}": - ensure => absent, - role => $user, - group => $group, - } - EOS - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :expect_changes => true) + apply_manifest(pp_three, catch_failures: true) + apply_manifest(pp_three, expect_changes: true) psql('--command="SELECT 1 WHERE pg_has_role(\'psql_grant_role_tester\', \'test_group\', \'MEMBER\') = true" grant_role_test', 'psql_grant_role_tester') do |r| - expect(r.stdout).to match(/\(0 rows\)/) + expect(r.stdout).to match(%r{\(0 rows\)}) expect(r.stderr).to eq('') end end end - it 'should not grant permission to a nonexistent user' do - begin - pp = <<-EOS - - $db = "#{db}" - $user = "#{user}" - $group = "#{group}" - $password = #{password} - - class { 'postgresql::server': } - - # Since we are not testing pg_hba or any of that, make a local user for ident auth - user { $user: - ensure => absent, - } - - postgresql::server::database { $db: - } - - # Create a role to grant to the nonexistent user - postgresql::server::role { $group: - db => $db, - login => false, - require => Postgresql::Server::Database[$db], - } - - # Grant the role to the nonexistent user - postgresql::server::grant_role { "grant_role ${group} to ${user}": - role => $user - group => $group, - } - EOS - apply_manifest(pp, :expect_failures => true) - - psql('--command="SELECT 1 WHERE pg_has_role(\'psql_grant_role_tester\', \'test_group\', \'MEMBER\') = true" grant_role_test', 'psql_grant_role_tester') do |r| - expect(r.stdout).to match(/\(0 rows\)/) - expect(r.stderr).to eq('') - end - end - end + it 'does not grant permission to a nonexistent user' do + begin + apply_manifest(pp_four, expect_failures: true) + + psql('--command="SELECT 1 WHERE pg_has_role(\'psql_grant_role_tester\', \'test_group\', \'MEMBER\') = true" grant_role_test', 'psql_grant_role_tester') do |r| + expect(r.stdout).to match(%r{\(0 rows\)}) + expect(r.stderr).to eq('') + end + end + end end diff --git a/spec/acceptance/server/grant_spec.rb b/spec/acceptance/server/grant_spec.rb index 5266a11..68a6252 100644 --- a/spec/acceptance/server/grant_spec.rb +++ b/spec/acceptance/server/grant_spec.rb @@ -1,521 +1,522 @@ require 'spec_helper_acceptance' -describe 'postgresql::server::grant:', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do - +describe 'postgresql::server::grant:', unless: UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + # rubocop:disable RSpec/ExampleLength + # rubocop:disable RSpec/MultipleExpectations let(:db) { 'grant_priv_test' } let(:owner) { 'psql_grant_priv_owner' } let(:user) { 'psql_grant_priv_tester' } let(:password) { 'psql_grant_role_pw' } - let(:pp_install) { "class {'postgresql::server': }"} - - let(:pp_setup) { pp_setup = <<-EOS.unindent - $db = #{db} - $owner = #{owner} - $user = #{user} - $password = #{password} - - class { 'postgresql::server': } - - postgresql::server::role { $owner: - password_hash => postgresql_password($owner, $password), - } - - # Since we are not testing pg_hba or any of that, make a local user for ident auth - user { $owner: - ensure => present, - } - - postgresql::server::database { $db: - owner => $owner, - require => Postgresql::Server::Role[$owner], - } - - # Create a user to grant privileges to - postgresql::server::role { $user: - db => $db, - require => Postgresql::Server::Database[$db], - } - - # Make a local user for ident auth - user { $user: - ensure => present, - } - - # Grant them connect to the database - postgresql::server::database_grant { "allow connect for ${user}": - privilege => 'CONNECT', - db => $db, - role => $user, - } - EOS - } + let(:pp_install) { "class {'postgresql::server': }" } + let(:pp_setup) do + <<-MANIFEST.unindent + $db = #{db} + $owner = #{owner} + $user = #{user} + $password = #{password} + + class { 'postgresql::server': } + + postgresql::server::role { $owner: + password_hash => postgresql_password($owner, $password), + } + + # Since we are not testing pg_hba or any of that, make a local user for ident auth + user { $owner: + ensure => present, + } + + postgresql::server::database { $db: + owner => $owner, + require => Postgresql::Server::Role[$owner], + } + + # Create a user to grant privileges to + postgresql::server::role { $user: + db => $db, + require => Postgresql::Server::Database[$db], + } + + # Make a local user for ident auth + user { $user: + ensure => present, + } + + # Grant them connect to the database + postgresql::server::database_grant { "allow connect for ${user}": + privilege => 'CONNECT', + db => $db, + role => $user, + } + MANIFEST + end context 'LANGUAGE' do describe 'GRANT * ON LANGUAGE' do - #testing grants on language requires a superuser + # testing grants on language requires a superuser let(:superuser) { 'postgres' } - let(:pp_lang) { pp_setup + <<-EOS.unindent - + let(:pp_lang) do + pp_setup + <<-MANIFEST.unindent postgresql_psql { 'make sure plpgsql exists': command => 'CREATE LANGUAGE plpgsql', db => $db, psql_user => '#{superuser}', unless => "SELECT 1 from pg_language where lanname = 'plpgsql'", require => Postgresql::Server::Database[$db], } postgresql::server::grant { 'grant usage on plpgsql': psql_user => '#{superuser}', privilege => 'USAGE', object_type => 'LANGUAGE', object_name => 'plpgsql', role => $user, db => $db, require => [ Postgresql_psql['make sure plpgsql exists'], Postgresql::Server::Role[$user], ] } - EOS - } - - it 'is expected to run idempotently' do - apply_manifest(pp_install) - - #postgres version - result = shell('psql --version') - version = result.stdout.match(%r{\s(\d\.\d)})[1] - - if version >= '8.4.0' - apply_manifest(pp_lang, :catch_failures => true) - apply_manifest(pp_lang, :catch_changes => true) - end - end - - it 'is expected to GRANT USAGE ON LANGUAGE plpgsql to ROLE' do - result = shell('psql --version') - version = result.stdout.match(%r{\s(\d\.\d)})[1] - - if version >= '8.4.0' - ## Check that the privilege was granted to the user - psql("-d #{db} --command=\"SELECT 1 WHERE has_language_privilege('#{user}', 'plpgsql', 'USAGE')\"", superuser) do |r| - expect(r.stdout).to match(/\(1 row\)/) - expect(r.stderr).to eq('') - end - end - end - - let(:pp_onlyif) { pp_setup + <<-EOS.unindent + MANIFEST + end + let(:pp_onlyif) do + pp_setup + <<-MANIFEST.unindent postgresql::server::grant { 'grant usage on BSql': psql_user => '#{superuser}', privilege => 'USAGE', object_type => 'LANGUAGE', object_name => 'bsql', role => $user, db => $db, onlyif_exists => true, } - EOS - } + MANIFEST + end + + it 'is expected to run idempotently' do + apply_manifest(pp_install) + + # postgres version + result = shell('psql --version') + version = result.stdout.match(%r{\s(\d\.\d)})[1] + + if version >= '8.4.0' + apply_manifest(pp_lang, catch_failures: true) + apply_manifest(pp_lang, catch_changes: true) + end + end + + it 'is expected to GRANT USAGE ON LANGUAGE plpgsql to ROLE' do + result = shell('psql --version') + version = result.stdout.match(%r{\s(\d\.\d)})[1] + + if version >= '8.4.0' + ## Check that the privilege was granted to the user + psql("-d #{db} --command=\"SELECT 1 WHERE has_language_privilege('#{user}', 'plpgsql', 'USAGE')\"", superuser) do |r| + expect(r.stdout).to match(%r{\(1 row\)}) + expect(r.stderr).to eq('') + end + end + end - #test onlyif_exists function + # test onlyif_exists function it 'is expected to not GRANT USAGE ON (dummy)LANGUAGE BSql to ROLE' do apply_manifest(pp_install) - #postgres version + # postgres version result = shell('psql --version') version = result.stdout.match(%r{\s(\d\.\d)})[1] if version >= '8.4.0' - apply_manifest(pp_onlyif, :catch_failures => true) - apply_manifest(pp_onlyif, :catch_changes => true) + apply_manifest(pp_onlyif, catch_failures: true) + apply_manifest(pp_onlyif, catch_changes: true) end end end end ### SEQUENCE grants context 'sequence' do - it 'should grant usage on a sequence to a user' do - begin - pp = pp_setup + <<-EOS.unindent - + let(:pp_one) do + pp_setup + <<-MANIFEST.unindent postgresql_psql { 'create test sequence': command => 'CREATE SEQUENCE test_seq', db => $db, psql_user => $owner, unless => "SELECT 1 FROM information_schema.sequences WHERE sequence_name = 'test_seq'", require => Postgresql::Server::Database[$db], } postgresql::server::grant { 'grant usage on test_seq': privilege => 'USAGE', object_type => 'SEQUENCE', object_name => 'test_seq', db => $db, role => $user, require => [ Postgresql_psql['create test sequence'], Postgresql::Server::Role[$user], ] } - EOS - - apply_manifest(pp_install, :catch_failures => true) - - #postgres version - result = shell('psql --version') - version = result.stdout.match(%r{\s(\d\.\d)})[1] - - if version >= '9.0' - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => true) - - ## Check that the privilege was granted to the user - psql("-d #{db} --tuples-only --command=\"SELECT * FROM has_sequence_privilege('#{user}', 'test_seq', 'USAGE')\"", user) do |r| - expect(r.stdout).to match(/t/) - expect(r.stderr).to eq('') - end - end - end + MANIFEST end - - it 'should grant update on a sequence to a user' do - begin - pp = pp_setup + <<-EOS.unindent - + let(:pp_two) do + pp_setup + <<-MANIFEST.unindent postgresql_psql { 'create test sequence': command => 'CREATE SEQUENCE test_seq', db => $db, psql_user => $owner, unless => "SELECT 1 FROM information_schema.sequences WHERE sequence_name = 'test_seq'", require => Postgresql::Server::Database[$db], } postgresql::server::grant { 'grant update on test_seq': privilege => 'UPDATE', object_type => 'SEQUENCE', object_name => 'test_seq', db => $db, role => $user, require => [ Postgresql_psql['create test sequence'], Postgresql::Server::Role[$user], ] } - EOS + MANIFEST + end + let(:result) do + shell('psql --version') + end + let(:version) do + result.stdout.match(%r{\s(\d\.\d)})[1] + end - apply_manifest(pp_install, :catch_failures => true) + before(:each) do + apply_manifest(pp_install, catch_failures: true) + end - #postgres version - result = shell('psql --version') - version = result.stdout.match(%r{\s(\d\.\d)})[1] + it 'grants usage on a sequence to a user' do + begin + if version >= '9.0' + apply_manifest(pp_one, catch_failures: true) + apply_manifest(pp_one, catch_changes: true) + + ## Check that the privilege was granted to the user + psql("-d #{db} --command=\"SELECT 1 WHERE has_sequence_privilege('#{user}', 'test_seq', 'USAGE')\"", user) do |r| + expect(r.stdout).to match(%r{\(1 row\)}) + expect(r.stderr).to eq('') + end + end + end + end + it 'grants update on a sequence to a user' do + begin if version >= '9.0' - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => true) + apply_manifest(pp_two, catch_failures: true) + apply_manifest(pp_two, catch_changes: true) ## Check that the privilege was granted to the user - psql("-d #{db} --tuples-only --command=\"SELECT * FROM has_sequence_privilege('#{user}', 'test_seq', 'UPDATE')\"", user) do |r| - expect(r.stdout).to match(/t/) + psql("-d #{db} --command=\"SELECT 1 WHERE has_sequence_privilege('#{user}', 'test_seq', 'UPDATE')\"", user) do |r| + expect(r.stdout).to match(%r{\(1 row\)}) expect(r.stderr).to eq('') end end end end end context 'all sequences' do - it 'should grant usage on all sequences to a user' do - begin - pp = pp_setup + <<-EOS.unindent + let(:pp_one) do + pp_setup + <<-MANIFEST.unindent postgresql_psql { 'create test sequences': command => 'CREATE SEQUENCE test_seq2; CREATE SEQUENCE test_seq3;', db => $db, psql_user => $owner, unless => "SELECT 1 FROM information_schema.sequences WHERE sequence_name = 'test_seq2'", require => Postgresql::Server::Database[$db], } postgresql::server::grant { 'grant usage on all sequences': privilege => 'USAGE', object_type => 'ALL SEQUENCES IN SCHEMA', object_name => 'public', db => $db, role => $user, require => [ Postgresql_psql['create test sequences'], Postgresql::Server::Role[$user], ] } - EOS - - apply_manifest(pp_install, :catch_failures => true) - - #postgres version - result = shell('psql --version') - version = result.stdout.match(%r{\s(\d\.\d)})[1] - - if version >= '9.0' - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => true) - - ## Check that the privileges were granted to the user, this check is not available on version < 9.0 - psql("-d #{db} --tuples-only --command=\"SELECT has_sequence_privilege('#{user}', 'test_seq2', 'USAGE') AND has_sequence_privilege('#{user}', 'test_seq3', 'USAGE')\"", user) do |r| - expect(r.stdout).to match(/t/) - expect(r.stderr).to eq('') - end - end - end + MANIFEST end - - it 'should grant update on all sequences to a user' do - begin - pp = pp_setup + <<-EOS.unindent + let(:pp_two) do + pp_setup + <<-MANIFEST.unindent postgresql_psql { 'create test sequences': command => 'CREATE SEQUENCE test_seq2; CREATE SEQUENCE test_seq3;', db => $db, psql_user => $owner, unless => "SELECT 1 FROM information_schema.sequences WHERE sequence_name = 'test_seq2'", require => Postgresql::Server::Database[$db], } postgresql::server::grant { 'grant usage on all sequences': privilege => 'UPDATE', object_type => 'ALL SEQUENCES IN SCHEMA', object_name => 'public', db => $db, role => $user, require => [ Postgresql_psql['create test sequences'], Postgresql::Server::Role[$user], ] } - EOS + MANIFEST + end + let(:result) do + shell('psql --version') + end + let(:version) do + result.stdout.match(%r{\s(\d\.\d)})[1] + end - apply_manifest(pp_install, :catch_failures => true) + before(:each) do + apply_manifest(pp_install, catch_failures: true) + end - #postgres version - result = shell('psql --version') - version = result.stdout.match(%r{\s(\d\.\d)})[1] + it 'grants usage on all sequences to a user' do + begin + if version >= '9.0' + apply_manifest(pp_one, catch_failures: true) + apply_manifest(pp_one, catch_changes: true) + ## Check that the privileges were granted to the user, this check is not available on version < 9.0 + psql("-d #{db} --command=\"SELECT 1 WHERE has_sequence_privilege('#{user}', 'test_seq2', 'USAGE') AND has_sequence_privilege('#{user}', 'test_seq3', 'USAGE')\"", user) do |r| + expect(r.stdout).to match(%r{\(1 row\)}) + expect(r.stderr).to eq('') + end + end + end + end + + it 'grants update on all sequences to a user' do + begin if version >= '9.0' - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => true) + apply_manifest(pp_two, catch_failures: true) + apply_manifest(pp_two, catch_changes: true) ## Check that the privileges were granted to the user - psql("-d #{db} --tuples-only --command=\"SELECT has_sequence_privilege('#{user}', 'test_seq2', 'UPDATE') AND has_sequence_privilege('#{user}', 'test_seq3', 'UPDATE')\"", user) do |r| - expect(r.stdout).to match(/t/) + psql("-d #{db} --command=\"SELECT 1 WHERE has_sequence_privilege('#{user}', 'test_seq2', 'UPDATE') AND has_sequence_privilege('#{user}', 'test_seq3', 'UPDATE')\"", user) do |r| + expect(r.stdout).to match(%r{\(1 row\)}) expect(r.stderr).to eq('') end end end end end ### TABLE grants context 'table' do describe 'GRANT ... ON TABLE' do - let(:pp_create_table) { pp_setup + <<-EOS.unindent + let(:pp_create_table) do + pp_setup + <<-EOS.unindent postgresql_psql { 'create test table': command => 'CREATE TABLE test_tbl (col1 integer)', db => $db, psql_user => $owner, unless => "SELECT table_name FROM information_schema.tables WHERE table_name = 'test_tbl'", require => Postgresql::Server::Database[$db], } EOS - } + end - it 'should grant select on a table to a user' do + it 'grant select on a table to a user' do begin pp = pp_create_table + <<-EOS.unindent postgresql::server::grant { 'grant select on test_tbl': privilege => 'SELECT', object_type => 'TABLE', object_name => 'test_tbl', db => $db, role => $user, require => [ Postgresql_psql['create test table'], Postgresql::Server::Role[$user], ] } EOS pp_revoke = pp_create_table + <<-EOS.unindent postgresql::server::grant { 'revoke select on test_tbl': ensure => absent, privilege => 'SELECT', object_type => 'TABLE', object_name => 'test_tbl', db => $db, role => $user, require => [ Postgresql_psql['create test table'], Postgresql::Server::Role[$user], ] } EOS - apply_manifest(pp_install, :catch_failures => true) + apply_manifest(pp_install, catch_failures: true) - #postgres version + # postgres version result = shell('psql --version') version = result.stdout.match(%r{\s(\d\.\d)})[1] if version >= '9.0' - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => true) + apply_manifest(pp, catch_failures: true) + apply_manifest(pp, catch_changes: true) ## Check that the privilege was granted to the user psql("-d #{db} --tuples-only --command=\"SELECT * FROM has_table_privilege('#{user}', 'test_tbl', 'SELECT')\"", user) do |r| - expect(r.stdout).to match(/t/) + expect(r.stdout).to match(%r{t}) expect(r.stderr).to eq('') end - apply_manifest(pp_revoke, :catch_failures => true) - apply_manifest(pp_revoke, :catch_changes => true) + apply_manifest(pp_revoke, catch_failures: true) + apply_manifest(pp_revoke, catch_changes: true) ## Check that the privilege was revoked from the user psql("-d #{db} --tuples-only --command=\"SELECT * FROM has_table_privilege('#{user}', 'test_tbl', 'SELECT')\"", user) do |r| - expect(r.stdout).to match(/f/) + expect(r.stdout).to match(%r{f}) expect(r.stderr).to eq('') end end end end - it 'should grant update on all tables to a user' do + it 'grant update on all tables to a user' do begin pp = pp_create_table + <<-EOS.unindent postgresql::server::grant { 'grant update on all tables': privilege => 'UPDATE', object_type => 'ALL TABLES IN SCHEMA', object_name => 'public', db => $db, role => $user, require => [ Postgresql_psql['create test table'], Postgresql::Server::Role[$user], ] } EOS pp_revoke = pp_create_table + <<-EOS.unindent postgresql::server::grant { 'revoke update on all tables': ensure => absent, privilege => 'UPDATE', object_type => 'ALL TABLES IN SCHEMA', object_name => 'public', db => $db, role => $user, require => [ Postgresql_psql['create test table'], Postgresql::Server::Role[$user], ] } EOS - apply_manifest(pp_install, :catch_failures => true) + apply_manifest(pp_install, catch_failures: true) - #postgres version + # postgres version result = shell('psql --version') version = result.stdout.match(%r{\s(\d\.\d)})[1] if version >= '9.0' - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => true) + apply_manifest(pp, catch_failures: true) + apply_manifest(pp, catch_changes: true) ## Check that all privileges were granted to the user psql("-d #{db} --command=\"SELECT table_name,privilege_type FROM information_schema.role_table_grants WHERE grantee = '#{user}' AND table_schema = 'public'\"", user) do |r| - expect(r.stdout).to match(/test_tbl[ |]*UPDATE\s*\(1 row\)/) + expect(r.stdout).to match(%r{test_tbl[ |]*UPDATE\s*\(1 row\)}) expect(r.stderr).to eq('') end - apply_manifest(pp_revoke, :catch_failures => true) - apply_manifest(pp_revoke, :catch_changes => true) + apply_manifest(pp_revoke, catch_failures: true) + apply_manifest(pp_revoke, catch_changes: true) ## Check that all privileges were revoked from the user psql("-d #{db} --command=\"SELECT table_name,privilege_type FROM information_schema.role_table_grants WHERE grantee = '#{user}' AND table_schema = 'public'\"", user) do |r| - expect(r.stdout).to match(/\(0 rows\)/) + expect(r.stdout).to match(%r{\(0 rows\)}) expect(r.stderr).to eq('') end end end end - it 'should grant all on all tables to a user' do + it 'grant all on all tables to a user' do begin pp = pp_create_table + <<-EOS.unindent postgresql::server::grant { 'grant all on all tables': privilege => 'ALL', object_type => 'ALL TABLES IN SCHEMA', object_name => 'public', db => $db, role => $user, require => [ Postgresql_psql['create test table'], Postgresql::Server::Role[$user], ] } EOS pp_revoke = pp_create_table + <<-EOS.unindent postgresql::server::grant { 'revoke all on all tables': ensure => absent, privilege => 'ALL', object_type => 'ALL TABLES IN SCHEMA', object_name => 'public', db => $db, role => $user, require => [ Postgresql_psql['create test table'], Postgresql::Server::Role[$user], ] } EOS - apply_manifest(pp_install, :catch_failures => true) + apply_manifest(pp_install, catch_failures: true) - #postgres version + # postgres version result = shell('psql --version') version = result.stdout.match(%r{\s(\d\.\d)})[1] if version >= '9.0' - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => true) + apply_manifest(pp, catch_failures: true) + apply_manifest(pp, catch_changes: true) ## Check that all privileges were granted to the user psql("-d #{db} --tuples-only --command=\"SELECT table_name,count(privilege_type) FROM information_schema.role_table_grants WHERE grantee = '#{user}' AND table_schema = 'public' AND privilege_type IN ('SELECT','UPDATE','INSERT','DELETE','TRIGGER','REFERENCES','TRUNCATE') GROUP BY table_name\"", user) do |r| - expect(r.stdout).to match(/test_tbl[ |]*7$/) + expect(r.stdout).to match(%r{test_tbl[ |]*7$}) expect(r.stderr).to eq('') end - apply_manifest(pp_revoke, :catch_failures => true) - apply_manifest(pp_revoke, :catch_changes => true) + apply_manifest(pp_revoke, catch_failures: true) + apply_manifest(pp_revoke, catch_changes: true) ## Check that all privileges were revoked from the user psql("-d #{db} --command=\"SELECT table_name FROM information_schema.role_table_grants WHERE grantee = '#{user}' AND table_schema = 'public'\"", user) do |r| - expect(r.stdout).to match(/\(0 rows\)/) + expect(r.stdout).to match(%r{\(0 rows\)}) expect(r.stderr).to eq('') end end end end end end context 'database' do describe 'REVOKE ... ON DATABASE...' do - it 'should not fail on revoke connect from non-existant user' do + it 'do not fail on revoke connect from non-existant user' do begin - apply_manifest(pp_setup, :catch_failures => true) + apply_manifest(pp_setup, catch_failures: true) pp = pp_setup + <<-EOS.unindent postgresql::server::grant { 'revoke connect on db from norole': ensure => absent, privilege => 'CONNECT', object_type => 'DATABASE', db => '#{db}', role => '#{user}_does_not_exist', } EOS - apply_manifest(pp, :catch_changes => true) - apply_manifest(pp, :catch_failures => true) - + apply_manifest(pp, catch_changes: true) + apply_manifest(pp, catch_failures: true) end end end end ##################### end diff --git a/spec/acceptance/server/reassign_owned_by_spec.rb b/spec/acceptance/server/reassign_owned_by_spec.rb index fc6c9cd..86db4c1 100644 --- a/spec/acceptance/server/reassign_owned_by_spec.rb +++ b/spec/acceptance/server/reassign_owned_by_spec.rb @@ -1,134 +1,140 @@ require 'spec_helper_acceptance' -describe 'postgresql::server::reassign_owned_by:', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do - +describe 'postgresql::server::reassign_owned_by:', unless: UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do let(:db) { 'reassign_test' } let(:old_owner) { 'psql_reassign_old_owner' } let(:new_owner) { 'psql_reassign_new_owner' } let(:password) { 'psql_reassign_pw' } let(:superuser) { 'postgres' } - let(:pp_setup) { pp_setup = <<-EOS.unindent - $db = #{db} - $old_owner = #{old_owner} - $new_owner = #{new_owner} - $password = #{password} - - class { 'postgresql::server': } - - postgresql::server::role { $old_owner: - password_hash => postgresql_password($old_owner, $password), - } - - # Since we are not testing pg_hba or any of that, make a local user for ident auth - user { $old_owner: - ensure => present, - } - - # Create a user to reassign ownership to - postgresql::server::role { $new_owner: - db => $db, - require => Postgresql::Server::Database[$db], - } - - # Make a local user for ident auth - user { $new_owner: - ensure => present, - } - - # Grant the new owner membership of the old owner (must have both for REASSIGN OWNED BY to work) - postgresql::server::grant_role { "grant_role to ${new_owner}": - role => $new_owner, - group => $old_owner, - } - - # Grant them connect to the database - postgresql::server::database_grant { "allow connect for ${old_owner}": - privilege => 'CONNECT', - db => $db, - role => $old_owner, - } - EOS - } - - let(:pp_db_old_owner) { <<-EOS.unindent - postgresql::server::database { $db: - owner => $old_owner, - require => Postgresql::Server::Role[$old_owner], - } - EOS - } - - let(:pp_db_no_owner) { <<-EOS.unindent - postgresql::server::database { $db: - } - EOS - } + let(:pp_setup) do + <<-MANIFEST.unindent + $db = #{db} + $old_owner = #{old_owner} + $new_owner = #{new_owner} + $password = #{password} + + class { 'postgresql::server': } + + postgresql::server::role { $old_owner: + password_hash => postgresql_password($old_owner, $password), + } + + # Since we are not testing pg_hba or any of that, make a local user for ident auth + user { $old_owner: + ensure => present, + } + + # Create a user to reassign ownership to + postgresql::server::role { $new_owner: + db => $db, + require => Postgresql::Server::Database[$db], + } + + # Make a local user for ident auth + user { $new_owner: + ensure => present, + } + + # Grant the new owner membership of the old owner (must have both for REASSIGN OWNED BY to work) + postgresql::server::grant_role { "grant_role to ${new_owner}": + role => $new_owner, + group => $old_owner, + } + + # Grant them connect to the database + postgresql::server::database_grant { "allow connect for ${old_owner}": + privilege => 'CONNECT', + db => $db, + role => $old_owner, + } + MANIFEST + end + + let(:pp_db_old_owner) do + <<-MANIFEST.unindent + postgresql::server::database { $db: + owner => $old_owner, + require => Postgresql::Server::Role[$old_owner], + } + MANIFEST + end + + let(:pp_db_no_owner) do + <<-MANIFEST.unindent + postgresql::server::database { $db: + } + MANIFEST + end context 'reassign_owned_by' do describe 'REASSIGN OWNED BY tests' do let(:db) { 'reassign_test' } let(:old_owner) { 'psql_reassign_old_owner' } let(:new_owner) { 'psql_reassign_new_owner' } - let(:pp_setup_objects) { <<-EOS.unindent + let(:pp_setup_objects) do + <<-MANIFEST.unindent postgresql_psql { 'create test table': command => 'CREATE TABLE test_tbl (col1 integer)', db => '#{db}', psql_user => '#{old_owner}', unless => "SELECT tablename FROM pg_catalog.pg_tables WHERE tablename = 'test_tbl'", require => Postgresql::Server::Database['#{db}'], } postgresql_psql { 'create test sequence': command => 'CREATE SEQUENCE test_seq', db => '#{db}', psql_user => '#{old_owner}', unless => "SELECT relname FROM pg_catalog.pg_class WHERE relkind='S' AND relname = 'test_seq'", require => [ Postgresql_psql['create test table'], Postgresql::Server::Database['#{db}'] ], } - EOS - } - let(:pp_reassign_owned_by) { <<-EOS.unindent + MANIFEST + end + let(:pp_reassign_owned_by) do + <<-MANIFEST.unindent postgresql::server::reassign_owned_by { 'test reassign to new_owner': db => '#{db}', old_role => '#{old_owner}', new_role => '#{new_owner}', psql_user => '#{new_owner}', } - EOS - } + MANIFEST + end - it 'should reassign all objects to new_owner' do + # rubocop:disable RSpec/ExampleLength + # rubocop:disable RSpec/MultipleExpectations + it 'reassigns all objects to new_owner' do begin - #postgres version + # postgres version result = shell('psql --version') version = result.stdout.match(%r{\s(\d\.\d)})[1] if version >= '9.0' - apply_manifest(pp_setup + pp_db_old_owner + pp_setup_objects, :catch_failures => true) + apply_manifest(pp_setup + pp_db_old_owner + pp_setup_objects, catch_failures: true) - apply_manifest(pp_setup + pp_db_no_owner + pp_reassign_owned_by, :catch_failures => true) - apply_manifest(pp_setup + pp_db_no_owner + pp_reassign_owned_by, :catch_changes => true) + apply_manifest(pp_setup + pp_db_no_owner + pp_reassign_owned_by, catch_failures: true) + apply_manifest(pp_setup + pp_db_no_owner + pp_reassign_owned_by, catch_changes: true) ## Check that the ownership was transferred psql("-d #{db} --tuples-only --no-align --command=\"SELECT tablename,tableowner FROM pg_catalog.pg_tables WHERE schemaname NOT IN ('pg_catalog', 'information_schema')\"", superuser) do |r| - expect(r.stdout).to match(/test_tbl.#{new_owner}/) + expect(r.stdout).to match(%r{test_tbl.#{new_owner}}) expect(r.stderr).to eq('') end psql("-d #{db} --tuples-only --no-align --command=\"SELECT relname,pg_get_userbyid(relowner) FROM pg_catalog.pg_class c WHERE relkind='S'\"", superuser) do |r| - expect(r.stdout).to match(/test_seq.#{new_owner}/) + expect(r.stdout).to match(%r{test_seq.#{new_owner}}) expect(r.stderr).to eq('') end if version >= '9.3' psql("-d #{db} --tuples-only --no-align --command=\"SELECT pg_get_userbyid(datdba) FROM pg_database WHERE datname = current_database()\"", superuser) do |r| - expect(r.stdout).to match(/#{new_owner}/) + expect(r.stdout).to match(%r{#{new_owner}}) expect(r.stderr).to eq('') end end end end - end # it should reassign all objects + end # it should reassign all objects end end ##################### end diff --git a/spec/acceptance/server/recovery_spec.rb b/spec/acceptance/server/recovery_spec.rb index b27a5c5..1ae5310 100644 --- a/spec/acceptance/server/recovery_spec.rb +++ b/spec/acceptance/server/recovery_spec.rb @@ -1,61 +1,58 @@ require 'spec_helper_acceptance' -describe 'postgresql::server::recovery', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do +describe 'postgresql::server::recovery', unless: UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do describe 'should manage recovery' do after(:all) do - pp = <<-EOS.unindent + pp = <<-MANIFEST.unindent file { '/tmp/recovery.conf': ensure => absent, } - EOS + MANIFEST - apply_manifest(pp, :catch_failures => true) + apply_manifest(pp, catch_failures: true) end - it 'adds conf file' do - pp = <<-EOS.unindent - class { 'postgresql::globals': - recovery_conf_path => '/tmp/recovery.conf', - manage_recovery_conf => true, - } + pp = <<-MANIFEST.unindent + class { 'postgresql::globals': + recovery_conf_path => '/tmp/recovery.conf', + manage_recovery_conf => true, + } - class { 'postgresql::server': } + class { 'postgresql::server': } - # Create a recovery.conf file - postgresql::server::recovery { "recovery.conf": - restore_command => 'restore_command', - recovery_target_timeline => 'recovery_target_timeline', - } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => true) + # Create a recovery.conf file + postgresql::server::recovery { "recovery.conf": + restore_command => 'restore_command', + recovery_target_timeline => 'recovery_target_timeline', + } + MANIFEST + it 'adds conf file' do + apply_manifest(pp, catch_failures: true) + apply_manifest(pp, catch_changes: true) end describe file('/tmp/recovery.conf') do it { is_expected.to be_file } - it { is_expected.to contain /restore_command = 'restore_command'/ } - it { is_expected.to contain /recovery_target_timeline = 'recovery_target_timeline'/ } + it { is_expected.to contain %r{restore_command = 'restore_command'} } + it { is_expected.to contain %r{recovery_target_timeline = 'recovery_target_timeline'} } end end describe 'should not manage recovery' do - it 'does not add conf file' do - pp = <<-EOS.unindent - class { 'postgresql::globals': - manage_recovery_conf => false, - } - - class { 'postgresql::server': } - EOS + pp = <<-MANIFEST.unindent + class { 'postgresql::globals': + manage_recovery_conf => false, + } - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => true) + class { 'postgresql::server': } + MANIFEST + it 'does not add conf file' do + apply_manifest(pp, catch_failures: true) + apply_manifest(pp, catch_changes: true) end describe file('/tmp/recovery.conf') do it { is_expected.not_to be_file } end end end - diff --git a/spec/acceptance/server/schema_spec.rb b/spec/acceptance/server/schema_spec.rb index 43b2c8a..1c10d1a 100644 --- a/spec/acceptance/server/schema_spec.rb +++ b/spec/acceptance/server/schema_spec.rb @@ -1,71 +1,72 @@ require 'spec_helper_acceptance' -describe 'postgresql::server::schema:', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do - +describe 'postgresql::server::schema:', unless: UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do let(:version) do - if fact('osfamily') == 'RedHat' and fact('operatingsystemrelease') =~ /5/ + if fact('osfamily') == 'RedHat' && fact('operatingsystemrelease') =~ %r{5} '8.1' end end + let(:pp) do + <<-MANIFEST.unindent + $db = 'schema_test' + $user = 'psql_schema_tester' + $password = 'psql_schema_pw' + $version = '#{version}' - it 'should create a schema for a user' do - begin - pp = <<-EOS.unindent - $db = 'schema_test' - $user = 'psql_schema_tester' - $password = 'psql_schema_pw' - $version = '#{version}' - - class { 'postgresql::server': } + class { 'postgresql::server': } - # Since we are not testing pg_hba or any of that, make a local user for ident auth - user { $user: - ensure => present, - } + # Since we are not testing pg_hba or any of that, make a local user for ident auth + user { $user: + ensure => present, + } - postgresql::server::role { $user: - password_hash => postgresql_password($user, $password), - } + postgresql::server::role { $user: + password_hash => postgresql_password($user, $password), + } - postgresql::server::database { $db: - owner => $user, - require => Postgresql::Server::Role[$user], - } + postgresql::server::database { $db: + owner => $user, + require => Postgresql::Server::Role[$user], + } - # Lets setup the base rules - $local_auth_option = $version ? { - '8.1' => 'sameuser', - default => undef, - } + # Lets setup the base rules + $local_auth_option = $version ? { + '8.1' => 'sameuser', + default => undef, + } - # Create a rule for the user - postgresql::server::pg_hba_rule { "allow ${user}": - type => 'local', - database => $db, - user => $user, - auth_method => 'ident', - auth_option => $local_auth_option, - order => 1, - } + # Create a rule for the user + postgresql::server::pg_hba_rule { "allow ${user}": + type => 'local', + database => $db, + user => $user, + auth_method => 'ident', + auth_option => $local_auth_option, + order => 1, + } - postgresql::server::schema { $user: - db => $db, - owner => $user, - require => Postgresql::Server::Database[$db], - } - EOS + postgresql::server::schema { $user: + db => $db, + owner => $user, + require => Postgresql::Server::Database[$db], + } + MANIFEST + end - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => true) + # rubocop:disable RSpec/ExampleLength + # rubocop:disable RSpec/MultipleExpectations + it 'creates a schema for a user' do + begin + apply_manifest(pp, catch_failures: true) + apply_manifest(pp, catch_changes: true) ## Check that the user can create a table in the database psql('--command="create table psql_schema_tester.foo (foo int)" schema_test', 'psql_schema_tester') do |r| - expect(r.stdout).to match(/CREATE TABLE/) + expect(r.stdout).to match(%r{CREATE TABLE}) expect(r.stderr).to eq('') end ensure psql('--command="drop table psql_schema_tester.foo" schema_test', 'psql_schema_tester') end end - end diff --git a/spec/acceptance/sql_task_spec.rb b/spec/acceptance/sql_task_spec.rb index 3b323c6..2cc4618 100644 --- a/spec/acceptance/sql_task_spec.rb +++ b/spec/acceptance/sql_task_spec.rb @@ -1,24 +1,24 @@ # run a test task require 'spec_helper_acceptance' describe 'postgresql task', if: puppet_version =~ %r{(5\.\d\.\d)} && !pe_install? do describe 'sql task' do - pp = <<-EOS + pp = <<-MANIFEST class { 'postgresql::server': } -> postgresql::server::db { 'spec1': user => 'root1', password => postgresql_password('root1', 'password'), } - EOS + MANIFEST it 'sets up a postgres db' do - apply_manifest(pp, :catch_failures => true) + apply_manifest(pp, catch_failures: true) end it 'execute some sql' do # equates to 'psql -c "SELECT table_name FROM information_schema.tables WHERE table_schema = 'information_schema';" --password --host localhost --dbname=spec1 --username root1' result = run_task(task_name: 'postgresql::sql', params: 'sql="SELECT count(table_name) FROM information_schema.tables;" host=localhost user=root1 password=password user=root1 database=spec1') expect_multiple_regexes(result: result, regexes: [%r{count}, %r{1 row}, %r{Job completed. 1/1 nodes succeeded|Ran on 1 node}]) end end end diff --git a/spec/acceptance/z_alternative_pgdata_spec.rb b/spec/acceptance/z_alternative_pgdata_spec.rb index 9f80f96..b893630 100644 --- a/spec/acceptance/z_alternative_pgdata_spec.rb +++ b/spec/acceptance/z_alternative_pgdata_spec.rb @@ -1,34 +1,33 @@ require 'spec_helper_acceptance' # These tests ensure that postgres can change itself to an alternative pgdata # location properly. # Allow postgresql to use /tmp/* as a datadir -if fact('osfamily') == 'RedHat' and fact('selinux') == 'true' +if fact('osfamily') == 'RedHat' && fact('selinux') == 'true' shell 'setenforce 0' end -describe 'postgresql::server', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do +describe 'postgresql::server', unless: UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do it 'on an alternative pgdata location' do - pp = <<-EOS + pp = <<-MAIFEST #file { '/var/lib/pgsql': ensure => directory, } -> # needs_initdb will be true by default for all OS's except Debian # in order to change the datadir we need to tell it explicitly to call initdb class { 'postgresql::server': datadir => '/tmp/data', needs_initdb => true } - EOS + MAIFEST - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => true) + apply_manifest(pp, catch_failures: true) + apply_manifest(pp, catch_changes: true) end describe file('/tmp/data') do - it { should be_directory } + it { is_expected.to be_directory } end it 'can connect with psql' do psql('--command="\l" postgres', 'postgres') do |r| - expect(r.stdout).to match(/List of databases/) + expect(r.stdout).to match(%r{List of databases}) end end - end diff --git a/spec/spec_helper_acceptance.rb b/spec/spec_helper_acceptance.rb index 77a3992..4a5d3ed 100644 --- a/spec/spec_helper_acceptance.rb +++ b/spec/spec_helper_acceptance.rb @@ -1,130 +1,129 @@ +require 'puppet' require 'beaker-rspec/spec_helper' require 'beaker-rspec/helpers/serverspec' require 'beaker/puppet_install_helper' require 'beaker/module_install_helper' require 'beaker/task_helper' run_puppet_install_helper install_ca_certs unless pe_install? -UNSUPPORTED_PLATFORMS = ['AIX','windows','Solaris','Suse'] +UNSUPPORTED_PLATFORMS = %w[AIX windows Solaris Suse].freeze # monkey patch to get around apt/forge issue (PUP-8008) module Beaker::ModuleInstallHelper include Beaker::DSL def module_dependencies_from_metadata metadata = module_metadata return [] unless metadata.key?('dependencies') dependencies = [] # get it outta here! - metadata['dependencies'].delete_if {|d| d['name'] == 'puppetlabs/apt' } + metadata['dependencies'].delete_if { |d| d['name'] == 'puppetlabs/apt' } metadata['dependencies'].each do |d| tmp = { module_name: d['name'].sub('/', '-') } if d.key?('version_requirement') tmp[:version] = module_version_from_requirement(tmp[:module_name], d['version_requirement']) end dependencies.push(tmp) end dependencies end end - install_bolt_on(hosts) unless pe_install? install_module_on(hosts) install_module_dependencies_on(hosts) -install_module_from_forge_on(hosts,'puppetlabs/apt','< 4.2.0') +install_module_from_forge_on(hosts, 'puppetlabs/apt', '< 4.2.0') DEFAULT_PASSWORD = if default[:hypervisor] == 'vagrant' 'vagrant' elsif default[:hypervisor] == 'vcloud' 'Qu@lity!' end class String # Provide ability to remove indentation from strings, for the purpose of # left justifying heredoc blocks. def unindent - gsub(/^#{scan(/^\s*/).min_by{|l|l.length}}/, "") + gsub(%r{^#{scan(%r{^\s*}).min_by { |l| l.length }}}, '') end end def shellescape(str) str = str.to_s # An empty argument will be skipped, so return empty quotes. return "''" if str.empty? str = str.dup # Treat multibyte characters as is. It is caller's responsibility # to encode the string in the right encoding for the shell # environment. - str.gsub!(/([^A-Za-z0-9_\-.,:\/@\n])/, "\\\\\\1") + str.gsub!(%r{([^A-Za-z0-9_\-.,:\/@\n])}, '\\\\\\1') # A LF cannot be escaped with a backslash because a backslash + LF # combo is regarded as line continuation and simply ignored. - str.gsub!(/\n/, "'\n'") + str.gsub!(%r{\n}, "'\n'") - return str + str end -def psql(psql_cmd, user = 'postgres', exit_codes = [0,1], &block) +def psql(psql_cmd, user = 'postgres', exit_codes = [0, 1], &block) psql = "psql #{psql_cmd}" - shell("su #{shellescape(user)} -c #{shellescape(psql)}", :acceptable_exit_codes => exit_codes, &block) + shell("su #{shellescape(user)} -c #{shellescape(psql)}", acceptable_exit_codes: exit_codes, &block) end RSpec.configure do |c| # Readable test descriptions c.formatter = :documentation # Configure all nodes in nodeset c.before :suite do run_puppet_access_login(user: 'admin') if pe_install? # Set up selinux if appropriate. if fact('osfamily') == 'RedHat' && fact('selinux') == 'true' pp = <<-EOS if $::osfamily == 'RedHat' and $::selinux == 'true' { $semanage_package = $::operatingsystemmajrelease ? { '5' => 'policycoreutils', default => 'policycoreutils-python', } package { $semanage_package: ensure => installed } exec { 'set_postgres': command => 'semanage port -a -t postgresql_port_t -p tcp 5433', path => '/bin:/usr/bin/:/sbin:/usr/sbin', subscribe => Package[$semanage_package], } } EOS - apply_manifest_on(agents, pp, :catch_failures => false) + apply_manifest_on(agents, pp, catch_failures: false) end # net-tools required for netstat utility being used by be_listening if fact('osfamily') == 'RedHat' && fact('operatingsystemmajrelease') == '7' pp = <<-EOS package { 'net-tools': ensure => installed } EOS - apply_manifest_on(agents, pp, :catch_failures => false) + apply_manifest_on(agents, pp, catch_failures: false) end hosts.each do |host| on host, 'chmod 755 /root' - if fact_on(host, 'osfamily') == 'Debian' - on host, "echo \"en_US ISO-8859-1\nen_NG.UTF-8 UTF-8\nen_US.UTF-8 UTF-8\n\" > /etc/locale.gen" - on host, '/usr/sbin/locale-gen' - on host, '/usr/sbin/update-locale' - end + next unless fact_on(host, 'osfamily') == 'Debian' + on host, "echo \"en_US ISO-8859-1\nen_NG.UTF-8 UTF-8\nen_US.UTF-8 UTF-8\n\" > /etc/locale.gen" + on host, '/usr/sbin/locale-gen' + on host, '/usr/sbin/update-locale' end end end diff --git a/spec/unit/classes/client_spec.rb b/spec/unit/classes/client_spec.rb index 3f2e58f..0ecdef8 100644 --- a/spec/unit/classes/client_spec.rb +++ b/spec/unit/classes/client_spec.rb @@ -1,58 +1,53 @@ require 'spec_helper' -describe 'postgresql::client', :type => :class do +describe 'postgresql::client', type: :class do let :facts do { - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => '6.0', + osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: '6.0', } end describe 'with parameters' do let :params do { - :validcon_script_path => '/opt/bin/my-validate-con.sh', - :package_ensure => 'absent', - :package_name => 'mypackage', - :file_ensure => 'file' + validcon_script_path: '/opt/bin/my-validate-con.sh', + package_ensure: 'absent', + package_name: 'mypackage', + file_ensure: 'file', } end - it 'should modify package' do - is_expected.to contain_package("postgresql-client").with({ - :ensure => 'absent', - :name => 'mypackage', - :tag => 'postgresql', - }) + it 'modifies package' do + is_expected.to contain_package('postgresql-client').with(ensure: 'absent', + name: 'mypackage', + tag: 'postgresql') end - it 'should have specified validate connexion' do - should contain_file('/opt/bin/my-validate-con.sh').with({ - :ensure => 'file', - :owner => 0, - :group => 0, - :mode => '0755' - }) + it 'has specified validate connexion' do + is_expected.to contain_file('/opt/bin/my-validate-con.sh').with(ensure: 'file', + owner: 0, + group: 0, + mode: '0755') end end describe 'with no parameters' do - it 'should create package with postgresql tag' do - is_expected.to contain_package('postgresql-client').with({ - :tag => 'postgresql', - }) + it 'creates package with postgresql tag' do + is_expected.to contain_package('postgresql-client').with(tag: 'postgresql') end end describe 'with client package name explicitly set undef' do let :params do { - :package_name => 'UNSET' + package_name: 'UNSET', } end - it 'should not manage postgresql-client package' do + + it 'does not manage postgresql-client package' do is_expected.not_to contain_package('postgresql-client') end end end diff --git a/spec/unit/classes/globals_spec.rb b/spec/unit/classes/globals_spec.rb index 6789090..e3d87ce 100644 --- a/spec/unit/classes/globals_spec.rb +++ b/spec/unit/classes/globals_spec.rb @@ -1,95 +1,97 @@ require 'spec_helper' describe 'postgresql::globals', type: :class do context 'on a debian 6' do - let (:facts) do + let(:facts) do { - :os => { - :family => 'Debian', - :name => 'Debian', - :release => { - :full => '6.0', - :major => '6' - } + os: { + family: 'Debian', + name: 'Debian', + release: { + full: '6.0', + major: '6', + }, }, - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => '6.0', - :lsbdistid => 'Debian', - :lsbdistcodename => 'squeeze' + osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: '6.0', + lsbdistid: 'Debian', + lsbdistcodename: 'squeeze', } end describe 'with no parameters' do - it 'should work' do + it 'works' do is_expected.to contain_class('postgresql::globals') end end describe 'manage_package_repo => true' do let(:params) do { - manage_package_repo: true + manage_package_repo: true, } end - it 'should pull in class postgresql::repo' do + + it 'pulls in class postgresql::repo' do is_expected.to contain_class('postgresql::repo') end end end context 'on redhat family systems' do - let (:facts) do + let(:facts) do { osfamily: 'RedHat', operatingsystem: 'RedHat', - operatingsystemrelease: '7.1' + operatingsystemrelease: '7.1', } end + describe 'with no parameters' do - it 'should work' do + it 'works' do is_expected.to contain_class('postgresql::globals') end end describe 'manage_package_repo on RHEL => true' do let(:params) do { manage_package_repo: true, - repo_proxy: 'http://proxy-server:8080' + repo_proxy: 'http://proxy-server:8080', } end - it 'should pull in class postgresql::repo' do + it 'pulls in class postgresql::repo' do is_expected.to contain_class('postgresql::repo') end it do - should contain_yumrepo('yum.postgresql.org').with( + is_expected.to contain_yumrepo('yum.postgresql.org').with( 'enabled' => '1', - 'proxy' => 'http://proxy-server:8080' - ) + 'proxy' => 'http://proxy-server:8080', + ) end end describe 'repo_baseurl on RHEL => mirror.localrepo.com' do let(:params) do { manage_package_repo: true, - repo_baseurl: 'http://mirror.localrepo.com' + repo_baseurl: 'http://mirror.localrepo.com', } end - it 'should pull in class postgresql::repo' do + it 'pulls in class postgresql::repo' do is_expected.to contain_class('postgresql::repo') end it do - should contain_yumrepo('yum.postgresql.org').with( + is_expected.to contain_yumrepo('yum.postgresql.org').with( 'enabled' => '1', - 'baseurl' => 'http://mirror.localrepo.com' + 'baseurl' => 'http://mirror.localrepo.com', ) end end end end diff --git a/spec/unit/classes/lib/devel_spec.rb b/spec/unit/classes/lib/devel_spec.rb index ca0ebb3..8317a4d 100644 --- a/spec/unit/classes/lib/devel_spec.rb +++ b/spec/unit/classes/lib/devel_spec.rb @@ -1,73 +1,84 @@ require 'spec_helper' -describe 'postgresql::lib::devel', :type => :class do +describe 'postgresql::lib::devel', type: :class do let :facts do { - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => '6.0', + osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: '6.0', } end - it { is_expected.to contain_class("postgresql::lib::devel") } + + it { is_expected.to contain_class('postgresql::lib::devel') } describe 'link pg_config to /usr/bin' do - it { should_not contain_file('/usr/bin/pg_config') \ - .with_ensure('link') \ - .with_target('/usr/lib/postgresql/8.4/bin/pg_config') + it { + is_expected.not_to contain_file('/usr/bin/pg_config') \ + .with_ensure('link') \ + .with_target('/usr/lib/postgresql/8.4/bin/pg_config') } end describe 'disable link_pg_config' do - let(:params) {{ - :link_pg_config => false, - }} - it { should_not contain_file('/usr/bin/pg_config') } + let(:params) do + { + link_pg_config: false, + } + end + + it { is_expected.not_to contain_file('/usr/bin/pg_config') } end describe 'should not link pg_config on RedHat with default version' do - let(:facts) {{ - :osfamily => 'RedHat', - :operatingsystem => 'CentOS', - :operatingsystemrelease => '6.3', - :operatingsystemmajrelease => '6', - }} - it { should_not contain_file('/usr/bin/pg_config') } + let(:facts) do + { + osfamily: 'RedHat', + operatingsystem: 'CentOS', + operatingsystemrelease: '6.3', + operatingsystemmajrelease: '6', + } + end + + it { is_expected.not_to contain_file('/usr/bin/pg_config') } end describe 'link pg_config on RedHat with non-default version' do - let(:facts) {{ - :osfamily => 'RedHat', - :operatingsystem => 'CentOS', - :operatingsystemrelease => '6.3', - :operatingsystemmajrelease => '6', - }} + let(:facts) do + { + osfamily: 'RedHat', + operatingsystem: 'CentOS', + operatingsystemrelease: '6.3', + operatingsystemmajrelease: '6', + } + end let :pre_condition do - "class { '::postgresql::globals': version => '9.3' }" + "class { '::postgresql::globals': version => '9.3' }" end - it { should contain_file('/usr/bin/pg_config') \ - .with_ensure('link') \ - .with_target('/usr/pgsql-9.3/bin/pg_config') + it { + is_expected.to contain_file('/usr/bin/pg_config') \ + .with_ensure('link') \ + .with_target('/usr/pgsql-9.3/bin/pg_config') } end describe 'on Gentoo' do let :facts do { - :osfamily => 'Gentoo', - :operatingsystem => 'Gentoo', + osfamily: 'Gentoo', + operatingsystem: 'Gentoo', } end let :params do { - :link_pg_config => false, + link_pg_config: false, } end - it 'should fail to compile' do + it 'fails to compile' do # rubocop:disable RSpec/MultipleExpectations expect { is_expected.to compile - }.to raise_error(/is not supported/) + }.to raise_error(%r{is not supported}) end end end diff --git a/spec/unit/classes/lib/java_spec.rb b/spec/unit/classes/lib/java_spec.rb index 76dbbd9..58ec2f8 100644 --- a/spec/unit/classes/lib/java_spec.rb +++ b/spec/unit/classes/lib/java_spec.rb @@ -1,43 +1,52 @@ require 'spec_helper' -describe 'postgresql::lib::java', :type => :class do - +describe 'postgresql::lib::java', type: :class do describe 'on a debian based os' do - let :facts do { - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => '6.0', - } + let :facts do + { + osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: '6.0', + } end - it { is_expected.to contain_package('postgresql-jdbc').with( - :name => 'libpg-java', - :ensure => 'present', - :tag => 'postgresql' - )} + + it { + is_expected.to contain_package('postgresql-jdbc').with( + name: 'libpg-java', + ensure: 'present', + tag: 'postgresql', + ) + } end describe 'on a redhat based os' do - let :facts do { - :osfamily => 'RedHat', - :operatingsystem => 'RedHat', - :operatingsystemrelease => '6.4', - } + let :facts do + { + osfamily: 'RedHat', + operatingsystem: 'RedHat', + operatingsystemrelease: '6.4', + } end - it { is_expected.to contain_package('postgresql-jdbc').with( - :name => 'postgresql-jdbc', - :ensure => 'present', - :tag => 'postgresql' - )} + + it { + is_expected.to contain_package('postgresql-jdbc').with( + name: 'postgresql-jdbc', + ensure: 'present', + tag: 'postgresql', + ) + } describe 'when parameters are supplied' do let :params do - {:package_ensure => 'latest', :package_name => 'somepackage'} + { package_ensure: 'latest', package_name: 'somepackage' } end - it { is_expected.to contain_package('postgresql-jdbc').with( - :name => 'somepackage', - :ensure => 'latest', - :tag => 'postgresql' - )} + + it { + is_expected.to contain_package('postgresql-jdbc').with( + name: 'somepackage', + ensure: 'latest', + tag: 'postgresql', + ) + } end end - end diff --git a/spec/unit/classes/lib/perl_spec.rb b/spec/unit/classes/lib/perl_spec.rb index 922cfa0..d8c8a59 100644 --- a/spec/unit/classes/lib/perl_spec.rb +++ b/spec/unit/classes/lib/perl_spec.rb @@ -1,31 +1,37 @@ require 'spec_helper' -describe 'postgresql::lib::perl', :type => :class do - +describe 'postgresql::lib::perl', type: :class do describe 'on a redhat based os' do - let :facts do { - :osfamily => 'RedHat', - :operatingsystem => 'RedHat', - :operatingsystemrelease => '6.4', - } + let :facts do + { + osfamily: 'RedHat', + operatingsystem: 'RedHat', + operatingsystemrelease: '6.4', + } end - it { is_expected.to contain_package('perl-DBD-Pg').with( - :name => 'perl-DBD-Pg', - :ensure => 'present' - )} + + it { + is_expected.to contain_package('perl-DBD-Pg').with( + name: 'perl-DBD-Pg', + ensure: 'present', + ) + } end describe 'on a debian based os' do - let :facts do { - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => '6.0', - } + let :facts do + { + osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: '6.0', + } end - it { is_expected.to contain_package('perl-DBD-Pg').with( - :name => 'libdbd-pg-perl', - :ensure => 'present' - )} - end + it { + is_expected.to contain_package('perl-DBD-Pg').with( + name: 'libdbd-pg-perl', + ensure: 'present', + ) + } + end end diff --git a/spec/unit/classes/lib/pgdocs_spec.rb b/spec/unit/classes/lib/pgdocs_spec.rb index a751e98..878abac 100644 --- a/spec/unit/classes/lib/pgdocs_spec.rb +++ b/spec/unit/classes/lib/pgdocs_spec.rb @@ -1,29 +1,34 @@ require 'spec_helper' -describe 'postgresql::lib::docs', :type => :class do - +describe 'postgresql::lib::docs', type: :class do describe 'on a redhat based os' do - let :facts do { - :osfamily => 'RedHat', - :operatingsystem => 'RedHat', - :operatingsystemrelease => '6.4', - } + let :facts do + { + osfamily: 'RedHat', + operatingsystem: 'RedHat', + operatingsystemrelease: '6.4', + } end - it { is_expected.to contain_package('postgresql-docs').with( - :name => 'postgresql-docs', - :ensure => 'present', - :tag => 'postgresql' - )} + + it { + is_expected.to contain_package('postgresql-docs').with( + name: 'postgresql-docs', + ensure: 'present', + tag: 'postgresql', + ) + } describe 'when parameters are supplied' do let :params do - {:package_ensure => 'latest', :package_name => 'somepackage'} + { package_ensure: 'latest', package_name: 'somepackage' } end - it { is_expected.to contain_package('postgresql-docs').with( - :name => 'somepackage', - :ensure => 'latest', - :tag => 'postgresql' - )} + + it { + is_expected.to contain_package('postgresql-docs').with( + name: 'somepackage', + ensure: 'latest', + tag: 'postgresql', + ) + } end end - end diff --git a/spec/unit/classes/lib/python_spec.rb b/spec/unit/classes/lib/python_spec.rb index 095c2e1..bbf93b4 100644 --- a/spec/unit/classes/lib/python_spec.rb +++ b/spec/unit/classes/lib/python_spec.rb @@ -1,31 +1,37 @@ require 'spec_helper' -describe 'postgresql::lib::python', :type => :class do - +describe 'postgresql::lib::python', type: :class do describe 'on a redhat based os' do - let :facts do { - :osfamily => 'RedHat', - :operatingsystem => 'RedHat', - :operatingsystemrelease => '6.4', - } + let :facts do + { + osfamily: 'RedHat', + operatingsystem: 'RedHat', + operatingsystemrelease: '6.4', + } end - it { is_expected.to contain_package('python-psycopg2').with( - :name => 'python-psycopg2', - :ensure => 'present' - )} + + it { + is_expected.to contain_package('python-psycopg2').with( + name: 'python-psycopg2', + ensure: 'present', + ) + } end describe 'on a debian based os' do - let :facts do { - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => '6.0', - } + let :facts do + { + osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: '6.0', + } end - it { is_expected.to contain_package('python-psycopg2').with( - :name => 'python-psycopg2', - :ensure => 'present' - )} - end + it { + is_expected.to contain_package('python-psycopg2').with( + name: 'python-psycopg2', + ensure: 'present', + ) + } + end end diff --git a/spec/unit/classes/params_spec.rb b/spec/unit/classes/params_spec.rb index a415966..49dbb19 100644 --- a/spec/unit/classes/params_spec.rb +++ b/spec/unit/classes/params_spec.rb @@ -1,12 +1,13 @@ require 'spec_helper' -describe 'postgresql::params', :type => :class do +describe 'postgresql::params', type: :class do let :facts do { - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => '6.0', + osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: '6.0', } end - it { is_expected.to contain_class("postgresql::params") } + + it { is_expected.to contain_class('postgresql::params') } end diff --git a/spec/unit/classes/repo_spec.rb b/spec/unit/classes/repo_spec.rb index 3942d65..f066093 100644 --- a/spec/unit/classes/repo_spec.rb +++ b/spec/unit/classes/repo_spec.rb @@ -1,27 +1,27 @@ require 'spec_helper' -describe 'postgresql::repo', :type => :class do +describe 'postgresql::repo', type: :class do let :facts do { - :os => { - :name => 'Debian', - :family => 'Debian', - :release => { - :full => '6.0', - :major => '6' - } + os: { + name: 'Debian', + family: 'Debian', + release: { + full: '6.0', + major: '6', + }, }, - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => '6.0', - :lsbdistid => 'Debian', - :lsbdistcodename => 'squeeze', + osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: '6.0', + lsbdistid: 'Debian', + lsbdistcodename: 'squeeze', } end describe 'with no parameters' do - it 'should instantiate apt_postgresql_org class' do + it 'instantiates apt_postgresql_org class' do is_expected.to contain_class('postgresql::repo::apt_postgresql_org') end end end diff --git a/spec/unit/classes/server/config_spec.rb b/spec/unit/classes/server/config_spec.rb index fbf5529..5e22d05 100644 --- a/spec/unit/classes/server/config_spec.rb +++ b/spec/unit/classes/server/config_spec.rb @@ -1,171 +1,175 @@ require 'spec_helper' -describe 'postgresql::server::config', :type => :class do - let (:pre_condition) do - "include postgresql::server" +describe 'postgresql::server::config', type: :class do + let(:pre_condition) do + 'include postgresql::server' end describe 'on RedHat 7' do - let :facts do + let(:facts) do { - :osfamily => 'RedHat', - :operatingsystem => 'CentOS', - :operatingsystemrelease => '7.0', - :concat_basedir => tmpfilename('server'), - :kernel => 'Linux', - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', - :selinux => true, + osfamily: 'RedHat', + operatingsystem: 'CentOS', + operatingsystemrelease: '7.0', + concat_basedir: tmpfilename('server'), + kernel: 'Linux', + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + selinux: true, } end - it 'should have the correct systemd-override file' do - is_expected.to contain_file('systemd-override').with ({ - :ensure => 'present', - :path => '/etc/systemd/system/postgresql.service', - :owner => 'root', - :group => 'root', - }) + + it 'has the correct systemd-override file' do + is_expected.to contain_file('systemd-override').with( + ensure: 'present', path: '/etc/systemd/system/postgresql.service', + owner: 'root', group: 'root' + ) + end + it 'has the correct systemd-override file #content' do is_expected.to contain_file('systemd-override') \ - .with_content(/.include \/usr\/lib\/systemd\/system\/postgresql.service/) + .with_content(%r{.include \/usr\/lib\/systemd\/system\/postgresql.service}) end describe 'with manage_package_repo => true and a version' do - let (:pre_condition) do + let(:pre_condition) do <<-EOS class { 'postgresql::globals': manage_package_repo => true, version => '9.4', }-> class { 'postgresql::server': } EOS end - it 'should have the correct systemd-override file' do - is_expected.to contain_file('systemd-override').with ({ - :ensure => 'present', - :path => '/etc/systemd/system/postgresql-9.4.service', - :owner => 'root', - :group => 'root', - }) + it 'has the correct systemd-override file' do + is_expected.to contain_file('systemd-override').with( + ensure: 'present', path: '/etc/systemd/system/postgresql-9.4.service', + owner: 'root', group: 'root' + ) + end + it 'has the correct systemd-override file #regex' do is_expected.to contain_file('systemd-override') \ - .with_content(/.include \/usr\/lib\/systemd\/system\/postgresql-9.4.service/) + .with_content(%r{.include \/usr\/lib\/systemd\/system\/postgresql-9.4.service}) end end end describe 'on Fedora 21' do - let :facts do + let(:facts) do { - :osfamily => 'RedHat', - :operatingsystem => 'Fedora', - :operatingsystemrelease => '21', - :concat_basedir => tmpfilename('server'), - :kernel => 'Linux', - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', - :selinux => true, + osfamily: 'RedHat', + operatingsystem: 'Fedora', + operatingsystemrelease: '21', + concat_basedir: tmpfilename('server'), + kernel: 'Linux', + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + selinux: true, } end - it 'should have the correct systemd-override file' do - is_expected.to contain_file('systemd-override').with ({ - :ensure => 'present', - :path => '/etc/systemd/system/postgresql.service', - :owner => 'root', - :group => 'root', - }) + + it 'has the correct systemd-override file' do + is_expected.to contain_file('systemd-override').with( + ensure: 'present', path: '/etc/systemd/system/postgresql.service', + owner: 'root', group: 'root' + ) + end + it 'has the correct systemd-override file #regex' do is_expected.to contain_file('systemd-override') \ - .with_content(/.include \/lib\/systemd\/system\/postgresql.service/) + .with_content(%r{.include \/lib\/systemd\/system\/postgresql.service}) end describe 'with manage_package_repo => true and a version' do - let (:pre_condition) do + let(:pre_condition) do <<-EOS class { 'postgresql::globals': manage_package_repo => true, version => '9.4', }-> class { 'postgresql::server': } EOS end - it 'should have the correct systemd-override file' do - is_expected.to contain_file('systemd-override').with ({ - :ensure => 'present', - :path => '/etc/systemd/system/postgresql-9.4.service', - :owner => 'root', - :group => 'root', - }) + it 'has the correct systemd-override file' do + is_expected.to contain_file('systemd-override').with( + ensure: 'present', path: '/etc/systemd/system/postgresql-9.4.service', + owner: 'root', group: 'root' + ) + end + it 'has the correct systemd-override file #regex' do is_expected.to contain_file('systemd-override') \ - .with_content(/.include \/lib\/systemd\/system\/postgresql-9.4.service/) + .with_content(%r{.include \/lib\/systemd\/system\/postgresql-9.4.service}) end end end describe 'on Gentoo' do - let (:pre_condition) do + let(:pre_condition) do <<-EOS class { 'postgresql::globals': version => '9.5', }-> class { 'postgresql::server': } EOS end - let :facts do + let(:facts) do { - :osfamily => 'Gentoo', - :operatingsystem => 'Gentoo', - :operatingsystemrelease => 'unused', - :concat_basedir => tmpfilename('server'), - :kernel => 'Linux', - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', - :selinux => false, + osfamily: 'Gentoo', + operatingsystem: 'Gentoo', + operatingsystemrelease: 'unused', + concat_basedir: tmpfilename('server'), + kernel: 'Linux', + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + selinux: false, } end - it 'should have the correct systemd-override file' do - is_expected.to contain_file('systemd-override').with ({ - :ensure => 'present', - :path => '/etc/systemd/system/postgresql-9.5.service', - :owner => 'root', - :group => 'root', - }) + + it 'has the correct systemd-override file' do + is_expected.to contain_file('systemd-override').with( + ensure: 'present', path: '/etc/systemd/system/postgresql-9.5.service', + owner: 'root', group: 'root' + ) + end + it 'has the correct systemd-override file #regex' do is_expected.to contain_file('systemd-override') \ - .with_content(/.include \/usr\/lib64\/systemd\/system\/postgresql-9.5.service/) + .with_content(%r{.include \/usr\/lib64\/systemd\/system\/postgresql-9.5.service}) end end describe 'with managed pg_hba_conf and ipv4acls' do - let (:pre_condition) do + let(:pre_condition) do <<-EOS class { 'postgresql::globals': version => '9.5', }-> class { 'postgresql::server': manage_pg_hba_conf => true, ipv4acls => [ 'hostnossl all all 0.0.0.0/0 reject', 'hostssl all all 0.0.0.0/0 md5' ] } EOS end - let :facts do + let(:facts) do { - :osfamily => 'RedHat', - :operatingsystem => 'CentOS', - :operatingsystemrelease => '7.0', - :concat_basedir => tmpfilename('server'), - :kernel => 'Linux', - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', - :selinux => true, + osfamily: 'RedHat', + operatingsystem: 'CentOS', + operatingsystemrelease: '7.0', + concat_basedir: tmpfilename('server'), + kernel: 'Linux', + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + selinux: true, } end - it 'should have hba rule default' do + + it 'has hba rule default' do is_expected.to contain_postgresql__server__pg_hba_rule('local access as postgres user') end - it 'should have hba rule ipv4acls' do + it 'has hba rule ipv4acls' do is_expected.to contain_postgresql__server__pg_hba_rule('postgresql class generated rule ipv4acls 0') end end end diff --git a/spec/unit/classes/server/contrib_spec.rb b/spec/unit/classes/server/contrib_spec.rb index e268436..221c857 100644 --- a/spec/unit/classes/server/contrib_spec.rb +++ b/spec/unit/classes/server/contrib_spec.rb @@ -1,59 +1,55 @@ require 'spec_helper' -describe 'postgresql::server::contrib', :type => :class do +describe 'postgresql::server::contrib', type: :class do let :pre_condition do "class { 'postgresql::server': }" end let :facts do { - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => '6.0', - :kernel => 'Linux', - :concat_basedir => tmpfilename('contrib'), - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: '6.0', + kernel: 'Linux', + concat_basedir: tmpfilename('contrib'), + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', } end describe 'with parameters' do let(:params) do { - :package_name => 'mypackage', - :package_ensure => 'absent', + package_name: 'mypackage', + package_ensure: 'absent', } end - it 'should create package with correct params' do - is_expected.to contain_package('postgresql-contrib').with({ - :ensure => 'absent', - :name => 'mypackage', - :tag => 'postgresql', - }) + it 'creates package with correct params' do + is_expected.to contain_package('postgresql-contrib').with(ensure: 'absent', + name: 'mypackage', + tag: 'postgresql') end end describe 'with no parameters' do - it 'should create package with postgresql tag' do - is_expected.to contain_package('postgresql-contrib').with({ - :tag => 'postgresql', - }) + it 'creates package with postgresql tag' do + is_expected.to contain_package('postgresql-contrib').with(tag: 'postgresql') end end describe 'on Gentoo' do let :facts do { - :osfamily => 'Gentoo', - :operatingsystem => 'Gentoo', + osfamily: 'Gentoo', + operatingsystem: 'Gentoo', } end - it 'should fail to compile' do + it 'fails to compile' do # rubocop:disable RSpec/MultipleExpectations expect { is_expected.to compile - }.to raise_error(/is not supported/) + }.to raise_error(%r{is not supported}) end end end diff --git a/spec/unit/classes/server/initdb_spec.rb b/spec/unit/classes/server/initdb_spec.rb index 3482970..3c05d07 100644 --- a/spec/unit/classes/server/initdb_spec.rb +++ b/spec/unit/classes/server/initdb_spec.rb @@ -1,127 +1,127 @@ require 'spec_helper' -describe 'postgresql::server::initdb', :type => :class do - let (:pre_condition) do - "include postgresql::server" +describe 'postgresql::server::initdb', type: :class do + let(:pre_condition) do + 'include postgresql::server' end + describe 'on RedHat' do let :facts do { - :osfamily => 'RedHat', - :operatingsystem => 'CentOS', - :operatingsystemrelease => '6.0', - :concat_basedir => tmpfilename('server'), - :kernel => 'Linux', - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', - :selinux => true, + osfamily: 'RedHat', + operatingsystem: 'CentOS', + operatingsystemrelease: '6.0', + concat_basedir: tmpfilename('server'), + kernel: 'Linux', + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + selinux: true, } end + it { is_expected.to contain_file('/var/lib/pgsql/data').with_ensure('directory') } end describe 'on Amazon' do let :facts do { - :osfamily => 'RedHat', - :operatingsystem => 'Amazon', - :operatingsystemrelease => '1.0', - :concat_basedir => tmpfilename('server'), - :kernel => 'Linux', - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', - :selinux => true, + osfamily: 'RedHat', + operatingsystem: 'Amazon', + operatingsystemrelease: '1.0', + concat_basedir: tmpfilename('server'), + kernel: 'Linux', + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + selinux: true, } end + it { is_expected.to contain_file('/var/lib/pgsql92/data').with_ensure('directory') } end describe 'exec with module_workdir => /var/tmp' do let :facts do { - :osfamily => 'RedHat', - :operatingsystem => 'CentOS', - :operatingsystemrelease => '6.0', - :concat_basedir => tmpfilename('server'), - :kernel => 'Linux', - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', - :selinux => true, + osfamily: 'RedHat', + operatingsystem: 'CentOS', + operatingsystemrelease: '6.0', + concat_basedir: tmpfilename('server'), + kernel: 'Linux', + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + selinux: true, } end - let (:pre_condition) do + let(:pre_condition) do <<-EOS class { 'postgresql::globals': module_workdir => '/var/tmp', }-> class { 'postgresql::server': } EOS end - it 'should contain exec with specified working directory' do - is_expected.to contain_exec('postgresql_initdb').with ({ - :cwd => '/var/tmp', - }) + it 'contains exec with specified working directory' do + is_expected.to contain_exec('postgresql_initdb').with( + cwd: '/var/tmp', + ) end end describe 'exec with module_workdir => undef' do let :facts do { - :osfamily => 'RedHat', - :operatingsystem => 'CentOS', - :operatingsystemrelease => '6.0', - :concat_basedir => tmpfilename('server'), - :kernel => 'Linux', - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', - :selinux => true, + osfamily: 'RedHat', + operatingsystem: 'CentOS', + operatingsystemrelease: '6.0', + concat_basedir: tmpfilename('server'), + kernel: 'Linux', + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + selinux: true, } end - let (:pre_condition) do + let(:pre_condition) do <<-EOS class { 'postgresql::globals': }-> class { 'postgresql::server': } EOS end - it 'should contain exec with default working directory' do - is_expected.to contain_exec('postgresql_initdb').with ({ - :cwd => '/tmp', - }) + it 'contains exec with default working directory' do + is_expected.to contain_exec('postgresql_initdb').with( + cwd: '/tmp', + ) end end - describe 'postgresql_psql with module_workdir => /var/tmp' do let :facts do { - :osfamily => 'RedHat', - :operatingsystem => 'CentOS', - :operatingsystemrelease => '6.0', - :concat_basedir => tmpfilename('server'), - :kernel => 'Linux', - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', - :selinux => true, + osfamily: 'RedHat', + operatingsystem: 'CentOS', + operatingsystemrelease: '6.0', + concat_basedir: tmpfilename('server'), + kernel: 'Linux', + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + selinux: true, } end - let (:pre_condition) do + let(:pre_condition) do <<-EOS class { 'postgresql::globals': module_workdir => '/var/tmp', encoding => 'test', needs_initdb => false, }-> class { 'postgresql::server': } EOS end - it 'should contain postgresql_psql with specified working directory' do - is_expected.to contain_postgresql_psql('Set template1 encoding to test').with({ - :cwd => '/var/tmp', - }) + + it 'contains postgresql_psql with specified working directory' do + is_expected.to contain_postgresql_psql('Set template1 encoding to test').with(cwd: '/var/tmp') end end end - diff --git a/spec/unit/classes/server/plperl_spec.rb b/spec/unit/classes/server/plperl_spec.rb index 00ddf09..90d7d2d 100644 --- a/spec/unit/classes/server/plperl_spec.rb +++ b/spec/unit/classes/server/plperl_spec.rb @@ -1,47 +1,43 @@ require 'spec_helper' -describe 'postgresql::server::plperl', :type => :class do +describe 'postgresql::server::plperl', type: :class do let :facts do { - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => '6.0', - :kernel => 'Linux', - :concat_basedir => tmpfilename('plperl'), - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: '6.0', + kernel: 'Linux', + concat_basedir: tmpfilename('plperl'), + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', } end let :pre_condition do "class { 'postgresql::server': }" end describe 'with no parameters' do - it { is_expected.to contain_class("postgresql::server::plperl") } - it 'should create package' do - is_expected.to contain_package('postgresql-plperl').with({ - :ensure => 'present', - :tag => 'postgresql', - }) + it { is_expected.to contain_class('postgresql::server::plperl') } + it 'creates package' do + is_expected.to contain_package('postgresql-plperl').with(ensure: 'present', + tag: 'postgresql') end end describe 'with parameters' do let :params do { - :package_ensure => 'absent', - :package_name => 'mypackage', + package_ensure: 'absent', + package_name: 'mypackage', } end - it { is_expected.to contain_class("postgresql::server::plperl") } - it 'should create package with correct params' do - is_expected.to contain_package('postgresql-plperl').with({ - :ensure => 'absent', - :name => 'mypackage', - :tag => 'postgresql', - }) + it { is_expected.to contain_class('postgresql::server::plperl') } + it 'creates package with correct params' do + is_expected.to contain_package('postgresql-plperl').with(ensure: 'absent', + name: 'mypackage', + tag: 'postgresql') end end end diff --git a/spec/unit/classes/server/plpython_spec.rb b/spec/unit/classes/server/plpython_spec.rb index 29a1440..ea87951 100644 --- a/spec/unit/classes/server/plpython_spec.rb +++ b/spec/unit/classes/server/plpython_spec.rb @@ -1,48 +1,44 @@ require 'spec_helper' -describe 'postgresql::server::plpython', :type => :class do +describe 'postgresql::server::plpython', type: :class do let :facts do { - :osfamily => 'RedHat', - :operatingsystem => 'CentOS', - :operatingsystemrelease => '6.0', - :concat_basedir => tmpfilename('plpython'), - :kernel => 'Linux', - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', - :selinux => true, + osfamily: 'RedHat', + operatingsystem: 'CentOS', + operatingsystemrelease: '6.0', + concat_basedir: tmpfilename('plpython'), + kernel: 'Linux', + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + selinux: true, } end let :pre_condition do "class { 'postgresql::server': }" end describe 'on RedHat with no parameters' do - it { is_expected.to contain_class("postgresql::server::plpython") } - it 'should create package' do - is_expected.to contain_package('postgresql-plpython').with({ - :ensure => 'present', - :tag => 'postgresql', - }) + it { is_expected.to contain_class('postgresql::server::plpython') } + it 'creates package' do + is_expected.to contain_package('postgresql-plpython').with(ensure: 'present', + tag: 'postgresql') end end - + describe 'with parameters' do - let :params do - { - :package_ensure => 'absent', - :package_name => 'mypackage', - } - end - - it { is_expected.to contain_class("postgresql::server::plpython") } - it 'should create package with correct params' do - is_expected.to contain_package('postgresql-plpython').with({ - :ensure => 'absent', - :name => 'mypackage', - :tag => 'postgresql', - }) - end + let :params do + { + package_ensure: 'absent', + package_name: 'mypackage', + } + end + + it { is_expected.to contain_class('postgresql::server::plpython') } + it 'creates package with correct params' do + is_expected.to contain_package('postgresql-plpython').with(ensure: 'absent', + name: 'mypackage', + tag: 'postgresql') end + end end diff --git a/spec/unit/classes/server/postgis_spec.rb b/spec/unit/classes/server/postgis_spec.rb index 1e53c21..b021bb3 100644 --- a/spec/unit/classes/server/postgis_spec.rb +++ b/spec/unit/classes/server/postgis_spec.rb @@ -1,44 +1,40 @@ require 'spec_helper' -describe 'postgresql::server::postgis', :type => :class do +describe 'postgresql::server::postgis', type: :class do let :pre_condition do "class { 'postgresql::server': }" end let :facts do { - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => '6.0', - :kernel => 'Linux', - :concat_basedir => tmpfilename('postgis'), - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: '6.0', + kernel: 'Linux', + concat_basedir: tmpfilename('postgis'), + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', } end describe 'with parameters' do let(:params) do { - :package_name => 'mypackage', - :package_ensure => 'absent', + package_name: 'mypackage', + package_ensure: 'absent', } end - it 'should create package with correct params' do - is_expected.to contain_package('postgresql-postgis').with({ - :ensure => 'absent', - :name => 'mypackage', - :tag => 'postgresql', - }) + it 'creates package with correct params' do + is_expected.to contain_package('postgresql-postgis').with(ensure: 'absent', + name: 'mypackage', + tag: 'postgresql') end end describe 'with no parameters' do - it 'should create package with postgresql tag' do - is_expected.to contain_package('postgresql-postgis').with({ - :tag => 'postgresql', - }) + it 'creates package with postgresql tag' do + is_expected.to contain_package('postgresql-postgis').with(tag: 'postgresql') end end end diff --git a/spec/unit/classes/server_spec.rb b/spec/unit/classes/server_spec.rb index 18013d8..02d5a95 100644 --- a/spec/unit/classes/server_spec.rb +++ b/spec/unit/classes/server_spec.rb @@ -1,168 +1,166 @@ require 'spec_helper' -describe 'postgresql::server', :type => :class do +describe 'postgresql::server', type: :class do let :facts do { - :os => { - :family => 'Debian', - :name => 'Debian', - :release => { - :full => '6.0', - :major => '6' - } + os: { + family: 'Debian', + name: 'Debian', + release: { + full: '6.0', + major: '6', + }, }, - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :lsbdistid => 'Debian', - :lsbdistcodename => 'jessie', - :operatingsystemrelease => '8.0', - :concat_basedir => tmpfilename('server'), - :kernel => 'Linux', - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + osfamily: 'Debian', + operatingsystem: 'Debian', + lsbdistid: 'Debian', + lsbdistcodename: 'jessie', + operatingsystemrelease: '8.0', + concat_basedir: tmpfilename('server'), + kernel: 'Linux', + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', } end describe 'with no parameters' do - it { is_expected.to contain_class("postgresql::params") } - it { is_expected.to contain_class("postgresql::server") } - it { is_expected.to contain_exec('postgresql_reload').with({ - 'command' => 'service postgresql reload', - }) + it { is_expected.to contain_class('postgresql::params') } + it { is_expected.to contain_class('postgresql::server') } + it { + is_expected.to contain_exec('postgresql_reload').with('command' => 'service postgresql reload') } - it 'should validate connection' do + it 'validates connection' do is_expected.to contain_postgresql_conn_validator('validate_service_is_running') end end describe 'service_ensure => running' do let(:params) do { - :service_ensure => 'running', - :postgres_password => 'new-p@s$word-to-set' + service_ensure: 'running', + postgres_password: 'new-p@s$word-to-set', } end - it { is_expected.to contain_class("postgresql::params") } - it { is_expected.to contain_class("postgresql::server") } - it { is_expected.to contain_class("postgresql::server::passwd") } - it 'should validate connection' do + + it { is_expected.to contain_class('postgresql::params') } + it { is_expected.to contain_class('postgresql::server') } + it { is_expected.to contain_class('postgresql::server::passwd') } + it 'validates connection' do is_expected.to contain_postgresql_conn_validator('validate_service_is_running') end - it 'should set postgres password' do - is_expected.to contain_exec('set_postgres_postgrespw').with({ - 'command' => '/usr/bin/psql -c "ALTER ROLE \"postgres\" PASSWORD ${NEWPASSWD_ESCAPED}"', - 'user' => 'postgres', - 'environment' => [ - "PGPASSWORD=new-p@s$word-to-set", - "PGPORT=5432", - "NEWPASSWD_ESCAPED=$$new-p@s$word-to-set$$" - ], - 'unless' => "/usr/bin/psql -h localhost -p 5432 -c 'select 1' > /dev/null", - }) + it 'sets postgres password' do + is_expected.to contain_exec('set_postgres_postgrespw').with('command' => '/usr/bin/psql -c "ALTER ROLE \"postgres\" PASSWORD ${NEWPASSWD_ESCAPED}"', + 'user' => 'postgres', + 'environment' => ['PGPASSWORD=new-p@s$word-to-set', 'PGPORT=5432', 'NEWPASSWD_ESCAPED=$$new-p@s$word-to-set$$'], + 'unless' => "/usr/bin/psql -h localhost -p 5432 -c 'select 1' > /dev/null") end end describe 'service_ensure => stopped' do - let(:params) {{ :service_ensure => 'stopped' }} - it { is_expected.to contain_class("postgresql::params") } - it { is_expected.to contain_class("postgresql::server") } + let(:params) { { service_ensure: 'stopped' } } + + it { is_expected.to contain_class('postgresql::params') } + it { is_expected.to contain_class('postgresql::server') } it 'shouldnt validate connection' do is_expected.not_to contain_postgresql_conn_validator('validate_service_is_running') end end describe 'service_restart_on_change => false' do - let(:params) {{ :service_restart_on_change => false }} - it { is_expected.to contain_class("postgresql::params") } - it { is_expected.to contain_class("postgresql::server") } - it { is_expected.to_not contain_Postgresql_conf('data_directory').that_notifies('Class[postgresql::server::service]') + let(:params) { { service_restart_on_change: false } } + + it { is_expected.to contain_class('postgresql::params') } + it { is_expected.to contain_class('postgresql::server') } + it { + is_expected.not_to contain_Postgresql_conf('data_directory').that_notifies('Class[postgresql::server::service]') } - it 'should validate connection' do + it 'validates connection' do is_expected.to contain_postgresql_conn_validator('validate_service_is_running') end end describe 'service_restart_on_change => true' do - let(:params) {{ :service_restart_on_change => true }} - it { is_expected.to contain_class("postgresql::params") } - it { is_expected.to contain_class("postgresql::server") } - it { is_expected.to contain_Postgresql_conf('data_directory').that_notifies('Class[postgresql::server::service]') + let(:params) { { service_restart_on_change: true } } + + it { is_expected.to contain_class('postgresql::params') } + it { is_expected.to contain_class('postgresql::server') } + it { + is_expected.to contain_Postgresql_conf('data_directory').that_notifies('Class[postgresql::server::service]') } - it 'should validate connection' do + it 'validates connection' do is_expected.to contain_postgresql_conn_validator('validate_service_is_running') end end describe 'service_reload => /bin/true' do - let(:params) {{ :service_reload => '/bin/true' }} - it { is_expected.to contain_class("postgresql::params") } - it { is_expected.to contain_class("postgresql::server") } - it { is_expected.to contain_exec('postgresql_reload').with({ - 'command' => '/bin/true', - }) + let(:params) { { service_reload: '/bin/true' } } + + it { is_expected.to contain_class('postgresql::params') } + it { is_expected.to contain_class('postgresql::server') } + it { + is_expected.to contain_exec('postgresql_reload').with('command' => '/bin/true') } - it 'should validate connection' do + it 'validates connection' do is_expected.to contain_postgresql_conn_validator('validate_service_is_running') end end describe 'service_manage => true' do - let(:params) {{ :service_manage => true }} + let(:params) { { service_manage: true } } + it { is_expected.to contain_service('postgresqld') } end describe 'service_manage => false' do - let(:params) {{ :service_manage => false }} + let(:params) { { service_manage: false } } + it { is_expected.not_to contain_service('postgresqld') } it 'shouldnt validate connection' do is_expected.not_to contain_postgresql_conn_validator('validate_service_is_running') end end describe 'package_ensure => absent' do let(:params) do { - :package_ensure => 'absent', + package_ensure: 'absent', } end - it 'should remove the package' do - is_expected.to contain_package('postgresql-server').with({ - :ensure => 'purged', - }) + it 'removes the package' do + is_expected.to contain_package('postgresql-server').with(ensure: 'purged') end - it 'should still enable the service' do - is_expected.to contain_service('postgresqld').with({ - :ensure => 'running', - }) + it 'stills enable the service' do + is_expected.to contain_service('postgresqld').with(ensure: 'running') end end describe 'needs_initdb => true' do let(:params) do { - :needs_initdb => true, + needs_initdb: true, } end - it 'should contain proper initdb exec' do + it 'contains proper initdb exec' do is_expected.to contain_exec('postgresql_initdb') end end describe 'postgresql_version' do let(:pre_condition) do <<-EOS class { 'postgresql::globals': manage_package_repo => true, version => '99.5', before => Class['postgresql::server'], } EOS end + it 'contains the correct package version' do is_expected.to contain_class('postgresql::repo').with_version('99.5') end end end diff --git a/spec/unit/defines/server/config_entry_spec.rb b/spec/unit/defines/server/config_entry_spec.rb index 34f0c70..852ced8 100644 --- a/spec/unit/defines/server/config_entry_spec.rb +++ b/spec/unit/defines/server/config_entry_spec.rb @@ -1,136 +1,144 @@ require 'spec_helper' -describe 'postgresql::server::config_entry', :type => :define do +describe 'postgresql::server::config_entry', type: :define do let :facts do { - :osfamily => 'RedHat', - :operatingsystem => 'RedHat', - :operatingsystemrelease => '6.4', - :kernel => 'Linux', - :concat_basedir => tmpfilename('contrib'), - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', - :selinux => true, + osfamily: 'RedHat', + operatingsystem: 'RedHat', + operatingsystemrelease: '6.4', + kernel: 'Linux', + concat_basedir: tmpfilename('contrib'), + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + selinux: true, } end - let(:title) { 'config_entry'} + let(:title) { 'config_entry' } let :target do tmpfilename('postgresql_conf') end let :pre_condition do "class {'postgresql::server':}" end - context "syntax check" do - let(:params) { { :ensure => 'present'} } + context 'syntax check' do + let(:params) { { ensure: 'present' } } + it { is_expected.to contain_postgresql__server__config_entry('config_entry') } end context 'ports' do context 'redhat 6' do let :facts do { - :osfamily => 'RedHat', - :operatingsystem => 'RedHat', - :operatingsystemrelease => '6.4', - :kernel => 'Linux', - :concat_basedir => tmpfilename('contrib'), - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', - :selinux => true, + osfamily: 'RedHat', + operatingsystem: 'RedHat', + operatingsystemrelease: '6.4', + kernel: 'Linux', + concat_basedir: tmpfilename('contrib'), + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + selinux: true, } end - let(:params) {{ :ensure => 'present', :name => 'port_spec', :value => '5432' }} + let(:params) { { ensure: 'present', name: 'port_spec', value: '5432' } } - it 'stops postgresql and changes the port' do + it 'stops postgresql and changes the port #exec' do is_expected.to contain_exec('postgresql_stop_port') + end + it 'stops postgresql and changes the port #augeas' do is_expected.to contain_augeas('override PGPORT in /etc/sysconfig/pgsql/postgresql') end end context 'redhat 7' do let :facts do { - :osfamily => 'RedHat', - :operatingsystem => 'RedHat', - :operatingsystemrelease => '7.0', - :kernel => 'Linux', - :concat_basedir => tmpfilename('contrib'), - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', - :selinux => true, + osfamily: 'RedHat', + operatingsystem: 'RedHat', + operatingsystemrelease: '7.0', + kernel: 'Linux', + concat_basedir: tmpfilename('contrib'), + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + selinux: true, } end - let(:params) {{ :ensure => 'present', :name => 'port_spec', :value => '5432' }} + let(:params) { { ensure: 'present', name: 'port_spec', value: '5432' } } - it 'stops postgresql and changes the port' do + it 'stops postgresql and changes the port #file' do is_expected.to contain_file('systemd-override') + end + it 'stops postgresql and changes the port #exec' do is_expected.to contain_exec('restart-systemd') end end context 'fedora 19' do let :facts do { - :osfamily => 'RedHat', - :operatingsystem => 'Fedora', - :operatingsystemrelease => '19', - :kernel => 'Linux', - :concat_basedir => tmpfilename('contrib'), - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', - :selinux => true, + osfamily: 'RedHat', + operatingsystem: 'Fedora', + operatingsystemrelease: '19', + kernel: 'Linux', + concat_basedir: tmpfilename('contrib'), + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + selinux: true, } end - let(:params) {{ :ensure => 'present', :name => 'port_spec', :value => '5432' }} + let(:params) { { ensure: 'present', name: 'port_spec', value: '5432' } } - it 'stops postgresql and changes the port' do + it 'stops postgresql and changes the port #file' do is_expected.to contain_file('systemd-override') + end + it 'stops postgresql and changes the port #exec' do is_expected.to contain_exec('restart-systemd') end end end - context "data_directory" do - let(:params) {{ :ensure => 'present', :name => 'data_directory_spec', :value => '/var/pgsql' }} + context 'data_directory' do + let(:params) { { ensure: 'present', name: 'data_directory_spec', value: '/var/pgsql' } } - it 'stops postgresql and changes the data directory' do + it 'stops postgresql and changes the data directory #exec' do is_expected.to contain_exec('postgresql_data_directory') + end + it 'stops postgresql and changes the data directory #augeas' do is_expected.to contain_augeas('override PGDATA in /etc/sysconfig/pgsql/postgresql') end end - context "passes values through appropriately" do - let(:params) {{ :ensure => 'present', :name => 'check_function_bodies', :value => 'off' }} + context 'passes values through appropriately' do + let(:params) { { ensure: 'present', name: 'check_function_bodies', value: 'off' } } it 'with no quotes' do - is_expected.to contain_postgresql_conf('check_function_bodies').with({ - :name => 'check_function_bodies', - :value => 'off' }) + is_expected.to contain_postgresql_conf('check_function_bodies').with(name: 'check_function_bodies', + value: 'off') end end context 'unix_socket_directories' do let :facts do { - :osfamily => 'RedHat', - :operatingsystem => 'RedHat', - :operatingsystemrelease => '7.0', - :kernel => 'Linux', - :concat_basedir => tmpfilename('contrib'), - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', - :selinux => true, + osfamily: 'RedHat', + operatingsystem: 'RedHat', + operatingsystemrelease: '7.0', + kernel: 'Linux', + concat_basedir: tmpfilename('contrib'), + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + selinux: true, } end - let(:params) {{ :ensure => 'present', :name => 'unix_socket_directories', :value => '/var/pgsql, /opt/postgresql, /root/' }} + let(:params) { { ensure: 'present', name: 'unix_socket_directories', value: '/var/pgsql, /opt/postgresql, /root/' } } - it 'should restart the server and change unix_socket_directories to the provided list' do + it 'restarts the server and change unix_socket_directories to the provided list' do is_expected.to contain_postgresql_conf('unix_socket_directories') - .with({ :name => 'unix_socket_directories', - :value => '/var/pgsql, /opt/postgresql, /root/'}) - .that_notifies('Class[postgresql::server::service]') + .with(name: 'unix_socket_directories', + value: '/var/pgsql, /opt/postgresql, /root/') + .that_notifies('Class[postgresql::server::service]') end end end diff --git a/spec/unit/defines/server/database_grant_spec.rb b/spec/unit/defines/server/database_grant_spec.rb index 19dfce9..d4c65b6 100644 --- a/spec/unit/defines/server/database_grant_spec.rb +++ b/spec/unit/defines/server/database_grant_spec.rb @@ -1,34 +1,34 @@ require 'spec_helper' -describe 'postgresql::server::database_grant', :type => :define do +describe 'postgresql::server::database_grant', type: :define do let :facts do { - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => '6.0', - :kernel => 'Linux', - :concat_basedir => tmpfilename('contrib'), - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: '6.0', + kernel: 'Linux', + concat_basedir: tmpfilename('contrib'), + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', } end let :title do 'test' end let :params do { - :privilege => 'ALL', - :db => 'test', - :role => 'test', + privilege: 'ALL', + db: 'test', + role: 'test', } end let :pre_condition do "class {'postgresql::server':}" end it { is_expected.to contain_postgresql__server__database_grant('test') } it { is_expected.to contain_postgresql__server__grant('database:test') } end diff --git a/spec/unit/defines/server/database_spec.rb b/spec/unit/defines/server/database_spec.rb index c9993f6..9880bbc 100644 --- a/spec/unit/defines/server/database_spec.rb +++ b/spec/unit/defines/server/database_spec.rb @@ -1,78 +1,80 @@ require 'spec_helper' -describe 'postgresql::server::database', :type => :define do +describe 'postgresql::server::database', type: :define do let :facts do { - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => '6.0', - :kernel => 'Linux', - :concat_basedir => tmpfilename('contrib'), - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: '6.0', + kernel: 'Linux', + concat_basedir: tmpfilename('contrib'), + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', } end let :title do 'test' end let :pre_condition do "class {'postgresql::server':}" end it { is_expected.to contain_postgresql__server__database('test') } it { is_expected.to contain_postgresql_psql('CREATE DATABASE "test"') } context "with comment set to 'test comment'" do - let (:params) {{ :comment => 'test comment' }} + let(:params) { { comment: 'test comment' } } - it { is_expected.to contain_postgresql_psql("COMMENT ON DATABASE \"test\" IS 'test comment'").with_connect_settings( {} ) } + it { is_expected.to contain_postgresql_psql("COMMENT ON DATABASE \"test\" IS 'test comment'").with_connect_settings({}) } end - context "with specific db connection settings - default port" do + context 'with specific db connection settings - default port' do let :pre_condition do "class {'postgresql::server':}" end - let (:params) {{ :connect_settings => { 'PGHOST' => 'postgres-db-server', - 'DBVERSION' => '9.1', }}} + let(:params) do + { connect_settings: { 'PGHOST' => 'postgres-db-server', + 'DBVERSION' => '9.1' } } + end - it { is_expected.to contain_postgresql_psql('CREATE DATABASE "test"').with_connect_settings( { 'PGHOST' => 'postgres-db-server','DBVERSION' => '9.1' } ).with_port( 5432 ) } + it { is_expected.to contain_postgresql_psql('CREATE DATABASE "test"').with_connect_settings('PGHOST' => 'postgres-db-server', 'DBVERSION' => '9.1').with_port(5432) } end - context "with specific db connection settings - including port" do + context 'with specific db connection settings - including port' do let :pre_condition do "class {'postgresql::globals':} class {'postgresql::server':}" end - let (:params) {{ :connect_settings => { 'PGHOST' => 'postgres-db-server', - 'DBVERSION' => '9.1', - 'PGPORT' => '1234' }}} - - it { is_expected.to contain_postgresql_psql('CREATE DATABASE "test"').with_connect_settings( { 'PGHOST' => 'postgres-db-server','DBVERSION' => '9.1','PGPORT' => '1234' } ).with_port( nil ) } + let(:params) do + { connect_settings: { 'PGHOST' => 'postgres-db-server', + 'DBVERSION' => '9.1', + 'PGPORT' => '1234' } } + end + it { is_expected.to contain_postgresql_psql('CREATE DATABASE "test"').with_connect_settings('PGHOST' => 'postgres-db-server', 'DBVERSION' => '9.1', 'PGPORT' => '1234').with_port(nil) } end - context "with global db connection settings - including port" do + context 'with global db connection settings - including port' do let :pre_condition do "class {'postgresql::globals': default_connect_settings => { 'PGHOST' => 'postgres-db-server', 'DBVERSION' => '9.2', 'PGPORT' => '1234' } } class {'postgresql::server':}" end - it { is_expected.to contain_postgresql_psql('CREATE DATABASE "test"').with_connect_settings( { 'PGHOST' => 'postgres-db-server','DBVERSION' => '9.2','PGPORT' => '1234' } ).with_port( nil ) } - + it { is_expected.to contain_postgresql_psql('CREATE DATABASE "test"').with_connect_settings('PGHOST' => 'postgres-db-server', 'DBVERSION' => '9.2', 'PGPORT' => '1234').with_port(nil) } end - context "with different owner" do - let (:params) {{ :owner => 'test_owner' }} + context 'with different owner' do + let(:params) { { owner: 'test_owner' } } it { is_expected.to contain_postgresql_psql('ALTER DATABASE "test" OWNER TO "test_owner"') } end end diff --git a/spec/unit/defines/server/db_spec.rb b/spec/unit/defines/server/db_spec.rb index 78e36b0..9dd9ad4 100644 --- a/spec/unit/defines/server/db_spec.rb +++ b/spec/unit/defines/server/db_spec.rb @@ -1,58 +1,55 @@ require 'spec_helper' -describe 'postgresql::server::db', :type => :define do +describe 'postgresql::server::db', type: :define do let :facts do { - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => '6.0', - :kernel => 'Linux', - :concat_basedir => tmpfilename('contrib'), - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: '6.0', + kernel: 'Linux', + concat_basedir: tmpfilename('contrib'), + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', } end let :title do 'test' end context 'without dbname param' do - let :params do { - :user => 'test', - :password => 'test', - :owner => 'tester', + user: 'test', + password: 'test', + owner: 'tester', } end let :pre_condition do "class {'postgresql::server':}" end it { is_expected.to contain_postgresql__server__db('test') } it { is_expected.to contain_postgresql__server__database('test').with_owner('tester') } it { is_expected.to contain_postgresql__server__role('test').that_comes_before('Postgresql::Server::Database[test]') } it { is_expected.to contain_postgresql__server__database_grant('GRANT test - ALL - test') } - end context 'dbname' do - let :params do { - :dbname => 'testtest', - :user => 'test', - :password => 'test', - :owner => 'tester', + dbname: 'testtest', + user: 'test', + password: 'test', + owner: 'tester', } end let :pre_condition do "class {'postgresql::server':}" end it { is_expected.to contain_postgresql__server__database('testtest') } end end diff --git a/spec/unit/defines/server/extension_spec.rb b/spec/unit/defines/server/extension_spec.rb index 6ce5de6..84bd53d 100644 --- a/spec/unit/defines/server/extension_spec.rb +++ b/spec/unit/defines/server/extension_spec.rb @@ -1,160 +1,153 @@ require 'spec_helper' -describe 'postgresql::server::extension', :type => :define do +describe 'postgresql::server::extension', type: :define do # rubocop:disable RSpec/MultipleDescribes let :pre_condition do "class { 'postgresql::server': } postgresql::server::database { 'template_postgis': template => 'template1', }" end let :facts do { - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => '6.0', - :kernel => 'Linux', - :concat_basedir => tmpfilename('postgis'), - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: '6.0', + kernel: 'Linux', + concat_basedir: tmpfilename('postgis'), + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', } end - let (:title) { 'postgis' } - let (:params) { { - :database => 'template_postgis', - } } + let(:title) { 'postgis' } + let(:params) do + { + database: 'template_postgis', + } + end + + context 'with mandatory arguments only' do + it { + is_expected.to contain_postgresql_psql('template_postgis: CREATE EXTENSION "postgis"') + .with(db: 'template_postgis', command: 'CREATE EXTENSION "postgis"').that_requires('Postgresql::Server::Database[template_postgis]') + } + end + + context 'when schema is specified' do + let(:params) do + super().merge(schema: 'pg_catalog') + end - context "with mandatory arguments only" do it { - is_expected.to contain_postgresql_psql('Add postgis extension to template_postgis').with({ - :db => 'template_postgis', - :command => 'CREATE EXTENSION "postgis"', - :unless => "SELECT t.count FROM (SELECT count(extname) FROM pg_extension WHERE extname = 'postgis') as t WHERE t.count = 1", - }).that_requires('Postgresql::Server::Database[template_postgis]') + is_expected.to contain_postgresql_psql('template_postgis: ALTER EXTENSION "postgis" SET SCHEMA "pg_catalog"') } end - context "when setting package name" do - let (:params) { super().merge({ - :package_name => 'postgis', - }) } + context 'when setting package name' do + let(:params) do + super().merge(package_name: 'postgis') + end it { - is_expected.to contain_package('postgis').with({ - :ensure => 'present', - :name => 'postgis', - }).that_comes_before('Postgresql_psql[Add postgis extension to template_postgis]') + is_expected.to contain_package('postgis') + .with(ensure: 'present', name: 'postgis').that_comes_before('Postgresql_psql[template_postgis: CREATE EXTENSION "postgis"]') } end - context "when ensuring absence" do - let (:params) { super().merge({ - :ensure => 'absent', - :package_name => 'postgis', - }) } + context 'when ensuring absence' do + let(:params) do + super().merge(ensure: 'absent', + package_name: 'postgis') + end it { - is_expected.to contain_postgresql_psql('Add postgis extension to template_postgis').with({ - :db => 'template_postgis', - :command => 'DROP EXTENSION "postgis"', - :unless => "SELECT t.count FROM (SELECT count(extname) FROM pg_extension WHERE extname = 'postgis') as t WHERE t.count != 1", - }).that_requires('Postgresql::Server::Database[template_postgis]') + is_expected.to contain_postgresql_psql('template_postgis: DROP EXTENSION "postgis"') + .with(db: 'template_postgis', command: 'DROP EXTENSION "postgis"').that_requires('Postgresql::Server::Database[template_postgis]') } it { - is_expected.to contain_package('postgis').with({ - :ensure => 'absent', - :name => 'postgis', - }) + is_expected.to contain_package('postgis').with(ensure: 'absent', + name: 'postgis') } - context "when keeping package installed" do - let (:params) { super().merge({ - :package_ensure => 'present', - }) } + context 'when keeping package installed' do + let(:params) do + super().merge(package_ensure: 'present') + end it { - is_expected.to contain_postgresql_psql('Add postgis extension to template_postgis').with({ - :db => 'template_postgis', - :command => 'DROP EXTENSION "postgis"', - :unless => "SELECT t.count FROM (SELECT count(extname) FROM pg_extension WHERE extname = 'postgis') as t WHERE t.count != 1", - }).that_requires('Postgresql::Server::Database[template_postgis]') + is_expected.to contain_postgresql_psql('template_postgis: DROP EXTENSION "postgis"') + .with(db: 'template_postgis', command: 'DROP EXTENSION "postgis"').that_requires('Postgresql::Server::Database[template_postgis]') } it { - is_expected.to contain_package('postgis').with({ - :ensure => 'present', - :name => 'postgis', - }).that_requires('Postgresql_psql[Add postgis extension to template_postgis]') + is_expected.to contain_package('postgis') + .with(ensure: 'present', name: 'postgis').that_requires('Postgresql_psql[template_postgis: DROP EXTENSION "postgis"]') } end end - context "when extension version is specified" do - let (:params) { super().merge({ - :ensure => 'absent', - :package_name => 'postgis', - :version => '99.99.99', - }) } + context 'when extension version is specified' do + let(:params) do + super().merge(ensure: 'absent', + package_name: 'postgis', + version: '99.99.99') + end it { - is_expected.to contain_postgresql_psql('template_postgis: ALTER EXTENSION "postgis" UPDATE TO \'99.99.99\'').with({ - :db => 'template_postgis', - :unless => "SELECT 1 FROM pg_extension WHERE extname='postgis' AND extversion='99.99.99'", - }).that_requires('Postgresql::Server::Database[template_postgis]') + is_expected.to contain_postgresql_psql('template_postgis: ALTER EXTENSION "postgis" UPDATE TO \'99.99.99\'') + .with(db: 'template_postgis', unless: "SELECT 1 FROM pg_extension WHERE extname='postgis' AND extversion='99.99.99'").that_requires('Postgresql::Server::Database[template_postgis]') } end - context "when extension version is latest" do - let (:params) { super().merge({ - :ensure => 'absent', - :package_name => 'postgis', - :version => 'latest', - }) } + context 'when extension version is latest' do + let(:params) do + super().merge(ensure: 'absent', + package_name: 'postgis', + version: 'latest') + end it { - is_expected.to contain_postgresql_psql('template_postgis: ALTER EXTENSION "postgis" UPDATE').with({ - :db => 'template_postgis', - :unless => "SELECT 1 FROM pg_available_extensions WHERE name = 'postgis' AND default_version = installed_version", - }).that_requires('Postgresql::Server::Database[template_postgis]') + is_expected.to contain_postgresql_psql('template_postgis: ALTER EXTENSION "postgis" UPDATE') + .with(db: 'template_postgis', + unless: "SELECT 1 FROM pg_available_extensions WHERE name = 'postgis' AND default_version = installed_version").that_requires('Postgresql::Server::Database[template_postgis]') } end end -describe 'postgresql::server::extension', :type => :define do +describe 'postgresql::server::extension', type: :define do let :pre_condition do "class { 'postgresql::server': } postgresql::server::database { 'template_postgis2': template => 'template1', }" end let :facts do { - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => '6.0', - :kernel => 'Linux', - :concat_basedir => tmpfilename('postgis'), - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: '6.0', + kernel: 'Linux', + concat_basedir: tmpfilename('postgis'), + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', } end - let (:title) { 'postgis_db2' } - let (:params) { { - :database => 'template_postgis2', - :extension => 'postgis', - } } + let(:title) { 'postgis_db2' } + let(:params) do + { + database: 'template_postgis2', + extension: 'postgis', + } + end - context "with mandatory arguments only" do + context 'with mandatory arguments only' do it { - is_expected.to contain_postgresql_psql('Add postgis extension to template_postgis2').with({ - :db => 'template_postgis2', - :command => 'CREATE EXTENSION "postgis"', - :unless => "SELECT t.count FROM (SELECT count(extname) FROM pg_extension WHERE extname = 'postgis') as t WHERE t.count = 1", - }).that_requires('Postgresql::Server::Database[template_postgis2]') + is_expected.to contain_postgresql_psql('template_postgis2: CREATE EXTENSION "postgis"') + .with(db: 'template_postgis2', command: 'CREATE EXTENSION "postgis"').that_requires('Postgresql::Server::Database[template_postgis2]') } end end diff --git a/spec/unit/defines/server/grant_role_spec.rb b/spec/unit/defines/server/grant_role_spec.rb index 12a41e2..6fbada8 100644 --- a/spec/unit/defines/server/grant_role_spec.rb +++ b/spec/unit/defines/server/grant_role_spec.rb @@ -1,105 +1,104 @@ require 'spec_helper' -describe 'postgresql::server::grant_role', :type => :define do +describe 'postgresql::server::grant_role', type: :define do let :pre_condition do "class { 'postgresql::server': }" end - let :facts do - {:osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => '6.0', - :kernel => 'Linux', :concat_basedir => tmpfilename('postgis'), - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', - } + let(:facts) do + { osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: '6.0', + kernel: 'Linux', concat_basedir: tmpfilename('postgis'), + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin' } end - let (:title) { 'test' } + let(:title) { 'test' } - let (:params) { { - :group => 'my_group', - :role => 'my_role', - } } + let(:params) do + { + group: 'my_group', + role: 'my_role', + } + end - context "with mandatory arguments only" do + context 'with mandatory arguments only' do it { - is_expected.to contain_postgresql_psql("grant_role:#{title}").with({ - :command => "GRANT \"#{params[:group]}\" TO \"#{params[:role]}\"", - :unless => "SELECT 1 WHERE EXISTS (SELECT 1 FROM pg_roles AS r_role JOIN pg_auth_members AS am ON r_role.oid = am.member JOIN pg_roles AS r_group ON r_group.oid = am.roleid WHERE r_group.rolname = '#{params[:group]}' AND r_role.rolname = '#{params[:role]}') = true", - }).that_requires('Class[postgresql::server]') + is_expected.to contain_postgresql_psql("grant_role:#{title}") + .with(command: "GRANT \"#{params[:group]}\" TO \"#{params[:role]}\"", + unless: "SELECT 1 WHERE EXISTS (SELECT 1 FROM pg_roles AS r_role JOIN pg_auth_members AS am ON r_role.oid = am.member JOIN pg_roles AS r_group ON r_group.oid = am.roleid WHERE r_group.rolname = '#{params[:group]}' AND r_role.rolname = '#{params[:role]}') = true") # rubocop:disable Metrics/LineLength + .that_requires('Class[postgresql::server]') } end - context "with db arguments" do - let (:params) { super().merge({ - :psql_db => 'postgres', - :psql_user => 'postgres', - :port => '5432', - }) } + context 'with db arguments' do + let(:params) do + super().merge(psql_db: 'postgres', + psql_user: 'postgres', + port: '5432') + end it { - is_expected.to contain_postgresql_psql("grant_role:#{title}").with({ - :command => "GRANT \"#{params[:group]}\" TO \"#{params[:role]}\"", - :unless => "SELECT 1 WHERE EXISTS (SELECT 1 FROM pg_roles AS r_role JOIN pg_auth_members AS am ON r_role.oid = am.member JOIN pg_roles AS r_group ON r_group.oid = am.roleid WHERE r_group.rolname = '#{params[:group]}' AND r_role.rolname = '#{params[:role]}') = true", - :db => params[:psql_db], - :psql_user => params[:psql_user], - :port => params[:port], - }).that_requires('Class[postgresql::server]') + is_expected.to contain_postgresql_psql("grant_role:#{title}") + .with(command: "GRANT \"#{params[:group]}\" TO \"#{params[:role]}\"", + unless: "SELECT 1 WHERE EXISTS (SELECT 1 FROM pg_roles AS r_role JOIN pg_auth_members AS am ON r_role.oid = am.member JOIN pg_roles AS r_group ON r_group.oid = am.roleid WHERE r_group.rolname = '#{params[:group]}' AND r_role.rolname = '#{params[:role]}') = true", # rubocop:disable Metrics/LineLength + db: params[:psql_db], psql_user: params[:psql_user], + port: params[:port]).that_requires('Class[postgresql::server]') } end - context "with ensure => absent" do - let (:params) { super().merge({ - :ensure => 'absent', - }) } + context 'with ensure => absent' do + let(:params) do + super().merge(ensure: 'absent') + end it { - is_expected.to contain_postgresql_psql("grant_role:#{title}").with({ - :command => "REVOKE \"#{params[:group]}\" FROM \"#{params[:role]}\"", - :unless => "SELECT 1 WHERE EXISTS (SELECT 1 FROM pg_roles AS r_role JOIN pg_auth_members AS am ON r_role.oid = am.member JOIN pg_roles AS r_group ON r_group.oid = am.roleid WHERE r_group.rolname = '#{params[:group]}' AND r_role.rolname = '#{params[:role]}') != true", - }).that_requires('Class[postgresql::server]') + is_expected.to contain_postgresql_psql("grant_role:#{title}") + .with(command: "REVOKE \"#{params[:group]}\" FROM \"#{params[:role]}\"", + unless: "SELECT 1 WHERE EXISTS (SELECT 1 FROM pg_roles AS r_role JOIN pg_auth_members AS am ON r_role.oid = am.member JOIN pg_roles AS r_group ON r_group.oid = am.roleid WHERE r_group.rolname = '#{params[:group]}' AND r_role.rolname = '#{params[:role]}') != true") # rubocop:disable Metrics/LineLength + .that_requires('Class[postgresql::server]') } end - context "with user defined" do - let :pre_condition do + context 'with user defined' do + let(:pre_condition) do "class { 'postgresql::server': } postgresql::server::role { '#{params[:role]}': }" end it { is_expected.to contain_postgresql_psql("grant_role:#{title}").that_requires("Postgresql::Server::Role[#{params[:role]}]") } it { is_expected.not_to contain_postgresql_psql("grant_role:#{title}").that_requires("Postgresql::Server::Role[#{params[:group]}]") } end - context "with group defined" do - let :pre_condition do + context 'with group defined' do + let(:pre_condition) do "class { 'postgresql::server': } postgresql::server::role { '#{params[:group]}': }" end it { is_expected.to contain_postgresql_psql("grant_role:#{title}").that_requires("Postgresql::Server::Role[#{params[:group]}]") } it { is_expected.not_to contain_postgresql_psql("grant_role:#{title}").that_requires("Postgresql::Server::Role[#{params[:role]}]") } end - context "with connect_settings" do - let (:params) { super().merge({ - :connect_settings => { 'PGHOST' => 'postgres-db-server' }, - }) } + context 'with connect_settings' do + let(:params) do + super().merge(connect_settings: { 'PGHOST' => 'postgres-db-server' }) + end it { - is_expected.to contain_postgresql_psql("grant_role:#{title}").with_connect_settings( { 'PGHOST' => 'postgres-db-server' } ) + is_expected.to contain_postgresql_psql("grant_role:#{title}").with_connect_settings('PGHOST' => 'postgres-db-server') } it { is_expected.not_to contain_postgresql_psql("grant_role:#{title}").that_requires('Class[postgresql::server]') } end end diff --git a/spec/unit/defines/server/grant_spec.rb b/spec/unit/defines/server/grant_spec.rb index b69b8a8..6b38458 100644 --- a/spec/unit/defines/server/grant_spec.rb +++ b/spec/unit/defines/server/grant_spec.rb @@ -1,264 +1,264 @@ require 'spec_helper' -describe 'postgresql::server::grant', :type => :define do +describe 'postgresql::server::grant', type: :define do let :facts do { - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => '6.0', - :kernel => 'Linux', - :concat_basedir => tmpfilename('contrib'), - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: '6.0', + kernel: 'Linux', + concat_basedir: tmpfilename('contrib'), + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', } end let :title do 'test' end context 'plain' do let :params do { - :db => 'test', - :role => 'test', + db: 'test', + role: 'test', } end let :pre_condition do "class {'postgresql::server':}" end it { is_expected.to contain_postgresql__server__grant('test') } end context 'sequence' do let :params do { - :db => 'test', - :role => 'test', - :privilege => 'usage', - :object_type => 'sequence', + db: 'test', + role: 'test', + privilege: 'usage', + object_type: 'sequence', } end let :pre_condition do "class {'postgresql::server':}" end it { is_expected.to contain_postgresql__server__grant('test') } - it { is_expected.to contain_postgresql_psql('grant:test').with( - { - 'command' => /GRANT USAGE ON SEQUENCE "test" TO\s* "test"/m, - 'unless' => /SELECT 1 WHERE has_sequence_privilege\('test',\s* 'test', 'USAGE'\) = true/m, - } - ) } + it { + is_expected.to contain_postgresql_psql('grant:test').with( + 'command' => %r{GRANT USAGE ON SEQUENCE "test" TO\s* "test"}m, + 'unless' => %r{SELECT 1 WHERE has_sequence_privilege\('test',\s* 'test', 'USAGE'\)}m, + ) + } end context 'SeQuEnCe case insensitive object_type match' do let :params do { - :db => 'test', - :role => 'test', - :privilege => 'usage', - :object_type => 'SeQuEnCe', + db: 'test', + role: 'test', + privilege: 'usage', + object_type: 'SeQuEnCe', } end let :pre_condition do "class {'postgresql::server':}" end it { is_expected.to contain_postgresql__server__grant('test') } - it { is_expected.to contain_postgresql_psql('grant:test').with( - { - 'command' => /GRANT USAGE ON SEQUENCE "test" TO\s* "test"/m, - 'unless' => /SELECT 1 WHERE has_sequence_privilege\('test',\s* 'test', 'USAGE'\)/m, - } - ) } + it { + is_expected.to contain_postgresql_psql('grant:test').with( + 'command' => %r{GRANT USAGE ON SEQUENCE "test" TO\s* "test"}m, + 'unless' => %r{SELECT 1 WHERE has_sequence_privilege\('test',\s* 'test', 'USAGE'\)}m, + ) + } end context 'all sequences' do let :params do { - :db => 'test', - :role => 'test', - :privilege => 'usage', - :object_type => 'all sequences in schema', - :object_name => 'public', + db: 'test', + role: 'test', + privilege: 'usage', + object_type: 'all sequences in schema', + object_name: 'public', } end let :pre_condition do "class {'postgresql::server':}" end it { is_expected.to contain_postgresql__server__grant('test') } - it { is_expected.to contain_postgresql_psql('grant:test').with( - { - 'command' => /GRANT USAGE ON ALL SEQUENCES IN SCHEMA "public" TO\s* "test"/m, - 'unless' => /SELECT 1 WHERE NOT EXISTS \(\s*SELECT sequence_name\s* FROM information_schema\.sequences\s* WHERE sequence_schema='public'\s* EXCEPT DISTINCT\s* SELECT object_name as sequence_name\s* FROM .* WHERE .*grantee='test'\s* AND object_schema='public'\s* AND privilege_type='USAGE'\s*\)/m, - } - ) } + it { + is_expected.to contain_postgresql_psql('grant:test').with( + 'command' => %r{GRANT USAGE ON ALL SEQUENCES IN SCHEMA "public" TO\s* "test"}m, + 'unless' => %r{SELECT 1 WHERE NOT EXISTS \(\s*SELECT sequence_name\s* FROM information_schema\.sequences\s* WHERE sequence_schema='public'\s* EXCEPT DISTINCT\s* SELECT object_name as sequence_name\s* FROM .* WHERE .*grantee='test'\s* AND object_schema='public'\s* AND privilege_type='USAGE'\s*\)}m, # rubocop:disable Metrics/LineLength + ) + } end - context "with specific db connection settings - default port" do + context 'with specific db connection settings - default port' do let :params do { - :db => 'test', - :role => 'test', - :connect_settings => { 'PGHOST' => 'postgres-db-server', - 'DBVERSION' => '9.1', }, + db: 'test', + role: 'test', + connect_settings: { 'PGHOST' => 'postgres-db-server', + 'DBVERSION' => '9.1' }, } end let :pre_condition do "class {'postgresql::server':}" end it { is_expected.to contain_postgresql__server__grant('test') } - it { is_expected.to contain_postgresql_psql("grant:test").with_connect_settings( { 'PGHOST' => 'postgres-db-server','DBVERSION' => '9.1' } ).with_port( 5432 ) } + it { is_expected.to contain_postgresql_psql('grant:test').with_connect_settings('PGHOST' => 'postgres-db-server', 'DBVERSION' => '9.1').with_port(5432) } end - context "with specific db connection settings - including port" do + context 'with specific db connection settings - including port' do let :params do { - :db => 'test', - :role => 'test', - :connect_settings => { 'PGHOST' => 'postgres-db-server', - 'DBVERSION' => '9.1', - 'PGPORT' => '1234', }, + db: 'test', + role: 'test', + connect_settings: { 'PGHOST' => 'postgres-db-server', + 'DBVERSION' => '9.1', + 'PGPORT' => '1234' }, } end let :pre_condition do "class {'postgresql::server':}" end it { is_expected.to contain_postgresql__server__grant('test') } - it { is_expected.to contain_postgresql_psql("grant:test").with_connect_settings( { 'PGHOST' => 'postgres-db-server','DBVERSION' => '9.1','PGPORT' => '1234' } ) } + it { is_expected.to contain_postgresql_psql('grant:test').with_connect_settings('PGHOST' => 'postgres-db-server', 'DBVERSION' => '9.1', 'PGPORT' => '1234') } end - context "with specific db connection settings - port overriden by explicit parameter" do + context 'with specific db connection settings - port overriden by explicit parameter' do let :params do { - :db => 'test', - :role => 'test', - :connect_settings => { 'PGHOST' => 'postgres-db-server', - 'DBVERSION' => '9.1', - 'PGPORT' => '1234', }, - :port => 5678, + db: 'test', + role: 'test', + connect_settings: { 'PGHOST' => 'postgres-db-server', + 'DBVERSION' => '9.1', + 'PGPORT' => '1234' }, + port: 5678, } end let :pre_condition do "class {'postgresql::server':}" end it { is_expected.to contain_postgresql__server__grant('test') } - it { is_expected.to contain_postgresql_psql("grant:test").with_connect_settings( { 'PGHOST' => 'postgres-db-server','DBVERSION' => '9.1','PGPORT' => '1234' } ).with_port( '5678' ) } + it { is_expected.to contain_postgresql_psql('grant:test').with_connect_settings('PGHOST' => 'postgres-db-server', 'DBVERSION' => '9.1', 'PGPORT' => '1234').with_port('5678') } end context 'with specific schema name' do let :params do { - :db => 'test', - :role => 'test', - :privilege => 'all', - :object_name => ['myschema', 'mytable'], - :object_type => 'table', + db: 'test', + role: 'test', + privilege: 'all', + object_name: %w[myschema mytable], + object_type: 'table', } end let :pre_condition do "class {'postgresql::server':}" end it { is_expected.to contain_postgresql__server__grant('test') } - it { is_expected.to contain_postgresql_psql('grant:test').with( - { - 'command' => /GRANT ALL ON TABLE "myschema"."mytable" TO\s* "test"/m, - 'unless' => /SELECT 1 WHERE has_table_privilege\('test',\s*'myschema.mytable', 'INSERT'\)/m, - } - ) } + it { + is_expected.to contain_postgresql_psql('grant:test').with( + 'command' => %r{GRANT ALL ON TABLE "myschema"."mytable" TO\s* "test"}m, + 'unless' => %r{SELECT 1 WHERE has_table_privilege\('test',\s*'myschema.mytable', 'INSERT'\)}m, + ) + } end context 'invalid object_type' do let :params do { - :db => 'test', - :role => 'test', - :privilege => 'usage', - :object_type => 'invalid', + db: 'test', + role: 'test', + privilege: 'usage', + object_type: 'invalid', } end let :pre_condition do "class {'postgresql::server':}" end - it { is_expected.to compile.and_raise_error(/parameter 'object_type' expects a match for Pattern/) } + it { is_expected.to compile.and_raise_error(%r{parameter 'object_type' expects a match for Pattern}) } end context 'invalid object_name - wrong type' do let :params do { - :db => 'test', - :role => 'test', - :privilege => 'all', - :object_name => 1, - :object_type => 'table', + db: 'test', + role: 'test', + privilege: 'all', + object_name: 1, + object_type: 'table', } end let :pre_condition do "class {'postgresql::server':}" end - it { is_expected.to compile.and_raise_error(/parameter 'object_name' expects a value of type (Array|Undef, Array,) or String, got Integer/) } + it { is_expected.to compile.and_raise_error(%r{parameter 'object_name' expects a value of type (Array|Undef, Array,) or String, got Integer}) } end context 'invalid object_name - insufficent array elements' do let :params do { - :db => 'test', - :role => 'test', - :privilege => 'all', - :object_name => ['oops'], - :object_type => 'table', + db: 'test', + role: 'test', + privilege: 'all', + object_name: ['oops'], + object_type: 'table', } end let :pre_condition do "class {'postgresql::server':}" end if Puppet::Util::Package.versioncmp(Puppet.version, '5.2.0') >= 0 - it { is_expected.to compile.and_raise_error(/parameter 'object_name' variant 1 expects size to be 2, got 1/) } + it { is_expected.to compile.and_raise_error(%r{parameter 'object_name' variant 1 expects size to be 2, got 1}) } else - it { is_expected.to compile.and_raise_error(/parameter 'object_name' variant 0 expects size to be 2, got 1/) } + it { is_expected.to compile.and_raise_error(%r{parameter 'object_name' variant 0 expects size to be 2, got 1}) } end end context 'invalid object_name - too many array elements' do let :params do { - :db => 'test', - :role => 'test', - :privilege => 'all', - :object_name => ['myschema', 'mytable', 'oops'], - :object_type => 'table', + db: 'test', + role: 'test', + privilege: 'all', + object_name: %w[myschema mytable oops], + object_type: 'table', } end let :pre_condition do "class {'postgresql::server':}" end if Puppet::Util::Package.versioncmp(Puppet.version, '5.2.0') >= 0 - it { is_expected.to compile.and_raise_error(/parameter 'object_name' variant 1 expects size to be 2, got 3/) } + it { is_expected.to compile.and_raise_error(%r{parameter 'object_name' variant 1 expects size to be 2, got 3}) } else - it { is_expected.to compile.and_raise_error(/parameter 'object_name' variant 0 expects size to be 2, got 3/) } + it { is_expected.to compile.and_raise_error(%r{parameter 'object_name' variant 0 expects size to be 2, got 3}) } end end end diff --git a/spec/unit/defines/server/pg_hba_rule_spec.rb b/spec/unit/defines/server/pg_hba_rule_spec.rb index 24ead07..44b854c 100644 --- a/spec/unit/defines/server/pg_hba_rule_spec.rb +++ b/spec/unit/defines/server/pg_hba_rule_spec.rb @@ -1,156 +1,148 @@ require 'spec_helper' -describe 'postgresql::server::pg_hba_rule', :type => :define do +describe 'postgresql::server::pg_hba_rule', type: :define do let :facts do { - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => '6.0', - :kernel => 'Linux', - :concat_basedir => tmpfilename('pg_hba'), - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: '6.0', + kernel: 'Linux', + concat_basedir: tmpfilename('pg_hba'), + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', } end let :title do 'test' end let :target do tmpfilename('pg_hba_rule') end context 'test template 1' do let :pre_condition do - <<-EOS + <<-MANIFEST class { 'postgresql::server': } - EOS + MANIFEST end let :params do { - :type => 'host', - :database => 'all', - :user => 'all', - :address => '1.1.1.1/24', - :auth_method => 'md5', - :target => target, + type: 'host', + database: 'all', + user: 'all', + address: '1.1.1.1/24', + auth_method: 'md5', + target: target, } end + it do - is_expected.to contain_concat__fragment('pg_hba_rule_test').with({ - :content => /host\s+all\s+all\s+1\.1\.1\.1\/24\s+md5/ - }) + is_expected.to contain_concat__fragment('pg_hba_rule_test').with(content: %r{host\s+all\s+all\s+1\.1\.1\.1\/24\s+md5}) end end context 'test template 2' do let :pre_condition do - <<-EOS + <<-MANIFEST class { 'postgresql::server': } - EOS + MANIFEST end let :params do { - :type => 'local', - :database => 'all', - :user => 'all', - :auth_method => 'ident', - :target => target, + type: 'local', + database: 'all', + user: 'all', + auth_method: 'ident', + target: target, } end + it do - is_expected.to contain_concat__fragment('pg_hba_rule_test').with({ - :content => /local\s+all\s+all\s+ident/ - }) + is_expected.to contain_concat__fragment('pg_hba_rule_test').with(content: %r{local\s+all\s+all\s+ident}) end end context 'test template 3' do let :pre_condition do - <<-EOS + <<-MANIFEST class { 'postgresql::server': } - EOS + MANIFEST end let :params do { - :type => 'host', - :database => 'all', - :user => 'all', - :address => '0.0.0.0/0', - :auth_method => 'ldap', - :auth_option => 'foo=bar', - :target => target, + type: 'host', + database: 'all', + user: 'all', + address: '0.0.0.0/0', + auth_method: 'ldap', + auth_option: 'foo=bar', + target: target, } end + it do - is_expected.to contain_concat__fragment('pg_hba_rule_test').with({ - :content => /host\s+all\s+all\s+0\.0\.0\.0\/0\s+ldap\s+foo=bar/ - }) + is_expected.to contain_concat__fragment('pg_hba_rule_test').with(content: %r{host\s+all\s+all\s+0\.0\.0\.0\/0\s+ldap\s+foo=bar}) end end context 'validation' do context 'validate supported auth_method' do let :pre_condition do - <<-EOS + <<-MANIFEST class { 'postgresql::globals': version => '9.2', } class { 'postgresql::server': } - EOS + MANIFEST end let :params do { - :type => 'local', - :database => 'all', - :user => 'all', - :address => '0.0.0.0/0', - :auth_method => 'peer', - :target => target, + type: 'local', + database: 'all', + user: 'all', + address: '0.0.0.0/0', + auth_method: 'peer', + target: target, } end it do is_expected.to contain_concat__fragment('pg_hba_rule_test').with( - { - :content => /local\s+all\s+all\s+0\.0\.0\.0\/0\s+peer/ - } + content: %r{local\s+all\s+all\s+0\.0\.0\.0\/0\s+peer}, ) end end context 'allows scram-sha-256 on postgres 10' do let :pre_condition do - <<-EOS + <<-MANIFEST class { 'postgresql::globals': version => '10', } class { 'postgresql::server': } - EOS + MANIFEST end let :params do { - :type => 'local', - :database => 'all', - :user => 'all', - :address => '0.0.0.0/0', - :auth_method => 'scram-sha-256', - :target => target, + type: 'local', + database: 'all', + user: 'all', + address: '0.0.0.0/0', + auth_method: 'scram-sha-256', + target: target, } end it do is_expected.to contain_concat__fragment('pg_hba_rule_test').with( - { - :content => /local\s+all\s+all\s+0\.0\.0\.0\/0\s+scram-sha-256/ - } + content: %r{local\s+all\s+all\s+0\.0\.0\.0\/0\s+scram-sha-256}, ) end end - end end diff --git a/spec/unit/defines/server/pg_ident_rule_spec.rb b/spec/unit/defines/server/pg_ident_rule_spec.rb index 71dfff8..68bdfb2 100644 --- a/spec/unit/defines/server/pg_ident_rule_spec.rb +++ b/spec/unit/defines/server/pg_ident_rule_spec.rb @@ -1,66 +1,66 @@ require 'spec_helper' -describe 'postgresql::server::pg_ident_rule', :type => :define do +describe 'postgresql::server::pg_ident_rule', type: :define do let :facts do { - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => '6.0', - :kernel => 'Linux', - :concat_basedir => tmpfilename('pg_ident'), - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: '6.0', + kernel: 'Linux', + concat_basedir: tmpfilename('pg_ident'), + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', } end let :title do 'test' end let :target do tmpfilename('pg_ident_rule') end context 'managing pg_ident' do let :pre_condition do - <<-EOS + <<-MANIFEST class { 'postgresql::globals': manage_pg_ident_conf => true, } class { 'postgresql::server': } - EOS + MANIFEST end let :params do { - :map_name => 'thatsmymap', - :system_username => 'systemuser', - :database_username => 'dbuser', + map_name: 'thatsmymap', + system_username: 'systemuser', + database_username: 'dbuser', } end + it do - is_expected.to contain_concat__fragment('pg_ident_rule_test').with({ - :content => /thatsmymap\s+systemuser\s+dbuser/ - }) + is_expected.to contain_concat__fragment('pg_ident_rule_test').with(content: %r{thatsmymap\s+systemuser\s+dbuser}) end end context 'not managing pg_ident' do let :pre_condition do - <<-EOS + <<-MANIFEST class { 'postgresql::globals': manage_pg_ident_conf => false, } class { 'postgresql::server': } - EOS + MANIFEST end let :params do { - :map_name => 'thatsmymap', - :system_username => 'systemuser', - :database_username => 'dbuser', + map_name: 'thatsmymap', + system_username: 'systemuser', + database_username: 'dbuser', } end - it 'should fail because $manage_pg_ident_conf is false' do + + it 'fails because $manage_pg_ident_conf is false' do expect { catalogue }.to raise_error(Puppet::Error, - /postgresql::server::manage_pg_ident_conf has been disabled/) + %r{postgresql::server::manage_pg_ident_conf has been disabled}) end end end diff --git a/spec/unit/defines/server/reassign_owned_by_spec.rb b/spec/unit/defines/server/reassign_owned_by_spec.rb index 72f67c3..1c8bd9f 100644 --- a/spec/unit/defines/server/reassign_owned_by_spec.rb +++ b/spec/unit/defines/server/reassign_owned_by_spec.rb @@ -1,44 +1,43 @@ require 'spec_helper' -describe 'postgresql::server::reassign_owned_by', :type => :define do +describe 'postgresql::server::reassign_owned_by', type: :define do let :facts do { - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => '6.0', - :kernel => 'Linux', - :concat_basedir => tmpfilename('reassign_owned_by'), - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: '6.0', + kernel: 'Linux', + concat_basedir: tmpfilename('reassign_owned_by'), + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', } end let :title do 'test' end let :params do { - :db => 'test', - :old_role => 'test_old_role', - :new_role => 'test_new_role', + db: 'test', + old_role: 'test_old_role', + new_role: 'test_new_role', } end let :pre_condition do - <<-EOS + <<-MANIFEST class {'postgresql::server':} postgresql::server::role{ ['test_old_role','test_new_role']: } - EOS + MANIFEST end it { is_expected.to contain_postgresql__server__reassign_owned_by('test') } it { - is_expected.to contain_postgresql_psql('reassign_owned_by:test:REASSIGN OWNED BY "test_old_role" TO "test_new_role"').with({ - 'command' => "REASSIGN OWNED BY \"test_old_role\" TO \"test_new_role\"", - 'onlyif' => /SELECT tablename FROM pg_catalog.pg_tables WHERE\s*schemaname NOT IN \('pg_catalog', 'information_schema'\) AND\s*tableowner = 'test_old_role'.*/m, - }).that_requires('Class[postgresql::server]') + is_expected.to contain_postgresql_psql('reassign_owned_by:test:REASSIGN OWNED BY "test_old_role" TO "test_new_role"') + .with('command' => 'REASSIGN OWNED BY "test_old_role" TO "test_new_role"', + 'onlyif' => %r{SELECT tablename FROM pg_catalog.pg_tables WHERE\s*schemaname NOT IN \('pg_catalog', 'information_schema'\) AND\s*tableowner = 'test_old_role'.*}m) + .that_requires('Class[postgresql::server]') } - end diff --git a/spec/unit/defines/server/recovery_spec.rb b/spec/unit/defines/server/recovery_spec.rb index 8c78e3e..25bc132 100644 --- a/spec/unit/defines/server/recovery_spec.rb +++ b/spec/unit/defines/server/recovery_spec.rb @@ -1,113 +1,115 @@ require 'spec_helper' -describe 'postgresql::server::recovery', :type => :define do +describe 'postgresql::server::recovery', type: :define do let :facts do { - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => '6.0', - :kernel => 'Linux', - :concat_basedir => tmpfilename('recovery'), - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: '6.0', + kernel: 'Linux', + concat_basedir: tmpfilename('recovery'), + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', } end - let :title do + let(:title) do 'test' end let :target do tmpfilename('recovery') end context 'managing recovery' do - let :pre_condition do - <<-EOS + let(:pre_condition) do + <<-MANIFEST class { 'postgresql::globals': manage_recovery_conf => true, } class { 'postgresql::server': } - EOS + MANIFEST end - let :params do + let(:params) do { - :restore_command => 'restore_command', - :recovery_target_timeline => 'recovery_target_timeline', + restore_command: 'restore_command', + recovery_target_timeline: 'recovery_target_timeline', } end + it do - is_expected.to contain_concat__fragment('recovery.conf').with({ - :content => /restore_command = 'restore_command'[\n]+recovery_target_timeline = 'recovery_target_timeline'/ - }) + is_expected.to contain_concat__fragment('recovery.conf') + .with(content: %r{restore_command = 'restore_command'[\n]+recovery_target_timeline = 'recovery_target_timeline'}) end end context 'not managing recovery' do - let :pre_condition do - <<-EOS + let(:pre_condition) do + <<-MANIFEST class { 'postgresql::globals': manage_recovery_conf => false, } class { 'postgresql::server': } - EOS + MANIFEST end - let :params do + let(:params) do { - :restore_command => '', + restore_command: '', } end - it 'should fail because $manage_recovery_conf is false' do + + it 'fails because $manage_recovery_conf is false' do expect { catalogue }.to raise_error(Puppet::Error, - /postgresql::server::manage_recovery_conf has been disabled/) + %r{postgresql::server::manage_recovery_conf has been disabled}) end end context 'not managing recovery, missing param' do - let :pre_condition do - <<-EOS + let(:pre_condition) do + <<-MANIFEST class { 'postgresql::globals': manage_recovery_conf => true, } class { 'postgresql::server': } - EOS + MANIFEST end - it 'should fail because no param set' do + + it 'fails because no param set' do expect { catalogue }.to raise_error(Puppet::Error, - /postgresql::server::recovery use this resource but do not pass a parameter will avoid creating the recovery.conf, because it makes no sense./) + %r{postgresql::server::recovery use this resource but do not pass a parameter will avoid creating the recovery.conf, because it makes no sense.}) end end context 'managing recovery with all params' do - let :pre_condition do - <<-EOS + let(:pre_condition) do + <<-MANIFEST class { 'postgresql::globals': manage_recovery_conf => true, } class { 'postgresql::server': } - EOS + MANIFEST end - let :params do + let(:params) do { - :restore_command => 'restore_command', - :archive_cleanup_command => 'archive_cleanup_command', - :recovery_end_command => 'recovery_end_command', - :recovery_target_name => 'recovery_target_name', - :recovery_target_time => 'recovery_target_time', - :recovery_target_xid => 'recovery_target_xid', - :recovery_target_inclusive => true, - :recovery_target => 'recovery_target', - :recovery_target_timeline => 'recovery_target_timeline', - :pause_at_recovery_target => true, - :standby_mode => 'on', - :primary_conninfo => 'primary_conninfo', - :primary_slot_name => 'primary_slot_name', - :trigger_file => 'trigger_file', - :recovery_min_apply_delay => 0, + restore_command: 'restore_command', + archive_cleanup_command: 'archive_cleanup_command', + recovery_end_command: 'recovery_end_command', + recovery_target_name: 'recovery_target_name', + recovery_target_time: 'recovery_target_time', + recovery_target_xid: 'recovery_target_xid', + recovery_target_inclusive: true, + recovery_target: 'recovery_target', + recovery_target_timeline: 'recovery_target_timeline', + pause_at_recovery_target: true, + standby_mode: 'on', + primary_conninfo: 'primary_conninfo', + primary_slot_name: 'primary_slot_name', + trigger_file: 'trigger_file', + recovery_min_apply_delay: 0, } end + it do - is_expected.to contain_concat__fragment('recovery.conf').with({ - :content => /restore_command = 'restore_command'[\n]+archive_cleanup_command = 'archive_cleanup_command'[\n]+recovery_end_command = 'recovery_end_command'[\n]+recovery_target_name = 'recovery_target_name'[\n]+recovery_target_time = 'recovery_target_time'[\n]+recovery_target_xid = 'recovery_target_xid'[\n]+recovery_target_inclusive = true[\n]+recovery_target = 'recovery_target'[\n]+recovery_target_timeline = 'recovery_target_timeline'[\n]+pause_at_recovery_target = true[\n]+standby_mode = on[\n]+primary_conninfo = 'primary_conninfo'[\n]+primary_slot_name = 'primary_slot_name'[\n]+trigger_file = 'trigger_file'[\n]+recovery_min_apply_delay = 0[\n]+/ - }) + is_expected.to contain_concat__fragment('recovery.conf') + .with(content: %r{restore_command = 'restore_command'[\n]+archive_cleanup_command = 'archive_cleanup_command'[\n]+recovery_end_command = 'recovery_end_command'[\n]+recovery_target_name = 'recovery_target_name'[\n]+recovery_target_time = 'recovery_target_time'[\n]+recovery_target_xid = 'recovery_target_xid'[\n]+recovery_target_inclusive = true[\n]+recovery_target = 'recovery_target'[\n]+recovery_target_timeline = 'recovery_target_timeline'[\n]+pause_at_recovery_target = true[\n]+standby_mode = on[\n]+primary_conninfo = 'primary_conninfo'[\n]+primary_slot_name = 'primary_slot_name'[\n]+trigger_file = 'trigger_file'[\n]+recovery_min_apply_delay = 0[\n]+}) # rubocop:disable Metrics/LineLength end end end diff --git a/spec/unit/defines/server/role_spec.rb b/spec/unit/defines/server/role_spec.rb index 1b061d0..1cd2ca9 100644 --- a/spec/unit/defines/server/role_spec.rb +++ b/spec/unit/defines/server/role_spec.rb @@ -1,152 +1,143 @@ require 'spec_helper' -describe 'postgresql::server::role', :type => :define do +describe 'postgresql::server::role', type: :define do let :facts do { - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => '6.0', - :kernel => 'Linux', - :concat_basedir => tmpfilename('contrib'), - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: '6.0', + kernel: 'Linux', + concat_basedir: tmpfilename('contrib'), + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', } end let :title do 'test' end let :params do { - :password_hash => 'new-pa$s', + password_hash: 'new-pa$s', } end let :pre_condition do - "class {'postgresql::server':}" + "class {'postgresql::server':}" end it { is_expected.to contain_postgresql__server__role('test') } - it 'should have create role for "test" user with password as ****' do - is_expected.to contain_postgresql_psql('CREATE ROLE test ENCRYPTED PASSWORD ****').with({ - 'command' => "CREATE ROLE \"test\" ENCRYPTED PASSWORD '$NEWPGPASSWD' LOGIN NOCREATEROLE NOCREATEDB NOSUPERUSER CONNECTION LIMIT -1", - 'environment' => "NEWPGPASSWD=new-pa$s", - 'unless' => "SELECT 1 FROM pg_roles WHERE rolname = 'test'", - 'port' => "5432", - }) + it 'has create role for "test" user with password as ****' do + is_expected.to contain_postgresql_psql('CREATE ROLE test ENCRYPTED PASSWORD ****') + .with('command' => "CREATE ROLE \"test\" ENCRYPTED PASSWORD '$NEWPGPASSWD' LOGIN NOCREATEROLE NOCREATEDB NOSUPERUSER CONNECTION LIMIT -1", + 'environment' => 'NEWPGPASSWD=new-pa$s', + 'unless' => "SELECT 1 FROM pg_roles WHERE rolname = 'test'", + 'port' => '5432') end - it 'should have alter role for "test" user with password as ****' do - is_expected.to contain_postgresql_psql('ALTER ROLE test ENCRYPTED PASSWORD ****').with({ - 'command' => "ALTER ROLE \"test\" ENCRYPTED PASSWORD '$NEWPGPASSWD'", - 'environment' => "NEWPGPASSWD=new-pa$s", - 'unless' => "SELECT 1 FROM pg_shadow WHERE usename = 'test' AND passwd = 'md5b6f7fcbbabb4befde4588a26c1cfd2fa'", - 'port' => "5432", - }) + it 'has alter role for "test" user with password as ****' do + is_expected.to contain_postgresql_psql('ALTER ROLE test ENCRYPTED PASSWORD ****') + .with('command' => "ALTER ROLE \"test\" ENCRYPTED PASSWORD '$NEWPGPASSWD'", + 'environment' => 'NEWPGPASSWD=new-pa$s', + 'unless' => "SELECT 1 FROM pg_shadow WHERE usename = 'test' AND passwd = 'md5b6f7fcbbabb4befde4588a26c1cfd2fa'", + 'port' => '5432') end - context "with specific db connection settings - default port" do + context 'with specific db connection settings - default port' do let :params do { - :password_hash => 'new-pa$s', - :connect_settings => { 'PGHOST' => 'postgres-db-server', - 'DBVERSION' => '9.1', - 'PGUSER' => 'login-user', - 'PGPASSWORD' => 'login-pass' }, + password_hash: 'new-pa$s', + connect_settings: { 'PGHOST' => 'postgres-db-server', + 'DBVERSION' => '9.1', + 'PGUSER' => 'login-user', + 'PGPASSWORD' => 'login-pass' }, } end let :pre_condition do - "class {'postgresql::server':}" + "class {'postgresql::server':}" end it { is_expected.to contain_postgresql__server__role('test') } - it 'should have create role for "test" user with password as ****' do - is_expected.to contain_postgresql_psql('CREATE ROLE test ENCRYPTED PASSWORD ****').with({ - 'command' => "CREATE ROLE \"test\" ENCRYPTED PASSWORD '$NEWPGPASSWD' LOGIN NOCREATEROLE NOCREATEDB NOSUPERUSER CONNECTION LIMIT -1", - 'environment' => "NEWPGPASSWD=new-pa$s", - 'unless' => "SELECT 1 FROM pg_roles WHERE rolname = 'test'", - 'port' => "5432", - - 'connect_settings' => { 'PGHOST' => 'postgres-db-server', - 'DBVERSION' => '9.1', - 'PGUSER' => 'login-user', - 'PGPASSWORD' => 'login-pass' }, - }) + it 'has create role for "test" user with password as ****' do + is_expected.to contain_postgresql_psql('CREATE ROLE test ENCRYPTED PASSWORD ****') + .with('command' => "CREATE ROLE \"test\" ENCRYPTED PASSWORD '$NEWPGPASSWD' LOGIN NOCREATEROLE NOCREATEDB NOSUPERUSER CONNECTION LIMIT -1", 'environment' => 'NEWPGPASSWD=new-pa$s', + 'unless' => "SELECT 1 FROM pg_roles WHERE rolname = 'test'", 'port' => '5432', + 'connect_settings' => { 'PGHOST' => 'postgres-db-server', 'DBVERSION' => '9.1', + 'PGUSER' => 'login-user', 'PGPASSWORD' => 'login-pass' }) end - it 'should have alter role for "test" user with password as ****' do - is_expected.to contain_postgresql_psql('ALTER ROLE test ENCRYPTED PASSWORD ****').with({ - 'command' => "ALTER ROLE \"test\" ENCRYPTED PASSWORD '$NEWPGPASSWD'", - 'environment' => "NEWPGPASSWD=new-pa$s", - 'unless' => "SELECT 1 FROM pg_shadow WHERE usename = 'test' AND passwd = 'md5b6f7fcbbabb4befde4588a26c1cfd2fa'", - 'port' => "5432", - - 'connect_settings' => { 'PGHOST' => 'postgres-db-server', - 'DBVERSION' => '9.1', - 'PGUSER' => 'login-user', - 'PGPASSWORD' => 'login-pass' }, - }) + it 'has alter role for "test" user with password as ****' do + is_expected.to contain_postgresql_psql('ALTER ROLE test ENCRYPTED PASSWORD ****') + .with('command' => "ALTER ROLE \"test\" ENCRYPTED PASSWORD '$NEWPGPASSWD'", 'environment' => 'NEWPGPASSWD=new-pa$s', + 'unless' => "SELECT 1 FROM pg_shadow WHERE usename = 'test' AND passwd = 'md5b6f7fcbbabb4befde4588a26c1cfd2fa'", 'port' => '5432', + 'connect_settings' => { 'PGHOST' => 'postgres-db-server', 'DBVERSION' => '9.1', + 'PGUSER' => 'login-user', 'PGPASSWORD' => 'login-pass' }) end end - context "with specific db connection settings - including port" do + context 'with specific db connection settings - including port' do let :params do { - :password_hash => 'new-pa$s', - :connect_settings => { 'PGHOST' => 'postgres-db-server', - 'DBVERSION' => '9.1', - 'PGPORT' => '1234', - 'PGUSER' => 'login-user', - 'PGPASSWORD' => 'login-pass' }, + password_hash: 'new-pa$s', + connect_settings: { 'PGHOST' => 'postgres-db-server', + 'DBVERSION' => '9.1', + 'PGPORT' => '1234', + 'PGUSER' => 'login-user', + 'PGPASSWORD' => 'login-pass' }, } end let :pre_condition do - "class {'postgresql::server':}" + "class {'postgresql::server':}" end it { is_expected.to contain_postgresql__server__role('test') } - it 'should have create role for "test" user with password as ****' do - is_expected.to contain_postgresql_psql('CREATE ROLE test ENCRYPTED PASSWORD ****').with({ - 'command' => "CREATE ROLE \"test\" ENCRYPTED PASSWORD '$NEWPGPASSWD' LOGIN NOCREATEROLE NOCREATEDB NOSUPERUSER CONNECTION LIMIT -1", - 'environment' => "NEWPGPASSWD=new-pa$s", - 'unless' => "SELECT 1 FROM pg_roles WHERE rolname = 'test'", - 'connect_settings' => { 'PGHOST' => 'postgres-db-server', - 'DBVERSION' => '9.1', - 'PGPORT' => '1234', - 'PGUSER' => 'login-user', - 'PGPASSWORD' => 'login-pass' }, - }) + it 'has create role for "test" user with password as ****' do + is_expected.to contain_postgresql_psql('CREATE ROLE test ENCRYPTED PASSWORD ****') + .with('command' => "CREATE ROLE \"test\" ENCRYPTED PASSWORD '$NEWPGPASSWD' LOGIN NOCREATEROLE NOCREATEDB NOSUPERUSER CONNECTION LIMIT -1", + 'environment' => 'NEWPGPASSWD=new-pa$s', 'unless' => "SELECT 1 FROM pg_roles WHERE rolname = 'test'", + 'connect_settings' => { 'PGHOST' => 'postgres-db-server', 'DBVERSION' => '9.1', + 'PGPORT' => '1234', 'PGUSER' => 'login-user', 'PGPASSWORD' => 'login-pass' }) end - it 'should have alter role for "test" user with password as ****' do - is_expected.to contain_postgresql_psql('ALTER ROLE test ENCRYPTED PASSWORD ****').with({ - 'command' => "ALTER ROLE \"test\" ENCRYPTED PASSWORD '$NEWPGPASSWD'", - 'environment' => "NEWPGPASSWD=new-pa$s", - 'unless' => "SELECT 1 FROM pg_shadow WHERE usename = 'test' AND passwd = 'md5b6f7fcbbabb4befde4588a26c1cfd2fa'", - 'connect_settings' => { 'PGHOST' => 'postgres-db-server', - 'DBVERSION' => '9.1', - 'PGPORT' => '1234', - 'PGUSER' => 'login-user', - 'PGPASSWORD' => 'login-pass' }, - }) + it 'has alter role for "test" user with password as ****' do + is_expected.to contain_postgresql_psql('ALTER ROLE test ENCRYPTED PASSWORD ****') + .with('command' => "ALTER ROLE \"test\" ENCRYPTED PASSWORD '$NEWPGPASSWD'", 'environment' => 'NEWPGPASSWD=new-pa$s', + 'unless' => "SELECT 1 FROM pg_shadow WHERE usename = 'test' AND passwd = 'md5b6f7fcbbabb4befde4588a26c1cfd2fa'", + 'connect_settings' => { 'PGHOST' => 'postgres-db-server', 'DBVERSION' => '9.1', + 'PGPORT' => '1234', 'PGUSER' => 'login-user', 'PGPASSWORD' => 'login-pass' }) end end context 'with update_password set to false' do let :params do { - :password_hash => 'new-pa$s', - :update_password => false, + password_hash: 'new-pa$s', + update_password: false, } end let :pre_condition do "class {'postgresql::server':}" end - it 'should not have alter role for "test" user with password as **** if update_password is false' do + it 'does not have alter role for "test" user with password as **** if update_password is false' do is_expected.not_to contain_postgresql_psql('ALTER ROLE test ENCRYPTED PASSWORD ****') end end + context 'with ensure set to absent' do + let :params do + { + ensure: 'absent', + } + end + + let :pre_condition do + "class {'postgresql::server':}" + end + + it 'has drop role for "test" user if ensure absent' do + is_expected.to contain_postgresql_psql('DROP ROLE "test"') + end + end end diff --git a/spec/unit/defines/server/schema_spec.rb b/spec/unit/defines/server/schema_spec.rb index c8fa3d9..a87f3dc 100644 --- a/spec/unit/defines/server/schema_spec.rb +++ b/spec/unit/defines/server/schema_spec.rb @@ -1,43 +1,43 @@ require 'spec_helper' -describe 'postgresql::server::schema', :type => :define do +describe 'postgresql::server::schema', type: :define do let :facts do { - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => '6.0', - :kernel => 'Linux', - :concat_basedir => tmpfilename('schema'), - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: '6.0', + kernel: 'Linux', + concat_basedir: tmpfilename('schema'), + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', } end let :title do 'test' end let :params do { - :owner => 'jane', - :db => 'janedb', + owner: 'jane', + db: 'janedb', } end let :pre_condition do "class {'postgresql::server':}" end - it { should contain_postgresql__server__schema('test') } + it { is_expected.to contain_postgresql__server__schema('test') } - context "with different owner" do + context 'with different owner' do let :params do { - :owner => 'nate', - :db => 'natedb', + owner: 'nate', + db: 'natedb', } end it { is_expected.to contain_postgresql_psql('natedb: ALTER SCHEMA "test" OWNER TO "nate"') } end end diff --git a/spec/unit/defines/server/table_grant_spec.rb b/spec/unit/defines/server/table_grant_spec.rb index eac55bd..4314eb2 100644 --- a/spec/unit/defines/server/table_grant_spec.rb +++ b/spec/unit/defines/server/table_grant_spec.rb @@ -1,35 +1,35 @@ require 'spec_helper' -describe 'postgresql::server::table_grant', :type => :define do +describe 'postgresql::server::table_grant', type: :define do let :facts do { - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => '6.0', - :kernel => 'Linux', - :concat_basedir => tmpfilename('table_grant'), - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: '6.0', + kernel: 'Linux', + concat_basedir: tmpfilename('table_grant'), + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', } end let :title do 'test' end let :params do { - :privilege => 'ALL', - :db => 'test', - :role => 'test', - :table => 'foo', + privilege: 'ALL', + db: 'test', + role: 'test', + table: 'foo', } end let :pre_condition do "class {'postgresql::server':}" end it { is_expected.to contain_postgresql__server__table_grant('test') } it { is_expected.to contain_postgresql__server__grant('table:test') } end diff --git a/spec/unit/defines/server/tablespace_spec.rb b/spec/unit/defines/server/tablespace_spec.rb index 50a93e2..96285d5 100644 --- a/spec/unit/defines/server/tablespace_spec.rb +++ b/spec/unit/defines/server/tablespace_spec.rb @@ -1,42 +1,42 @@ require 'spec_helper' -describe 'postgresql::server::tablespace', :type => :define do +describe 'postgresql::server::tablespace', type: :define do let :facts do { - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => '6.0', - :kernel => 'Linux', - :concat_basedir => tmpfilename('tablespace'), - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: '6.0', + kernel: 'Linux', + concat_basedir: tmpfilename('tablespace'), + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', } end let :title do 'test' end let :params do { - :location => '/srv/data/foo', + location: '/srv/data/foo', } end let :pre_condition do "class {'postgresql::server':}" end it { is_expected.to contain_postgresql__server__tablespace('test') } - context "with different owner" do + context 'with different owner' do let :params do { - :location => '/srv/data/foo', - :owner => 'test_owner', + location: '/srv/data/foo', + owner: 'test_owner', } end it { is_expected.to contain_postgresql_psql('ALTER TABLESPACE "test" OWNER TO "test_owner"') } end end diff --git a/spec/unit/defines/validate_db_connection_spec.rb b/spec/unit/defines/validate_db_connection_spec.rb index c7406dc..243c591 100644 --- a/spec/unit/defines/validate_db_connection_spec.rb +++ b/spec/unit/defines/validate_db_connection_spec.rb @@ -1,72 +1,66 @@ require 'spec_helper' -describe 'postgresql::validate_db_connection', :type => :define do +describe 'postgresql::validate_db_connection', type: :define do let :facts do { - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => '6.0', + osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: '6.0', } end let :title do 'test' end describe 'should work with only default parameters' do it { is_expected.to contain_postgresql__validate_db_connection('test') } end describe 'should work with all parameters' do let :params do { - :database_host => 'test', - :database_name => 'test', - :database_password => 'test', - :database_username => 'test', - :database_port => 5432, - :run_as => 'postgresq', - :sleep => 4, - :tries => 30, + database_host: 'test', + database_name: 'test', + database_password: 'test', + database_username: 'test', + database_port: 5432, + run_as: 'postgresq', + sleep: 4, + tries: 30, } end + it { is_expected.to contain_postgresql__validate_db_connection('test') } - it 'should have proper path for validate command' do - is_expected.to contain_exec('validate postgres connection for test@test:5432/test').with({ - :unless => %r'^/usr/local/bin/validate_postgresql_connection.sh\s+\d+' - }) + it 'has proper path for validate command' do + is_expected.to contain_exec('validate postgres connection for test@test:5432/test').with(unless: %r{^/usr/local/bin/validate_postgresql_connection.sh\s+\d+}) end end describe 'should work while specifying validate_connection in postgresql::client' do - let :params do { - :database_host => 'test', - :database_name => 'test', - :database_password => 'test', - :database_username => 'test', - :database_port => 5432 + database_host: 'test', + database_name: 'test', + database_password: 'test', + database_username: 'test', + database_port: 5432, } end let :pre_condition do - <<-EOS + <<-MANIFEST class { 'postgresql::globals': module_workdir => '/var/tmp', } -> class { 'postgresql::client': validcon_script_path => '/opt/something/validate.sh' } - EOS - end - - it 'should have proper path for validate command and correct cwd' do - is_expected.to contain_exec('validate postgres connection for test@test:5432/test').with({ - :unless => %r'^/opt/something/validate.sh\s+\d+', - :cwd => '/var/tmp', - }) + MANIFEST end + it 'has proper path for validate command and correct cwd' do + is_expected.to contain_exec('validate postgres connection for test@test:5432/test').with(unless: %r{^/opt/something/validate.sh\s+\d+}, + cwd: '/var/tmp') + end end - end diff --git a/spec/unit/functions/postgresql_acls_to_resources_hash_spec.rb b/spec/unit/functions/postgresql_acls_to_resources_hash_spec.rb index e21b521..76df663 100644 --- a/spec/unit/functions/postgresql_acls_to_resources_hash_spec.rb +++ b/spec/unit/functions/postgresql_acls_to_resources_hash_spec.rb @@ -1,137 +1,74 @@ require 'spec_helper' -describe 'postgresql_acls_to_resources_hash', :type => :puppet_function do +describe 'postgresql_acls_to_resources_hash', type: :puppet_function do context 'individual transform tests' do it do input = 'local all postgres ident' - result = { - "postgresql class generated rule test 0"=>{ - "type"=>"local", - "database"=>"all", - "user"=>"postgres", - "auth_method"=>"ident", - "order"=>"100", - }, - } + result = { 'postgresql class generated rule test 0' => { 'type' => 'local', 'database' => 'all', 'user' => 'postgres', + 'auth_method' => 'ident', 'order' => '100' } } is_expected.to run.with_params([input], 'test', 100).and_return(result) end it do input = 'local all root ident' - result = { - "postgresql class generated rule test 0"=>{ - "type"=>"local", - "database"=>"all", - "user"=>"root", - "auth_method"=>"ident", - "order"=>"100", - }, - } + result = { 'postgresql class generated rule test 0' => { 'type' => 'local', 'database' => 'all', 'user' => 'root', + 'auth_method' => 'ident', 'order' => '100' } } is_expected.to run.with_params([input], 'test', 100).and_return(result) end it do - input_array = [ - 'local all all ident', - ] - result = { - "postgresql class generated rule test 0"=>{ - "type"=>"local", - "database"=>"all", - "user"=>"all", - "auth_method"=>"ident", - "order"=>"100", - }, - } + input_array = ['local all all ident'] + result = { 'postgresql class generated rule test 0' => { 'type' => 'local', 'database' => 'all', 'user' => 'all', + 'auth_method' => 'ident', 'order' => '100' } } is_expected.to run.with_params(input_array, 'test', 100).and_return(result) end it do input = 'host all all 127.0.0.1/32 md5' - result = { - "postgresql class generated rule test 0"=>{ - "type"=>"host", - "database"=>"all", - "user"=>"all", - "address"=>"127.0.0.1/32", - "auth_method"=>"md5", - "order"=>"100", - }, - } + result = { 'postgresql class generated rule test 0' => { 'type' => 'host', 'database' => 'all', 'user' => 'all', 'address' => '127.0.0.1/32', + 'auth_method' => 'md5', 'order' => '100' } } is_expected.to run.with_params([input], 'test', 100).and_return(result) end it do input = 'host all all 0.0.0.0/0 md5' - result = { - "postgresql class generated rule test 0"=>{ - "type"=>"host", - "database"=>"all", - "user"=>"all", - "address"=>"0.0.0.0/0", - "auth_method"=>"md5", - "order"=>"100", - }, - } + result = { 'postgresql class generated rule test 0' => { 'type' => 'host', 'database' => 'all', 'user' => 'all', 'address' => '0.0.0.0/0', + 'auth_method' => 'md5', 'order' => '100' } } is_expected.to run.with_params([input], 'test', 100).and_return(result) end it do input = 'host all all ::1/128 md5' - result = { - "postgresql class generated rule test 0"=>{ - "type"=>"host", - "database"=>"all", - "user"=>"all", - "address"=>"::1/128", - "auth_method"=>"md5", - "order"=>"100", - }, - } + result = { 'postgresql class generated rule test 0' => { 'type' => 'host', 'database' => 'all', 'user' => 'all', 'address' => '::1/128', + 'auth_method' => 'md5', 'order' => '100' } } is_expected.to run.with_params([input], 'test', 100).and_return(result) end it do input = 'host all all 1.1.1.1 255.255.255.0 md5' - result = { - "postgresql class generated rule test 0"=>{ - "type"=>"host", - "database"=>"all", - "user"=>"all", - "address"=>"1.1.1.1 255.255.255.0", - "auth_method"=>"md5", - "order"=>"100", - }, - } + result = { 'postgresql class generated rule test 0' => { 'type' => 'host', 'database' => 'all', 'user' => 'all', 'address' => '1.1.1.1 255.255.255.0', + 'auth_method' => 'md5', 'order' => '100' } } is_expected.to run.with_params([input], 'test', 100).and_return(result) end it do input = 'host all all 1.1.1.1 255.255.255.0 ldap ldapserver=ldap.example.net ldapprefix="cn=" ldapsuffix=", dc=example, dc=net"' - result = { - "postgresql class generated rule test 0"=>{ - "type"=>"host", - "database"=>"all", - "user"=>"all", - "address"=>"1.1.1.1 255.255.255.0", - "auth_method"=>"ldap", - "auth_option"=>"ldapserver=ldap.example.net ldapprefix=\"cn=\" ldapsuffix=\", dc=example, dc=net\"", - "order"=>"100", - }, - } + result = { 'postgresql class generated rule test 0' => { 'type' => 'host', 'database' => 'all', 'user' => 'all', 'address' => '1.1.1.1 255.255.255.0', + 'auth_method' => 'ldap', 'auth_option' => 'ldapserver=ldap.example.net ldapprefix="cn=" ldapsuffix=", dc=example, dc=net"', + 'order' => '100' } } is_expected.to run.with_params([input], 'test', 100).and_return(result) end end - it 'should return an empty hash when input is empty array' do + it 'returns an empty hash when input is empty array' do is_expected.to run.with_params([], 'test', 100).and_return({}) end end diff --git a/spec/unit/functions/postgresql_escape_spec.rb b/spec/unit/functions/postgresql_escape_spec.rb index b4c9488..2edd388 100644 --- a/spec/unit/functions/postgresql_escape_spec.rb +++ b/spec/unit/functions/postgresql_escape_spec.rb @@ -1,14 +1,21 @@ require 'spec_helper' - -describe 'postgresql_escape', :type => :puppet_function do - it { is_expected.to run.with_params('foo'). - and_return('$$foo$$') } -end -describe 'postgresql_escape', :type => :puppet_function do - it { is_expected.to run.with_params('fo$$o'). - and_return('$ed$fo$$o$ed$') } -end -describe 'postgresql_escape', :type => :puppet_function do - it { is_expected.to run.with_params('foo$'). - and_return('$a$foo$$a$') } +describe 'postgresql_escape' do + describe 'postgresql_escape', type: :puppet_function do + it { + is_expected.to run.with_params('foo') + .and_return('$$foo$$') + } + end + describe 'postgresql_escape', type: :puppet_function do + it { + is_expected.to run.with_params('fo$$o') + .and_return('$ed$fo$$o$ed$') + } + end + describe 'postgresql_escape', type: :puppet_function do + it { + is_expected.to run.with_params('foo$') + .and_return('$a$foo$$a$') + } + end end diff --git a/spec/unit/functions/postgresql_password_spec.rb b/spec/unit/functions/postgresql_password_spec.rb index 89699f6..aef13ea 100644 --- a/spec/unit/functions/postgresql_password_spec.rb +++ b/spec/unit/functions/postgresql_password_spec.rb @@ -1,8 +1,12 @@ require 'spec_helper' -describe 'postgresql_password', :type => :puppet_function do - it { is_expected.to run.with_params('foo', 'bar'). - and_return('md596948aad3fcae80c08a35c9b5958cd89') } - it { is_expected.to run.with_params('foo', 1234). - and_return('md539a0e1b308278a8de5e007cd1f795920') } +describe 'postgresql_password', type: :puppet_function do + it { + is_expected.to run.with_params('foo', 'bar') + .and_return('md596948aad3fcae80c08a35c9b5958cd89') + } + it { + is_expected.to run.with_params('foo', 1234) + .and_return('md539a0e1b308278a8de5e007cd1f795920') + } end diff --git a/spec/unit/provider/postgresql_conf/parsed_spec.rb b/spec/unit/provider/postgresql_conf/parsed_spec.rb index 24e31c1..511f6c8 100644 --- a/spec/unit/provider/postgresql_conf/parsed_spec.rb +++ b/spec/unit/provider/postgresql_conf/parsed_spec.rb @@ -1,147 +1,146 @@ require 'spec_helper' -require "tempfile" +require 'tempfile' provider_class = Puppet::Type.type(:postgresql_conf).provider(:parsed) describe provider_class do let(:title) { 'postgresql_conf' } - let(:provider) { + let(:provider) do conf_class = Puppet::Type.type(:postgresql_conf) provider = conf_class.provider(:parsed) conffile = tmpfilename('postgresql.conf') - allow_any_instance_of(provider).to receive(:target).and_return conffile + allow_any_instance_of(provider).to receive(:target).and_return conffile # rubocop:disable RSpec/AnyInstance provider - } + end - before do + before(:each) do end after :each do provider.initvars end - describe "simple configuration that should be allowed" do - it "should parse a simple ini line" do + describe 'simple configuration that should be allowed' do + it 'parses a simple ini line' do expect(provider.parse_line("listen_addreses = '*'")).to eq( - { :name=>"listen_addreses", :value=>"*", :comment=>nil, :record_type=>:parsed } + name: 'listen_addreses', value: '*', comment: nil, record_type: :parsed, ) end - it "should parse a simple ini line (2)" do + it 'parses a simple ini line (2)' do expect(provider.parse_line(" listen_addreses = '*'")).to eq( - { :name=>"listen_addreses", :value=>"*", :comment=>nil, :record_type=>:parsed } + name: 'listen_addreses', value: '*', comment: nil, record_type: :parsed, ) end - it "should parse a simple ini line (3)" do + it 'parses a simple ini line (3)' do expect(provider.parse_line("listen_addreses = '*' # dont mind me")).to eq( - { :name=>"listen_addreses", :value=>"*", :comment=>"dont mind me", :record_type=>:parsed } + name: 'listen_addreses', value: '*', comment: 'dont mind me', record_type: :parsed, ) end - it "should parse a comment" do - expect(provider.parse_line("# dont mind me")).to eq( - { :line=>"# dont mind me", :record_type=>:comment } + it 'parses a comment' do + expect(provider.parse_line('# dont mind me')).to eq( + line: '# dont mind me', record_type: :comment, ) end - it "should parse a comment (2)" do + it 'parses a comment (2)' do expect(provider.parse_line(" \t# dont mind me")).to eq( - { :line=>" \t# dont mind me", :record_type=>:comment } + line: " \t# dont mind me", record_type: :comment, ) end - it "should allow includes" do - expect(provider.parse_line("include puppetextra")).to eq( - { :name=>"include", :value=>"puppetextra", :comment=>nil, :record_type=>:parsed } + it 'allows includes' do + expect(provider.parse_line('include puppetextra')).to eq( + name: 'include', value: 'puppetextra', comment: nil, record_type: :parsed, ) end - it "should allow numbers through without quotes" do - expect(provider.parse_line("wal_keep_segments = 32")).to eq( - { :name=>"wal_keep_segments", :value=>"32", :comment=>nil, :record_type=>:parsed } + it 'allows numbers through without quotes' do + expect(provider.parse_line('wal_keep_segments = 32')).to eq( + name: 'wal_keep_segments', value: '32', comment: nil, record_type: :parsed, ) end - it "should allow blanks through " do - expect(provider.parse_line("")).to eq( - { :line=>"", :record_type=>:blank } + it 'allows blanks through' do + expect(provider.parse_line('')).to eq( + line: '', record_type: :blank, ) end - it "should parse keys with dots " do - expect(provider.parse_line("auto_explain.log_min_duration = 1ms")).to eq( - { :name => "auto_explain.log_min_duration", :value => "1ms", :comment => nil, :record_type => :parsed } + it 'parses keys with dots' do + expect(provider.parse_line('auto_explain.log_min_duration = 1ms')).to eq( + name: 'auto_explain.log_min_duration', value: '1ms', comment: nil, record_type: :parsed, ) end end - describe "configuration that should be set" do - it "should set comment lines" do - expect(provider.to_line({ :line=>"# dont mind me", :record_type=>:comment })).to eq( - '# dont mind me' + describe 'configuration that should be set' do + it 'sets comment lines' do + expect(provider.to_line(line: '# dont mind me', record_type: :comment)).to eq( + '# dont mind me', ) end - it "should set blank lines" do - expect(provider.to_line({ :line=>"", :record_type=>:blank })).to eq( - '' + it 'sets blank lines' do + expect(provider.to_line(line: '', record_type: :blank)).to eq( + '', ) end - it "should set simple configuration" do - expect(provider.to_line({:name=>"listen_addresses", :value=>"*", :comment=>nil, :record_type=>:parsed })).to eq( - "listen_addresses = '*'" + it 'sets simple configuration' do + expect(provider.to_line(name: 'listen_addresses', value: '*', comment: nil, record_type: :parsed)).to eq( + "listen_addresses = '*'", ) end - it "should set simple configuration with period in name" do - expect(provider.to_line({:name => "auto_explain.log_min_duration", :value => '100ms', :comment => nil, :record_type => :parsed })).to eq( - "auto_explain.log_min_duration = 100ms" + it 'sets simple configuration with period in name' do + expect(provider.to_line(name: 'auto_explain.log_min_duration', value: '100ms', comment: nil, record_type: :parsed)).to eq( + 'auto_explain.log_min_duration = 100ms', ) end - it "should set simple configuration even with comments" do - expect(provider.to_line({:name=>"listen_addresses", :value=>"*", :comment=>'dont mind me', :record_type=>:parsed })).to eq( - "listen_addresses = '*' # dont mind me" + it 'sets simple configuration even with comments' do + expect(provider.to_line(name: 'listen_addresses', value: '*', comment: 'dont mind me', record_type: :parsed)).to eq( + "listen_addresses = '*' # dont mind me", ) end - it 'should quote includes' do - expect(provider.to_line( {:name=>"include", :value=>"puppetextra", :comment=>nil, :record_type=>:parsed })).to eq( - "include 'puppetextra'" + it 'quotes includes' do + expect(provider.to_line(name: 'include', value: 'puppetextra', comment: nil, record_type: :parsed)).to eq( + "include 'puppetextra'", ) end - it 'should quote multiple words' do - expect(provider.to_line( {:name=>"archive_command", :value=>"rsync up", :comment=>nil, :record_type=>:parsed })).to eq( - "archive_command = 'rsync up'" + it 'quotes multiple words' do + expect(provider.to_line(name: 'archive_command', value: 'rsync up', comment: nil, record_type: :parsed)).to eq( + "archive_command = 'rsync up'", ) end - it 'shouldn\'t quote numbers' do - expect(provider.to_line( {:name=>"wal_segments", :value=>"32", :comment=>nil, :record_type=>:parsed })).to eq( - "wal_segments = 32" + it 'does not quote numbers' do + expect(provider.to_line(name: 'wal_segments', value: '32', comment: nil, record_type: :parsed)).to eq( + 'wal_segments = 32', ) end - it "should allow numbers" do - expect(provider.to_line( {:name=>"integer", :value=>42, :comment=>nil, :record_type=>:parsed })).to eq( - "integer = 42" + it 'allows numbers' do + expect(provider.to_line(name: 'integer', value: 42, comment: nil, record_type: :parsed)).to eq( + 'integer = 42', ) end - it "should allow floats" do - expect(provider.to_line( {:name=>"float", :value=>2.71828182845, :comment=>nil, :record_type=>:parsed })).to eq( - "float = 2.71828182845" + it 'allows floats' do + expect(provider.to_line(name: 'float', value: 2.71828182845, comment: nil, record_type: :parsed)).to eq( + 'float = 2.71828182845', ) end - it "quotes addresses" do - expect(provider.to_line( {:name=>"listen_addresses", :value=>"0.0.0.0", :comment=>nil, :record_type=>:parsed })).to eq( - "listen_addresses = '0.0.0.0'" + it 'quotes addresses' do + expect(provider.to_line(name: 'listen_addresses', value: '0.0.0.0', comment: nil, record_type: :parsed)).to eq( + "listen_addresses = '0.0.0.0'", ) end end end - diff --git a/spec/unit/puppet/provider/postgresql_conn_validator/ruby_spec.rb b/spec/unit/puppet/provider/postgresql_conn_validator/ruby_spec.rb index 3d678ea..d4989ab 100644 --- a/spec/unit/puppet/provider/postgresql_conn_validator/ruby_spec.rb +++ b/spec/unit/puppet/provider/postgresql_conn_validator/ruby_spec.rb @@ -1,66 +1,65 @@ require 'spec_helper' describe Puppet::Type.type(:postgresql_conn_validator).provider(:ruby) do - - let(:resource) { Puppet::Type.type(:postgresql_conn_validator).new({ - :name => "testname" - }.merge attributes) } + let(:resource) do + Puppet::Type.type(:postgresql_conn_validator).new({ + name: 'testname', + }.merge(attributes)) + end let(:provider) { resource.provider } - let(:attributes) do { - :psql_path => '/usr/bin/psql', - :host => 'db.test.com', - :port => 4444, - :db_username => 'testuser', - :db_password => 'testpass' + psql_path: '/usr/bin/psql', + host: 'db.test.com', + port: 4444, + db_username: 'testuser', + db_password: 'testpass', + } + end + let(:connect_settings) do + { + connect_settings: { + PGPASSWORD: 'testpass', + PGHOST: 'db.test.com', + PGPORT: '1234', + }, } end describe '#build_psql_cmd' do it 'contains expected commandline options' do - expect(provider.validator.build_psql_cmd).to match /\/usr\/bin\/psql.*--host.*--port.*--username.*/ + expect(provider.validator.build_psql_cmd).to match %r{/usr/bin/psql.*--host.*--port.*--username.*} end end describe '#parse_connect_settings' do it 'returns array if password is present' do expect(provider.validator.parse_connect_settings).to eq(['PGPASSWORD=testpass']) end it 'returns an empty array if password is nil' do attributes.delete(:db_password) expect(provider.validator.parse_connect_settings).to eq([]) end - let(:connect_settings) do - { - :connect_settings => { - :PGPASSWORD => 'testpass', - :PGHOST => 'db.test.com', - :PGPORT => '1234' - } - } - end it 'returns an array of settings' do attributes.delete(:db_password) attributes.merge! connect_settings - expect(provider.validator.parse_connect_settings).to eq(['PGPASSWORD=testpass','PGHOST=db.test.com','PGPORT=1234']) + expect(provider.validator.parse_connect_settings).to eq(['PGPASSWORD=testpass', 'PGHOST=db.test.com', 'PGPORT=1234']) end end describe '#attempt_connection' do - let(:sleep_length) {1} - let(:tries) {3} - let(:exec) { + let(:sleep_length) { 1 } + let(:tries) { 3 } + let(:exec) do provider.validator.stub(:execute_command).and_return(true) - } + end it 'tries the correct number of times' do - expect(provider.validator).to receive(:execute_command).exactly(3).times - - provider.validator.attempt_connection(sleep_length,tries) + expect(provider.validator).to receive(:execute_command).exactly(3).times # rubocop:disable RSpec/MessageSpies + provider.validator.attempt_connection(sleep_length, tries) end end end diff --git a/spec/unit/puppet/provider/postgresql_psql/ruby_spec.rb b/spec/unit/puppet/provider/postgresql_psql/ruby_spec.rb index b75bd98..ee1444f 100644 --- a/spec/unit/puppet/provider/postgresql_psql/ruby_spec.rb +++ b/spec/unit/puppet/provider/postgresql_psql/ruby_spec.rb @@ -1,104 +1,109 @@ require 'spec_helper' describe Puppet::Type.type(:postgresql_psql).provider(:ruby) do + # rubocop:disable RSpec/MessageSpies let(:name) { 'rspec psql test' } let(:resource) do - Puppet::Type.type(:postgresql_psql).new({ :name => name, :provider => :ruby }.merge attributes) + Puppet::Type.type(:postgresql_psql).new({ name: name, provider: :ruby }.merge(attributes)) end - let(:provider) { resource.provider } - context("#run_sql_command") do - describe "with default attributes" do - let(:attributes) do { :db => 'spec_db' } end + context('#run_sql_command') do + describe 'with default attributes' do + let(:attributes) { { db: 'spec_db' } } - it "executes with the given psql_path on the given DB" do + it 'executes with the given psql_path on the given DB' do expect(provider).to receive(:run_command).with(['psql', '-d', - attributes[:db], '-t', '-c', '"SELECT \'something\' as \"Custom column\""'], 'postgres', - 'postgres', {}) + attributes[:db], '-t', '-c', '"SELECT \'something\' as \"Custom column\""'], 'postgres', + 'postgres', {}) provider.run_sql_command('SELECT \'something\' as "Custom column"') end end - describe "with psql_path and db" do - let(:attributes) do { - :psql_path => '/opt/postgres/psql', - :psql_user => 'spec_user', - :psql_group => 'spec_group', - :cwd => '/spec', - :db => 'spec_db' - } end - - it "executes with the given psql_path on the given DB" do + describe 'with psql_path and db' do + let(:attributes) do + { + psql_path: '/opt/postgres/psql', + psql_user: 'spec_user', + psql_group: 'spec_group', + cwd: '/spec', + db: 'spec_db', + } + end + + it 'executes with the given psql_path on the given DB' do # rubocop:disable RSpec/MultipleExpectations expect(Dir).to receive(:chdir).with(attributes[:cwd]).and_yield expect(provider).to receive(:run_command).with([attributes[:psql_path], - '-d', attributes[:db], '-t', '-c', '"SELECT \'something\' as \"Custom column\""'], - attributes[:psql_user], attributes[:psql_group], {}) + '-d', attributes[:db], '-t', '-c', '"SELECT \'something\' as \"Custom column\""'], + attributes[:psql_user], attributes[:psql_group], {}) provider.run_sql_command('SELECT \'something\' as "Custom column"') end end - describe "with search_path string" do - let(:attributes) do { - :search_path => "schema1" - } end + describe 'with search_path string' do + let(:attributes) do + { + search_path: 'schema1', + } + end - it "executes with the given search_path" do + it 'executes with the given search_path' do expect(provider).to receive(:run_command).with(['psql', '-t', '-c', - '"set search_path to schema1; SELECT \'something\' as \"Custom column\""'], - 'postgres', 'postgres', {}) + '"set search_path to schema1; SELECT \'something\' as \"Custom column\""'], + 'postgres', 'postgres', {}) provider.run_sql_command('SELECT \'something\' as "Custom column"') end end - describe "with search_path array" do - let(:attributes) do { - :search_path => ['schema1','schema2'], - } end + describe 'with search_path array' do + let(:attributes) do + { + search_path: %w[schema1 schema2], + } + end - it "executes with the given search_path" do + it 'executes with the given search_path' do expect(provider).to receive(:run_command).with(['psql', '-t', '-c', - '"set search_path to schema1,schema2; SELECT \'something\' as \"Custom column\""'], - 'postgres', - 'postgres', - {} - ) + '"set search_path to schema1,schema2; SELECT \'something\' as \"Custom column\""'], + 'postgres', 'postgres', + {}) provider.run_sql_command('SELECT \'something\' as "Custom column"') end end end - describe "with port string" do - let(:attributes) do { :port => '5555' } end + describe 'with port string' do + let(:attributes) { { port: '5555' } } - it "executes with the given port" do - expect(provider).to receive(:run_command).with(["psql", - "-p", "5555", - "-t", "-c", "\"SELECT something\""], - "postgres", "postgres", {} ) + it 'executes with the given port' do + expect(provider).to receive(:run_command).with(['psql', + '-p', '5555', + '-t', '-c', '"SELECT something"'], + 'postgres', 'postgres', {}) - provider.run_sql_command("SELECT something") - end + provider.run_sql_command('SELECT something') end - describe "with connect_settings" do - let(:attributes) do { :connect_settings => { 'PGHOST' => '127.0.0.1' } } end + end + describe 'with connect_settings' do + let(:attributes) { { connect_settings: { 'PGHOST' => '127.0.0.1' } } } - it "executes with the given host" do - expect(provider).to receive(:run_command).with(["psql", - "-t", "-c", - "\"SELECT something\""], - "postgres", "postgres", { 'PGHOST' => '127.0.0.1' } ) + it 'executes with the given host' do + expect(provider).to receive(:run_command).with(['psql', + '-t', '-c', + '"SELECT something"'], + 'postgres', 'postgres', 'PGHOST' => '127.0.0.1') - provider.run_sql_command("SELECT something") - end + provider.run_sql_command('SELECT something') end + end - context("#run_unless_sql_command") do - let(:attributes) do { } end + context('#run_unless_sql_command') do + let(:attributes) { {} } - it "calls #run_sql_command with SQL" do + it 'calls #run_sql_command with SQL' do expect(provider).to receive(:run_sql_command).with('SELECT COUNT(*) FROM (SELECT 1) count') provider.run_unless_sql_command('SELECT 1') end end + # rubocop:enable RSpec/MessageSpies end diff --git a/spec/unit/puppet/provider/postgresql_replication_slot/ruby_spec.rb b/spec/unit/puppet/provider/postgresql_replication_slot/ruby_spec.rb index 4fc8b55..8ac59f7 100644 --- a/spec/unit/puppet/provider/postgresql_replication_slot/ruby_spec.rb +++ b/spec/unit/puppet/provider/postgresql_replication_slot/ruby_spec.rb @@ -1,92 +1,97 @@ require 'spec_helper' type = Puppet::Type.type(:postgresql_replication_slot) describe type.provider(:ruby) do - let(:name) { 'standby' } - let(:resource) do - type.new({ :name => name, :provider => :ruby }.merge attributes) - end - - let(:sql_instances) do - "abc | | physical | | | t | | | 0/3000420 -def | | physical | | | t | | | 0/3000420\n" - end - class SuccessStatus def success? true end end - let(:success_status) { SuccessStatus.new } - class FailStatus def success? false end end - let(:fail_status) { FailStatus.new } + let(:name) { 'standby' } + let(:resource) do + type.new({ name: name, provider: :ruby }.merge(attributes)) + end + let(:sql_instances) do + "abc | | physical | | | t | | | 0/3000420 +def | | physical | | | t | | | 0/3000420\n" + end + let(:success_status) { SuccessStatus.new } + let(:fail_status) { FailStatus.new } let(:provider) { resource.provider } context 'when listing instances' do - let(:attributes) do { } end + before(:each) do + provider.class.expects(:run_command).with(['psql', '-t', '-c', 'SELECT * FROM pg_replication_slots;'], 'postgres', 'postgres').returns([sql_instances, nil]) + end + let(:attributes) { {} } + let(:instances) { provider.class.instances } + let(:expected) { %w[abc def] } - it 'should list instances' do - provider.class.expects(:run_command).with( - ['psql', '-t', '-c', 'SELECT * FROM pg_replication_slots;'], - 'postgres', 'postgres').returns([sql_instances, nil]) - instances = provider.class.instances + it 'lists instances #size' do expect(instances.size).to eq 2 - expect(instances[0].name).to eq 'abc' - expect(instances[1].name).to eq 'def' + end + it 'lists instances #content' do + expected.each_with_index do |expect, index| + expect(instances[index].name).to eq expect + end end end context 'when creating slot' do - let(:attributes) do { :ensure => 'present' } end + let(:attributes) { { ensure: 'present' } } context 'when creation works' do - it 'should call psql and succeed' do + it 'calls psql and succeed' do provider.class.expects(:run_command).with( ['psql', '-t', '-c', "SELECT * FROM pg_create_physical_replication_slot('standby');"], - 'postgres', 'postgres').returns([nil, success_status]) + 'postgres', 'postgres' + ).returns([nil, success_status]) expect { provider.create }.not_to raise_error end end context 'when creation fails' do - it 'should call psql and fail' do + it 'calls psql and fail' do provider.class.expects(:run_command).with( ['psql', '-t', '-c', "SELECT * FROM pg_create_physical_replication_slot('standby');"], - 'postgres', 'postgres').returns([nil, fail_status]) + 'postgres', 'postgres' + ).returns([nil, fail_status]) - expect { provider.create }.to raise_error(Puppet::Error, /Failed to create replication slot standby:/) + expect { provider.create }.to raise_error(Puppet::Error, %r{Failed to create replication slot standby:}) end end end context 'when destroying slot' do - let(:attributes) do { :ensure => 'absent' } end + let(:attributes) { { ensure: 'absent' } } context 'when destruction works' do - it 'should call psql and succeed' do + it 'calls psql and succeed' do provider.class.expects(:run_command).with( ['psql', '-t', '-c', "SELECT pg_drop_replication_slot('standby');"], - 'postgres', 'postgres').returns([nil, success_status]) + 'postgres', 'postgres' + ).returns([nil, success_status]) expect { provider.destroy }.not_to raise_error end end context 'when destruction fails' do - it 'should call psql and fail' do + it 'calls psql and fail' do provider.class.expects(:run_command).with( ['psql', '-t', '-c', "SELECT pg_drop_replication_slot('standby');"], - 'postgres', 'postgres').returns([nil, fail_status]) + 'postgres', 'postgres' + ).returns([nil, fail_status]) - expect { provider.destroy }.to raise_error(Puppet::Error, /Failed to destroy replication slot standby:/) + expect { provider.destroy }.to raise_error(Puppet::Error, %r{Failed to destroy replication slot standby:}) end end end end diff --git a/spec/unit/puppet/type/postgresql_conn_validator.rb b/spec/unit/puppet/type/postgresql_conn_validator.rb index ef3a1ed..663ce3a 100644 --- a/spec/unit/puppet/type/postgresql_conn_validator.rb +++ b/spec/unit/puppet/type/postgresql_conn_validator.rb @@ -1,42 +1,44 @@ -#! /usr/bin/env ruby +#! /usr/bin/env ruby # rubocop:disable Lint/ScriptPermission require 'spec_helper' describe Puppet::Type.type(:postgresql_conn_validator) do - before do + before(:each) do @provider_class = described_class.provide(:simple) { mk_resource_methods } - @provider_class.stub(:suitable?).and_return true - described_class.stub(:defaultprovider).and_return @provider_class + @provider_class.stub(:suitable?).and_return true # rubocop:disable RSpec/InstanceVariable + described_class.stub(:defaultprovider).and_return @provider_class # rubocop:disable RSpec/InstanceVariable end - describe "when validating attributes" do + describe 'when validating attributes' do [:name, :db_name, :db_username, :command, :host, :port, :connect_settings, :sleep, :tries, :psql_path].each do |param| it "should have a #{param} parameter" do expect(described_class.attrtype(param)).to eq(:param) end end end - describe "when validating values" do - describe "tries and sleep" do + describe 'when validating values' do + describe 'tries and sleep' do [:tries, :sleep, :port].each do |param| - it "#{param} should be able to cast value as integer" do - expect { described_class.new(:name => 'test', param => '1') }.to_not raise_error - expect { described_class.new(:name => 'test', param => 1) }.to_not raise_error + it "#{param} should be able to cast value as integer #string" do + expect { described_class.new(:name => 'test', param => '1') }.not_to raise_error + end + it "#{param} should be able to cast value as integer #integer" do + expect { described_class.new(:name => 'test', param => 1) }.not_to raise_error end it "#{param} should not accept non-numeric string" do expect { described_class.new(:name => 'test', param => 'test') }.to raise_error Puppet::ResourceError end end end - describe "connect_settings" do - it "should accept a hash" do - expect { described_class.new(:name => 'test', :connect_settings => { "PGPASSWORD" => "test1" }) }.to_not raise_error + describe 'connect_settings' do + it 'accepts a hash' do + expect { described_class.new(name: 'test', connect_settings: { 'PGPASSWORD' => 'test1' }) }.not_to raise_error end end - describe "port" do - it "does not accept a word" do - expect { described_class.new(:name => 'test', :port => 'test')}.to raise_error Puppet::Error + describe 'port' do + it 'does not accept a word' do + expect { described_class.new(name: 'test', port: 'test') }.to raise_error Puppet::Error end end end end diff --git a/spec/unit/puppet/type/postgresql_psql_spec.rb b/spec/unit/puppet/type/postgresql_psql_spec.rb index 3883327..85e844f 100644 --- a/spec/unit/puppet/type/postgresql_psql_spec.rb +++ b/spec/unit/puppet/type/postgresql_psql_spec.rb @@ -1,251 +1,268 @@ require 'spec_helper' -describe Puppet::Type.type(:postgresql_psql), "when validating attributes" do - [:name, :unless, :db, :psql_path, :psql_user, :psql_group, :connect_settings].each do |attr| - it "should have a #{attr} parameter" do - expect(Puppet::Type.type(:postgresql_psql).attrtype(attr)).to eq(:param) +describe Puppet::Type.type(:postgresql_psql) do # rubocop:disable RSpec/MultipleDescribes + context 'when validating attributes' do + [:name, :unless, :db, :psql_path, :psql_user, :psql_group, :connect_settings].each do |attr| + it "should have a #{attr} parameter" do + expect(Puppet::Type.type(:postgresql_psql).attrtype(attr)).to eq(:param) + end end - end - [:command].each do |attr| - it "should have a #{attr} property" do - expect(Puppet::Type.type(:postgresql_psql).attrtype(attr)).to eq(:property) + [:command].each do |attr| + it "should have a #{attr} property" do + expect(Puppet::Type.type(:postgresql_psql).attrtype(attr)).to eq(:property) + end end end end -describe Puppet::Type.type(:postgresql_psql), :unless => Puppet.features.microsoft_windows? do +describe Puppet::Type.type(:postgresql_psql), unless: Puppet.features.microsoft_windows? do subject do - Puppet::Type.type(:postgresql_psql).new({:name => 'rspec'}.merge attributes) + Puppet::Type.type(:postgresql_psql).new({ name: 'rspec' }.merge(attributes)) end - describe "available attributes" do + describe 'available attributes' do { - :name => "rspec", - :command => "SELECT stuff", - :unless => "SELECT other,stuff", - :db => "postgres", - :psql_path => "/bin/false", - :psql_user => "postgres", - :psql_group => "postgres", - :cwd => "/var/lib", - :refreshonly => :true, - :search_path => [ "schema1", "schema2"], - :connect_settings => { 'PGHOST' => 'postgres-db-server', - 'DBVERSION' => '9.1', }, + name: 'rspec', + command: 'SELECT stuff', + unless: 'SELECT other,stuff', + db: 'postgres', + psql_path: '/bin/false', + psql_user: 'postgres', + psql_group: 'postgres', + cwd: '/var/lib', + refreshonly: :true, + search_path: %w[schema1 schema2], + connect_settings: { 'PGHOST' => 'postgres-db-server', + 'DBVERSION' => '9.1' }, }.each do |attr, value| context attr do - let(:attributes) do { attr => value } end + describe [attr] + subject { super()[attr] } - describe [attr] do - subject { super()[attr] } - it { is_expected.to eq(value) } - end + let(:attributes) { { attr => value } } + + it { is_expected.to eq(value) } end end + let(:attributes) { {} } - context "default values" do - let(:attributes) do {} end + context 'default value: [:psql_path]' do + subject { super()[:psql_path] } - describe '[:psql_path]' do - subject { super()[:psql_path] } - it { is_expected.to eq("psql") } - end + it { is_expected.to eq('psql') } + end + context 'default value: [:psql_user]' do + subject { super()[:psql_user] } - describe '[:psql_user]' do - subject { super()[:psql_user] } - it { is_expected.to eq("postgres") } - end + it { is_expected.to eq('postgres') } + end + context 'default value: [:psql_group]' do + subject { super()[:psql_group] } - describe '[:psql_group]' do - subject { super()[:psql_group] } - it { is_expected.to eq("postgres") } - end + it { is_expected.to eq('postgres') } + end + context 'default value: [:cwd]' do + subject { super()[:cwd] } - describe '[:cwd]' do - subject { super()[:cwd] } - it { is_expected.to eq("/tmp") } - end + it { is_expected.to eq('/tmp') } + end + context 'default value: #refreshonly?' do + subject { super().refreshonly? } - describe '#refreshonly?' do - subject { super().refreshonly? } - it { is_expected.to be_falsey } - end + it { is_expected.to be_falsey } end end - describe "#command" do - let(:attributes) do {:command => 'SELECT stuff'} end + # rubocop:disable RSpec/MultipleExpectations + # rubocop:disable RSpec/MessageSpies + # rubocop:disable RSpec/NamedSubject + # rubocop:disable RSpec/SubjectStub + describe '#command' do + let(:attributes) { { command: 'SELECT stuff' } } - it "will have the value :notrun if the command should execute" do + it 'will have the value :notrun if the command should execute' do expect(subject).to receive(:should_run_sql).and_return(true) expect(subject.property(:command).retrieve).to eq(:notrun) end it "will be the 'should' value if the command should not execute" do expect(subject).to receive(:should_run_sql).and_return(false) expect(subject.property(:command).retrieve).to eq('SELECT stuff') end - it "will call provider#run_sql_command on sync" do - expect(subject.provider).to receive(:run_sql_command).with('SELECT stuff').and_return(["done", 0]) + it 'will call provider#run_sql_command on sync' do + expect(subject.provider).to receive(:run_sql_command).with('SELECT stuff').and_return(['done', 0]) subject.property(:command).sync end end - describe "#unless" do - let(:attributes) do {:unless => 'SELECT something'} end + describe '#unless' do + let(:attributes) { { unless: 'SELECT something' } } - describe "#matches" do - it "does not fail when the status is successful" do - expect(subject.provider).to receive(:run_unless_sql_command).and_return ["1 row returned", 0] + describe '#matches' do + it 'does not fail when the status is successful' do + expect(subject.provider).to receive(:run_unless_sql_command).and_return ['1 row returned', 0] subject.parameter(:unless).matches('SELECT something') end - it "returns true when rows are returned" do - expect(subject.provider).to receive(:run_unless_sql_command).and_return ["1 row returned", 0] + it 'returns true when rows are returned' do + expect(subject.provider).to receive(:run_unless_sql_command).and_return ['1 row returned', 0] expect(subject.parameter(:unless).matches('SELECT something')).to be_truthy end - it "returns false when no rows are returned" do - expect(subject.provider).to receive(:run_unless_sql_command).and_return ["0 rows returned", 0] + it 'returns false when no rows are returned' do + expect(subject.provider).to receive(:run_unless_sql_command).and_return ['0 rows returned', 0] expect(subject.parameter(:unless).matches('SELECT something')).to be_falsey end - it "raises an error when the sql command fails" do - allow(subject.provider).to receive(:run_unless_sql_command).and_return ["Something went wrong", 1] + it 'raises an error when the sql command fails' do + allow(subject.provider).to receive(:run_unless_sql_command).and_return ['Something went wrong', 1] expect { subject.parameter(:unless).matches('SELECT something') - }.to raise_error(Puppet::Error, /Something went wrong/) + }.to raise_error(Puppet::Error, %r{Something went wrong}) end end end + # rubocop:enable RSpec/MultipleExpectations - describe "#should_run_sql" do - context "without 'unless'" do - [true, :true].each do |refreshonly| - context "refreshonly => #{refreshonly.inspect}" do - let(:attributes) do { - :refreshonly => refreshonly, - } end - - context "not refreshing" do - it { expect(subject.should_run_sql).to be_falsey } - end - - context "refreshing" do - it { expect(subject.should_run_sql(true)).to be_truthy } - end + describe "#should_run_sql without 'unless'" do + [true, :true].each do |refreshonly| + context "refreshonly => #{refreshonly.inspect}" do + let(:attributes) do + { refreshonly: refreshonly } end + + context 'not refreshing' + it { expect(subject.should_run_sql).to be_falsey } end + context "refreshonly => #{refreshonly.inspect}" do + let(:attributes) do + { refreshonly: refreshonly } + end - [false, :false].each do |refreshonly| - context "refreshonly => #{refreshonly.inspect}" do - let(:attributes) do { - :refreshonly => refreshonly, - } end + context 'refreshing' + it { expect(subject.should_run_sql(true)).to be_truthy } + end + end - context "not refreshing" do - it { expect(subject.should_run_sql).to be_truthy } - end + [false, :false].each do |refreshonly| + context "refreshonly => #{refreshonly.inspect}" do + let(:attributes) do + { refreshonly: refreshonly } + end - context "refreshing" do - it { expect(subject.should_run_sql(true)).to be_truthy } - end + context 'not refreshing' + it { expect(subject.should_run_sql).to be_truthy } + end + context "refreshonly => #{refreshonly.inspect}" do + let(:attributes) do + { refreshonly: refreshonly } end + + context 'refreshing' + it { expect(subject.should_run_sql(true)).to be_truthy } end end + end - context "with matching 'unless'" do - before { expect(subject.parameter(:unless)).to receive(:matches).with('SELECT something').and_return(true) } - - [true, :true].each do |refreshonly| - context "refreshonly => #{refreshonly.inspect}" do - let(:attributes) do { - :refreshonly => refreshonly, - :unless => 'SELECT something', - } end - - context "not refreshing" do - it { expect(subject.should_run_sql).to be_falsey } - end + describe "#should_run_sql with matching 'unless'" do + before(:each) { expect(subject.parameter(:unless)).to receive(:matches).with('SELECT something').and_return(true) } # rubocop:disable RSpec/ExpectInHook - context "refreshing" do - it { expect(subject.should_run_sql(true)).to be_falsey } - end + [true, :true].each do |refreshonly| + context "refreshonly => #{refreshonly.inspect}" do + let(:attributes) do + { refreshonly: refreshonly, unless: 'SELECT something' } end + + context 'not refreshing' + it { expect(subject.should_run_sql).to be_falsey } end + context "refreshonly => #{refreshonly.inspect}" do + let(:attributes) do + { refreshonly: refreshonly, unless: 'SELECT something' } + end - [false, :false].each do |refreshonly| - context "refreshonly => #{refreshonly.inspect}" do - let(:attributes) do { - :refreshonly => refreshonly, - :unless => 'SELECT something', - } end + context 'refreshing' + it { expect(subject.should_run_sql(true)).to be_falsey } + end + end - context "not refreshing" do - it { expect(subject.should_run_sql).to be_falsey } - end + [false, :false].each do |refreshonly| + context "refreshonly => #{refreshonly.inspect}" do + let(:attributes) do + { refreshonly: refreshonly, unless: 'SELECT something' } + end - context "refreshing" do - it { expect(subject.should_run_sql(true)).to be_falsey } - end + context 'not refreshing' + it { expect(subject.should_run_sql).to be_falsey } + end + context "refreshonly => #{refreshonly.inspect}" do + let(:attributes) do + { refreshonly: refreshonly, unless: 'SELECT something' } end + + context 'refreshing' + it { expect(subject.should_run_sql(true)).to be_falsey } end end + end - context "when not matching 'unless'" do - before { expect(subject.parameter(:unless)).to receive(:matches).with('SELECT something').and_return(false) } - - [true, :true].each do |refreshonly| - context "refreshonly => #{refreshonly.inspect}" do - let(:attributes) do { - :refreshonly => refreshonly, - :unless => 'SELECT something', - } end - - context "not refreshing" do - it { expect(subject.should_run_sql).to be_falsey } - end + describe "#should_run_sql when not matching 'unless'" do + before(:each) { expect(subject.parameter(:unless)).to receive(:matches).with('SELECT something').and_return(false) } # rubocop:disable RSpec/ExpectInHook - context "refreshing" do - it { expect(subject.should_run_sql(true)).to be_truthy } - end + [true, :true].each do |refreshonly| + context "refreshonly => #{refreshonly.inspect}" do + let(:attributes) do + { refreshonly: refreshonly, unless: 'SELECT something' } end + + context 'not refreshing' + it { expect(subject.should_run_sql).to be_falsey } end + context "refreshonly => #{refreshonly.inspect}" do + let(:attributes) do + { refreshonly: refreshonly, unless: 'SELECT something' } + end - [false, :false].each do |refreshonly| - context "refreshonly => #{refreshonly.inspect}" do - let(:attributes) do { - :refreshonly => refreshonly, - :unless => 'SELECT something', - } end + context 'refreshing' + it { expect(subject.should_run_sql(true)).to be_truthy } + end + end - context "not refreshing" do - it { expect(subject.should_run_sql).to be_truthy } - end + [false, :false].each do |refreshonly| + context "refreshonly => #{refreshonly.inspect}" do + let(:attributes) do + { refreshonly: refreshonly, unless: 'SELECT something' } + end - context "refreshing" do - it { expect(subject.should_run_sql(true)).to be_truthy } - end + context 'not refreshing' + it { expect(subject.should_run_sql).to be_truthy } + end + context "refreshonly => #{refreshonly.inspect}" do + let(:attributes) do + { refreshonly: refreshonly, unless: 'SELECT something' } end + + context 'refreshing' + it { expect(subject.should_run_sql(true)).to be_truthy } end end end - describe "#refresh" do - let(:attributes) do {} end + describe '#refresh' do + let(:attributes) { {} } - it "syncs command property when command should run" do + it 'syncs command property when command should run' do # rubocop:disable RSpec/MultipleExpectations expect(subject).to receive(:should_run_sql).with(true).and_return(true) expect(subject.property(:command)).to receive(:sync) subject.refresh end - it "does not sync command property when command should not run" do + it 'does not sync command property when command should not run' do # rubocop:disable RSpec/MultipleExpectations expect(subject).to receive(:should_run_sql).with(true).and_return(false) expect(subject.property(:command)).not_to receive(:sync) subject.refresh end end end diff --git a/spec/unit/puppet/type/postgresql_replication_slot_spec.rb b/spec/unit/puppet/type/postgresql_replication_slot_spec.rb index 0d7c668..37d85a6 100644 --- a/spec/unit/puppet/type/postgresql_replication_slot_spec.rb +++ b/spec/unit/puppet/type/postgresql_replication_slot_spec.rb @@ -1,11 +1,11 @@ require 'spec_helper' describe Puppet::Type.type(:postgresql_replication_slot) do subject do - Puppet::Type.type(:postgresql_psql).new({:name => 'standby'}) + Puppet::Type.type(:postgresql_psql).new(name: 'standby') end - it 'should have a name parameter' do - expect(subject[:name]).to eq 'standby' + it 'has a name parameter' do + expect(subject[:name]).to eq 'standby' # rubocop:disable RSpec/NamedSubject end end diff --git a/spec/unit/type/postgresql_conf_spec.rb b/spec/unit/type/postgresql_conf_spec.rb index a406b0c..0cbab10 100644 --- a/spec/unit/type/postgresql_conf_spec.rb +++ b/spec/unit/type/postgresql_conf_spec.rb @@ -1,50 +1,50 @@ -#! /usr/bin/env ruby +#! /usr/bin/env ruby # rubocop:disable Lint/ScriptPermission require 'spec_helper' describe Puppet::Type.type(:postgresql_conf) do - before do + before(:each) do @provider_class = described_class.provide(:simple) { mk_resource_methods } - allow(@provider_class).to receive(:suitable?).and_return true - allow(described_class).to receive(:defaultprovider).and_return @provider_class + allow(@provider_class).to receive(:suitable?).and_return true # rubocop:disable RSpec/InstanceVariable + allow(described_class).to receive(:defaultprovider).and_return @provider_class # rubocop:disable RSpec/InstanceVariable end - describe "namevar validation" do - it "should have :name as its namevar" do + describe 'namevar validation' do + it 'has :name as its namevar' do expect(described_class.key_attributes).to eq([:name]) end - it "should not invalid names" do - expect { described_class.new(:name => 'foo bar') }.to raise_error(Puppet::Error, /Invalid value/) + it 'does not invalid names' do + expect { described_class.new(name: 'foo bar') }.to raise_error(Puppet::Error, %r{Invalid value}) end - it "should allow dots in names" do - expect { described_class.new(:name => 'foo.bar') }.to_not raise_error + it 'allows dots in names' do + expect { described_class.new(name: 'foo.bar') }.not_to raise_error end end - describe "when validating attributes" do + describe 'when validating attributes' do [:name, :provider].each do |param| it "should have a #{param} parameter" do expect(described_class.attrtype(param)).to eq(:param) end end [:value, :target].each do |property| it "should have a #{property} property" do expect(described_class.attrtype(property)).to eq(:property) end end end - describe "when validating values" do - describe "ensure" do - it "should support present as a value for ensure" do - expect { described_class.new(:name => 'foo', :ensure => :present) }.to_not raise_error + describe 'when validating values' do + describe 'ensure' do + it 'supports present as a value for ensure' do + expect { described_class.new(name: 'foo', ensure: :present) }.not_to raise_error end - it "should support absent as a value for ensure" do - expect { described_class.new(:name => 'foo', :ensure => :absent) }.to_not raise_error + it 'supports absent as a value for ensure' do + expect { described_class.new(name: 'foo', ensure: :absent) }.not_to raise_error end - it "should not support other values" do - expect { described_class.new(:name => 'foo', :ensure => :foo) }.to raise_error(Puppet::Error, /Invalid value/) + it 'does not support other values' do + expect { described_class.new(name: 'foo', ensure: :foo) }.to raise_error(Puppet::Error, %r{Invalid value}) end end end end diff --git a/tasks/sql.rb b/tasks/sql.rb index c706016..dc407c9 100755 --- a/tasks/sql.rb +++ b/tasks/sql.rb @@ -1,33 +1,33 @@ #!/opt/puppetlabs/puppet/bin/ruby require 'json' require 'open3' require 'puppet' def get(sql, database, user, port, password, host) - env_hash = {'PGPASSWORD' => password} unless password.nil? + env_hash = { 'PGPASSWORD' => password } unless password.nil? cmd_string = "psql -c \"#{sql}\"" cmd_string << " --dbname=#{database}" unless database.nil? cmd_string << " --username=#{user}" unless user.nil? cmd_string << " --port=#{port}" unless port.nil? cmd_string << " --host=#{host}" unless host.nil? stdout, stderr, status = Open3.capture3(env_hash, cmd_string) raise Puppet::Error, stderr if status != 0 { status: stdout.strip } end params = JSON.parse(STDIN.read) database = params['database'] host = params['host'] password = params['password'] port = params['port'] sql = params['sql'] user = params['user'] begin result = get(sql, database, user, port, password, host) puts result.to_json exit 0 rescue Puppet::Error => e puts({ status: 'failure', error: e.message }.to_json) exit 1 end