OTHERS
VPC flow in Terraform
Create Flow Log via terraform
We are using Previously project scripit, but we will add “VPC Flow capture” on the VPC which we create via terraform.
We will create a new file tf.log , input code as below
resource "aws_iam_policy" "policy" {
name = "test_policy"
path = "/"
description = "My test policy"
# Terraform's "jsonencode" function converts a
# Terraform expression result to valid JSON syntax.
policy = jsonencode({
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents",
"logs:DescribeLogGroups",
"logs:DescribeLogStreams"
],
"Resource": "*"
}
]
})
}
resource "aws_iam_role" "test_role" {
name = "test_role"
# Terraform's "jsonencode" function converts a
# Terraform expression result to valid JSON syntax.
assume_role_policy = jsonencode({
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "vpc-flow-logs.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
})
tags = {
tag-key = "terra"
}
}
resource "aws_iam_role_policy_attachment" "test-attach" {
role = aws_iam_role.test_role.name
policy_arn = aws_iam_policy.policy.arn
}
resource "aws_cloudwatch_log_group" "tera" {
name = "tera"
tags = {
Name = "${var.env_prefix}-Flow"
Environment = "production"
Application = "serviceA"
}
}
resource "aws_flow_log" "example" {
iam_role_arn = aws_iam_role.test_role.arn
log_destination = aws_cloudwatch_log_group.tera.arn
traffic_type = "ALL"
vpc_id = aws_vpc.myapp-vpc.id
}
Terraform plan / apply
Terraform apply -> EC2 instance will be created with EIP with internet access. Additional it created as below:
- New Policy
- New Role
- Policy attached to the Role
- New Log Group
- New Log Group attached to VPC, with the role that we just created.
Cloud Watch -> Logs
After we succesfully deploy, now the “Flow log”. It will capture the log as we set “All” ( Accept & Rejct)
We can store the log in S3 bucket or in Cloud Watch. Via Cloud watch, we will can view the log directly.
With Logs Insights, we can custom the format, filter, sort…etc
admin
0