Unsetting a set_fact variable

Hi guys,

I’ve got a setup which sets a fact based on whether a file exists or not.

This fact works for one run in the play but doesn’t work when I want that value to be removed for another task inside the play.

  • name: Check if a bucket_policy file exists for {{ bucket_name.name }}

stat:

path: “{{ role_path }}/files/{{ bucket_name.name }}.json”

register: bucket_policy_status

  • name: Read in bucket_policy if policy_file exists for {{ bucket_name.name }}

set_fact:

bucket_policy_json: “{{ lookup(‘file’, bucket_name.name + ‘.json’) }}”

when: bucket_policy_status.stat.exists

  • name: Set policy variable to None when bucket policy doesn’t exist for {{ bucket_name.name }}

set_fact:

bucket_policy_json: “{{ omit }}”

when: not bucket_policy_status.stat.exists

  • name: Create S3 bucket {{ bucket_name.name }}

s3_bucket:

name: “{{ item }}”

state: present

policy: “{{ bucket_policy_json | default(omit) }}”

profile: “{{ aws_account_name }}”

region: “{{ bucket_name.region }}”

with_items: “{{ bucket_name.name | default({}) }}”

register: created_bucket

Is there a way to “unset” a set_fact to something that default(omit) can recognise?

At the moment, if the first run through sets bucket_policy_json to a value, the next thing that comes along that hits the when: not bucket_policy_status.stat.exists statement does not successfully clear that fact to an undefined state.

Is there a magic variable to “undefine” a fact by any chance?

Regards

Karen

Pretty sure there isn’t an unset function for set_fact. Ended up going with a ternary jinja2 filter instead which appears to work: