问题描述
我有一个可以通过 ssh 进入的 DataDomain 系统。我需要在 DataDomain 上自动执行一个过程,该过程在命令后提出问题:
storage add tier active dev3
Object-store is not enabled. Filesystem will use block storage for user data.
Do you want to continue? (yes|no) [no]: yes
我确实在 Ansible 上尝试过,并且确实使用了原始模块
- name: add dev3 active tier
raw: storage add tier active dev3
register: RESULT
这是失败的:
TASK [add dev3 active tier] *******************************************************************************************************************************************************************
fatal: [3.127.218.96]: Failed! => {"changed": true,"msg": "non-zero return code","rc": 9,"stderr": "Shared connection to 3.127.218.96 closed.\r\n","stderr_lines": ["Shared connection to 3.127.218.96 closed."],"stdout": "\r\n**** Could not add storage: system capacity exceeds the limit allowable by the license.\r\n\r\n","stdout_lines": ["","**** Could not add storage: system capacity exceeds the limit allowable by the license.",""]}
以下 ansible-playbook 也失败了:
- name: add dev3 active tier
raw: |
yes | storage add tier active dev3
register: RESULT
expect 模块不接受原始数据并且也失败了。
- name expect for add dev3 active tier
expect:
raw: storage add tier active dev3
responses:
Question:
- Do you want to continue? (yes|no) [no]: y
timeout: 30
register: RESULT
知道如何用“是”来回答问题吗?
解决方法
您的 expect
任务的问题来自两个方面:
首先,事实是:
响应下的问题或关键字是 Python 正则表达式匹配。
来源:https://docs.ansible.com/ansible/latest/collections/ansible/builtin/expect_module.html#notes
因此,您将不得不转义每个可能在正则表达式中有意义的符号。
在您的情况下,这些符号是 ?
、(
、|
、)
、[
和 ]
。
注意:这些种类或行为在像这样的正则表达式工具中很容易测试:https://regex101.com/r/ubtVfH/1/
其次,responses
键具有您在此处混合的两种格式。
- 无论你有
您没有从脚本中指定问题,而是指定答案的顺序列表。当然,这只有在问题和回答始终以相同的顺序出现时才有效。responses: Question: - response1 - response2 - response3
- 无论你使用
在这里,您确定您将每个答案正确映射到相应问题。请注意,这本字典中没有responses: This is the prompt of the question in the script: that is the answer This is another question: and here is the corresponding answer
Question
键,答案是字典的键,而不是列表。
因此,对于您的用例,expect 的正确用法是:
- expect:
command: storage add tier active dev3
responses:
Do you want to continue\? \(yes\|no\) \[no\]: 'yes'
timeout: 30
register: result
,
yes
命令默认发送 y
。但是您的命令需要 yes
。您可以将字符串传递给 yes
命令以重复。
- name: add dev3 active tier
shell:
cmd: yes yes | storage add tier active dev3
register: RESULT