community.postgresql.postgresql_script module – Run PostgreSQL statements from a file
Note
This module is part of the community.postgresql collection (version 3.14.2).
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_script.
New in community.postgresql 2.1.0
Synopsis
- Runs arbitrary PostgreSQL statements from a file. 
- The module always reports that the state has changed. 
- Do NOT run the module against files generated by - pg_dump,- pg_dumpall,- pg_restoreand other PostgreSQL utilities.
- Use community.postgresql.postgresql_db with state=restore to run queries from files generated by - pg_dump/pg_dumpall.
Requirements
The below requirements are needed on the host that executes this module.
- psycopg2 >= 2.5.1 
Parameters
| Parameter | Comments | 
|---|---|
| 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:  | |
| Set the client encoding for the current session (e.g.  The default is the encoding defined by the database. | |
| Name of database to connect to and run queries against. The  | |
| 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 substitute variable placeholders within the file content. When the value is a list, it will be converted to PostgreSQL array. Mutually exclusive with positional_args. | |
| Path to a SQL script on the target machine. To upload dumps, the preferable way is to use the community.postgresql.postgresql_db module with state=restore. | |
| Database port to connect to. Default:  | |
| List of values to substitute variable placeholders within the file content. When the value is a list, it will be converted to PostgreSQL array. Mutually exclusive with named_args. | |
| Overrides the list of schemas to search for db objects in. | |
| Switch to  Permissions checking for SQL commands is carried out as though the  | |
| 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: none | 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 - postgresaccount 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 that- psycopg2 >= 2.5.1or- psycopg3 >= 3.1.8is 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- python3-psycopg2packages on the remote host before using this module.
See Also
See also
- community.postgresql.postgresql_db
- Add or remove PostgreSQL databases from a remote host. 
- community.postgresql.postgresql_query
- Run PostgreSQL queries. 
- PostgreSQL Schema reference
- Complete reference of the PostgreSQL schema documentation. 
Examples
# Assuming that the file contains
# SELECT * FROM id_talbe WHERE id = %s,
# '%s' will be substituted with 1
- name: Run query from SQL script using UTF-8 client encoding for session and positional args
  community.postgresql.postgresql_script:
    login_db: test_db
    path: /var/lib/pgsql/test.sql
    positional_args:
      - 1
    encoding: UTF-8
# Assuming that the file contains
# SELECT * FROM test WHERE id = %(id_val)s AND story = %(story_val)s,
# %-values will be substituted with 1 and 'test'
- name: Select query to test_db with named_args
  community.postgresql.postgresql_script:
    login_db: test_db
    path: /var/lib/pgsql/test.sql
    named_args:
      id_val: 1
      story_val: test
- block:
  # Assuming that the the file contains
  # SELECT * FROM test_array_table WHERE arr_col1 = %s AND arr_col2 = %s
  # 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: Passing positional_args as arrays
    community.postgresql.postgresql_script:
      path: /var/lib/pgsql/test.sql
      positional_args:
        - '{{ my_list }}'
        - '{{ my_arr|string }}'
# Assuming that the the file contains
# SELECT * FROM test_table,
# look 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_script:
    path: /var/lib/pgsql/test.sql
    search_path:
    - app1
    - public
- block:
    # If you use a variable in positional_args/named_args that can
    # be undefined and you wish to set it as NULL, 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 using 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, assuming that the file contains
    # INSERT INTO test_table (col1) VALUES (%s)
    - name: Insert a value using positional arguments
      community.postgresql.postgresql_script:
        path: /var/lib/pgsql/test.sql
        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 the  Returned: success Sample:  | |
| List of dictionaries in the column:value form representing returned rows. When there are several statements in the script, returns result of the last statement. Returned: success Sample:  | |
| Number of produced or affected rows. When there are several statements in the script, returns a number of rows affected by the last statement. Returned: changed Sample:  | |
| Attribute containing the message returned by the database connector after executing the script content. When there are several statements in the script, returns a message related to the last statement. Returned: success Sample:  | 
