Carlos Aguni

Highly motivated self-taught IT analyst. Always learning and ready to explore new skills. An eternal apprentice.


EC2 Terraform Study

01 Sep 2022 »

https://thecloudbootcamp.com/pt/blog/aws/criando-uma-instancia-ec2-utilizando-o-terraform

iam.tf


resource "aws_iam_instance_profile" "yace_profile" {
  name = "yace_profile"
  role = aws_iam_role.ec2-yace.name
}

resource "aws_iam_role" "ec2-yace" {
  name = "ec2-yace-ec2"

  assume_role_policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": "sts:AssumeRole",
      "Principal": {
        "Service": "ec2.amazonaws.com"
      },
      "Effect": "Allow"
    }
  ]
}
EOF

  inline_policy {
    name = "yace-policy"

    policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
      {
          "Sid": "CloudWatchExporterPolicy",
          "Effect": "Allow",
          "Action": [
              "tag:GetResources",
              "cloudwatch:ListTagsForResource",
              "cloudwatch:GetMetricData",
              "cloudwatch:ListMetrics"
          ],
          "Resource": "*"
      }
  ]
}
EOF
  }
}

resource "aws_iam_role_policy_attachment" "ec2-ssm" {
  role = aws_iam_role.ec2-yace.id
  policy_arn = "arn:aws:iam::aws:policy/service-role/AmazonEC2RoleforSSM"
}

main.tf



data "aws_ami" "amazn2" {
  most_recent = true

  filter {
    name   = "name"
    values = ["amzn2-ami-kernel-*"]
  }

  filter {
    name   = "virtualization-type"
    values = ["hvm"]
  }

  owners = ["137112412989"] # Amazon
}

variable subnet_idc {
    default = "subnet-0c805a45"
}

resource "aws_instance" "ec2-yace" {
  ami           = data.aws_ami.amazn2.id
  instance_type = "t2.micro"
  key_name = "automation" # Insira o nome da chave criada antes.
  subnet_id = var.subnet_idc
  iam_instance_profile = aws_iam_instance_profile.yace_profile.id
  #vpc_security_group_ids = [aws_security_group.permitir_ssh_http.id]
  #associate_public_ip_address = true

  root_block_device {
    volume_size = 30
    volume_type = "gp2"
    delete_on_termination = true
  }

  ebs_block_device {
    device_name = "/dev/xvdba"
    volume_size = "2"
    volume_type = "gp3"
    tags = {
      FileSystem = "/mnt/data"
    }
  }

  ebs_block_device {
    device_name = "/dev/xvdbb"
    volume_size = "2"
    volume_type = "gp3"
    tags = {
      FileSystem = "/mnt/data2"
    }
  }

  tags = {
    Name = "blogserver01"
 # Insira o nome da instância de sua preferência.
  }
}