AWS networking with Terraform

In our previous blog we talked about provisioning an AWS Provider into Terraform. It was important to note that it differed from the vSphere provider in that you can create multiple AWS providers for different regions and give an alias to each region or login credentials as desired. With vSphere you can only have one provider and no aliases.

Once we have a provider defined we need to create elements inside the provider. If our eventual goal is to create a database using software as a service or a virtual machine using infrastructure as a service then we need to create a network to communicate with these services. With AWS there are basically two layers of network that you can define and two components associated with these networks.

The first layer is the virtual private network which defines an address range and access rights into the network. The network can be completely closed and private. The network can be an extension of your existing datacenter through a virtual private network connection. The network can be an isolated network that has public access points allowing clients and consumers access to websites and services hosted in AWS.

Underneath the virtual private network is either a public or private subnet that segments the IP addresses into smaller chunks and allows for instances to be addressed on the subnet network. Multiple subnet definitions can be created inside a virtual private network to segment communications with the outside world and private communications between servers (for example a database server and applications server). The application server might need a public IP address and an private IP address while the database server typically will only have a private IP address.

Associated with the network and subnets are a network security group and internet gateway to restrict access to servers in the AWS cloud. A diagram of this configurations with a generic compute instance is shown below.

The first element that needs to be defined is the AWS Provider.

provider “aws” {
version = “> 2”
profile = “default”
region = “us-east-1”
alias = “east”
}

The second component would be the virtual private cloud or aws_vpc.

resource “aws_vpc” “myNet” {
cidr_block = “10.0.0.0/16”
provider = aws.east
tags = {
Name = “myNet”
environment = var.environment
createdby = var.createdby
}
}

Note that the only required attribute for the aws_vpc is the cidr_block. Everything else is optional. It is important to note that the aws_vpc can be defined as a resource or as a data element that does not create or destroy the network definition in AWS with terraform apply and destroy. With the data declaration the cidr_block is optional given that it has already been defined and the only only attribute needed to match the existing VPC is the name or the ID of the existing VPC.

Once the VPC has been created an aws_subnet can be defined and the two required elements for a resource definition are the cidr_block and the vpc_id. If you want to define the aws_subnet as a data element the only required resource is the vpc_id.

resource “aws_subnet” “MySubnet” {
provider = aws.east
vpc_id = aws_vpc.myNet.id
cidr_block = “10.0.1.0/24”
tags = {
Name = “MySubnet”
environment = var.environment
createdby = var.createdby
}
}

The provider declaration is not required but does help with debugging and troubleshooting at a later date. It is important to note that the VPC was defined with a /16 cidr_block and the subnet was a more restrictive /24 cidr_block. If we were going to place a database in a private network we would create another subnet definition and use a different cidr_block to isolate the network.

Another element that needs to be defined is an aws_internet_gateway to define access from one network (public or private) to another network. The only required element that is needed for the resource declaration is the internet gateway id. If you define the aws_internet_gateway as a data declaration then the name or the vpc_id is required to map to an existing gateway declaration.

resource “aws_internet_gateway” “igw” {
provider = aws.aws
vpc_id = aws_vpc.myNet.id
tags = {
Name = “igw”
environment = var.environment
createdby = var.createdby
}
}

The final element that we want to define is the network security group which defines ports that are open inbound and outbound. In the following example we define inbound rules for ports 80, 443, and 8400-8403, ssh (port 22), and rdp (port 3389) as well as outbound traffic for all ports.

resource “aws_security_group” “cmvltRules” {
provider = aws.aws
name = “cmvltRules”
description = “allow ports 80, 443, 8400-8403 inbound traffic”
vpc_id = aws_vpc.myNet.id

ingress {
description = “Allow 443 from anywhere”
from_port = 443
to_port = 443
protocol = “tcp”
cidr_blocks = [“0.0.0.0/0”]
}

ingress {
description = “Allow 80 from anywhere”
from_port = 80
to_port = 80
protocol = “tcp”
cidr_blocks = [“0.0.0.0/0”]
}

ingress {
description = “Allow 8400-8403 from anywhere”
from_port = 8400
to_port = 8403
protocol = “tcp”
cidr_blocks = [“0.0.0.0/0”]
}

ingress {
description = “Allow ssh from anywhere”
from_port = 22
to_port = 22
protocol = “tcp”
cidr_blocks = [“0.0.0.0/0”]
}

ingress {
description = “Allow rdp from anywhere”
from_port = 3389
to_port = 3389
protocol = “tcp”
cidr_blocks = [“0.0.0.0/0”]
}

egress {
description = “Allow all to anywhere”
from_port = 0
to_port = 0
protocol = “-1”
cidr_blocks = [“0.0.0.0/0”]
}

tags = {
Name = “cmvltRules”
environment = var.environment
createdby = var.createdby
}

}

For the security group the protocol and from_port are the only required definitions when defining an aws_security_group resource. If you declare an aws_security_group data declaration then the name is the only required element. For the declaration shown above the provider and vpc_id to help identify the network that the roles are associated with for debugging and troubleshooting.

This simple video looks at the AWS console to see the changes defined by terraform using the main.tf and network.tf files saved in github.com.

In summary, network definitions on AWS are radically different and more secure than a typical vSphere provider definition with undefined network configurations. Understanding network configurations in Terraform help build a more predictable and secure deployment in the cloud. If you are part of a larger organization you might need to use data declarations rather than resource declarations unless you are creating your own sandbox. You might need to join a corporate VPC or dedicated subnet assigned to your team. Once networking is defined, new and creating things like moving dev/test to the cloud or testing database as a service to reduce license costs. The only step missing from these configuration files are setting up the aws configure and authentication using the AWS CLI interface. Terraform does a good job leveraging the command line authentication so that the public and private keys don’t need to be stored in files or configuration templates.

87 thoughts on “AWS networking with Terraform”

  1. Привет уважаемые!

    Есть такой интересный сайт https://ruposters.ru/

    Из последних новостей шоу бизнеса узнал, что:Знаменитости из России Лобода и Константин Меладзе поселились в Латвии, а детей пристроили в элитные школы.

    А певец Николай Басков впервые высказался по политической теме, осудив бежавших звезд из России.

    Рэпер Тимати посетил военный госпиталь, и привез около полусотни средств реабилитации для раненных военнослужащих, чтобы те быстрее возвращались к обычной жизни.

    Увидимся!

  2. Приветствую Вас дамы и господа!
    Предлагаем Вашему вниманию замечательный сайт https://dengi-do-zarplaty.ru/
    Отличные наличные – ведущая компания в сфере микрокредитования, деньги будут у вас на карте через 15 минут. Оформить займ можно круглосуточно, в выходные и праздники.Мы применяем самые передовые технологии, чтобы вы могли за 15 минут получить займ на карту или наличными.Наш сервис доступен везде где есть интернет, получить деньги можно в одном из наших отделений или круглосуточно не выходя из дома.

  3. Приветствую Вас дамы и господа!
    Есть такой замечательный сайт https://dengi-do-zarplaty.ru/
    Чтобы оформить деньги в долг, вам не нужен специальный пакет документов, достаточно только паспорта. Это выгодно отличает микрофинансовые компании от банков в, которые требуют собрать несколько бумаг, на подготовку которых уходит пара дней.В заключение стоит сказать, что взять средства в МФО — простой и быстрый способ решения денежных проблем. Компании предоставляют множество заемных линий для людей с разными возможностями, поэтому вы обязательно найдете подходящий вариант. Главное — грамотно распорядиться займом и не тратить деньги на ненужные вещи.

  4. I and my guys happened to be examining the excellent strategies from the blog and then all of the sudden got a horrible suspicion I never expressed respect to you for them. My ladies were definitely as a consequence glad to learn all of them and have in effect clearly been enjoying these things. Thanks for simply being really accommodating and for pick out some terrific ideas millions of individuals are really wanting to learn about. My personal sincere regret for not expressing gratitude to sooner.

  5. My wife and i got very contented when Edward could finish off his survey while using the ideas he obtained from your own weblog. It’s not at all simplistic to just happen to be giving away information the others may have been trying to sell. We fully grasp we have got the blog owner to give thanks to because of that. These explanations you made, the straightforward website navigation, the relationships you can help to engender – it’s most wonderful, and it is facilitating our son and the family consider that that idea is cool, and that’s pretty indispensable. Thank you for everything!

  6. I would like to express some thanks to you for rescuing me from this particular situation. Right after surfing through the the web and getting suggestions which are not productive, I thought my entire life was done. Living without the presence of answers to the issues you’ve resolved as a result of your good post is a crucial case, and ones which may have negatively affected my entire career if I had not encountered your site. Your actual knowledge and kindness in dealing with the whole lot was helpful. I’m not sure what I would’ve done if I had not come across such a solution like this. It’s possible to at this time relish my future. Thanks for your time so much for the expert and results-oriented guide. I won’t hesitate to refer your blog to any individual who desires guidelines about this issue.

  7. Needed to put you a tiny word to finally say thank you again about the marvelous suggestions you’ve shown on this website. It’s seriously open-handed of you to give without restraint what a few individuals would’ve made available for an electronic book to get some profit for their own end, and in particular since you could have tried it in case you desired. The creative ideas as well worked like a fantastic way to be sure that many people have the same eagerness like my very own to see very much more in regard to this issue. I know there are a lot more fun periods up front for individuals who browse through your blog post.

  8. I’m just writing to make you know what a wonderful experience my princess went through checking your site. She came to find a good number of issues, not to mention what it’s like to have a very effective giving heart to have the others without difficulty gain knowledge of some impossible subject matter. You undoubtedly exceeded our expectations. Thank you for rendering such insightful, healthy, edifying and as well as fun guidance on that topic to Mary.

  9. I would like to express thanks to this writer for bailing me out of this instance. Right after searching through the online world and finding proposals that were not productive, I thought my entire life was over. Living devoid of the approaches to the issues you’ve sorted out all through your main posting is a serious case, as well as ones that would have in a wrong way damaged my entire career if I hadn’t encountered your blog. Your primary knowledge and kindness in playing with all the stuff was helpful. I don’t know what I would’ve done if I hadn’t come across such a subject like this. I can also at this point look forward to my future. Thanks so much for this high quality and result oriented guide. I will not hesitate to suggest your web blog to anyone who requires guidelines on this problem.

  10. I precisely needed to appreciate you all over again. I’m not certain the things I would have carried out without the entire secrets documented by you over my situation. It absolutely was an absolute fearsome issue in my opinion, however , looking at the very expert avenue you solved the issue forced me to jump for gladness. I am just grateful for this service and even sincerely hope you are aware of a great job you were undertaking instructing many others with the aid of your blog. I know that you have never come across any of us.

  11. Thanks for your entire labor on this web page. Kim enjoys engaging in research and it’s easy to understand why. A lot of people learn all relating to the lively way you present functional tricks on this web site and therefore encourage participation from other individuals on the area and our own daughter is undoubtedly understanding a lot. Take advantage of the remaining portion of the year. You are always doing a great job.

  12. I am only commenting to make you understand of the cool encounter my cousin’s daughter experienced going through your webblog. She learned some details, with the inclusion of how it is like to possess a very effective giving mood to get a number of people with no trouble have an understanding of several complicated matters. You undoubtedly surpassed people’s desires. I appreciate you for churning out such essential, trusted, informative and even easy tips on the topic to Kate.

  13. I have to express thanks to you for bailing me out of this instance. Because of researching throughout the the net and getting suggestions that were not helpful, I believed my life was over. Living without the presence of solutions to the difficulties you’ve sorted out as a result of your main short article is a crucial case, and those that would have badly affected my entire career if I hadn’t encountered the blog. That skills and kindness in playing with a lot of stuff was important. I am not sure what I would’ve done if I had not come upon such a step like this. I can also at this moment look ahead to my future. Thanks so much for your skilled and sensible help. I will not be reluctant to suggest your site to anyone who should have care on this matter.

  14. I am just commenting to let you understand of the notable encounter our princess enjoyed visiting yuor web blog. She learned many issues, which include how it is like to have a great helping style to make a number of people effortlessly know just exactly selected advanced subject areas. You actually exceeded my expectations. I appreciate you for churning out such warm and helpful, safe, explanatory not to mention unique thoughts on your topic to Lizeth.

  15. I must show appreciation to this writer for rescuing me from this particular matter. As a result of exploring throughout the the net and obtaining concepts which are not helpful, I thought my life was well over. Existing without the approaches to the difficulties you have resolved as a result of the article is a crucial case, as well as the ones which may have in a negative way affected my career if I hadn’t discovered your web blog. Your own expertise and kindness in handling a lot of things was valuable. I don’t know what I would have done if I hadn’t come across such a step like this. It’s possible to now relish my future. Thank you very much for the impressive and effective guide. I will not hesitate to endorse your blog post to any individual who needs to have guidance about this topic.

  16. My spouse and i felt absolutely relieved when Ervin could conclude his basic research while using the ideas he received from your own web page. It is now and again perplexing to just choose to be giving out tricks some people could have been selling. And we also consider we have the website owner to give thanks to because of that. The most important explanations you’ve made, the straightforward site menu, the relationships you help promote – it is many great, and it is aiding our son in addition to the family reason why this concept is awesome, and that’s particularly vital. Many thanks for all the pieces!

  17. I just wanted to type a brief remark in order to say thanks to you for those nice suggestions you are writing on this site. My time intensive internet investigation has now been compensated with excellent insight to share with my partners. I ‘d assume that we visitors are extremely fortunate to be in a fantastic site with so many awesome individuals with insightful points. I feel somewhat blessed to have used your web pages and look forward to many more enjoyable minutes reading here. Thanks once more for a lot of things.

  18. A lot of thanks for all your effort on this website. Kim delights in getting into investigation and it’s really obvious why. My spouse and i know all relating to the powerful mode you make very important tactics via this web site and therefore improve contribution from people on that subject plus my child is now understanding a lot. Take advantage of the rest of the new year. You have been performing a first class job.

  19. I really wanted to develop a quick message to say thanks to you for those amazing guides you are giving at this website. My extended internet lookup has finally been paid with good knowledge to write about with my pals. I ‘d tell you that many of us visitors are undoubtedly blessed to exist in a great network with so many outstanding professionals with useful guidelines. I feel very grateful to have come across the webpages and look forward to some more fabulous minutes reading here. Thanks a lot once again for a lot of things.

Leave a Reply

Your email address will not be published. Required fields are marked *