community.postgresql.postgresql_query module – Run PostgreSQL queries
Note
This module is part of the community.postgresql collection (version 3.7.0).
You might already have this collection installed if you are using the ansible
package.
It is not included in ansible-core
.
To check whether it is installed, run ansible-galaxy collection list
.
To install it, use: ansible-galaxy collection install community.postgresql
.
You need further requirements to be able to use this module,
see Requirements for details.
To use it in a playbook, specify: community.postgresql.postgresql_query
.
Synopsis
Runs arbitrary PostgreSQL queries.
Requirements
The below requirements are needed on the host that executes this module.
psycopg2 >= 2.5.1
Parameters
Parameter |
Comments |
---|---|
Execute in autocommit mode when the query can’t be run inside a transaction block (e.g., VACUUM). Mutually exclusive with check_mode. Choices:
|
|
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. |
|
Any additional parameters to be passed to libpg. These parameters take precedence. Default: |
|
Name of database to connect to and run queries against. |
|
Set the client encoding for the current session (e.g. The default is the encoding defined by the database. |
|
Host running the database. If you have connection issues when using Default: |
|
The password this module should use to establish its PostgreSQL session. Default: |
|
Path to a Unix domain socket for local connections. Default: |
|
The username this module should use to establish its PostgreSQL session. Default: |
|
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. |
|
Database port to connect to. Default: |
|
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. |
|
SQL query string or list of queries to run. Variables can be escaped with psycopg syntax https://www.psycopg.org/psycopg3/docs/basic/params.html. |
|
List of schema names to look in. |
|
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. |
|
Specifies the file name of the client SSL certificate. |
|
Specifies the location for the secret key used for the client certificate. |
|
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 Choices:
|
|
If It makes sense to use Choices:
|
Attributes
Attribute |
Support |
Description |
---|---|---|
Support: full |
Can run in check_mode and return changed status prediction without modifying target. |
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
psycopg
, a Python PostgreSQL database adapter. You must ensure thatpsycopg2 >= 2.5.1
orpsycopg3 >= 3.1.8
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
, andpython3-psycopg2
packages on the remote host before using this module.
See Also
See also
- community.postgresql.postgresql_script
Run PostgreSQL statements from a file.
- community.postgresql.postgresql_db
Add or remove PostgreSQL databases from a remote host.
- PostgreSQL Schema reference
Complete reference of the PostgreSQL schema documentation.
Examples
- name: Simple select query to acme db
community.postgresql.postgresql_query:
db: acme
query: SELECT version()
# The result of each query will be stored in query_all_results return value
- name: Run several queries against acme db
community.postgresql.postgresql_query:
db: acme
query:
- SELECT version()
- SELECT id FROM accounts
- name: Select query to db acme with positional arguments and non-default credentials
community.postgresql.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.postgresql.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.postgresql.postgresql_query:
db: test_db
query: INSERT INTO test_table (id, story) VALUES (2, 'my_long_story')
- name: Use connect_params to add any additional connection parameters that libpg supports
community.postgresql.postgresql_query:
connect_params:
target_session_attrs: read-write
connect_timeout: 10
login_host: "host1,host2"
login_user: "test"
login_password: "test1234"
db: 'test'
query: 'insert into test (test) values (now())'
- name: Example of using autocommit parameter
community.postgresql.postgresql_query:
db: test_db
query: VACUUM
autocommit: true
- 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.postgresql.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.postgresql.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.postgresql.postgresql_query:
query: SELECT * FROM test_array_table
search_path:
- app1
- public
# If you use a variable in positional_args / named_args that can
# be undefined and you wish to set it as NULL, the constructions like
# "{{ my_var if (my_var is defined) else none | default(none) }}"
# will not work as expected substituting an empty string instead of NULL.
# If possible, we suggest to use Ansible's DEFAULT_JINJA2_NATIVE configuration
# (https://docs.ansible.com/ansible/latest/reference_appendices/config.html#default-jinja2-native).
# Enabling it fixes this problem. If you cannot enable it, the following workaround
# can be used.
# You should precheck such a value and define it as NULL when undefined.
# For example:
- name: When undefined, set to NULL
set_fact:
my_var: NULL
when: my_var is undefined
# Then:
- name: Insert a value using positional arguments
community.postgresql.postgresql_query:
query: INSERT INTO test_table (col1) VALUES (%s)
positional_args:
- '{{ my_var }}'
Return Values
Common return values are documented here, the following are the fields unique to this module:
Key |
Description |
---|---|
Executed query. When reading several queries from a file, it contains only the last one. Returned: success Sample: |
|
List containing results of all queries executed (one sublist for every query). Returned: success Sample: |
|
List of executed queries. Returned: success Sample: |
|
List of dictionaries in column:value form representing returned rows. When running queries from a file, returns result of the last query. Returned: success Sample: |
|
Number of produced or affected rows. When using a script with multiple queries, it contains a total number of produced or affected rows. Returned: changed Sample: |
|
Attribute containing the message returned by the command. When reading several queries from a file, it contains a message of the last one. Returned: success Sample: |