On this page
community.general.postgresql_query – Run PostgreSQL queries
Note
This plugin is part of the community.general collection (version 1.3.2).
To install it use: ansible-galaxy collection install community.general
.
To use it in a playbook, specify: community.general.postgresql_query
.
Synopsis
- Runs arbitrary PostgreSQL queries.
- Can run queries from SQL script files.
- Does not run against backup files. Use community.general.postgresql_db with state=restore to run queries on files made by pg_dump/pg_dumpall utilities.
Requirements
The below requirements are needed on the host that executes this module.
- psycopg2
Parameters
Parameter | Choices/Defaults | Comments |
---|---|---|
autocommit
boolean
|
|
Execute in autocommit mode when the query can't be run inside a transaction block (e.g., VACUUM).
Mutually exclusive with check_mode.
|
ca_cert
string
|
Specifies the name of a file containing SSL certificate authority (CA) certificate(s).
If the file exists, the server's certificate will be verified to be signed by one of these authorities.
aliases: ssl_rootcert |
|
db
string
|
Name of database to connect to and run queries against.
aliases: login_db |
|
encoding
string
added in 0.2.0 of community.general
|
Set the client encoding for the current session (e.g.
UTF-8 ).
The default is the encoding defined by the database.
|
|
login_host
string
|
Host running the database.
|
|
login_password
string
|
The password used to authenticate with.
|
|
login_unix_socket
string
|
Path to a Unix domain socket for local connections.
|
|
login_user
string
|
Default:
"postgres"
|
The username used to authenticate with.
|
named_args
dictionary
|
Dictionary of key-value arguments to pass to the query. When the value is a list, it will be converted to PostgreSQL array.
Mutually exclusive with positional_args.
|
|
path_to_script
path
|
Path to a SQL script on the target machine.
If the script contains several queries, they must be semicolon-separated.
Mutually exclusive with query.
|
|
port
integer
|
Default:
5432
|
Database port to connect to.
aliases: login_port |
positional_args
list / elements=raw
|
List of values to be passed as positional arguments to the query. When the value is a list, it will be converted to PostgreSQL array.
Mutually exclusive with named_args.
|
|
query
string
|
SQL query to run. Variables can be escaped with psycopg2 syntax http://initd.org/psycopg/docs/usage.html.
|
|
search_path
list / elements=string
added in 1.0.0 of community.general
|
List of schema names to look in.
|
|
session_role
string
|
Switch to session_role after connecting. The specified session_role must be a role that the current login_user is a member of.
Permissions checking for SQL commands is carried out as though the session_role were the one that had logged in originally.
|
|
ssl_mode
string
|
|
Determines whether or with what priority a secure SSL TCP/IP connection will be negotiated with the server.
See https://www.postgresql.org/docs/current/static/libpq-ssl.html for more information on the modes.
Default of prefer matches libpq default.
|
trust_input
boolean
added in 0.2.0 of community.general
|
|
If
no , check whether a value of session_role is potentially dangerous.
It makes sense to use no only when SQL injections via session_role are possible.
|
Notes
Note
- The default authentication assumes that you are either logging in as or sudo’ing to the
postgres
account on the host. - To avoid “Peer authentication failed for user postgres” error, use postgres user as a become_user.
- This module uses psycopg2, a Python PostgreSQL database adapter. You must ensure that psycopg2 is installed on the host before using this module.
- If the remote host is the PostgreSQL server (which is the default case), then PostgreSQL must also be installed on the remote host.
- For Ubuntu-based systems, install the postgresql, libpq-dev, and python-psycopg2 packages on the remote host before using this module.
- The ca_cert parameter requires at least Postgres version 8.4 and psycopg2 version 2.4.3.
See Also
See also
- community.general.postgresql_db
-
The official documentation on the community.general.postgresql_db module.
- PostgreSQL Schema reference
-
Complete reference of the PostgreSQL schema documentation.
Examples
- name: Simple select query to acme db
community.general.postgresql_query:
db: acme
query: SELECT version()
- name: Select query to db acme with positional arguments and non-default credentials
community.general.postgresql_query:
db: acme
login_user: django
login_password: mysecretpass
query: SELECT * FROM acme WHERE id = %s AND story = %s
positional_args:
- 1
- test
- name: Select query to test_db with named_args
community.general.postgresql_query:
db: test_db
query: SELECT * FROM test WHERE id = %(id_val)s AND story = %(story_val)s
named_args:
id_val: 1
story_val: test
- name: Insert query to test_table in db test_db
community.general.postgresql_query:
db: test_db
query: INSERT INTO test_table (id, story) VALUES (2, 'my_long_story')
- name: Run queries from SQL script using UTF-8 client encoding for session
community.general.postgresql_query:
db: test_db
path_to_script: /var/lib/pgsql/test.sql
positional_args:
- 1
encoding: UTF-8
- name: Example of using autocommit parameter
community.general.postgresql_query:
db: test_db
query: VACUUM
autocommit: yes
- name: >
Insert data to the column of array type using positional_args.
Note that we use quotes here, the same as for passing JSON, etc.
community.general.postgresql_query:
query: INSERT INTO test_table (array_column) VALUES (%s)
positional_args:
- '{1,2,3}'
# Pass list and string vars as positional_args
- name: Set vars
ansible.builtin.set_fact:
my_list:
- 1
- 2
- 3
my_arr: '{1, 2, 3}'
- name: Select from test table by passing positional_args as arrays
community.general.postgresql_query:
query: SELECT * FROM test_array_table WHERE arr_col1 = %s AND arr_col2 = %s
positional_args:
- '{{ my_list }}'
- '{{ my_arr|string }}'
# Select from test table looking into app1 schema first, then,
# if the schema doesn't exist or the table hasn't been found there,
# try to find it in the schema public
- name: Select from test using search_path
community.general.postgresql_query:
query: SELECT * FROM test_array_table
search_path:
- app1
- public
Return Values
Common return values are documented here, the following are the fields unique to this module:
Key | Returned | Description |
---|---|---|
query
string
|
always |
Executed query.
When reading several queries from a file, it contains only the last one.
Sample:
SELECT * FROM bar
|
query_all_results
list / elements=list
|
always |
List containing results of all queries executed (one sublist for every query). Useful when reading several queries from a file.
Sample:
[[{'Column': 'Value1'}, {'Column': 'Value2'}], [{'Column': 'Value1'}, {'Column': 'Value2'}]]
|
query_list
list / elements=string
|
always |
List of executed queries. Useful when reading several queries from a file.
Sample:
['SELECT * FROM foo', 'SELECT * FROM bar']
|
query_result
list / elements=dictionary
|
always |
List of dictionaries in column:value form representing returned rows.
When running queries from a file, returns result of the last query.
Sample:
[{'Column': 'Value1'}, {'Column': 'Value2'}]
|
rowcount
integer
|
changed |
Number of produced or affected rows.
When using a script with multiple queries, it contains a total number of produced or affected rows.
Sample:
5
|
statusmessage
string
|
always |
Attribute containing the message returned by the command.
When reading several queries from a file, it contains a message of the last one.
Sample:
INSERT 0 1
|
Authors
- Felix Archambault (@archf)
- Andrew Klychkov (@Andersson007)
- Will Rouesnel (@wrouesnel)
© 2012–2018 Michael DeHaan
© 2018–2019 Red Hat, Inc.
Licensed under the GNU General Public License version 3.
https://docs.ansible.com/ansible/2.10/collections/community/general/postgresql_query_module.html