Run a task on only one server in a group in inventory.

,

Hi guys,

I have a situation where I need to run one task in only one server of a particular group.

For example i have inventory as below
[aws]
server1
server2

[gcp]
server3
server4

now I need to run a task on whichever server connects first and task should be run only once.
I am using when condition to run tasks on gcp group as " inventory_hostname in groups['gcp'] " but when I use run_once: true it is taking the server1 from aws group and whole task is getting skipped.

Please help and guide me.

Regards,
Soumya

Split the playbook into two plays. For example

  - hosts: aws
    tasks:
      - debug:
          msg: Run this task on one server only
        run_once: true
  - hosts: gcp
    tasks:
      - debug:
          msg: Run this task on one server only
        run_once: true

You might want to put such tasks into a role. For example

  - hosts: aws
    tasks:
      - include_role:
          name: my_library_of_tasks
          tasks_from: task_on_one_server_only.yml
        run_once: true
  - hosts: gcp
    tasks:
      - include_role:
          name: my_library_of_tasks
          tasks_from: task_on_one_server_only.yml
        run_once: true

HTH,

  -vlado