The Infrastructure Technology I Use

概要

インフラエンジニアとして, AWS 上でサーバーを構築する場合が多いのですが, その際に使用している技術について記載しようかと思います。

# 使用技術

  • Terraform
  • Ansible
  • Docker
  • Serverless Framework
  • Capistrano
  • GitHub Actions

# 使用用途(随時更新)

Terraform

Terraform は IaC を実現できるツールで AWS 上でサーバーを立てる際に使用しています。

Terraform を書くときは module の構成で, かつ, Terraform Registry の Terraform AWS modules を使用しています。AWS modules を使用することで, 下記のようにコードの記述量が減らすことができます。

# NatGateway を使用した VPC
module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "~> 5.0"

  name = local.vpc_name
  cidr = var.vpc_cidr

  azs              = ["ap-northeast-1a", "ap-northeast-1c"]
  private_subnets  = var.private_subnets
  public_subnets   = var.public_subnets
  database_subnets = var.database_subnets

  enable_nat_gateway = true

  tags = local.tags
}

# ライフサイクルポリシー(最新の5つのイメージだけ残す)を考慮した ECR
module "ecr" {
  for_each = local.ecr_repositories
  source   = "terraform-aws-modules/ecr/aws"
  version  = "~> 1.0"

  repository_name = each.value

  repository_image_tag_mutability = "MUTABLE"

  repository_lifecycle_policy = jsonencode({
    rules = [
      {
        action = {
          type = "expire"
        }
        description  = "Keep last 5 images"
        rulePriority = 1
        selection = {
          countNumber = 5
          countType   = "imageCountMoreThan"
          tagStatus   = "any"
        }
      },
    ]
  })

  tags = local.tags
}

Ansible

Ansible は オンプレのサーバーや EC2 などのミドルウェアを IaC で管理できるツールです。

Nginx や Firewall, Docker などの設定管理で使用します。

ディレクトリ構成は, Ansible のベストプラクティスを参考にして, 下記のような構成にしています。

.
├── hosts
│   └── production.yml
├── main.yml
├── private.yml
└── roles
    ├── firewalld
    │   ├── handlers
    │   │   └── main.yml
    │   ├── tasks
    │   │   └── main.yml
    │   └── templates
    │       └── public.xml.j2
    └── nginx
        ├── handlers
        │   └── main.yml
        ├── tasks
        │   └── main.yml
        └── templates
            ├── cert
            │   └── server.crt.j2
            ├── conf.d
            │   └── default.conf.j2
            ├── htpasswd.j2
            ├── nginx.conf.j2
            └── private
                └── server.key.j2

Nginx の設定を例に記述方法を紹介します。

下記の設定で, Nginx のインストールと設定ファイルの管理を行っています。j2 と呼ばれるテンプレートエンジンを使用することによって, 変数を埋め込んだ設定ファイルを管理することができます。

---
- name: install nginx
  dnf:
    name: nginx
    state: latest
- name: write the nginx config file
  template:
    src: "{{ item  }}"
    dest: "/etc/nginx/{{ item | regex_replace('^.*templates/','') | regex_replace('.j2', '') }}"
  with_fileglob:
    - "../templates/*.j2"
    - "../templates/conf.d/*.j2"
  notify:
    - restart nginx