ansible.builtin.expect 模块 – 执行命令并响应提示
注意
此模块是 ansible-core 的一部分,并包含在所有 Ansible 安装中。在大多数情况下,即使不指定集合关键字,您也可以使用简短的模块名称 expect。但是,我们建议您使用完全限定集合名称 (FQCN) ansible.builtin.expect,以便轻松链接到模块文档并避免与其他可能具有相同模块名称的集合冲突。
概要
- ansible.builtin.expect 模块执行命令并响应提示。 
- 给定的命令将在所有选定节点上执行。它不会通过 shell 处理,因此像 - $HOME这样的变量以及像- "<"、- ">"、- "|"和- "&"这样的操作将不起作用。
要求
执行此模块的主机需要以下要求。
- python >= 2.6 
- pexpect >= 3.3 
参数
| 参数 | 注释 | 
|---|---|
| 在运行命令之前更改到此目录。 | |
| command 模块需要运行的命令。 | |
| 当文件名已经存在时,此步骤将不会运行。 | |
| 是否回显您的响应字符串。 选择 
 | |
| 当文件名不存在时,此步骤将不会运行。 | |
| 提示正则表达式和相应答案的映射。 
 每个键的值是一个字符串或字符串列表。如果该值是一个字符串并且多次遇到提示,则会重复该答案。将该值作为列表提供,以便为连续匹配给出不同的答案。 | |
| 等待预期字符串的秒数。使用  默认值:  | 
属性
| 属性 | 支持 | 描述 | 
|---|---|---|
| 支持:无 | 可以在 check_mode 中运行并返回更改的状态预测,而无需修改目标,如果不支持,则会跳过该操作。 | |
| 支持:无 | 在 diff 模式下,将返回有关已更改内容(或可能需要在 check_mode 中更改的内容)的详细信息 | |
| 平台: posix | 可以操作的目标操作系统/系列 | 
注意
注意
- 如果您想通过 shell 运行命令(假设您正在使用 - <、- >、- |等),则必须在命令中指定一个 shell,例如- /bin/bash -c "/path/to/something | grep else"。
- 不区分大小写的搜索以 - (?i) 前缀表示。
- 此模块使用的 - pexpect库以 2000 字节的搜索窗口进行操作,并且不使用多行正则表达式匹配。要执行行首绑定匹配,请使用类似- (?m^pattern) 的模式。
- ansible.builtin.expect 模块专为简单场景设计。对于更复杂的需求,请考虑将 expect 代码与 ansible.builtin.shell 或 ansible.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 }}"
