ansibleでwinrmセットアップ済みのec2インスタンスを作成しました。
ansibleのec2モジュールを使ってWindows 2012R2のAMIを作成します。
インスタンス作成時に実行されるスクリプトをuser_dataに設定しておくことでwinrmが利用可能なec2インスタンスが作成されます。
playbookは以下の通りで、user_dataは、こちらを使わせて頂きました。
---
- name: Create an Windows instance with winrm on Amazon EC2
hosts: localhost
vars:
ec2_ami_id: ami-e0e00f8d
ec2_region: us-east-1
ec2_instance_type: t2.micro
ec2_key_name: mykey
ec2_subnet_id: subnet-3beddb4d
tasks:
- name: Create a new keypair
ec2_key: name="{{ec2_key_name}}" region="{{ec2_region}}"
register: keypair
- name: Write the key to a file
copy:
dest: files/mykey.pem
content: "{{keypair.key.private_key}}"
mode: 0600
when: keypair.changed
- name: start windows instance
ec2:
image: "{{ec2_ami_id}}"
region: "{{ec2_region}}"
instance_type: "{{ec2_instance_type}}"
key_name: "{{ec2_key_name}}"
group: [rdswinrm]
exact_count: 1
count_tag: { Name: winrm }
vpc_subnet_id: "{{ec2_subnet_id}}"
assign_public_ip: yes
instance_tags:
Name: ansible
env: develop
wait: true
user_data: "<powershell>
Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Force\n
$storageDir = $pwd\n
$webclient = New-Object System.Net.WebClient\n
$url = \"https://raw.githubusercontent.com/ansible/ansible/devel/examples/scripts/ConfigureRemotingForAnsible.ps1\"\n
$file = \"C:\\Program Files\\Amazon\\Ec2ConfigService\\Scripts\\ConfigureRemotingForAnsible.ps1\"\n
$webclient.DownloadFile($url,$file)\n
$VerbosePreference=\"Continue\"\n
& $file\n
</powershell>"
botoインストールやAWSの接続情報の設定は、省略します。
これで、しばらくするとインスタンス作成が完了します。
$ ansible-playbook ec2-winrm.yml PLAY [Create an Windows instance with winrm on Amazon EC2] ********************* TASK [Create a new keypair] **************************************************** ok: [localhost] TASK [Write the key to a file] ************************************************* skipping: [localhost] TASK [start windows instance] ************************************************** changed: [localhost] PLAY RECAP ********************************************************************* localhost : ok=2 changed=1 unreachable=0 failed=0 $
インベントリは、以下の通りです。
awsコンソールで確認した情報を追加すれば複数台のサーバを一括管理できます。
$ cat inventory/hosts-win [windows] winrm1 ansible_ssh_host=<IP or サーバ名> ansible_password=<パスワード> winrm2 ansible_ssh_host=<IP or サーバ名> ansible_password=<パスワード> [windows:vars] ansible_user=Administrator ansible_port=5986 ansible_connection=winrm ansible_winrm_server_cert_validation=ignore
接続を確認します。
$ ansible -i inventory/hosts-win windows -m win_ping
winrm2 | SUCCESS => {
"changed": false,
"ping": "pong"
}
winrm1 | SUCCESS => {
"changed": false,
"ping": "pong"
}
$