Skip to content

Instantly share code, notes, and snippets.

@sechiro
Created September 2, 2014 17:09
Show Gist options
  • Save sechiro/6cc11c62fd0e63d0fce6 to your computer and use it in GitHub Desktop.
Save sechiro/6cc11c62fd0e63d0fce6 to your computer and use it in GitHub Desktop.
AnsibleのEC2モジュールで、user_dataを指定するときのメモ
---
- hosts: localhost
gather_facts: no
tasks:
- name: Create EC2 Instance with user-data
local_action:
module: ec2
region: ap-northeast-1
image: ami-efbe98ee # Ubuntu 12.04 LTS, hvm:ebs, 20140829.2
instance_type: t2.micro
# ec2_settingsは、group_vars/all.yml に書き込んである。
vpc_subnet_id: "{{ ec2_settings.default.subnet }}"
assign_public_ip: yes
key_name: "{{ ec2_settings.default.key_name }}"
wait: true
# "|"を使った継続行の記法を使うと、その下にそのままスクリプトがかける。("#"もそのまま書いてOK)
# YAMLでの複数行の文字列の書き方やこの記事が参考になる
# プログラマーのための YAML 入門 (初級編): http://magazine.rubyist.net/?0009-YAML
user_data: |
#!/bin/bash
echo Hello, World! > /tmp/hello
register: ec2
# 以下は続けて、今作成したインスタンスにユーザを作成するタスクを行う場合のサンプル
- name: Add newhost group
local_action: add_host name={{ item.public_dns_name }} group=newhosts
with_items: ec2.instances
- name: Wait for SSH to come up
local_action: wait_for host={{ item.public_dns_name }} port=22 delay=60 timeout=320 state=started
with_items: ec2.instances
- hosts: newhosts
user: ubuntu
tasks:
- name: Create User
sudo: yes
user:
name: sechiro
ssh_key_file: "{{ ec2_settings.default.ssh_key_file }}"
- name: Deploy authorized_keys
authorized_key:
user: sechiro
key: "{{ lookup('file', '{{ ec2_settings.default.ssh_pubkey_file }}') }}"
---
- hosts: localhost
gather_facts: no
vars:
hello: "{{ lookup('file', 'hello.sh') }}"
tasks:
- name: Create EC2 Instance with user-data
local_action:
module: ec2
region: ap-northeast-1
image: ami-efbe98ee # Ubuntu 12.04 LTS, hvm:ebs, 20140829.2
instance_type: t2.micro
# ec2_settingsは、group_vars/all.yml に書き込んである。
vpc_subnet_id: "{{ ec2_settings.default.subnet }}"
assign_public_ip: yes
key_name: "{{ ec2_settings.default.key_name }}"
wait: true
# lookup pluginを使って一旦変数にスクリプトを読み込ませてから
# user_dataに渡すこともできる。
# Using Lookups: http://docs.ansible.com/playbooks_lookups.html
user_data: "{{ hello }}"
register: ec2
# 以下は続けて、今作成したインスタンスにユーザを作成するタスクを行う場合のサンプル
- name: Add newhost group
local_action: add_host name={{ item.public_dns_name }} group=newhosts
with_items: ec2.instances
- name: Wait for SSH to come up
local_action: wait_for host={{ item.public_dns_name }} port=22 delay=60 timeout=320 state=started
with_items: ec2.instances
- hosts: newhosts
user: ubuntu
tasks:
- name: Create User
sudo: yes
user:
name: sechiro
ssh_key_file: "{{ ec2_settings.default.ssh_key_file }}"
- name: Deploy authorized_keys
authorized_key:
user: sechiro
key: "{{ lookup('file', '{{ ec2_settings.default.ssh_pubkey_file }}') }}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment