Repository: ansible/ansible

Issue:
[rpm_key] When no key is installed module fail to install any new key
<!---
Verify first that your issue/request is not already reported on GitHub.
Also test if the latest release, and master branch are affected too.
-->

##### ISSUE TYPE
<!--- Pick one below and delete the rest: -->
 - Bug Report

##### COMPONENT NAME
<!--- Name of the module/plugin/task/feature -->
rpm_key

##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes below -->
```
ansible 2.4.0.0
  config file = /etc/ansible/ansible.cfg
  configured module search path = [u'/home/lbednar/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /home/lbednar/work/kubevirt-org/kubevirt-ansible/E/lib/python2.7/site-packages/ansible
  executable location = /home/lbednar/work/kubevirt-org/kubevirt-ansible/E/bin/ansible
  python version = 2.7.13 (default, May 10 2017, 20:04:28) [GCC 6.3.1 20161221 (Red Hat 6.3.1-1)]
```

##### 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).

-->
```
DEFAULT_ROLES_PATH(env: ANSIBLE_ROLES_PATH) = [u'/home/lbednar/work/kubevirt-org/kubevirt-ansible/galaxy-roles']
```

##### 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.
-->
Target system CentOS 7.3

##### SUMMARY
<!--- Explain the problem briefly -->

When running `rpm_key` to add new key on system which doesn't have any keys installed yet (I want to install first key), then module fails to add new key during execution following line:

https://github.com/ansible/ansible/blob/e609618274db6a7e3c273abde457f53de8c9976c/lib/ansible/modules/packaging/os/rpm_key.py#L173

the command fails with:
```
$ /usr/bin/rpm -q  gpg-pubkey --qf "%{description}"
package gpg-pubkey is not installed
```
and then following command in shell pipe fails on
```
$ /usr/bin/gpg --no-tty --batch --with-colons --fixed-list-mode -
gpg: no valid OpenPGP data found.
gpg: processing message failed: Unknown system error
```
At this point module stops execution and fail.

##### 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.
-->

**You need to make sure that you don't have any RPM KEY installed yet.**
This issue is reproducible only in case of when you are adding first rpm key.

<!--- Paste example playbooks or commands between quotes below -->
```yaml
- name: import rpm keys
  rpm_key: 
    state: present
    key: "{{ item }}"
  with_items:
    - "https://packages.cloud.google.com/yum/doc/rpm-package-key.gpg"
```

<!--- You can also paste gist.github.com links for larger files -->

##### EXPECTED RESULTS
<!--- What did you expect to happen when running the steps above? -->

I would like to get rpm keys imported.

##### ACTUAL RESULTS
<!--- What actually happened? If possible run with extra verbosity (-vvvv) -->

No key is added and getting following output instead.

<!--- Paste verbatim command output between quotes below -->
```
failed: [vm-69-15.qa.lab.tlv.redhat.com] (item=https://packages.cloud.google.com/yum/doc/rpm-package-key.gpg) => {"changed": false, "failed": true, "item": "https://packages.cloud.google.com/yum/doc/rpm-package-key.gpg", "msg": "gpg: no valid OpenPGP data found.\ngpg: processing message failed: Unknown system error\n"}
```



Discussion:
cc @hacosta
[click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md)
<!--- boilerplate: notify --->
cc @schwatvogel 

Resolving patch:
diff --git a/lib/ansible/modules/packaging/os/rpm_key.py b/lib/ansible/modules/packaging/os/rpm_key.py
--- a/lib/ansible/modules/packaging/os/rpm_key.py
+++ b/lib/ansible/modules/packaging/os/rpm_key.py
@@ -170,11 +170,15 @@ def execute_command(self, cmd):
         return stdout, stderr
 
     def is_key_imported(self, keyid):
-        cmd=self.rpm + ' -q  gpg-pubkey --qf "%{description}" | ' + self.gpg + ' --no-tty --batch --with-colons --fixed-list-mode -'
+        cmd = self.rpm + ' -q  gpg-pubkey'
+        rc, stdout, stderr = self.module.run_command(cmd)
+        if rc != 0:  # No key is installed on system
+            return False
+        cmd += ' --qf "%{description}" | ' + self.gpg + ' --no-tty --batch --with-colons --fixed-list-mode -'
         stdout, stderr = self.execute_command(cmd)
         for line in stdout.splitlines():
             if keyid in line.split(':')[4]:
-                    return True
+                return True
         return False
 
     def import_key(self, keyfile):


Test patch:
diff --git a/test/integration/targets/rpm_key/tasks/rpm_key.yaml b/test/integration/targets/rpm_key/tasks/rpm_key.yaml
--- a/test/integration/targets/rpm_key/tasks/rpm_key.yaml
+++ b/test/integration/targets/rpm_key/tasks/rpm_key.yaml
@@ -101,3 +101,11 @@
 - name: confirm that signature check succeeded
   assert:
     that: "'rsa sha1 (md5) pgp md5 OK' in sl_check.stdout"
+
+- name: remove all keys from key ring
+  shell: "rpm -q  gpg-pubkey | xargs rpm -e"
+
+- name: add very first key on system
+  rpm_key:
+    state: present
+    key: https://download.fedoraproject.org/pub/epel/RPM-GPG-KEY-EPEL-7