尝试使用Ansible创建一个自定义的Windows模块
在这里,我们将使用Ansible制作一个简单的Windows自定义模块。
1. 前提
假设Windows系统中已执行ConfigureRemotingForAnsible.ps1脚本以配置WinRM。
2. 开发环境 fā
項目バージョンAnsible2.5.5RHEL7.4Windows Server2016
3. 关于Windows模块
Windows的模块由以下两个文件组成。
ファイル説明.ps1Winowsで実行するPowreshellスクリプト、実際にこのスクリプトがWindows側へ送られて実行される.pyAnsibleのドキュメント用pythonファイル、無くても動作はする
4. Windows的模块工具
如果要创建Windows模块,请使用以下module_utils。
有关详细信息,请参阅以下链接中的代码。
请以中文给出以下内容的释义,只需要一种选项:
https://github.com/ansible/ansible/tree/devel/lib/ansible/module_utils/powershell
只需使用 Exit-Json Fail-Json Parse-Args Get-AnsibleParam,然后仅需导入 Ansible.ModuleUtils.Legacy 即可。
尝试制作模块。
在这里,为了更容易理解,我们将创建一个简单的模块。
我打算创建一个仅用于检查文件是否存在的模块。
5-1. PowerShell源代码
#!powershell
# module_utilsから必要なモジュールを読み込む
#Requires -Module Ansible.ModuleUtils.Legacy
# 結果の連想配列(ハッシュ)を作る
$result = @{ changed = $false }
# モジュールのオプション処理
$params = Parse-Args $args -supports_check_mode $true
$path = Get-AnsibleParam -obj $params -name "path" -type "str"
# path変数に値がない場合は `Fail-Json` を実行
if(!$path) { Fail-Json -message "Absolute path is not specified for path" }
# path変数に指定された絶対パスでファイルの存在確認
$r = Test-Path $path
# Test-Pathの戻り値がFalseの場合は `Fail-Json` を実行
if(!$r) { Fail-Json -message "$path not found" }
# ファイルが存在すればresult変数(連想配列)を `Exit-Json` に渡す
Exit-Json $result
需要加载所需的模块。
使用Parse-Args和Get-AnsibleParam解析并获取传递给模块的选项。
5-2. Python代码示例
#!/usr/bin/python
# -*- coding: utf-8 -*-
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'individual'}
DOCUMENTATION = '''
module: win_file_check
short_description: Module to check existence of windows files
description:
- Confirm existence of file by using absolute path as an argument.
options:
- path:
description:
- Absolute path of the file.
'''
EXAMPLE = '''
---
- name: win file check
win_file_check:
path: C:\Users\Administrator\Desktop\hoge.txt
'''
6. 试试动一下
6-1. 运筹
---
- name: salf-made windows module test
hosts: all
gather_facts: no
tasks:
- win_file_check:
path: C:\Users\Administrator\Desktop\hoge.txt
6-2. 库存
[windows]
192.168.0.135
[windows:vars]
ansible_user=administrator
ansible_password=secret
ansible_port=5986
ansible_connection=winrm
ansible_winrm_server_cert_validation=ignore
6-3. 进行
我自己创建的模块保存在module目录下。
[root@localhost ~]# ansible-playbook main.yml -i inventory --module-path module/
PLAY [salf-made windows module test] ****************************************************************************************************
TASK [win_file_check] *******************************************************************************************************************
ok: [192.168.0.135]
PLAY RECAP ******************************************************************************************************************************
192.168.0.135 : ok=1 changed=0 unreachable=0 failed=0
7. 最后
我个人已经用Python创建了几个模块,但Powershell也是一样的。
-
- 必要なモジュールを読み込んで
-
- オプションをパースして
-
- 必要な変数に格納して
-
- 処理を実行して
- 結果を返す(Exit-Json Fail-Json)
用Ansible真是方便啊 🙂