LoginSignup
6
4

More than 5 years have passed since last update.

ansibleからinstance作成し、instance内の処理を実行する方法

Posted at

ansibleを使った、AWSでインスタンスを作成し、サーバの設定までを1つのplaybookで書くには、どうすればよいか?
色々と調べたところ、以下のように書くと、いけました。

main.yml

# インタンスの作成を行う(EBS付き)
- name: Create instance
  hosts: 127.0.0.1
  connection: local
  user: www
  sudo: no
  vars_files:
    - vars/dev-front-deploy-vars.yml

  tasks:
   - name: インスタンスとEBSを作成し、attachまで行う
     ec2:
       aws_access_key: "{{ aws_access_key }}"
       aws_secret_key: "{{ aws_secret_key }}"
       region: "{{ region }}"
       zone: "{{ zone }}"
       key_name: "{{ keypair }}"
       instance_type: "{{ instance_type }}"
       image: "{{ ami }}"
       wait: "{{ instance_running_wait }}"
       group: "{{ security_group }}"
       count: 1
       vpc_subnet_id: "{{ vpc_subnet_id }}"
       assign_public_ip: "{{ assign_public_ip }}"
       instance_tags:
          Name: "{{ instance_name }}"
       volumes: # ここがEBSの設定
          - volume_size: "{{ ebs_volume_size }}"
            device_name: "{{ ebs_device_name }}"
            name: "{{ ebs_tag_name }}"
            delete_on_termination: true
     register: ec2

   - name: 新規作成したインタンスをホストグループに追加する
     add_host: 
       name={{ item.private_ip }}
       groups=dev-front 
     with_items: ec2.instances

   - name: インスタンスが起動し、SSHで接続できるようになるまで待つ
     wait_for: 
       host={{item.public_dns_name}} 
       port=22 delay=60 timeout=320 state=started
     with_items: ec2.instances


# 新規作成したインスタンスに対する処理を行う 
- name: Configure instance
  hosts: dev-front # 上記で作成したホストグループ名を指定
  user: www
  sudo: no
  vars_files:
    - vars/dev-front-deploy-vars.yml

  tasks:
   # ここに作成したインスタンス内での処理を書いていく

このような、playbookを書くとインスタンス作成〜インスタンス内での処理を一連の流れで行うことができます。
荒削りな部分もありますので、あくまで参考までに。

参考

Github:ansible-example

6
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
4