これから始めるAnsible入門ver.4

1.9K Views

April 12, 23

スライド概要

【Terraform と連携してAWS 上の環境を構築しよう】
全4回にわたってAnsible の魅力をお伝えするこの連載は、今回で最後となります。最後を飾る今回は、インフラ自動構築ツールのひとつであるTerraform をAnsible と組み合わせることによって、インフラの構築からシステムの設定まで、一連の構築作業を全て自動化する手法をご紹介します。

◆執筆◆
サイオスOSSよろず相談室 サポートエンジニア
https://sios.jp/lp/yorozu/

profile-image

サイオステクノロジーのプロフェッショナルサービスチームが運営しています。クラウド、OSS、認証など、皆様に役立つ技術情報を発信しています!

シェア

またはPlayer版

埋め込む »CMSなどでJSが使えない場合

関連スライド

各ページのテキスト
1.

サイオスOSSよろず相談室 これから始める 「Ansible」入門 (4) ©SIOS Technology, Inc. All Rights Reserved.

2.

Terraform と連携して AWS 上の環境を構築しよう 全4回にわたって Ansible の魅力をお伝えするこの連載は、今回で最後となります。 最後を飾る今回は、インフラ自動構築ツールのひとつである Terraform を Ansible と組み合わせることによって、インフラの構築からシステムの設定まで、一連の構 築作業を全て自動化する手法をご紹介します。 目次 Terraform とは Terraform と Ansible を連携する Terraform と Ansible を使った環境 構築の一例 ©SIOS Technology, Inc. All Rights Reserved. 2

3.

Terraform とは Terraform は、HashiCorp 社が開発したインフラ自動構築ツールで、AWS や GCP などのクラウド環境において構築するリソースをコードで表現し、コマンドを実行 することで自動で構築することが可能になります。 Terraform が対応しているクラウドサービスは前述の AWS や GCP の他にも、 Azure や Kubernetes などにも対応しています。 これらは Terraform のプロバイダと呼ばれるもので構築可能なクラウドサービスを 設定しますので、その一覧については こちら を参照してください。 ©SIOS Technology, Inc. All Rights Reserved. 3

4.

まず Terraform がどのようなものなのかを体験するために、さっそく手元の環境に Terraform をインストールしましょう。 Terraform はそれぞれの Linux ディストリビューション向けにリポジトリを提供し ていますので、そのリポジトリを登録した上でインストールすることが可能です。 インストール方法は以下のとおりです。 - Rocky Linux $ sudo dnf config-manager --add-repo https://rpm.releases.hashicorp.com/RHEL/hashicorp.repo sh $ sudo dnf -y install terraform - Ubuntu $ wget -O- https://apt.releases.hashicorp.com/gpg | gpg --dearmor | sudo tee /usr/share/keyrings/hashicorp-archive-keyring.gpg sh $ echo "deb [signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/hashicorp.list $ sudo apt update && sudo apt install terraform ©SIOS Technology, Inc. All Rights Reserved. 4

5.

正しくインストールされたかどうかを確認するために、以下のようなコマンドを実 行してバージョン情報が出力されることを確認してください。 sh $ terraform -version Terraform v1.3.7 on linux_amd64 次に、Terraform で AWS の環境を操作するためには AWS CLI のインストールも 必要ですので、以下の手順でインストールします。 $ curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip" sh $ unzip awscliv2.zip $ sudo ./aws/install あわせて、AWS を操作するご自身の IAM アカウントで アクセスキーを作成 し、発 行されたアクセスキー ID とシークレットアクセスキーを以下の手順で登録しておき ます。 sh $ aws configure AWS Access Key ID [None]: (アクセスキーIDを入力) AWS Secret Access Key [None]: (シークレットアクセスキーを入力) Default region name [None]: (何も入力せずエンター) Default output format [None]: (何も入力せずエンター) ©SIOS Technology, Inc. All Rights Reserved. 5

6.

