diff --git a/lib/puppet/provider/grafana_datasource/grafana.rb b/lib/puppet/provider/grafana_datasource/grafana.rb index e6d13bec..83fd0059 100644 --- a/lib/puppet/provider/grafana_datasource/grafana.rb +++ b/lib/puppet/provider/grafana_datasource/grafana.rb @@ -52,6 +52,7 @@ def fetch_organization end def datasource_by_name + change_organization response = send_request('GET', format('%s/datasources/name/%s', resource[:grafana_api_path], ERB::Util.url_encode(resource[:name]))) return nil if response.code == '404' @@ -149,12 +150,15 @@ def secure_json_data {} end + def change_organization + response = send_request 'POST', format('%s/user/using/%s', resource[:grafana_api_path], fetch_organization[:id]) + raise format('Failed to switch to org %s (HTTP response: %s/%s)', fetch_organization[:id], response.code, response.body) unless response.code == '200' + end + def flush return if resource['ensure'] == :absent - # change organizations - response = send_request 'POST', format('%s/user/using/%s', resource[:grafana_api_path], fetch_organization[:id]) - raise format('Failed to switch to org %s (HTTP response: %s/%s)', fetch_organization[:id], response.code, response.body) unless response.code == '200' + change_organization # Build the `data` to POST/PUT by first creating a hash with some defaults which will be used if we're _creating_ a datasource data = { @@ -252,6 +256,11 @@ def destroy end def exists? - datasource + # check organization first. If it does not exist, then + # the datasource does not exist either. Furthermore this + # avoids the issue that a noop run does not actually create + # the organization, so that datasource(_by_name) cannot + # invoke change_organization(). + fetch_organization and datasource end end diff --git a/spec/acceptance/grafana_datasource_spec.rb b/spec/acceptance/grafana_datasource_spec.rb index f5d40db6..6018de88 100644 --- a/spec/acceptance/grafana_datasource_spec.rb +++ b/spec/acceptance/grafana_datasource_spec.rb @@ -110,5 +110,38 @@ class { 'grafana': end end end + + describe 'postgres ds' do + context 'without basic auth' do + let(:manifest) do + <<-PUPPET + ['Foo', 'Bar'].each |$organization| { + grafana_organization { $organization: + ensure => present, + grafana_url => 'http://localhost:3000', + grafana_user => 'admin', + grafana_password => 'admin', + } -> + grafana_datasource { $organization: + organization => $organization, + type => 'grafana-postgresql-datasource', + url => 'localhost', + grafana_url => 'http://localhost:3000', + grafana_user => 'admin', + grafana_password => 'admin', + } + } + PUPPET + end + + it 'works with no errors' do + apply_manifest_on(default, manifest, catch_failures: true) + end + + it 'is idempotent' do + apply_manifest_on(default, manifest, catch_changes: true) + end + end + end end end