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

时间:2019-07-19 09:39:15

标签: ansible devops ansible-2.x

我写了一个名为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为真时有效。
  • 2。salve.yaml如何访问值工作者。我在stock.yaml中定义了小组工作人员

1 个答案:

答案 0 :(得分:0)

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

重点是您不能在剧本中使用import_playbook。查看module documentation了解更多信息。 因此,我建议使用角色而不是剧本共享代码。您将能够在slave剧本和另一个剧本(例如master剧本)之间共享slave角色。

ansible文件夹结构如下。

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

Master.yml

---
- name: 'Master Playbook' 
  hosts: master
  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的末尾包含有效的用户组名称。