ab’s blog

インフラの呟きです。

AnsibleでWindowsをコンロールするための準備

hahahahahaha

AnsibleサーバからWindowsサーバをコントロールするため準備しておくことをメモ。(Window2019で検証)

ターゲット(Windows側)の設定

コントロールされる側のWindowsサーバには以下の設定が必要です。

.Netframeworkの追加

Windowsの機能」で「.NetFramework」を有効にします。(Win2019ならデフォルトで有効化されてるはずですが無ければ追加します)

WinRMの設定

ansibleサーバがWindowsサーバに接続できるようにするための設定を入れます。 まず以下のURLからPowershell スクリプト「ConfigureRemotingForAnsible.ps1」を取得してWindowdサーバに置きます。

---URL: ansible/examples/scripts at devel · ansible/ansible · GitHub

次にPowershellを管理者権限で起動します。(起動するときにPowershell→右クリック→管理者として実行) スクリプトをWindwosサーバに配置して実行します。スクリプトをC:\tmp配下に置いたのでであれば以下を実施します。

PS> cd C:\tmp
PS> powershell -ExecutionPolicy RemoteSigned .\ConfigureRemotingForAnsible.ps1

#最後に以下でListenerポート(TCP:5985 & 5986)が確認できたらOK
PS> winrm enumerate winrm/config/Listener

ansibleユーザ作成とAdmin権限付与

最初一般ユーザでログインしてその後administratorに昇格してということができないのかと思ったのですがいま時点ではできないみたいです。なのでAdmin権限付きのユーザを作ります。 これでWindowsサーバの準備は終わりです。


Ansibleサーバ側でやること

Ansible側ではpywinrmの追加と接続確認を実施します。

pywinrmを追加

pywinrmを追加します。下記コマンドはRHEL8環境でAnsibleをインストールした前提です。

$ su -
$ pip3 install pywinrm

接続確認

ansibleサーバ→Windowsサーバに接続か確認。以下のファイル「host.txt」を作ってAnsibleを実行させます。

[host.txt]

#WindowsサーバのIPまたはホスト名
#入力例:[windows_servers]
#        192.168.0.100
[windows_servers]
xxx.xxx.xxx.xxx


[windows_servers:vars]
#接続先ユーザ
ansible_user=ansible

#パスワード (※隠したい場合は「Ansible-Vault」でパスワードを暗号化する。実行毎にパスワードの入力をする場合はAnsible実行時に--ask-vault-passを入れる。
ansible_password=[Windowsサーバに作成したAnsibleユーザのパスワード]

#接続先ポート
ansible_port=5986

#接続形式、WindowsならWinrm
ansible_connection=winrm

#電子証明(自己証明書)の警告を無視
ansible_winrm_server_cert_validation=ignore

実行

$ ansible -i hosts.txt windows_servers -m win_ping
 →以下みたいにSUCCESSとでればOK
  xxx.xxx.xxx.xxx | SUCCESS => {
     "changed": false,
     "ping": "pong"

以上