Using variables in changed_when/failed_when directives

Hello lovley ansible community,

i have a question regarding the usage of variables in changed_when/failed_when directives due to the warning [WARNING]: conditional statements should not include jinja2 templating delimiters such as {{ }} or {% %}

I am aware of:

All the examples refer to variables introduced via the register directive.

I am using the following playbook for creating a serviceaccount via SSH, to use later on the k8s module itself:

The playbook looks like this:

- name: K8s
  hosts: k8s_executor
  vars:
    serviceaccountuser: ansible-user

  tasks:

    - name: Create service account on k8s
      ansible.builtin.shell: kubectl --kubeconfig=$HOME/.kube/config create serviceaccount {{ serviceaccountuser }} --namespace kube-system
      register: tmp
      changed_when:
        - tmp.rc == 0
        - "tmp.stdout == \"serviceaccount/{{ serviceaccountuser }} created\""
      failed_when:
        - tmp.rc > 0
        - "'already exists' not in tmp.stderr"
  ....

As u can see i want to avoid retyping ansible-user everywhere, why i have introduced the variable.

Q: Is there the possibility to reference those vars in the changed_when or failed_when directives?

Thank you in advance!

All variables are referenced the same way, so that’s irrelevant.

Conditional statements should not include Jinja delimiters, because it’s already a Jinja context. Just reference variables by name.

- tmp.stdout == "serviceaccount/" ~ serviceaccountuser ~ "created"
2 Likes

amazing - that was the missing link.

thanks a lot.

Guess ill raise a PR to add this to the docs. Somehow missing tbh :smiley:

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.