あめがえるのITブログ

頑張りすぎない。ほどほどに頑張るブログ。

TerraformでAWSのIAM関連のリソースを作成してみた

Terraformが思いのほか簡単でいろいろ作りたくなったので今回はIAM関連のリソースを作成してみた。※これくらい簡単だとやる気がでてくる(´Д`)

やること

 1.IAM Policy作成(サンプルでS3にアクセスできる権限を付与)
 2.IAM Group作成
  ・Group作成
  ・Policyアタッチ
 3.IAM User作成
  ・User作成
  ・Group追加
 4.IAM Role作成
  ・Role作成
  ・Policyアタッチ
※下記を参考にprofileを設定し各コマンドを実行してますがAWS CLIで接続できればOKです。その場合はprofile周りのコードを削除して実行してください。
amegaeru.hatenablog.jp

実践!

1.IAM Policy作成
1-1.tfファイル作成

provider "aws" {
    region = "ap-northeast-1"
    profile = "testvault"
}
variable "env" {
    default = {
        env_name = "test"
    }
}

resource "aws_iam_policy" "example_policy" {
  name        = "${var.env.env_name}example_policy"
  description = "Example policy"

  policy = jsonencode({
    Version = "2012-10-17",
    Statement = [
      {
        Action   = [
          "s3:ListBucket",
          "s3:GetObject"
        ],
        Effect   = "Allow",
        Resource = "*"
      }
    ]
  })
}

1-2.適用

> terraform plan
> terraform apply
※tfファイルがある場所に作業ディレクトリを移動して実行してね★

1-3.確認

> aws iam list-policies --profile testvault | jq ".Policies[] | .PolicyName " | findstr "test" 
"testexample_policy"


2.IAM Group作成
2-1.tfファイル作成(新規作成)

resource "aws_iam_group" "example_group" {
  name = "${var.env.env_name}example_group"
}
resource "aws_iam_group_policy_attachment" "example_group" {
  group = aws_iam_group.example_group.name
  policy_arn = aws_iam_policy.example_policy.arn
}

2-2.適用

> terraform plan
> terraform apply

2-3.確認

> aws iam list-groups --profile testvault | jq ".Groups[] | .GroupName"
"testexample_group"


3.IAM User作成
3-1.tfファイル作成(新規作成)

resource "aws_iam_user" "example_user1" {
  name = "${var.env.env_name}example_user1"
}
resource "aws_iam_user_group_membership" "example_membership" {
  user = aws_iam_user.example_user1.name
  groups = [aws_iam_group.example_group.name]
}

3-2.適用

> terraform plan
> terraform apply

3-3.確認

> aws iam list-users --profile testvault | jq ".Users[] | .UserName "
"testexample_user1"


4.IAM Role作成
4-1.tfファイル作成(新規作成)

resource "aws_iam_role" "example_role" {
  name = "${var.env.env_name}example_role"

  assume_role_policy = jsonencode({
    Version = "2012-10-17",
    Statement = [
      {
        Action = "sts:AssumeRole",
        Principal = {
          Service = "ec2.amazonaws.com"
        },
        Effect = "Allow",
        Sid    = ""
      }
    ]
  })
}
resource "aws_iam_role_policy_attachment" "example_attach" {
  role       = aws_iam_role.example_role.name
  policy_arn = aws_iam_policy.example_policy.arn
}

4-2.適用

> terraform plan
> terraform apply

4-3.確認

>aws iam list-roles --profile testvault | jq ".Roles[] | .RoleName " | findstr "test"
"testexample_role"


5.後始末

# terraform destroy



感想

次はなにを作ろうかー(´Д`)