community.postgresql.postgresql_query 模块 – 运行 PostgreSQL 查询

注意

此模块是 community.postgresql 集合 (版本 3.9.0) 的一部分。

如果您使用的是 ansible 包,则可能已经安装了此集合。它不包含在 ansible-core 中。要检查它是否已安装,请运行 ansible-galaxy collection list

要安装它,请使用:ansible-galaxy collection install community.postgresql。您需要其他要求才能使用此模块,请参阅 要求 获取详细信息。

要在剧本中使用它,请指定:community.postgresql.postgresql_query

概要

  • 运行任意 PostgreSQL 查询。

要求

以下要求是在执行此模块的主机上需要的。

  • psycopg2 >= 2.5.1

参数

参数

注释

autocommit

布尔值

当查询无法在事务块内运行时(例如,VACUUM)以自动提交模式执行。

与 *check_mode* 互斥。

选项

  • false ← (默认)

  • true

ca_cert

别名:ssl_rootcert

字符串

指定包含 SSL 证书颁发机构 (CA) 证书的文件名。

如果文件存在,则服务器的证书将被验证是否由这些机构之一签名。

connect_params

字典

在 community.postgresql 2.3.0 中添加

要传递给 libpg 的任何其他参数。

这些参数具有优先级。

默认值: {}

db

别名:login_db

字符串

要连接到的数据库名称以及要针对其运行查询的数据库。

encoding

字符串

在 community.postgresql 0.2.0 中添加

设置当前会话的客户端编码(例如 UTF-8)。

默认值为数据库定义的编码。

login_host

别名:host

字符串

运行数据库的主机。

如果您在使用 localhost 时遇到连接问题,请尝试使用 127.0.0.1 代替。

默认值: ""

login_password

字符串

此模块应用于建立其 PostgreSQL 会话的密码。

默认值: ""

login_unix_socket

别名:unix_socket

字符串

本地连接的 Unix 域套接字的路径。

默认值: ""

login_user

别名:login

字符串

此模块应用于建立其 PostgreSQL 会话的用户名。

默认值: "postgres"

named_args

字典

要传递给查询的键值参数字典。当值为列表时,它将转换为 PostgreSQL 数组。

与 *positional_args* 互斥。

port

别名:login_port

整数

要连接到的数据库端口。

默认值: 5432

positional_args

列表 / 元素=任意

要作为位置参数传递给查询的值列表。当值为列表时,它将转换为 PostgreSQL 数组。

与 *named_args* 互斥。

query

任意

要运行的 SQL 查询字符串或查询列表。可以使用 psycopg 语法转义变量 https://www.psycopg.org/psycopg3/docs/basic/params.html

search_path

列表 / 元素=字符串

在 community.postgresql 1.0.0 中添加

要查找的模式名称列表。

session_role

字符串

连接后切换到 session_role。指定的 session_role 必须是当前 login_user 所属的角色。

SQL 命令的权限检查将像最初登录的用户一样进行。

ssl_cert

路径

在 community.postgresql 2.4.0 中添加

指定客户端 SSL 证书的文件名。

ssl_key

路径

在 community.postgresql 2.4.0 中添加

指定用于客户端证书的密钥的位置。

ssl_mode

字符串

确定是否以及以何种优先级与服务器协商安全的 SSL TCP/IP 连接。

有关模式的更多信息,请参阅 https://postgresql.ac.cn/docs/current/static/libpq-ssl.html

prefer 的默认值与 libpq 默认值匹配。

选项

  • "allow"

  • "disable"

  • "prefer" ← (默认)

  • "require"

  • "verify-ca"

  • "verify-full"

trust_input

布尔值

在 community.postgresql 0.2.0 中添加

如果为 false,则检查 *session_role* 的值是否潜在危险。

只有当可能通过 *session_role* 进行 SQL 注入时,使用 false 才有意义。

选项

  • false

  • true ← (默认)

属性

属性

支持

描述

check_mode

支持:完全支持

可以在check_mode下运行,并返回更改状态预测,而无需修改目标。

备注

注意

  • 默认身份验证假设您正在以主机上的postgres帐户身份登录或使用sudo。

  • 为避免“Peer authentication failed for user postgres”错误,请使用postgres用户作为become_user

  • 此模块使用psycopg,这是一个Python PostgreSQL数据库适配器。在使用此模块之前,必须确保主机上安装了psycopg2 >= 2.5.1psycopg3 >= 3.1.8

  • 如果远程主机是PostgreSQL服务器(这是默认情况),则必须在远程主机上安装PostgreSQL。

  • 对于基于Ubuntu的系统,在使用此模块之前,请在远程主机上安装postgresqllibpq-devpython3-psycopg2软件包。

另请参阅

另请参阅

community.postgresql.postgresql_script

从文件中运行PostgreSQL语句。

community.postgresql.postgresql_db

从远程主机添加或删除PostgreSQL数据库。

PostgreSQL模式参考

PostgreSQL模式文档的完整参考。

示例

- 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.org.cn/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 }}'

返回值

常见的返回值已在此处记录,以下是此模块特有的字段

描述

query

字符串

已执行的查询。

当从文件读取多个查询时,它只包含最后一个查询。

返回:成功

示例:"SELECT * FROM bar"

query_all_results

列表 / 元素=列表

包含所有已执行查询结果的列表(每个查询一个子列表)。

返回:成功

示例:[[{"Column": "Value1"}, {"Column": "Value2"}], [{"Column": "Value1"}, {"Column": "Value2"}]]

query_list

列表 / 元素=字符串

已执行查询的列表。

返回:成功

示例:["SELECT * FROM foo", "SELECT * FROM bar"]

query_result

列表 / 元素=字典

以列:值形式表示返回行的字典列表。

当从文件运行查询时,返回最后一个查询的结果。

返回:成功

示例:[{"Column": "Value1"}, {"Column": "Value2"}]

rowcount

整数

生成的或受影响的行数。

当使用包含多个查询的脚本时,它包含生成的或受影响的行总数。

返回:已更改

示例:5

statusmessage

字符串

包含命令返回的消息的属性。

当从文件读取多个查询时,它包含最后一个查询的消息。

返回:成功

示例:"INSERT 0 1"

作者

  • Felix Archambault (@archf)

  • Andrew Klychkov (@Andersson007)

  • Will Rouesnel (@wrouesnel)