Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

issue while including another playbook in ansible?

I have written a playbook named as master.yaml as defined below

- 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']

I am trying run another playbook named as slave.yaml as defined below, after a certain condition is met.

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

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

Now i have two question:

  • I am not able to set the value of var isDone. slave.yaml should only work when isDone is true.
  • 2.How salve.yaml access the value worker. I have defined group worker in inventory.yaml
like image 732
TechChain Avatar asked Jul 19 '19 09:07

TechChain


1 Answers

I do not know if it's the right way to go to reach your objective. However I tried to make this playbook work by keeping as much as possible your logic. Hope it helps.

The point is that you cannot use import_playbook inside the play. Check the module documentation for more information. So I propose to share code with a role instead of a playbook. You will be able to share the slave role between the master playbook and another playbooks, a slave playbook for example.

The ansible folder structure is the following.

├── 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'

Slave main.yml

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

At the end the /tmp/test.text contains the effective user group name.

like image 114
Romain Avatar answered Sep 30 '22 22:09

Romain