ansible.builtin.expect 模块 – 执行命令并响应提示

注意

此模块是 ansible-core 的一部分,包含在所有 Ansible 安装中。在大多数情况下,您可以使用简短的模块名称 expect,即使没有指定 集合关键字。但是,我们建议您使用 完全限定集合名称 (FQCN) ansible.builtin.expect 来方便链接到模块文档,并避免与可能具有相同模块名称的其他集合冲突。

概要

  • ansible.builtin.expect 模块执行命令并响应提示。

  • 给定命令将在所有选定的节点上执行。它不会通过 shell 处理,因此 $HOME 等变量以及 "<"">""|""&" 等操作将不起作用。

要求

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

  • python >= 2.6

  • pexpect >= 3.3

参数

参数

注释

chdir

路径

在运行命令之前更改到此目录。

命令

字符串 / 必需

命令模块接受要运行的命令。

创建

路径

一个文件名,如果它已经存在,则不会运行此步骤。

回显

布尔值

是否回显您的响应字符串。

选择

  • false ← (默认)

  • 真的

删除

路径

一个文件名,如果它不存在,则不会运行此步骤。

响应

字典 / 必需

提示正则表达式与其对应答案的映射。

中的每个键responses是一个 Python 正则表达式 https://docs.pythonlang.cn/3/library/re.html#regular-expression-syntax.

每个键的值是字符串或字符串列表。如果该值是字符串并且遇到多个提示,则会重复答案。将值提供为列表以对连续匹配给出不同的答案。

超时

任何

等待预期字符串的秒数。使用 null 禁用超时。

默认: 30

属性

属性

支持

描述

check_mode

支持:

可以在 check_mode 中运行并返回更改状态预测,而无需修改目标,如果不支持,则将跳过操作。

diff_mode

支持:

将在 diff 模式下返回有关已更改内容(或可能需要在 check_mode 中更改的内容)的详细信息

平台

平台: posix

可以针对其操作的目标操作系统/系列

注释

注意

  • 如果要通过 shell 运行命令(例如,您正在使用 <>| 等),则必须在命令中指定一个 shell,例如 /bin/bash -c "/path/to/something | grep else"

  • 不区分大小写的搜索用 (?i 前缀表示。

  • 该模块使用的 pexpect 库使用 2000 字节的搜索窗口,并且不使用多行正则表达式匹配。要执行行首绑定匹配,请使用类似 (?m^pattern) 的模式。

  • ansible.builtin.expect 模块专为简单场景设计。对于更复杂的需求,请考虑使用 ansible.builtin.shellansible.builtin.script 模块中的 expect 代码。(示例是 ansible.builtin.shell 模块文档的一部分)。

  • 如果命令返回非 UTF-8 数据,则必须对其进行编码以避免问题。一种选择是将输出通过 base64 管道。

另请参阅

另请参阅

ansible.builtin.script

在将本地脚本传输到远程节点后运行它。

ansible.builtin.shell

在目标上执行 shell 命令。

示例

- name: Case insensitive password string match
  ansible.builtin.expect:
    command: passwd username
    responses:
      (?i)password: "MySekretPa$$word"
  # you don't want to show passwords in your logs
  no_log: true

- name: Match multiple regular expressions and demonstrate individual and repeated responses
  ansible.builtin.expect:
    command: /path/to/custom/command
    responses:
      Question:
        # give a unique response for each of the 3 hypothetical prompts matched
        - response1
        - response2
        - response3
      # give the same response for every matching prompt
      "^Match another prompt$": "response"

- name: Multiple questions with responses
  ansible.builtin.expect:
    command: /path/to/custom/command
    responses:
        "Please provide your name":
            - "Anna"
        "Database user":
            - "{{ db_username }}"
        "Database password":
            - "{{ db_password }}"

作者

  • Matt Martz (@sivel)