これで Terraform から AWS を操作する準備が整いましたので、さっそく Terraform を使って EC2 インスタンスを作成しようと思います。 以降の Ansible との連携でも使用するため、これまでの連載で作成した Ansible Playbook を格納しているディレクトリ上に、 terraform というディレクトリを作 成します。 その中に、EC2 インスタンスを構築する Terraform 設定ファイル main.tf を作成 します。ディレクトリ・ファイル構成は以下のようになります。 ansible-example text ├(前回までに作成したファイル群) └terraform └main.tf ©SIOS Technology, Inc. All Rights Reserved. 6

7.
[beta]
次に、 main.tf に以下の内容を入力します。
<キーペア名> と <セキュリティグループID> のところは、ご自身の環境に合
わせて適宜変更してください。
なお、ここで指定している AMI は Amazon Linux 2 のものです。
text

terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 4.0"
}
}
}
provider "aws" {
region = "ap-northeast-1"
}
resource "aws_instance" "example" {
ami
instance_type
key_name

= "ami-0bba69335379e17f8"
= "t3.micro"
= "<キーペア名>"

vpc_security_group_ids = ["<セキュリティグループID>"]
tags = {
Name = "ansible-example"
}
}

©SIOS Technology, Inc. All Rights Reserved.

7

8.

main.tf が作成できたら、以下のコマンドを実行して初期化します。 sh $ terraform init Initializing the backend... Initializing provider plugins... (中略) Terraform has been successfully initialized! 上記のようなメッセージが出力されれば初期化が成功しています。 それではさっそく、以下のコマンドを実行して AWS 上に EC2 インスタンスを作成 します。 ©SIOS Technology, Inc. All Rights Reserved. 8

9.

sh $ terraform apply Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols : + create Terraform will perform the following actions : (どのような構成でリソースを作成するか表示される) Plan: 1 to add, 0 to change, 0 to destroy. Do you want to perform these actions? Terraform will perform the actions described above. Only 'yes' will be accepted to approve. Enter a value : yes (←「yes」と入力する) aws_instance.example : Creating... aws_instance.example : Still creating... [10s elapsed] aws_instance.example : Creation complete after 13s [id=i-xxxxxxxxxxxxxxxxx] Apply complete! Resources : 1 added, 0 changed, 0 destroyed. 実行が完了して AWS マネジメントコンソールを確認すると、ansible-example と いう名前の付いた EC2 インスタンスが作成されていることが確認できます。 次項の Ansible との連携で再度インスタンスの作成を試みたいので、ここでは一旦 作成したインスタンスを削除します。 Terraform を使用していれば、Terraform 管理下のリソースの削除もコマンドを一 回実行するだけで可能です。 ©SIOS Technology, Inc. All Rights Reserved. 9

10.

sh $ terraform destroy aws_instance.example : Refreshing state... [id=i-xxxxxxxxxxxxxxxxx] Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols : - destroy Terraform will perform the following actions : (削除対象のリソース情報が表示される) Plan: 0 to add, 0 to change, 1 to destroy. Do you really want to destroy all resources? Terraform will destroy all your managed infrastructure, as shown above. There is no undo. Only 'yes' will be accepted to confirm. Enter a value : yes (←「yes」と入力する) aws_instance.example : Destroying... [id=i-xxxxxxxxxxxxxxxxx] aws_instance.example : Still destroying... [id=i-xxxxxxxxxxxxxxxxx, 10s elapsed] aws_instance.example : Still destroying... [id=i-xxxxxxxxxxxxxxxxx, 20s elapsed] aws_instance.example : Still destroying... [id=i-xxxxxxxxxxxxxxxxx, 30s elapsed] aws_instance.example : Still destroying... [id=i-xxxxxxxxxxxxxxxxx, 40s elapsed] aws_instance.example : Still destroying... [id=i-xxxxxxxxxxxxxxxxx, 50s elapsed] aws_instance.example : Still destroying... [id=i-xxxxxxxxxxxxxxxxx, 1m0s elapsed] aws_instance.example : Destruction complete after 1m0s Destroy complete! Resources : 1 destroyed. ©SIOS Technology, Inc. All Rights Reserved. 10

11.

Terraform と Ansible を連携する 先ほどまでは Terraform をコマンドで実行していましたが、今度は Ansible と連携 して Ansible 側から Terraform を実行してみましょう。 先ほど作成した Terraform の設定ファイルを保存しているディレクトリの親ディレ クトリ上に terraform.yml という名前で Ansible Playbook を作成します。 text ansible-example ├(前回までに作成したファイル群) ├terraform.yml └terraform └main.tf Ansible から Terraform を実行するモジュールは community.general.terraform です。これを使って、 terraform.yml に以下の内容を入力します。 - Hosts : localhost yaml tasks : - name : Terraform を実行する community.general.terraform : project_path : 'terraform/' state : present ©SIOS Technology, Inc. All Rights Reserved. 11

12.

内容としては非常にシンプルです。localhost を対象に terraform ディレクトリ内 にある設定ファイルを使って Terraform の実行を定義しています。 この Playbook を実行すると以下のようになります。 sh $ ansible-playbook terraform.yml PLAY [localhost] ********************************************************************************* ******************* TASK [Gathering Facts] ********************************************************************************* ************* ok: [localhost] TASK [Terraform を実行する] ********************************************************************************* ******** changed: [localhost] PLAY RECAP ********************************************************************************* ************************* localhost rescued=0 : ok=2 ignored=0 changed=1 unreachable=0 failed=0 skipped=0 実行が完了すると、先ほどと同様に EC2 インスタンスが作成されていると思います。 ©SIOS Technology, Inc. All Rights Reserved. 12

13.

Terraform と Ansible を使った 環境構築の一例 それでは最後に、Ansible を使って Terraform を実行し、EC2 インスタンスを作成 したあとに、その EC2 インスタンスに対して Ansible からタスクを実行するところ まで自動化してみましょう。 まず、Terraform で EC2 インスタンスを作成するため、実際に実行してみないと作 成したインスタンスの接続先 IP アドレスを知ることはできません。 それでも、作成から環境構築までを自動化するためには、Ansible のダイナミック インベントリという機能を使います。 ダイナミックインベントリは、クラウド環境のように実行対象の IP アドレスが変わ る可能性がある場合に、柔軟にインベントリ情報を用意するための機能です。 今回は AWS の環境で使用するため、 amazon.aws.aws_ec2 というプラグインを 使用します。 aws_ec2.yml というファイルを作成して、以下の内容を入力します。 yaml plugin : amazon.aws.aws_ec2 regions : - ap-northeast-1 keyed_groups : - prefix : tag key : tags これで、EC2 インスタンスのタグ「Name」に設定された文字列を使って、 「tag_Name_<名前>」で Ansible から接続できるようになります。 次に、先ほど作成した terraform.yml の内容を以下のように変更します。 ©SIOS Technology, Inc. All Rights Reserved. 13

14.

yaml - hosts : localhost tasks : - name : Terraform を実行する community.general.terraform : project_path : 'terraform/' state : present - name : 作成した EC2 インスタンスをインベントリに反映させる ansible.builtin.meta : refresh_inventory - hosts : tag_Name_ansible_example remote_user : ec2-user become : yes gather_facts : no tasks : - name : SSH 接続できるまで待つ ansible.builtin.wait_for_connection : - name : ホストの情報を取得する ansible.builtin.setup : - name : Apache HTTPD をインストールする ansible.builtin.yum : name : httpd state : present - name : Apache HTTPD を起動する ansible.builtin.system : name : httpd.service enabled : yes state : started ©SIOS Technology, Inc. All Rights Reserved. 14

15.

この Playbook では、Terraform を実行したあとにインベントリ情報のリフレッ シュを実行しています。これによって、Terraform で作成したインスタンス情報が インベントリに反映されます。 続いて、作成したインスタンスに対して操作を実行しますが、EC2 インスタンスの 作成直後は SSH 接続が可能になるまで時間がかかるため、接続できるまで待ちます。 そのため、最初にホスト情報の取得を無効化するため gather_facts: no という設 定をしています。接続できるようになったらホスト情報を取得し、Apache をイン ストールして起動するまでの処理を記述しています。 この Playbook を以下のコマンドで実行すると、環境の構築が完了します。 $ ansible-playbook -i aws_ec2.yml terraform.yml sh PLAY [localhost] ********************************************************************************* ******************* TASK [Gathering Facts] ********************************************************************************* ************* ok: [localhost] TASK [Terraform を実行する] ********************************************************************************* ******** changed: [localhost] TASK [作成した EC2 インスタンスをインベントリに反映させる] ********************************************************** PLAY [tag_Name_ansible_example] ********************************************************************************* **** ©SIOS Technology, Inc. All Rights Reserved. 15

16.

TASK [SSH 接続できるまで待つ] ********************************************************************************* ****** ok: [ec2-xxx-xxx-xxx-xxx.ap-northeast-1.compute.amazonaws.com] TASK [ホストの情報を取得する] ********************************************************************************* ****** ok: [ec2-xxx-xxx-xxx-xxx.ap-northeast-1.compute.amazonaws.com] TASK [Apache HTTPD をインストールする] ****************************************************************************** changed: [ec2-xxx-xxx-xxx-xxx.ap-northeast-1.compute.amazonaws.com] TASK [Apache HTTPD を起動する] ********************************************************************************* ***** changed: [ec2-xxx-xxx-xxx-xxx.ap-northeast-1.compute.amazonaws.com] PLAY RECAP ********************************************************************************* ************************* ec2-xxx-xxx-xxx-xxx.ap-northeast-1.compute.amazonaws.com : ok=4 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 changed=2 localhost rescued=0 skipped=0 : ok=2 ignored=0 changed=1 unreachable=0 failed=0 ©SIOS Technology, Inc. All Rights Reserved. 16

17.

4回にわたって Ansible の魅力を紹介させていただきましたが、いかがでしたでしょ うか。 Ansible のモジュールは非常にたくさんの種類が存在ますので、この連載記事で紹 介できなかったものの中にもとても便利なものが存在します。 この記事をご覧になったことをきっかけに、皆様があらゆることの自動化を実現し、 効率的に業務が遂行できるようになることを願っています。 最後までお読みいただき、ありがとうございました。 ©SIOS Technology, Inc. All Rights Reserved. 17

18.

Ansible入門シリーズ 【これから始めるAnsible】 本連載では、自動化ツールの一つであるAnsible について、これから 入門1 Ansible を学ぼうという方、使っていきたい方を対象に、導入方法から 実用例までを簡単に紹介していきます。今回は、まずAnsible がどんな ツールなのかについて紹介し、その導入方法をお伝えします。 →こちらから 【Word やExcel の手順書をAnsible Playbook に置き換えよう】 よくありがちなWordやExcelの手順書は、書き手によってフォーマット 入門2 が変わったり、変更点がわかりづらいといったことはありませんか? WordやExcelの手順書をAnsiblePlaybookに置き換え、上記のような問題 点を解消する方法についてご紹介します。 →こちらから 【Ansible で複数サーバのセキュリティチェックをしよう】 現在管理しているシステムが脆弱性の影響を受けるバージョンかを確 認するには、システムが多いほど手間がかかり、対策を実施するとな 入門3 ると更に膨大な時間がかかります。今回は、このような場面でAnsible を使い、複数のシステムに対するバージョンチェックや脆弱性への対 策を一度に実行する方法についてご紹介します。 →こちらから 【Terraform と連携してAWS 上の環境を構築しよう】 全4回にわたってAnsible の魅力をお伝えするこの連載は、今回で最後と 入門4 なります。最後を飾る今回は、インフラ自動構築ツールのひとつであ るTerraform をAnsible と組み合わせることによって、インフラの構築か らシステムの設定まで、一連の構築作業を全て自動化する手法をご紹 介します。 ©SIOS Technology, Inc. All Rights Reserved. 18

19.

https://sios.jp/products/oss/yorozu/ ©SIOS Technology, Inc. All Rights Reserved.