我写了一个名为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"

现在我有两个问题:
  • 我无法设置var isDone的值。 slave.yaml应该
    仅在isDone为true时有效。
  • 2. salve.yaml如何访问值 worker 。我在inventory.yaml
  • 中定义了小组工作人员

    最佳答案

    我不知道这是否是实现目标的正确方法。但是,我试图通过尽可能多地保持逻辑来使这本剧本发挥作用。希望能帮助到你。

    关键是您不能在剧本中使用import_playbook。检查module documentation以获取更多信息。
    因此,我建议使用角色而不是剧本来共享代码。您将能够在slave剧本和另一个剧本(例如master剧本)之间共享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包含有效的用户组名称。

    关于ansible - 同时在ansible中包含另一本剧本时出现问题?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57109694/

    10-11 08:44