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

注意

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

概要

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

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

要求

执行此模块的主机需要满足以下要求。

  • python >= 2.6

  • pexpect >= 3.3

参数

参数

注释

chdir

路径

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

command

字符串 / 必需

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

creates

路径

如果文件已存在,则此步骤将不会运行。

echo

布尔值

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

选项

  • false ←(默认)

  • true

removes

路径

如果文件不存在,则此步骤将不会运行。

responses

字典 / 必需

提示正则表达式和相应答案的映射。

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

每个键的值都是一个字符串或字符串列表。如果该值是一个字符串并且多次遇到提示,则将重复该答案。以列表形式提供该值,以便为连续匹配提供不同的答案。

timeout

任意

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

默认值: 30

属性

属性

支持

描述

check_mode

支持:

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

diff_mode

支持:

当处于 diff 模式时,将返回有关已更改(或可能需要在 check_mode 中更改)的详细信息

platform

平台: posix

可以操作的目标操作系统/系列

注释

注意

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

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

  • 此模块使用的 pexpect 库使用 2000 字节的搜索窗口进行操作,并且不使用多行正则表达式匹配。要执行行首边界匹配,请使用诸如 ``(?m)^pattern`` 之类的模式

  • ansible.builtin.expect 模块是为简单场景设计的。对于更复杂的需求,请考虑将 expect 代码与 ansible.builtin.shellansible.builtin.script 模块结合使用。(一个示例是 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)