使用 Ansible 将数据从 Google Compute Engine 发送到 Google Pub/Sub

Send data from Google Compute Engine to Google Pub/Sub using Ansible

我想使用 Ansible 将数据从 Google vm 实例发送到 Google Pub/Sub。

Ansible 剧本

---
- hosts: localhost
  tasks:

  - name: Write into log file
    local_action:
      shell echo "Hello" >> /etc/ansible/log.txt

  - name: Send message through pubsub
    shell: python pub.py project-344421 topic_test
    args:
      chdir: /home/pubsub 

错误

    "msg": "non-zero return code", 
    "rc": 1, 
    "start": "2020-04-14 18:20:00.723265", 
    "stderr": "Traceback (most recent call last):\n  File \"pub.py\", line 22, in <module>\n    from google.cloud import pubsub_v1\nImportError: No module named google.cloud", 
    "stderr_lines": [
        "Traceback (most recent call last):", 
        "  File \"pub.py\", line 22, in <module>", 
        "    from google.cloud import pubsub_v1", 
        "ImportError: No module named google.cloud"
    ], 
    "stdout": "", 
    "stdout_lines": []

手动,脚本 pub.pypython pub.py project-344421 topic_test

一起正常运行

输出

der_topic
Published message Hello
 now has message ID 874436722336138
Published 1 message(s).

已安装模块 google.cloud、google-cloud-pubsub 和 google-auth

pip install --upgrade google-cloud
pip install --upgrade google-cloud-pubsub
pip install --upgrade google-auth 

Ansible 使用的 python 可执行文件可能与您在命令行中使用的不同。

使用以下命令找出可执行文件运行的路径...

$ which python

...然后 copy/paste 可执行文件的路径进入您的 shell 命令。

  - name: Send message through pubsub
    shell: /<FULL>/<PATH>/python pub.py project-344421 topic_test
    args:
      chdir: /home/pubsub 

如果这不起作用,那么您也可以尝试检查您的 PYTHONPATH 环境变量,看看它在您的终端和 Ansible 上下文中是否相同。