diff --git a/plugins/modules/ec2_instance.py b/plugins/modules/ec2_instance.py index 2bc65d9a729..efca90e5740 100644 --- a/plugins/modules/ec2_instance.py +++ b/plugins/modules/ec2_instance.py @@ -1780,7 +1780,7 @@ def determine_iam_role(name_or_arn): def handle_existing(existing_matches, state): - tags = dict(module.params.get('tags', None)) + tags = module.params.get('tags') purge_tags = module.params.get('purge_tags') name = module.params.get('name') @@ -1788,7 +1788,7 @@ def handle_existing(existing_matches, state): # into tags, but since tags isn't explicitly passed we'll treat it not being # set as purge_tags == False if name: - if purge_tags and tags is None: + if tags is None: purge_tags = False tags = {} tags.update({'Name': name}) diff --git a/tests/integration/targets/ec2_instance/roles/ec2_instance/tasks/tags_and_vpc_settings.yml b/tests/integration/targets/ec2_instance/roles/ec2_instance/tasks/tags_and_vpc_settings.yml index 04ecd22a241..a81e0040b42 100644 --- a/tests/integration/targets/ec2_instance/roles/ec2_instance/tasks/tags_and_vpc_settings.yml +++ b/tests/integration/targets/ec2_instance/roles/ec2_instance/tasks/tags_and_vpc_settings.yml @@ -138,11 +138,45 @@ - check_tags.instances[0].tags.Name.startswith(resource_prefix) - "'{{ check_tags.instances[0].state.name }}' in ['pending', 'running']" + - name: "Try setting purge_tags to True without specifiying tags (should NOT purge tags)" + ec2_instance: + state: present + name: "{{ resource_prefix }}-test-basic-vpc-create" + image_id: "{{ ec2_ami_id }}" + purge_tags: true + security_groups: "{{ sg.group_id }}" + vpc_subnet_id: "{{ testing_subnet_b.subnet.id }}" + instance_type: "{{ ec2_instance_type }}" + register: _purge_tags_without_tags + + - name: Assert tags were not purged + assert: + that: + - _purge_tags_without_tags.instances[0].tags | length > 1 + + - name: "Purge all tags (aside from Name)" + ec2_instance: + state: present + name: "{{ resource_prefix }}-test-basic-vpc-create" + image_id: "{{ ec2_ami_id }}" + purge_tags: true + tags: {} + security_groups: "{{ sg.group_id }}" + vpc_subnet_id: "{{ testing_subnet_b.subnet.id }}" + instance_type: "{{ ec2_instance_type }}" + register: _purge_tags + + - name: Assert tags were purged + assert: + that: + - _purge_tags.instances[0].tags | length == 1 + - _purge_tags.instances[0].tags.Name.startswith(resource_prefix) + - name: "Terminate instance" ec2_instance: state: absent filters: - "tag:TestId": "{{ ec2_instance_tag_TestId }}" + "tag:Name": "{{ resource_prefix }}-test-basic-vpc-create" wait: false register: result - assert: