Shashank Agrawal
Shashank Agrawal

Reputation: 345

How to run a task only once during entire Ansible Playbook?

I have a Ansible playbook which does multiple things as below -

  1. Download artifacts fron nexus into local server (Ansible Master).
  2. Copy those artifacts onto multiple remote machines let's say server1/2/3 etc..

And I have used roles in my playbook and the role (repodownload) which downloads the artifacts I want to run it only once because why would i want to download the same thing again. I have tried to use run_once: true but i guess that won't work because that only works for one playbook run but my playbook is running multiple times for multiple hosts.

--- - name: Deploy my Application to tomcat nodes hosts: '{{ target_env }}' serial: 1 roles: - role: repodownload tags: - repodownload - role: copyrepo tags: - copyrepo - role: stoptomcat tags: - stoptomcat - role: deploy tags: - deploy

Here target_env is being passed from the command line and it's the remote host group. Any help is appreciated.

Below is the code from main.yml from repodownload role -

- connection: local name: Downloading files from Nexus to local server get_url: url="{{ nexus_url }}/{{item}}/{{ myvm_release_version }}/{{item}}-{{ release_ver }}.war" dest={{ local_server_location }} with_items: - "{{ temps }}"

Upvotes: 1

Views: 3990

Answers (2)

Gabriel Fortuna
Gabriel Fortuna

Reputation: 132

This is a really simple one that I battled with too.

Try this:

- connection: local
   name: Downloading files from Nexus to local server
   get_url:
     url:  "{{ nexus_url }}/{{item}}/{{ myvm_release_version }}/{{item}}-{{ release_ver }}.war"
     dest: "{{ local_server_location }}"
   with_items:
    - "{{ temps }}"
   run_once: true

Just something else, unrelated to your main question;

When you run a module that has really long args, like in your example above, rather break the params into their own lines nested under the module. It makes for easier reading, and it makes it easier to spot any potential typos or syntax errors early.

Upvotes: 4

Uttam
Uttam

Reputation: 596

Okay extending from your converstation with Zeitounator. The following workaround will work without changing your vars files. Just remember that this is a workaround, might not be the most efficient way to do the job.

---
- name: Download my repo to localhost
  # Executes only for first host in target_env and has visibility to group vars of target_env
  hosts: '{{ target_env }}[0]'
  serial: 1
  roles:
    - role: repodownload
      tags:
        - repodownload

- name: Deploy my Application to tomcat nodes
  # Executes for all hosts in target_env
  hosts: '{{ target_env }}'
  serial: 1
  roles:
    - role: copyrepo
      tags:
        - copyrepo
    - role: stoptomcat
      tags:
        - stoptomcat
    - role: deploy
      tags:
        - deploy

Upvotes: 0

Related Questions