LoginSignup
5
6

More than 5 years have passed since last update.

AnsibleでAmazon EFSの作成からマウントするまで

Last updated at Posted at 2018-11-29

概要

Amazon EFSの作成からEC2にマウントするまでをAnsibleでやります
Ansibleのmountモジュールを使用することで、マウント済みチェック自動マウント設定もやってくれるので便利

手順

  1. EFSアクセス用のセキュリティグループの作成もしくは、既存のセキュリティグループに追加(手動)
  2. EFSボリュームの作成
  3. EC2にマウント

コード

amazon_efs.yml
---
# EFSボリュームの作成
- name: create efs volume
  hosts: localhost
  connection: local
  gather_facts: False
  tasks:
    # create EFS volume
    - name: Create EFS
      efs:
        state: present
        region: "リージョンID"
        name: "sample_efs"
        tags:
          Name: "タグ名"
        targets:
          - subnet_id: "AZ-aのサブネットID"
            security_groups: [ "EFS接続できるセキュリティグループID" ]
          - subnet_id: "AZ-cのサブネットID"
            security_groups: [ "EFS接続できるセキュリティグループID" ]
        performance_mode: general_purpose
        encrypt: yes

# EFSボリュームのマウント
- name: efs mount to ec2
  hosts: my_ec2
  vars:
    efs_vol_name: "sample_efs"
  tasks:
    # EFSボリュームIDを取得する
    - local_action:
        module: efs_facts
        name: "{{ efs_vol_name }}"
      run_once: true
      register: _efs_fact

    - set_fact:
        _efs_fact_id: "{{ _efs_fact.ansible_facts.efs[0].file_system_id }}"

    # EFSマウント用のユーティリティツールをインストール
    # amazon-efs-utilsを使用して、マウントしないが、とりあえずインストールしておく
    - name: install efs libs
      yum:
        name: "{{ item }}"
        state: present
      become: yes
      with_items:
        - "nfs-utils"
        - "amazon-efs-utils"

    # EC2にマウント用のディレクトリを作成しておく
    - name: Create data store directory for efs mount
      file:
        dest: "/home/ec2-user/{{ efs_vol_name }}"
        state: directory

    # EFSのマウント
    - name: mount efs volume
      mount:
        path: "/home/ec2-user/{{ efs_vol_name }}"
        src: "{{ _efs_fact_id }}.efs.ap-northeast-1.amazonaws.com:/"
        fstype: "nfs4"
        opts: "nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2,noresvport"
        state: mounted
      become: yes  

    # マウント後はrootユーザの所有権になるため、明示的に所有権を変更
    - name: change directory owner
      file:
        dest: "/home/ec2-user/{{ efs_vol_name }}"
        owner: "ec2-user"
        group: "ec2-user"
        state: directory
      become: yes

ポイント

mountモジュール

  • stateでmountedにすることで自動マウントの設定(/etc/fstab)もやってくれます
  • optsはAmazon EFSの設定値を用いる
5
6
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
5
6