大网数据广告活动
服务器运维问答

Custom diff output from a shell task in ansible?

· 52CE 我爱测

I am making an ansible task which needs some custom logic, so I'm writting a little shell script and using the shell task. Is there anyway I can output any sort of "diff" output to display to the user if they are using --diff ? I…

问题原文

原帖链接 · Amandasaurus · CC BY-SA 4.0

I am making an ansible task which needs some custom logic, so I'm writting a little shell script and using the shell task. Is there anyway I can output any sort of "diff" output to display to the user if they are using --diff? I know about using -vv to look at the stdout & stderr of the script, but that's not formatted well, and you get lots of extra output too

Ansible version 2.9.6

已采纳解答

原帖链接 · flowerysong · CC BY-SA 4.0

In order to do this you would need to write a custom module, not simply a custom script. The command and shell modules do not have any provision for returning custom attributes based on command output.

Custom Python modules are fairly easy to write and can be placed in a library directory adjacent to your playbook or within a role (see https://docs.ansible.com/ansible/latest/dev_guide/developing_locally.html#adding-a-module-locally). You can also write custom modules as bash scripts and deploy them the same way, but you'll miss out on a lot of the convenience functions available to Python modules for things like argument validation.

Here's a quick and dirty bash module that returns a text file:

#!/bin/bash

source $1
jq -n -r \
    --arg contents "$(cat $src)"\
    '{ changed: false, result: $contents }'

Or some fairly equivalent Python:

!/usr/bin/python
# -*- coding: utf-8 -*-

from __future__ import absolute_import, division, print_function
__metaclass__ = type

from ansible.module_utils.basic import AnsibleModule


def main():
    module = AnsibleModule(
        argument_spec = {
            'src': {
                'required': True,
                'type': 'path',
            }
        }
    )

    with open(module.params['src'], 'r') as f:
        contents = f.read()

    module.exit_json(changed=False, result=contents)


if __name__ == '__main__':
    main()

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2021-03-17)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。