使提示变量在整个剧本中可用

Making prompted vars usable across the playbook

我有一本包含多个任务的剧本,这些任务必须 运行 在不同的主机上。 在播放开始时,我想提示操作员输入他们的凭证,这些凭证对于播放中的每个主机都是相同的。我想将这些凭据 "stored" 放在某个地方,以便在任务中使用它们来登录提供的主机。

剧本如下,

---
- name: Ask for credentials
  vars_prompt:
    - name: username
      prompt: "Username?"
    - name: password
      prompt: "Password?"
  tasks:
    - set_fact:
        username: "{{username}}"
    - set_fact:
        password: "{{password}}"

- hosts: Host1
  vars:
    ansible_user: "{{ username }}"
    ansible_password: "{{ password }}"
  tasks:
    - name: Do stuff  

- hosts: Host2
  vars:
    ansible_user: "{{username}}"
    ansible_password: "{{password}}"
  tasks:
    - name: Do stuff
...

从播放执行第一个任务的那一刻起,它将因流动错误而失败,

msg: 'The field ''remote_user'' has an invalid value, which includes an undefined variable. The error was: ''username'' is undefined'

有没有人有过让提示变量在整个游戏和所有任务中可用的经验?

Q: "Make prompted vars usable across the whole play and all tasks>"

答:运行先用所有主机组先玩,以后应该连上。 运行 一次 set_fact 任务。这将为组中的所有主机创建变量 usernamepassword

例如,如果组 test_jails 包含主机 test_01, test_02, test_03 播放

- hosts: test_jails
  vars_prompt:
    - name: "username"
      prompt: "Username?"
    - name: "password"
      prompt: "Password?"
  tasks:
    - set_fact:
        username: "{{ username }}"
        password: "{{ password }}"
      run_once: true

- hosts: test_01
  vars:
    ansible_user: "{{ username }}"
    ansible_password: "{{ password }}"
  tasks:
    - debug:
        msg: "{{ ansible_user }} {{ ansible_password }}"

给予

ok: [test_01] => {
    "msg": "admin 1234"
}