You are on page 1of 8

$ terraform version

Terraform v0.15.0
├── main.tf
├── providers.tf
└── variables.tf
main.tf
terraform {required_version = ">= 0.12"
}

# 1. Create vpc
resource "aws_vpc" "prod-vpc" {
cidr_block = "10.0.0.0/16"
tags = {
Name = "production"
}
}

# 2. Create Internet Gateway


resource "aws_internet_gateway" "gw" {
vpc_id = aws_vpc.prod-vpc.id
}

# 3. Create Custom Route Table


resource "aws_route_table" "prod-route-table" {
vpc_id = aws_vpc.prod-vpc.id
route {
cidr_block = "0.0.0.0/0"
gateway_id = aws_internet_gateway.gw.id
}
route {
ipv6_cidr_block = "::/0"
gateway_id = aws_internet_gateway.gw.id
}

tags = {
Name = "Prod"
}
}

# 4. Create subnets
resource "aws_subnet" "subnet-1" {
vpc_id = aws_vpc.prod-vpc.id
cidr_block = var.subnet_cidr[0]
availability_zone = "us-east-1a"
tags = {
Name = "subnet-1"
}
}

resource "aws_subnet" "subnet-2" {


vpc_id = aws_vpc.prod-vpc.id
cidr_block = var.subnet_cidr[1]
availability_zone = "us-east-1a"
tags = {
Name = "subnet-2"
}
}

# 5. Associate subnet with Route Table


resource "aws_route_table_association" "a" {
subnet_id = aws_subnet.subnet-1.id
route_table_id = aws_route_table.prod-route-table.id
}

# 6. Create Security Group to allow port 22,80,443


resource "aws_security_group" "allow_web" {
name = "allow_web_traffic"
description = "Allow Web inbound traffic"
vpc_id = aws_vpc.prod-vpc.id
ingress {
description = "HTTPS"
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
ingress {
description = "HTTP"
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
ingress {
description = "SSH"
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
egress {
from_port = 0
to_port = 0
protocol = "-1" # any protocol
cidr_blocks = ["0.0.0.0/0"]
}
tags = {
Name = "allow_web"
}
}

# 7. Create a network interface with an ip in the subnet that was created


in step 4
resource "aws_network_interface" "web-server-nic" {
subnet_id = aws_subnet.subnet-1.id
private_ips = ["10.0.0.50"]
security_groups = [aws_security_group.allow_web.id]
}

# 8. Assign an elastic IP to the network interface created in step 7


resource "aws_eip" "one" {
vpc = true
network_interface = aws_network_interface.web-server-nic.id
associate_with_private_ip = "10.0.0.50"
depends_on = [aws_internet_gateway.gw]
}

# 9. Create a Ubuntu server and install/enable apache2


resource "aws_instance" "web-server-instance" {
ami = "ami-085925f297f89fce1"
instance_type = var.ec2_instance_type
availability_zone = "us-east-1a"
key_name = "einsteinish"
network_interface {
device_index = 0
network_interface_id = aws_network_interface.web-server-nic.id
}
user_data = <<-EOF
#!/bin/bash
sudo apt update -y
sudo apt install apache2 -y
sudo systemctl start apache2
sudo bash -c 'echo our first web server >
/var/www/html/index.html'
EOF
tags = {
Name = var.ec2_instance_name
}
}

output "my_webserver_public_ip" {
value = aws_eip.one.public_ip
}

output "my_webserver_private_ip" {
value = aws_instance.web-server-instance.private_ip
}

output "my_webserver_instance_id" {
value = aws_instance.web-server-instance.id
}

providers.tf

provider "aws" {
region = "us-east-1"
}

________________________________________________________
Variables.tf

variable "subnet_cidr" {
type = list
default = ["10.0.0.0/24", "10.0.1.0/24"]
}
_______________________________________________________
Command Description

git init Initialize a local Git repository


git clone
Create a local copy of a remote
ssh://git@github.com/[username]/[repo
sitory-name].git repository

Basic Snapshotting
Command Description

git status Check status

git add [file-name.txt] Add a file to the staging area

Add all new and changed files to the


git add -A
staging area

git commit -m "[commit message]" Commit changes

git rm -r [file-name.txt] Remove a file (or folder)


Branching & Merging
Command Description

List branches (the asterisk denotes the


git branch
current branch)

git branch -a List all branches (local and remote)

git branch [branch name] Create a new branch

git branch -d [branch name] Delete a branch


git push origin --delete [branch
name] Delete a remote branch

git checkout -b [branch name] Create a new branch and switch to it


git checkout -b [branch name]
origin/[branch name] Clone a remote branch and switch to it

git branch -m [old branch name] [new


branch name] Rename a local branch

git checkout [branch name] Switch to a branch

git checkout - Switch to the branch last checked out

git checkout -- [file-name.txt] Discard changes to a file

git merge [branch name] Merge a branch into the active branch
git merge [source branch] [target
branch] Merge a branch into a target branch

Stash changes in a dirty working


git stash
directory

git stash clear Remove all stashed entries


Sharing & Updating Projects
Command Description

Push a branch to your remote


git push origin [branch name]
repository

Push changes to remote repository


git push -u origin [branch name]
(and remember the branch)

Push changes to remote repository


git push
(remembered branch)
git push origin --delete [branch
name] Delete a remote branch

Update local repository to the newest


git pull
commit

git pull origin [branch name] Pull changes from remote repository
git remote add origin
ssh://git@github.com/[username]/[repo Add a remote repository
sitory-name].git

git remote set-url origin


ssh://git@github.com/[username]/[repo Set a repository's origin branch to SSH
sitory-name].git

