# Changing UFW rules

**URL:** <https://forum.ansible.com/t/changing-ufw-rules/21567>\
**Category:** Ansible Project\
**Created:** [May 25, 2016, 5:49pm UTC](https://forum.ansible.com/t/changing-ufw-rules/21567 "2016-05-25T17:49:51Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Guy\_Knights](https://avatars.discourse-cdn.com/v4/letter/g/db5fbb/32.png) [@Guy\_Knights](https://forum.ansible.com/u/Guy_Knights)\
**Post date:** [May 25, 2016, 5:49pm UTC](https://forum.ansible.com/t/changing-ufw-rules/21567/1 "2016-05-25T17:49:51Z")

</div>

Does anyone have a solution for dealing with changes to UFW rules in Ansible? The issue is that occasionally, I have to change a rule in some way (change IPs/networks, change port) but the old rule still remains. I could add a separate, special rule to delete the old version but that seems overly fiddly to me.

When I was first playing around with this, I did have a rule at the beginning of my firewall playbook that reset UFW on every run before applying the rule tasks but I decided to remove it because it seems like the wrong approach.

Thanks,  
Guy

---

<div class="post-metadata">

**Author:** ![sivel](https://sea1.discourse-cdn.com/ansible/user_avatar/forum.ansible.com/sivel/32/1198_2.png) [@sivel](https://forum.ansible.com/u/sivel)\
**Post date:** [May 25, 2016, 5:55pm UTC](https://forum.ansible.com/t/changing-ufw-rules/21567/2 "2016-05-25T17:55:52Z")

</div>

I’d recommend handling it much the same way I recommend handling users. Create a var containing the rules and state of the rule. And have it loop using with\_items. Something like:

ufw\_rules:

- port: 22  
rule: allow  
proto: tcp
- port: 80  
delete: yes  
rule: allow  
proto: tcp

and then a task like:

ufw:  
port: “{{ item.port }}”  
rule: “{{ item.rule }}”  
proto: “{{ item.proto }}”  
delete: “{{ item.delete|default(omit) }}”  
with\_items: “{{ ufw\_rules }}”

In the above, if delete is specified it is used, otherwise, if missing that param is omitted. This is effectively how we handle this today.
