2019年9月4日水曜日

Terrafom入門編ー設定、及びEC2インスタンスを作成

作業用フォルダを作成

作成するフォルダ名はterraform_test1を例します。
$mkdir terraform_test1

AWSにアクセス用認証情報を設定

AWSコンソール画面でterraform用IAMユーザーを作成し、accessキーとsecretキーを控えておきます。

terraform.tfvars というファイルを作成、以下のようにAWSアクセスキーとシークレットキー情報を入れます。
PS:terraform.tfvars や、*.auto.fvars というファイル名にしておきば、自動的に変数を読み込んでくれます。
aws_access_key = "AKIXXXXXXXPNN6KXXXXXXX"
aws_secret_key = "6sGivXXXXXXXXXXXbyd1ssLXXXXXY"

EC2インスタンスを作ってみる

ec2.tfというファイルを作成します。中身は以下の通りです。
variable "aws_access_key" {}
variable "aws_secret_key" {}

provider "aws" {
    access_key = "${var.aws_access_key}"
    secret_key = "${var.aws_secret_key}"
    region = "ap-northeast-1"
}

resource "aws_instance" "example" {
  ami           = "ami-02757f631"
  instance_type = "t3.nano"
}
簡単に説明すると、AMIami-02757f631をベースにしてインスタンスタイプt3.nanoのEC2一台を作成します。アクセスキーとシークレットキーはterraform.tfvars に設定した値を使用します。

初期化

terraform init コマンドを使って初期化します。

$ terraform init
Initializing the backend...
Initializing provider plugins...
- Checking for available provider plugins...
- Downloading plugin for provider "aws" (terraform-providers/aws) 2.25.0...
The following providers do not have any version constraints in configuration,
so the latest version was installed.
To prevent automatic upgrades to new major versions that may contain breaking
changes, it is recommended to add version = "..." constraints to the
corresponding provider blocks in configuration, with the constraint strings
suggested below.
* provider.aws: version = "~> 2.25"
Terraform has been successfully initialized!
You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.
If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.

文法チェック

terraform plan コマンドを使って先程作成したec2.tfファイルの正しさをチェックします。
$ terraform plan
Refreshing Terraform state in-memory prior to plan...
The refreshed state will be used to calculate this plan, but will not be
persisted to local or remote state storage.
------------------------------------------------------------------------
An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
  + create
Terraform will perform the following actions:
  # aws_instance.example will be created
  + resource "aws_instance" "example" {
      + ami                          = "ami-031b61f0c1afb3454"
      + arn                          = (known after apply)
      + associate_public_ip_address  = (known after apply)
      + availability_zone            = (known after apply)
      + cpu_core_count               = (known after apply)
      + cpu_threads_per_core         = (known after apply)
      + get_password_data            = false
      + host_id                      = (known after apply)
      + id                           = (known after apply)
      + instance_state               = (known after apply)
      + instance_type                = "t3.nano"
      + ipv6_address_count           = (known after apply)
      + ipv6_addresses               = (known after apply)
      + key_name                     = (known after apply)
      + network_interface_id         = (known after apply)
      + password_data                = (known after apply)
      + placement_group              = (known after apply)
      + primary_network_interface_id = (known after apply)
      + private_dns                  = (known after apply)
      + private_ip                   = (known after apply)
      + public_dns                   = (known after apply)
      + public_ip                    = (known after apply)
      + security_groups              = (known after apply)
      + source_dest_check            = true
      + subnet_id                    = (known after apply)
      + tenancy                      = (known after apply)
      + volume_tags                  = (known after apply)
      + vpc_security_group_ids       = (known after apply)
      + ebs_block_device {
          + delete_on_termination = (known after apply)
          + device_name           = (known after apply)
          + encrypted             = (known after apply)
          + iops                  = (known after apply)
          + kms_key_id            = (known after apply)
          + snapshot_id           = (known after apply)
          + volume_id             = (known after apply)
          + volume_size           = (known after apply)
          + volume_type           = (known after apply)
        }
      + ephemeral_block_device {
          + device_name  = (known after apply)
          + no_device    = (known after apply)
          + virtual_name = (known after apply)
        }
      + network_interface {
          + delete_on_termination = (known after apply)
          + device_index          = (known after apply)
          + network_interface_id  = (known after apply)
        }
      + root_block_device {
          + delete_on_termination = (known after apply)
          + encrypted             = (known after apply)
          + iops                  = (known after apply)
          + kms_key_id            = (known after apply)
          + volume_id             = (known after apply)
          + volume_size           = (known after apply)
          + volume_type           = (known after apply)
        }
    }
