在 ansible 中包含另一个剧本时出现问题?

issue while including another playbook in ansible?

我写了一个名为 master.yaml 的剧本,定义如下

- hosts: master
  remote_user: "{{ ansible_user }}"

  tasks:
    - name: Get env
      command: id -g -n {{  lookup('env', '$USER') }}
      register: group_user
      vars:
        is_done: "false"

    - include: slave.yaml
      vars:
        sethostname: "{{ group_user }}"
        worker: worker
      when: is_done == "true"
      where: inventory_hostname in groups['worker']

我正在尝试 运行 另一个名为 slave.yaml 的剧本,在满足特定条件后定义如下。

- hosts: worker
  remote_user: "{{ ansible_user }}"

  tasks:
    - name: Write to a file for deamon setup
      copy:
        content: "{{ sethostname }}"
        dest: "/home/ubuntu/test.text"

现在我有两个问题:

我不知道到达您的 objective 是否正确。但是,我试图通过尽可能多地保留您的逻辑来使这本剧本发挥作用。希望对你有帮助。

关键是你不能在剧中使用import_playbook。查看 module documentation 了解更多信息。 所以我建议与 role 共享代码而不是 playbook。您将能够在 master 剧本和其他剧本之间共享 slave 角色,例如 slave 剧本。

ansible文件夹结构如下

├── hosts
├── master.yml
└── roles
    └── slave
        └── tasks
            └── main.yml

Master.yml

---
- name: 'Master Playbook'
  # Using the serial keyword to run the playbook for each host one by one
  hosts: master
  serial: 1
  remote_user: "{{ ansible_user }}"

  tasks:
    - name: 'Get env'
      command: id -g -n {{ lookup('env', '$USER') }}
      register: group_user

    - name: 'Calling the slave role'
      import_role:
        name: 'slave'
      # The return value of the command is stored in stdout
      vars:
        sethostname: "{{ group_user.stdout }}"
      # Only run when the task get env has been done (state changed)
      when: group_user.changed
      # Delegate the call to the worker host(s) -> don't know if it's the expected behavior
      delegate_to: 'worker'

奴隶main.yml

---
- name: 'Write to a file for deamon setup'
  copy:
    content: "{{ sethostname }}"
    dest: "/tmp/test.text"

最后 /tmp/test.text 包含有效的用户组名称。