1

I have a variables file that defines a number of users:

my_users:
  admin:
    - admin1
    - admin2
  user:
    - bob

I have a task that adds these users to mongodb. I don't want to execute the task every time but only if the users changed. I tried the following:

- name: add users
  command: "<add users>"
  when: my_users|changed

However, this does not work as intended. If I add a user, the task is still skipped.

How can I execute a task only if a variable has changed?

1 Answer 1

3

Normally you don't do it the way you are trying. Instead, ansible must create the users if they don't already exist. The way to do it with one user is like this:

- name: Check if user george exists
  command: "<return a status code of zero if user george exists>"
  register: check_george_exists
  ignore_errors: yes
  always_run: yes
  changed_when: False

- name: Create user george
  command: "<create user george>"
  when: check_george_exists.rc == 0

To do it for many users, see Register variables in with_items loop in Ansible playbook.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.