Plan: 1 to add, 0 to change, 0 to destroy.
------------------------------------------------------------------------
Note: You didn't specify an "-out" parameter to save this plan, so Terraform
can't guarantee that exactly these actions will be performed if
"terraform apply" is subsequently run.

インスタンスを作成

terraform apply コマンドを使ってインスタンを作成します。
$ terraform apply
An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
  + create
Terraform will perform the following actions:
  # aws_instance.example will be created
  + resource "aws_instance" "example" {
      + ami                          = "ami-031b61f0c1afb3454"
      + arn                          = (known after apply)
      + associate_public_ip_address  = (known after apply)
      + availability_zone            = (known after apply)
      + cpu_core_count               = (known after apply)
      + cpu_threads_per_core         = (known after apply)
      + get_password_data            = false
      + host_id                      = (known after apply)
      + id                           = (known after apply)
      + instance_state               = (known after apply)
      + instance_type                = "t3.nano"
      + ipv6_address_count           = (known after apply)
      + ipv6_addresses               = (known after apply)
      + key_name                     = (known after apply)
      + network_interface_id         = (known after apply)
      + password_data                = (known after apply)
      + placement_group              = (known after apply)
      + primary_network_interface_id = (known after apply)
      + private_dns                  = (known after apply)
      + private_ip                   = (known after apply)
      + public_dns                   = (known after apply)
      + public_ip                    = (known after apply)
      + security_groups              = (known after apply)
      + source_dest_check            = true
      + subnet_id                    = (known after apply)
      + tenancy                      = (known after apply)
      + volume_tags                  = (known after apply)
      + vpc_security_group_ids       = (known after apply)
      + ebs_block_device {
          + delete_on_termination = (known after apply)
          + device_name           = (known after apply)
          + encrypted             = (known after apply)
          + iops                  = (known after apply)
          + kms_key_id            = (known after apply)
          + snapshot_id           = (known after apply)
          + volume_id             = (known after apply)
          + volume_size           = (known after apply)
          + volume_type           = (known after apply)
        }
      + ephemeral_block_device {
          + device_name  = (known after apply)
          + no_device    = (known after apply)
          + virtual_name = (known after apply)
        }
      + network_interface {
          + delete_on_termination = (known after apply)
          + device_index          = (known after apply)
          + network_interface_id  = (known after apply)
        }
      + root_block_device {
          + delete_on_termination = (known after apply)
          + encrypted             = (known after apply)
          + iops                  = (known after apply)
          + kms_key_id            = (known after apply)
          + volume_id             = (known after apply)
          + volume_size           = (known after apply)
          + volume_type           = (known after apply)
        }
    }
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
aws_instance.example: Creating...
aws_instance.example: Still creating... [10s elapsed]
aws_instance.example: Creation complete after 16s [id=i-054c4a5d5f65d7633]
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

作成したインスタンを確認

terraform show コマンドを使ってインスタンを確認します。

$ terraform show
# aws_instance.example:
resource "aws_instance" "example" {
    ami                          = "ami-031b61f0c1afb3454"
    arn                          = "arn:aws:ec2:ap-northeast-1:994787028884:instance/i-054c4a5d5f65d7633"
    associate_public_ip_address  = true
    availability_zone            = "ap-northeast-1a"
    cpu_core_count               = 1
    cpu_threads_per_core         = 2
    disable_api_termination      = false
    ebs_optimized                = false
    get_password_data            = false
    id                           = "i-054c4a5d5f65d7633"
    instance_state               = "running"
    instance_type                = "t3.nano"
    ipv6_address_count           = 0
    ipv6_addresses               = []
    monitoring                   = false
    primary_network_interface_id = "eni-068a1099ebe134ed4"
    private_dns                  = "ip-172-31-45-252.ap-northeast-1.compute.internal"
    private_ip                   = "172.31.45.252"
    public_dns                   = "ec2-13-231-108-188.ap-northeast-1.compute.amazonaws.com"
    public_ip                    = "13.231.108.188"
    security_groups              = [
        "default",
    ]
    source_dest_check            = true
    subnet_id                    = "subnet-8a04efc2"
    tenancy                      = "default"
    volume_tags                  = {}
    vpc_security_group_ids       = [
        "sg-3b359644",
    ]
    credit_specification {
        cpu_credits = "unlimited"
    }
    root_block_device {
        delete_on_termination = true
        encrypted             = false
        iops                  = 300
        volume_id             = "vol-03eedb71c41a89002"
        volume_size           = 100
        volume_type           = "gp2"
    }
}

2019年8月30日金曜日

Visual Studioを使ってGolang開発時に、覚えておけば開発スピードがだいぶ上がれるショートカットキー一覧

Golangの開発エディターといえば、Visual Studioはかなりおすすめです。
しかも無料です。
最小限に以下のショートカットキーを覚えておけば開発スピードがだいぶ上げられます。

1. Ctrl + TAB

開いたタブを切り替え

2. Ctrl+SHIFT+TAB

前回開いたタブを開く

3. Ctrl+Shift+S 

全保存

4. Command+F

検索

5. Command+Shift+F

全ファイルから検索

6. F3

次を検索

7. Shift+F3

前を検索

8. Shift+Option+左クリック

矩形選択

9. Ctrl+G

指定行へジャンプ

10. Ctrl+E

行末に移動

11. Ctrl+-

直前に参照した行に移動

12. Command+p

指定したファイルを開く

13. Command+-

縮小

14. Command+Shift++

拡大





2019年8月29日木曜日

AWSの外部からAWSのredisに接続可能にする方法

ローカル開発環境構築するため、自分のローカルPC(AWSの外)からAWS redisに接続する必要になりました。
調べたところ、aws redisはVPCのプライベートサブネットに作られているため、外部からの直接接続は不可能です。
踏み台用インスタンス(NATインスタンス)を立てて、アクセス転送の仕組みを使えばなんとかなることがわかりました。
具体的なやり方は以下にまとめました。

NAT用セキュリティグループを作成

EC2コンソール画面から「セキュリティグループ」/「セキュリティグループの作成」の順に操作します。
「インバウンド」タブから「ルールの追加」をクリックして、以下の2つルールを追加します。
・SSH TCP  22 自分のローカルIP
・カスタムTCP TCP 6379 自分のローカルIP

NAT用インスタンスを作成

「AMIの選択」画面、左メニュー「コミュニティAMI」を選択、「amzn-ami-vpc-nat-hvm」を入れて検索します。

出てきた一番最新バージョンのamiを選択します。
PS:自分は最初普通のインスタンスを使っていたが、iptablesの設定など結構苦戦して結局設定できなかったです。やはり用意されたものを使うのが一番です。もしiptablesの設定に詳しいなら、通常のインスタンスでも大丈夫かと思います。


「インスタンス詳細の設定画面」、「自動割当てパブリックIP」を有効にします。

セキュリティグループの設定

前のステップで作成したNAT用セキュリティグループと「default VPC security group」を両方選びます。(2つ同時設定するのは大事!)

NAT インスタンスのSrcDestCheck属性を無効にします。

インスタンス一覧に対象インスタンスをチェックし、「アクション」/「ネットワーキング」/「送信元/送信先の変更チェック」の順に無効化します。





NATインスタンスにiptablesルールを追加

ローカルから作成したNATインスタンスにsshします。
NATインスタンスからのアクセスをRedisに転送するため、以下のiptablesルールを追加します。
iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 6379 -j DNAT --to redisサーバのIPアドレス:6379
redisサーバのIPアドレスを知る方法はまずElastiCacheダッシュボード/Redis/対象クラスター名の画面からredisサーバのホスト名を取得します。次にhostコマンドでサーバのIPアドレスを取得します。ドメインからIPアドレスを逆引き方法について

service iptables statusコマンドでルールが追加されたことを確認します。
# service iptables status
Table: nat
Chain PREROUTING (policy ACCEPT)
num  target     prot opt source               destination      
1    DNAT       tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:6379 to:172.31.78.185:6379

Chain INPUT (policy ACCEPT)
num  target     prot opt source               destination      

Chain OUTPUT (policy ACCEPT)
num  target     prot opt source               destination      

Chain POSTROUTING (policy ACCEPT)
num  target     prot opt source               destination      
1    MASQUERADE  all  --  0.0.0.0/0            0.0.0.0/0

ローカルから接続確認

これで準備が整いましたので、ローカルから接続してみます。
telnet NATインスタンスのパブリックIP 6379