I am using Ansible and I want to run a task only once. I follow the documentation about how to configure and run a task only once
- name: apt update
shell: apt-get update
run_once: true
But when I run Ansible, it always runs this task. How can I run my task only once.
The run_once option will run every time your Playbook/tasks runs, but will only run it once during the specific run itself. So every time you run the play, it will run, but only on the first host in the list. If you're looking for a way to only run that command once, period, you'll need to use the creates argument. Using your example, this can be achieved by using the following -
- name: apt update
shell: apt-get update && touch /root/.aptupdated
args:
creates: /root/.aptupdated
In this case the file /root/.aptupdated is created. The task will now check to see if that exists, and if it does it will not run.
On a related note if the task you are trying to run is the apt-get update, you may want to use the native apt module. You can then do something like this -
- name: apt update
apt: update_cache=yes cache_valid_time=86400
Now this will only run if the cache is older than one day.