Python将ansible msg输出作为变量

2024-10-02 22:29:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用python3和ansible 2.9.2, 我使用python脚本运行剧本:

subprocess.Popen(["ansible-playbook",  "create.yml"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

我以字符串的形式获取输出:

"(b'\nPLAY [localhost] **\n\nTASK [Creating abc] ***\nok: [localhost]\n\nTASK [debug] ***\nok: [localhost] => {\n    "msg": "10.0.0.1"\n}\n\nPLAY RECAP ******\nlocalhost  : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   \n\n', b"[WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all'\n[WARNING]: Found variable using reserved name: name\n")"

如何在python中只过滤“msg”输出

我想将ip地址10.0.0.1作为变量,但找不到合适的正则表达式来捕获它

谢谢


Tags: name脚本localhostismsgansiblepython3subprocess
2条回答

由于ansible输出(playbook的结果)与2.9.2中的语法没有变化,因此我将使用类似的方法来捕获作为变量的ip:

import json

long_output = '''"(b'\nPLAY [localhost] **\n\nTASK [Creating abc] ***\nok: [localhost]\n\nTASK [debug] ***\nok: [localhost] => {\n    "msg": "10.0.0.1"\n}\n\nPLAY RECAP ******\nlocalhost  : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   \n\n', b"[WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all'\n[WARNING]: Found variable using reserved name: name\n")"'''

cut_string = json.loads(long_output.split("=> ")[1].split('PLAY RECAP')[0])
print(cut_string)

输出:

{'msg': '10.0.0.1'}

然后做这个小把戏,将所有IP地址捕获为列表:(如果您要在多个目的地上运行playbook,可能供将来使用)

ip_addresses = [ip for ip in dict(cut_string).values()]
print(ip_addresses)

输出:

['10.0.0.1']

希望你会觉得这很有用

因为您已经从python脚本启动了一个剧本,所以我推荐Ansible Runner

相关问题 更多 >