Inspection & Comparison


Command Description

git log View changes

git log --summary View changes (detailed)

git log --oneline View changes (briefly)

git diff [source branch] [destination Preview changes before merging

Command Usage
docker attach Attach local standard input, output, and error streams to a running container
docker build Build an image from a Dockerfile
Command Usage
docker builder Manage builds
docker checkpoint Manage checkpoints
docker commit Create a new image from a container’s changes
docker config Manage Docker configs
docker container Manage containers
docker context Manage contexts
docker cp Copy files/folders between a container and the local filesystem
docker create Create a new container
docker diff Inspect changes to files or directories on a container’s filesystem
docker events Get real time events from the server
docker exec Run a command in a running container
docker export Export a container’s filesystem as a tar archive
docker history Show the history of an image
docker image Manage images
docker images List images
docker import Import the contents from a tarball to create a filesystem image
docker info Display system-wide information
docker inspect Return low-level information on Docker objects
docker kill Kill one or more running containers
docker load Load an image from a tar archive or STDIN
docker login Log in to a Docker registry
docker logout Log out from a Docker registry
docker logs Fetch the logs of a container
docker manifest Manage Docker image manifests and manifest lists
docker network Manage networks
docker node Manage Swarm nodes
docker pause Pause all processes within one or more containers
docker plugin Manage plugins
docker port List port mappings or a specific mapping for the container
docker ps List containers
docker pull Pull an image or a repository from a registry
docker push Push an image or a repository to a registry
docker rename Rename a container
docker restart Restart one or more containers
docker rm Remove one or more containers
docker rmi Remove one or more images
docker run Run a command in a new container
docker save Save one or more images to a tar archive (streamed to STDOUT by default)
docker search Search the Docker Hub for images
docker secret Manage Docker secrets
docker service Manage services
docker stack Manage Docker stacks
Command Usage
docker start Start one or more stopped containers
docker stats Display a live stream of container(s) resource usage statistics
docker stop Stop one or more running containers
docker swarm Manage Swarm
docker system Manage Docker
docker tag Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE
docker top Display the running processes of a container
docker trust Manage trust on Docker images
docker unpause Unpause all processes within one or more containers
docker update Update configuration of one or more containers
docker version Show the Docker version information
docker volume Manage volumes
docker wait Block until one or more containers stop, then print their exit codes

Terraform CLI tricks

• terraform -install-autocomplete #Setup tab auto-completion, requires logging back in


Format and Validate Terraform code
• terraform fmt #format code per HCL canonical standard
• terraform validate #validate code for syntax
• terraform validate -backend=false #validate code skip backend validation
Initialize your Terraform working directory
• terraform init #initialize directory, pull down providers
• terraform init -get-plugins=false #initialize directory, do not download plugins
• terraform init -verify-plugins=false #initialize directory, do not verify plugins for Hashicorp
signature
Plan, Deploy and Cleanup Infrastructure
• terraform apply --auto-approve #apply changes without being prompted to enter "yes"
• terraform destroy --auto-approve #destroy/cleanup deployment without being prompted for
“yes”
• terraform plan -out plan.out #output the deployment plan to plan.out
• terraform apply plan.out #use the plan.out plan file to deploy infrastructure
• terraform plan -destroy #outputs a destroy plan
• terraform apply -target=aws_instance.my_ec2 #only apply/deploy changes to the targeted
resource
• terraform apply -var my_region_variable=us-east-1 #pass a variable via command-line while
applying a configuration
• terraform apply -lock=true #lock the state file so it can't be modified by any other Terraform
apply or modification action(possible only where backend allows locking)
• terraform apply refresh=false # do not reconcile state file with real-world resources(helpful
with large complex deployments for saving deployment time)
• terraform apply --parallelism=5 #number of simultaneous resource operations
• terraform refresh #reconcile the state in Terraform state file with real-world resources
• terraform providers #get information about providers used in current configuration
Terraform Workspaces
• terraform workspace new mynewworkspace #create a new workspace
• terraform workspace select default #change to the selected workspace
• terraform workspace list #list out all workspaces
Terraform State Manipulation
• terraform state show aws_instance.my_ec2 #show details stored in Terraform state for the
resource
• terraform state pull > terraform.tfstate #download and output terraform state to a file
• terraform state mv aws_iam_role.my_ssm_role module.custom_module #move a resource
tracked via state to different module
• terraform state replace-provider hashicorp/aws registry.custom.com/aws #replace an existing
provider with another
• terraform state list #list out all the resources tracked via the current state file
• terraform state rm aws_instance.myinstace #unmanage a resource, delete it from Terraform
state file
Terraform Import And Outputs
• terraform import aws_instance.new_ec2_instance i-abcd1234 #import EC2 instance with id i-
abcd1234 into the Terraform resource named "new_ec2_instance" of type "aws_instance"
• terraform import 'aws_instance.new_ec2_instance[0]' i-abcd1234 #same as above, imports a
real-world resource into an instance of Terraform resource
• terraform output #list all outputs as stated in code
• terraform output instance_public_ip # list out a specific declared output
• terraform output -json #list all outputs in JSON format
Terraform Miscelleneous commands
• terraform version #display Terraform binary version, also warns if version is old
• terraform get -update=true #download and update modules in the "root" module.
Terraform Console(Test out Terraform interpolations)
• echo 'join(",",["foo","bar"])' | terraform console #echo an expression into terraform console
and see its expected result as output
• echo '1 + 5' | terraform console #Terraform console also has an interactive CLI just enter
"terraform console"
• echo "aws_instance.my_ec2.public_ip" | terraform console #display the Public IP against the
"my_ec2" Terraform resource as seen in the Terraform state file
Terraform Graph(Dependency Graphing)
• terraform graph | dot -Tpng > graph.png #produce a PNG diagrams showing relationship and
dependencies between Terraform resource in your configuration/code
Terraform Taint/Untaint(mark/unmark resource for recreation -> delete and then recreate)
• terraform taint aws_instance.my_ec2 #taints resource to be recreated on next apply
• terraform untaint aws_instance.my_ec2 #Remove taint from a resource
• terraform force-unlock LOCK_ID #forcefully unlock a locked state file, LOCK_ID provided
when locking the State file beforehand
Terraform Cloud
• terraform login #obtain and save API token for Terraform cloud
• terraform logout #Log out of Terraform Cloud, defaults to hostname app.terraform.io

You might also like