Repository: ansible/ansible

Issue:
cs_instance "user_data"  and "state: destroyed" return  An exception occurred during task execution 
<!---
Verify first that your issue/request is not already reported on GitHub.
Also test if the latest release, and devel branch are affected too.
-->

##### ISSUE TYPE
<!--- Pick one below and delete the rest -->
 - Bug Report


##### COMPONENT NAME
<!---
cs_instance
-->

##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes below -->
```
ansible 2.4.3.0
  config file = /Users/nbari/ansible/ansible.cfg
  configured module search path = [u'/Users/nbari/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /Users/nbari/Library/Python/2.7/lib/python/site-packages/ansible
  executable location = /Users/nbari/Library/Python/2.7/bin/ansible
  python version = 2.7.14 (default, Mar  1 2018, 19:24:37) [GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)]

```

##### CONFIGURATION
<!---
If using Ansible 2.4 or above, paste the results of "ansible-config dump --only-changed"
Otherwise, mention any settings you have changed/added/removed in ansible.cfg
(or using the ANSIBLE_* environment variables).
-->

##### OS / ENVIRONMENT
<!---
Mention the OS you are running Ansible from, and the OS you are
managing, or say "N/A" for anything that is not platform-specific.
Also mention the specific version of what you are trying to control,
e.g. if this is a network bug the version of firmware on the network device.
-->
macOS High Sierra, brew install python2

##### SUMMARY
<!--- Explain the problem briefly -->

when using the `state: destroyed` and using/having `user_data` the instance is destroyed but an error 
is displayed

##### STEPS TO REPRODUCE
<!---
For bugs, show exactly how to reproduce the problem, using a minimal test-case.
For new features, show how the feature would be used.
-->

`ansible-playbook play.yml`

The first time will return an error but after running it the second time it will just work fine ( no error)



<!--- Paste example playbooks or commands between quotes below -->
```yaml
 - name: Creat VM
      cs_instance:
        name: cloudinit-test
        template: Linux CentOS 7.4 64-bit 10G Disk (2018-01-08-d617dd)
        service_offering: Micro
        ssh_key: devops
        api_region: exoscale
        state: destroyed
        tags:
          - key: provisioner
            value: ansible
        user_data: |
            #cloud-config
            package_upgrade: true
            packages:
              - tmux
```

<!--- You can also paste gist.github.com links for larger files -->

##### EXPECTED RESULTS
<!--- What did you expect to happen when running the steps above? -->

No error

##### ACTUAL RESULTS
<!--- What actually happened? If possible run with extra verbosity (-vvvv) -->

<!--- Paste verbatim command output between quotes below -->
```
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: KeyError: 'id'
fatal: [localhost]: FAILED! => {"changed": false, "module_stderr": "Traceback (most recent call last):\n  File \"/var/folders/75/8jzhscr56j13rv6tj6805ch40000gn/T/ansible_b9HigX/ansible_module_cs_instance.py\", line 1088, in <module>\n    main()\n  File \"/var/folders/75/8jzhscr56j13rv6tj6805ch40000gn/T/ansible_b9HigX/ansible_module_cs_instance.py\", line 1078, in main\n    result = acs_instance.get_result(instance)\n  File \"/var/folders/75/8jzhscr56j13rv6tj6805ch40000gn/T/ansible_b9HigX/ansible_module_cs_instance.py\", line 973, in get_result\n    self.result['user_data'] = self._get_instance_user_data(instance)\n  File \"/var/folders/75/8jzhscr56j13rv6tj6805ch40000gn/T/ansible_b9HigX/ansible_module_cs_instance.py\", line 544, in _get_instance_user_data\n    res = self.cs.getVirtualMachineUserData(virtualmachineid=instance['id'])\nKeyError: 'id'\n", "module_stdout": "", "msg": "MODULE FAILURE", "rc": 1}
```



Discussion:

Resolving patch:
diff --git a/lib/ansible/modules/cloud/cloudstack/cs_instance.py b/lib/ansible/modules/cloud/cloudstack/cs_instance.py
--- a/lib/ansible/modules/cloud/cloudstack/cs_instance.py
+++ b/lib/ansible/modules/cloud/cloudstack/cs_instance.py
@@ -460,7 +460,7 @@ def _get_instance_user_data(self, instance):
             return instance['userdata']
 
         user_data = ""
-        if self.get_user_data() is not None:
+        if self.get_user_data() is not None and instance.get('id'):
             res = self.query_api('getVirtualMachineUserData', virtualmachineid=instance['id'])
             user_data = res['virtualmachineuserdata'].get('userdata', "")
         return user_data


Test patch: