SlideShare a Scribd company logo
Testing Terraform
Nathen Harvey
Chef
@nathenharvey
What am I talking about
• Suppose you use a tool like Terraform to create your infrastructure
• You're onboard with infrastructure as code
• Code should be tested
• How can we test Terraform?
@nathenharvey
1. Deploy n-tier cloud infra
2. Deploy some app
3. Profit
A Motivational Example
Load
Balancer
VM
Instance
VM
Instance
...
@nathenharvey
1. Deploy n-tier cloud infra
2. Deploy some app ???
3. Profit
A Motivational Example
Load
Balancer
VM
Instance
VM
Instance
...
@nathenharvey
So how do you do that in
Terraform?
@nathenharvey
Terraform on AWS: Define an Instance (VM)
resource "aws_instance" "web" {
count = 3
instance_type = "t2.micro"
ami = "${lookup(var.aws_amis, var.aws_region)}"
key_name = "${var.key_name}"
subnet_id = "${aws_subnet.default.id}"
vpc_security_group_ids = [
"${aws_security_group.lb_to_webservers.id}",
"${aws_security_group.ssh_from_office.id}",
]
...
}
@nathenharvey
Terraform on AWS: Define Load Balancer (ELB)
resource "aws_elb" "web" {
name = "testing-terraform-elb"
subnets = ["${aws_subnet.default.id}"]
security_groups = [
"${aws_security_group.world_to_elb.id}",
"${aws_security_group.lb_to_webservers.id}",
]
instances = ["${aws_instance.web.*.id}"]
listener {
instance_port = 80
instance_protocol = "http"
lb_port = 80
lb_protocol = "http"
}
}
@nathenharvey
Terraform on AWS: Define a Firewall Rule
resource "aws_security_group" "ssh_from_office" {
name = "testing-terraform-ssh"
vpc_id = "${aws_vpc.testing_terraform.id}"
# SSH access from special office addresses
ingress {
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = "${var.ssh_cidrs}"
}
# outbound internet access
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
}
@nathenharvey
Terraform on AWS: Define a Firewall Rule
resource "aws_security_group" "ssh_from_office" {
name = "testing-terraform-ssh"
vpc_id = "${aws_vpc.testing_terraform.id}"
# SSH access from special office addresses
ingress {
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = "${var.ssh_cidrs}"
}
# outbound internet access
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
}
variable "ssh_cidrs" {
default = [
"173.239.212.22/32",
"12.130.117.75/32"
]
}
$
What's the plan, Phil?
terraform plan -out plan.out
Refreshing Terraform state in-memory prior to plan...
The refreshed state will be used to calculate this plan, but will not be
persisted to local or remote state storage.
...
Plan: 11 to add, 0 to change, 0 to destroy.
------------------------------------------------------------------------
This plan was saved to: plan.out
To perform exactly these actions, run the following command to apply:
terraform apply "plan.out"
$
Make it so!
terraform apply "plan.out"
aws_vpc.testing_terraform: Creating...
assign_generated_ipv6_cidr_block: "" => "false"
cidr_block: "" => "10.0.0.0/16"
default_network_acl_id: "" => "<computed>"
default_route_table_id: "" => "<computed>"
default_security_group_id: "" => "<computed>”
...
aws_elb.web: Creation complete after 25s (ID: testing-terraform-elb)
Apply complete! Resources: 11 added, 0 changed, 0 destroyed.
Outputs:
address = testing-terraform-elb-1345186905.us-east-1.elb.amazonaws.com
@nathenharvey
It's alive!
@nathenharvey
Part of a balanced diet
$
Verify with Terraform
terraform plan
Refreshing Terraform state in-memory prior to plan...
The refreshed state will be used to calculate this plan, but will not be
persisted to local or remote state storage.
aws_vpc.testing_terraform: Refreshing state... (ID: vpc-091427c0ca8ed3c29)
...
aws_elb.web: Refreshing state... (ID: testing-terraform-elb)
------------------------------------------------------------------------
No changes. Infrastructure is up-to-date.
This means that Terraform did not detect any differences between your
configuration and real physical resources that exist. As a result, no
actions need to be performed.
@nathenharvey
And all is well.
@nathenharvey
Meanwhile, at Team Shady….
@nathenharvey
An Innocent-Seeming Change…
@nathenharvey
An Innocent-Seeming Change…
$
Audit with Terraform
terraform plan
An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
~ update in-place
Terraform will perform the following actions:
~ aws_instance.web[0]
vpc_security_group_ids.#: "3" => "2"
vpc_security_group_ids.1298918294: "sg-01eefd0164f2de498" => "sg-01eefd0164f2de498"
vpc_security_group_ids.35497876: "sg-0c6388fa3e956cc15" => ""
vpc_security_group_ids.645334896: "sg-03bca2a0e861c01e7" => "sg-03bca2a0e861c01e7”
Plan: 0 to add, 1 to change, 0 to destroy.
@nathenharvey
Detected the new security group
Will detach it
Is that enough?
Awesome! Terraform found the change!
@nathenharvey
It only audits what is known in the Terraform config
All change is drift (considered bad)
Only express what you want,
not what you don't
How does terraform plan fall short?
@nathenharvey
We need something else.
@nathenharvey
@nathenharvey
PART OF A PROCESS OF CONTINUOUS COMPLIANCE
Scan for
Compliance
Build & Test
Locally
Build & Test
CI/CD Remediate Verify
A SIMPLE EXAMPLE OF AN INSPEC CIS RULE
InSpec
▪ Translate compliance into Code
▪ Clearly express statements of policy
▪ Move risk to build/test from runtime
▪ Find issues early
▪ Write code quickly
▪ Run code anywhere
▪ Inspect machines, data and APIs
Turn security and
compliance into code
control 'cis-1.4.1' do
title '1.4.1 Enable SELinux in /etc/grub.conf'
desc '
Do not disable SELinux and enforcing in your GRUB
configuration. These are important security features that
prevent attackers from escalating their access to your systems.
For reference see …
'
impact 1.0
expect(grub_conf.param 'selinux').to_not eq '0'
expect(grub_conf.param 'enforcing').to_not eq '0'
end
$
InSpec Shell
inspec shell –t aws://
Welcome to the interactive InSpec Shell
To find out how to use it, type: help
You are currently running on:
Name: aws
Families: cloud, api
Release: aws-sdk-v2.11.50
$
InSpec Shell
inspec shell –t aws://
Welcome to the interactive InSpec Shell
To find out how to use it, type: help
You are currently running on:
Name: aws
Families: cloud, api
Release: aws-sdk-v2.11.50
Targeting AWS!
inspec>
InSpec Shell – Tab Completion
aws_<TAB>
aws_cloudtrail_trail aws_iam_access_keys aws_iam_users aws_security_group
aws_cloudtrail_trails aws_iam_group aws_kms_key aws_security_groups
aws_cloudwatch_alarm aws_iam_groups aws_kms_keys aws_sns_subscription
aws_cloudwatch_log_metric_filter aws_iam_password_policy aws_rds_instance aws_sns_topic
aws_config_delivery_channel aws_iam_policies aws_route_table aws_sns_topics
aws_config_recorder aws_iam_policy aws_route_tables aws_subnet
aws_ec2_instance aws_iam_role aws_s3_bucket aws_subnets
aws_ec2_instances aws_iam_root_user aws_s3_bucket_object aws_vpc
aws_iam_access_key aws_iam_user aws_s3_buckets aws_vpcs
inspec>
Find the shady security group
aws_security_group('sg-0c6388fa3e956cc15').group_name
=> "uat_executive"
inspec>
Check the Rules
aws_security_group('sg-0c6388fa3e956cc15').inbound_rules
=> [{:from_port=>22,
:ip_protocol=>"tcp",
:ip_ranges=>[{:cidr_ip=>"0.0.0.0/0"}],
:ipv_6_ranges=>[{:cidr_ipv_6=>"::/0"}],
:prefix_list_ids=>[],
:to_port=>22,
:user_id_group_pairs=>[]}]
inspec> describe aws_security_group('sg-0c6388fa3e956cc15') do
inspec> it { should_not allow_in ipv4_range: '0.0.0.0/0' }
inspec> end
Write a proper test
inspec> describe aws_security_group('sg-0c6388fa3e956cc15') do
inspec> it { should_not allow_in ipv4_range: '0.0.0.0/0' }
inspec> end
Profile: inspec-shell
Version: (not specified)
EC2 Security Group sg-0c6388fa3e956cc15
× should not allow in {}
expected `EC2 Security Group sg-0c6388fa3e956cc15.allow_in?({})` to
return false, got true
Test Summary: 0 successful, 1 failure, 0 skipped
Write a proper test
@nathenharvey
An InSpec Control
security_groups.rb
control 'Make sure unrestricted SSH is not permitted' do
# Loop over each of the security group IDs in the region
aws_security_groups.group_ids.each do |group_id|
# Examine a security group in detail
describe aws_security_group(group_id) do
# Examine Ingress rules, and complain if
# there is unrestricted SSH
it { should_not allow_in(port: 22, ipv4_range: '0.0.0.0/0') }
end
end
end
$
InSpec Shell
inspec exec –t aws:// secruity_groups.rb
Profile: tests from security_groups.rb (tests from security_groups.rb)
Version: (not specified)
Target: aws://
× Make sure unrestricted SSH is not permitted: EC2 Security Group sg-003262589de21dbf5 (15
failed)
✔ EC2 Security Group sg-003262589de21dbf5 should not allow in {}
✔ EC2 Security Group sg-00f0b54bd7c8d93a1 should not allow in {}
× EC2 Security Group sg-0c6388fa3e956cc15 should not allow in {}
expected `EC2 Security Group sg-0c6388fa3e956cc15.allow_in?({})` to return false, got
true
...
Profile Summary: 0 successful controls, 1 control failure, 0 controls skipped
Test Summary: 4 successful, 15 failures, 0 skipped
@nathenharvey
Where to next?
@nathenharvey
What else to validate?
Concern
Terraform
Plan
InSpec
Number and type of instances requested
All instances are part of our app
Right security groups created and attached
No security group allows in SSH
Only security group open to the world should
be port 80 for the ELB
ELB correctly configured
Should only be one ELB
@nathenharvey
Check instances
instances.rb
control "Should only have instances associated with my app" do
aws_ec2_instances.instance_ids.each do |instance_id|
describe aws_ec2_instance(instance_id) do
its('instance_type') { should cmp 't2.micro' }
its('tags') { should include(key:'X-Application', value:'Testing Terraform') }
end
end
end
@nathenharvey
More Security Groups
security_groups.rb
control "The only world-open security groups should be on the ELB" do
elb_sg_ids = aws_elbs.security_group_ids
aws_security_groups.group_ids.each do |sg_id|
sg = aws_security_group(sg_id)
if sg.allow_in? ipv4_range: '0.0.0.0/0'
describe sg do
its('group_id') { should be_in elb_sg_ids }
it { should allow_in_only port: 80 }
end
end
end
end
$
Put it all together with a profile
inspec init profile my_app
Create new profile at /Users/nathenharvey/projects/nathenharvey/testing-
terraform/inspec/profiles/my_app
* Create directory libraries
* Create file README.md
* Create directory controls
* Create file controls/example.rb
* Create file inspec.yml
* Create file libraries/.gitkeep
$
Put it all together with a profile
inspec exec -t aws:// my_app
Profile: tests from security_groups.rb (tests from security_groups.rb)
Version: (not specified)
Target: aws://
× Make sure unrestricted SSH is not permitted: EC2 Security Group sg-003262589de21dbf5 (15
failed)
✔ EC2 Security Group sg-003262589de21dbf5 should not allow in {}
✔ EC2 Security Group sg-00f0b54bd7c8d93a1 should not allow in {}
× EC2 Security Group sg-01b504b800f32e1ff should not allow in {}
expected `EC2 Security Group sg-01b504b800f32e1ff.allow_in?({})` to return false, got
true
...
Profile Summary: 0 successful controls, 3 control failures, 0 controls skipped
Test Summary: 43 successful, 65 failures, 0 skipped
@nathenharvey
Terraform: A Power Tool for the Cloud!
Terraform and InSpec?
InSpec: A Verification tool for OS's and API's
@nathenharvey
Terraform: A Power Tool for the Cloud!
Terraform and InSpec!
InSpec: A Verification tool for OS's and API's
@nathenharvey
Bonus Round
Iggy
$
Install InSpec-Iggy
gem install inspec-iggy
Successfully installed inspec-iggy-0.2.0
1 gem installed
$
Create a Profile from tfstate file
inspec terraform generate --tfstate terraform.tfstate > my_terra.rb
$
Run InSpec
inspec exec -t aws:// my_terra.rb
inspec exec -t aws:// my_terra.rb
Profile: tests from my_terra.rb (tests from my_terra.rb)
Version: (not specified)
Target: aws://
✔ aws_ec2_instance::i-03663e4b9cb2858d6: Iggy terraform.tfstate
aws_ec2_instance::i-03663e4b9cb2858d6
✔ EC2 Instance i-03663e4b9cb2858d6 should exist
...
Profile Summary: 8 successful controls, 0 control failures, 0 controls skipped
Test Summary: 32 successful, 0 failures, 0 skipped
@nathenharvey
Join us on Slack!
● http://community-slack.chef.io
● #general (for Chef stuff)
● #inspec
@nathenharvey
What questions can I answer for you?
https://github.com/nathenharvey/testing-terraform
Testing Terraform

More Related Content

What's hot

Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...
Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...
Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...
Ivan Piskunov
 
How to add a new hypervisor to CloudStack:Lessons learned from Hyper-V effort
How to add a new hypervisor to CloudStack:Lessons learned from Hyper-V effortHow to add a new hypervisor to CloudStack:Lessons learned from Hyper-V effort
How to add a new hypervisor to CloudStack:Lessons learned from Hyper-V effort
Donal Lafferty
 
Attacking Oracle with the Metasploit Framework
Attacking Oracle with the Metasploit FrameworkAttacking Oracle with the Metasploit Framework
Attacking Oracle with the Metasploit Framework
Chris Gates
 
FreeBSD: Dev to Prod
FreeBSD: Dev to ProdFreeBSD: Dev to Prod
FreeBSD: Dev to Prod
Sean Chittenden
 
BuildStuff.LT 2018 InSpec Workshop
BuildStuff.LT 2018 InSpec WorkshopBuildStuff.LT 2018 InSpec Workshop
BuildStuff.LT 2018 InSpec Workshop
Mandi Walls
 
IstSec'14 - İbrahim BALİÇ - Automated Malware Analysis
IstSec'14 - İbrahim BALİÇ -  Automated Malware AnalysisIstSec'14 - İbrahim BALİÇ -  Automated Malware Analysis
IstSec'14 - İbrahim BALİÇ - Automated Malware Analysis
BGA Cyber Security
 
Threat stack aws
Threat stack awsThreat stack aws
Threat stack aws
Jen Andre
 
Embedded software development using BDD
Embedded software development using BDDEmbedded software development using BDD
Embedded software development using BDD
Itamar Hassin
 
Security in PHP - 那些在滲透測試的小技巧
Security in PHP - 那些在滲透測試的小技巧Security in PHP - 那些在滲透測試的小技巧
Security in PHP - 那些在滲透測試的小技巧
Orange Tsai
 
Meder Kydyraliev - Mining Mach Services within OS X Sandbox
Meder Kydyraliev - Mining Mach Services within OS X SandboxMeder Kydyraliev - Mining Mach Services within OS X Sandbox
Meder Kydyraliev - Mining Mach Services within OS X Sandbox
DefconRussia
 
Inspec one tool to rule them all
Inspec one tool to rule them allInspec one tool to rule them all
Inspec one tool to rule them all
Kimball Johnson
 
Terraform Introduction
Terraform IntroductionTerraform Introduction
Terraform Introduction
soniasnowfrog
 
infra-as-code
infra-as-codeinfra-as-code
infra-as-code
Itamar Hassin
 
2019 Chef InSpec Jumpstart Part 2 of 2
2019 Chef InSpec Jumpstart Part 2 of 22019 Chef InSpec Jumpstart Part 2 of 2
2019 Chef InSpec Jumpstart Part 2 of 2
Larry Eichenbaum
 
Infrastructure as Code with Terraform
Infrastructure as Code with TerraformInfrastructure as Code with Terraform
Infrastructure as Code with Terraform
Tim Berry
 
(Un)safe Python
(Un)safe Python(Un)safe Python
(Un)safe Python
Ivan Tsyganov
 
So you want to be a security expert
So you want to be a security expertSo you want to be a security expert
So you want to be a security expert
Royce Davis
 
Adventures in Asymmetric Warfare
Adventures in Asymmetric WarfareAdventures in Asymmetric Warfare
Adventures in Asymmetric Warfare
Will Schroeder
 
Node.js vs Play Framework
Node.js vs Play FrameworkNode.js vs Play Framework
Node.js vs Play Framework
Yevgeniy Brikman
 
Defending Your Network
Defending Your NetworkDefending Your Network
Defending Your Network
Adam Getchell
 

What's hot (20)

Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...
Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...
Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...
 
How to add a new hypervisor to CloudStack:Lessons learned from Hyper-V effort
How to add a new hypervisor to CloudStack:Lessons learned from Hyper-V effortHow to add a new hypervisor to CloudStack:Lessons learned from Hyper-V effort
How to add a new hypervisor to CloudStack:Lessons learned from Hyper-V effort
 
Attacking Oracle with the Metasploit Framework
Attacking Oracle with the Metasploit FrameworkAttacking Oracle with the Metasploit Framework
Attacking Oracle with the Metasploit Framework
 
FreeBSD: Dev to Prod
FreeBSD: Dev to ProdFreeBSD: Dev to Prod
FreeBSD: Dev to Prod
 
BuildStuff.LT 2018 InSpec Workshop
BuildStuff.LT 2018 InSpec WorkshopBuildStuff.LT 2018 InSpec Workshop
BuildStuff.LT 2018 InSpec Workshop
 
IstSec'14 - İbrahim BALİÇ - Automated Malware Analysis
IstSec'14 - İbrahim BALİÇ -  Automated Malware AnalysisIstSec'14 - İbrahim BALİÇ -  Automated Malware Analysis
IstSec'14 - İbrahim BALİÇ - Automated Malware Analysis
 
Threat stack aws
Threat stack awsThreat stack aws
Threat stack aws
 
Embedded software development using BDD
Embedded software development using BDDEmbedded software development using BDD
Embedded software development using BDD
 
Security in PHP - 那些在滲透測試的小技巧
Security in PHP - 那些在滲透測試的小技巧Security in PHP - 那些在滲透測試的小技巧
Security in PHP - 那些在滲透測試的小技巧
 
Meder Kydyraliev - Mining Mach Services within OS X Sandbox
Meder Kydyraliev - Mining Mach Services within OS X SandboxMeder Kydyraliev - Mining Mach Services within OS X Sandbox
Meder Kydyraliev - Mining Mach Services within OS X Sandbox
 
Inspec one tool to rule them all
Inspec one tool to rule them allInspec one tool to rule them all
Inspec one tool to rule them all
 
Terraform Introduction
Terraform IntroductionTerraform Introduction
Terraform Introduction
 
infra-as-code
infra-as-codeinfra-as-code
infra-as-code
 
2019 Chef InSpec Jumpstart Part 2 of 2
2019 Chef InSpec Jumpstart Part 2 of 22019 Chef InSpec Jumpstart Part 2 of 2
2019 Chef InSpec Jumpstart Part 2 of 2
 
Infrastructure as Code with Terraform
Infrastructure as Code with TerraformInfrastructure as Code with Terraform
Infrastructure as Code with Terraform
 
(Un)safe Python
(Un)safe Python(Un)safe Python
(Un)safe Python
 
So you want to be a security expert
So you want to be a security expertSo you want to be a security expert
So you want to be a security expert
 
Adventures in Asymmetric Warfare
Adventures in Asymmetric WarfareAdventures in Asymmetric Warfare
Adventures in Asymmetric Warfare
 
Node.js vs Play Framework
Node.js vs Play FrameworkNode.js vs Play Framework
Node.js vs Play Framework
 
Defending Your Network
Defending Your NetworkDefending Your Network
Defending Your Network
 

Similar to Testing Terraform

Modern tooling to assist with developing applications on FreeBSD
Modern tooling to assist with developing applications on FreeBSDModern tooling to assist with developing applications on FreeBSD
Modern tooling to assist with developing applications on FreeBSD
Sean Chittenden
 
Docker Security workshop slides
Docker Security workshop slidesDocker Security workshop slides
Docker Security workshop slides
Docker, Inc.
 
Dive into DevOps | March, Building with Terraform, Volodymyr Tsap
Dive into DevOps | March, Building with Terraform, Volodymyr TsapDive into DevOps | March, Building with Terraform, Volodymyr Tsap
Dive into DevOps | March, Building with Terraform, Volodymyr Tsap
Provectus
 
Shopping for Vulnerabilities - How Cloud Service Provider Marketplaces can He...
Shopping for Vulnerabilities - How Cloud Service Provider Marketplaces can He...Shopping for Vulnerabilities - How Cloud Service Provider Marketplaces can He...
Shopping for Vulnerabilities - How Cloud Service Provider Marketplaces can He...
Tenchi Security
 
Shopping for Vulnerabilities - How Cloud Service Provider Marketplaces can He...
Shopping for Vulnerabilities - How Cloud Service Provider Marketplaces can He...Shopping for Vulnerabilities - How Cloud Service Provider Marketplaces can He...
Shopping for Vulnerabilities - How Cloud Service Provider Marketplaces can He...
Alexandre Sieira
 
Enterprise Vulnerability Management - ZeroNights16
Enterprise Vulnerability Management - ZeroNights16Enterprise Vulnerability Management - ZeroNights16
Enterprise Vulnerability Management - ZeroNights16
Alexander Leonov
 
Azure from scratch part 4
Azure from scratch part 4Azure from scratch part 4
Azure from scratch part 4
Girish Kalamati
 
SaltConf14 - Ben Cane - Using SaltStack in High Availability Environments
SaltConf14 - Ben Cane - Using SaltStack in High Availability EnvironmentsSaltConf14 - Ben Cane - Using SaltStack in High Availability Environments
SaltConf14 - Ben Cane - Using SaltStack in High Availability Environments
SaltStack
 
(ARC402) Deployment Automation: From Developers' Keyboards to End Users' Scre...
(ARC402) Deployment Automation: From Developers' Keyboards to End Users' Scre...(ARC402) Deployment Automation: From Developers' Keyboards to End Users' Scre...
(ARC402) Deployment Automation: From Developers' Keyboards to End Users' Scre...
Amazon Web Services
 
Continuous Integration Testing in Django
Continuous Integration Testing in DjangoContinuous Integration Testing in Django
Continuous Integration Testing in Django
Kevin Harvey
 
An intro to Docker, Terraform, and Amazon ECS
An intro to Docker, Terraform, and Amazon ECSAn intro to Docker, Terraform, and Amazon ECS
An intro to Docker, Terraform, and Amazon ECS
Yevgeniy Brikman
 
Continuous Delivery: The Next Frontier
Continuous Delivery: The Next FrontierContinuous Delivery: The Next Frontier
Continuous Delivery: The Next Frontier
Carlos Sanchez
 
Test-Driven Infrastructure with Chef
Test-Driven Infrastructure with ChefTest-Driven Infrastructure with Chef
Test-Driven Infrastructure with Chef
Michael Lihs
 
Reusable, composable, battle-tested Terraform modules
Reusable, composable, battle-tested Terraform modulesReusable, composable, battle-tested Terraform modules
Reusable, composable, battle-tested Terraform modules
Yevgeniy Brikman
 
Automated Intrusion Detection and Response on AWS
Automated Intrusion Detection and Response on AWSAutomated Intrusion Detection and Response on AWS
Automated Intrusion Detection and Response on AWS
Teri Radichel
 
Philly security shell meetup
Philly security shell meetupPhilly security shell meetup
Philly security shell meetup
Nicole Johnson
 
DevOpsDaysRiga 2017: Mandi Walls - Building security into your workflow with ...
DevOpsDaysRiga 2017: Mandi Walls - Building security into your workflow with ...DevOpsDaysRiga 2017: Mandi Walls - Building security into your workflow with ...
DevOpsDaysRiga 2017: Mandi Walls - Building security into your workflow with ...
DevOpsDays Riga
 
Keeping Your Kubernetes Cluster Secure
Keeping Your Kubernetes Cluster SecureKeeping Your Kubernetes Cluster Secure
Keeping Your Kubernetes Cluster Secure
Gene Gotimer
 
Building an HPC Cluster in 10 Minutes
Building an HPC Cluster in 10 MinutesBuilding an HPC Cluster in 10 Minutes
Building an HPC Cluster in 10 Minutes
Monica Rut Avellino
 
Antons Kranga Building Agile Infrastructures
Antons Kranga   Building Agile InfrastructuresAntons Kranga   Building Agile Infrastructures
Antons Kranga Building Agile Infrastructures
Antons Kranga
 

Similar to Testing Terraform (20)

Modern tooling to assist with developing applications on FreeBSD
Modern tooling to assist with developing applications on FreeBSDModern tooling to assist with developing applications on FreeBSD
Modern tooling to assist with developing applications on FreeBSD
 
Docker Security workshop slides
Docker Security workshop slidesDocker Security workshop slides
Docker Security workshop slides
 
Dive into DevOps | March, Building with Terraform, Volodymyr Tsap
Dive into DevOps | March, Building with Terraform, Volodymyr TsapDive into DevOps | March, Building with Terraform, Volodymyr Tsap
Dive into DevOps | March, Building with Terraform, Volodymyr Tsap
 
Shopping for Vulnerabilities - How Cloud Service Provider Marketplaces can He...
Shopping for Vulnerabilities - How Cloud Service Provider Marketplaces can He...Shopping for Vulnerabilities - How Cloud Service Provider Marketplaces can He...
Shopping for Vulnerabilities - How Cloud Service Provider Marketplaces can He...
 
Shopping for Vulnerabilities - How Cloud Service Provider Marketplaces can He...
Shopping for Vulnerabilities - How Cloud Service Provider Marketplaces can He...Shopping for Vulnerabilities - How Cloud Service Provider Marketplaces can He...
Shopping for Vulnerabilities - How Cloud Service Provider Marketplaces can He...
 
Enterprise Vulnerability Management - ZeroNights16
Enterprise Vulnerability Management - ZeroNights16Enterprise Vulnerability Management - ZeroNights16
Enterprise Vulnerability Management - ZeroNights16
 
Azure from scratch part 4
Azure from scratch part 4Azure from scratch part 4
Azure from scratch part 4
 
SaltConf14 - Ben Cane - Using SaltStack in High Availability Environments
SaltConf14 - Ben Cane - Using SaltStack in High Availability EnvironmentsSaltConf14 - Ben Cane - Using SaltStack in High Availability Environments
SaltConf14 - Ben Cane - Using SaltStack in High Availability Environments
 
(ARC402) Deployment Automation: From Developers' Keyboards to End Users' Scre...
(ARC402) Deployment Automation: From Developers' Keyboards to End Users' Scre...(ARC402) Deployment Automation: From Developers' Keyboards to End Users' Scre...
(ARC402) Deployment Automation: From Developers' Keyboards to End Users' Scre...
 
Continuous Integration Testing in Django
Continuous Integration Testing in DjangoContinuous Integration Testing in Django
Continuous Integration Testing in Django
 
An intro to Docker, Terraform, and Amazon ECS
An intro to Docker, Terraform, and Amazon ECSAn intro to Docker, Terraform, and Amazon ECS
An intro to Docker, Terraform, and Amazon ECS
 
Continuous Delivery: The Next Frontier
Continuous Delivery: The Next FrontierContinuous Delivery: The Next Frontier
Continuous Delivery: The Next Frontier
 
Test-Driven Infrastructure with Chef
Test-Driven Infrastructure with ChefTest-Driven Infrastructure with Chef
Test-Driven Infrastructure with Chef
 
Reusable, composable, battle-tested Terraform modules
Reusable, composable, battle-tested Terraform modulesReusable, composable, battle-tested Terraform modules
Reusable, composable, battle-tested Terraform modules
 
Automated Intrusion Detection and Response on AWS
Automated Intrusion Detection and Response on AWSAutomated Intrusion Detection and Response on AWS
Automated Intrusion Detection and Response on AWS
 
Philly security shell meetup
Philly security shell meetupPhilly security shell meetup
Philly security shell meetup
 
DevOpsDaysRiga 2017: Mandi Walls - Building security into your workflow with ...
DevOpsDaysRiga 2017: Mandi Walls - Building security into your workflow with ...DevOpsDaysRiga 2017: Mandi Walls - Building security into your workflow with ...
DevOpsDaysRiga 2017: Mandi Walls - Building security into your workflow with ...
 
Keeping Your Kubernetes Cluster Secure
Keeping Your Kubernetes Cluster SecureKeeping Your Kubernetes Cluster Secure
Keeping Your Kubernetes Cluster Secure
 
Building an HPC Cluster in 10 Minutes
Building an HPC Cluster in 10 MinutesBuilding an HPC Cluster in 10 Minutes
Building an HPC Cluster in 10 Minutes
 
Antons Kranga Building Agile Infrastructures
Antons Kranga   Building Agile InfrastructuresAntons Kranga   Building Agile Infrastructures
Antons Kranga Building Agile Infrastructures
 

More from Nathen Harvey

Accelerate Your DevOps Journey
Accelerate Your DevOps JourneyAccelerate Your DevOps Journey
Accelerate Your DevOps Journey
Nathen Harvey
 
Continuous Delivery - GDG Cloud Baltimore
Continuous Delivery - GDG Cloud BaltimoreContinuous Delivery - GDG Cloud Baltimore
Continuous Delivery - GDG Cloud Baltimore
Nathen Harvey
 
Using Error Budgets to Prioritize Work
Using Error Budgets to Prioritize WorkUsing Error Budgets to Prioritize Work
Using Error Budgets to Prioritize Work
Nathen Harvey
 
Introduction to Test Kitchen and InSpec
Introduction to Test Kitchen and InSpecIntroduction to Test Kitchen and InSpec
Introduction to Test Kitchen and InSpec
Nathen Harvey
 
Introduction to Test Kitchen
Introduction to Test KitchenIntroduction to Test Kitchen
Introduction to Test Kitchen
Nathen Harvey
 
Effective Testing with Ansible and InSpec
Effective Testing with Ansible and InSpecEffective Testing with Ansible and InSpec
Effective Testing with Ansible and InSpec
Nathen Harvey
 
Effective Testing with Ansible and InSpec
Effective Testing with Ansible and InSpecEffective Testing with Ansible and InSpec
Effective Testing with Ansible and InSpec
Nathen Harvey
 
DevOps Days India Keynote
DevOps Days India KeynoteDevOps Days India Keynote
DevOps Days India Keynote
Nathen Harvey
 
Compliance Automation with InSpec
Compliance Automation with InSpecCompliance Automation with InSpec
Compliance Automation with InSpec
Nathen Harvey
 
Introduction to Infrastructure as Code & Automation / Introduction to Chef
Introduction to Infrastructure as Code & Automation / Introduction to ChefIntroduction to Infrastructure as Code & Automation / Introduction to Chef
Introduction to Infrastructure as Code & Automation / Introduction to Chef
Nathen Harvey
 
Step AFK: Practical Advice for Career Adavancement
Step AFK: Practical Advice for Career AdavancementStep AFK: Practical Advice for Career Adavancement
Step AFK: Practical Advice for Career Adavancement
Nathen Harvey
 
DevOp with Me!
DevOp with Me!DevOp with Me!
DevOp with Me!
Nathen Harvey
 
Walk This Way - An Introduction to DevOps
Walk This Way - An Introduction to DevOpsWalk This Way - An Introduction to DevOps
Walk This Way - An Introduction to DevOps
Nathen Harvey
 
Mongo db at_customink
Mongo db at_custominkMongo db at_customink
Mongo db at_customink
Nathen Harvey
 

More from Nathen Harvey (14)

Accelerate Your DevOps Journey
Accelerate Your DevOps JourneyAccelerate Your DevOps Journey
Accelerate Your DevOps Journey
 
Continuous Delivery - GDG Cloud Baltimore
Continuous Delivery - GDG Cloud BaltimoreContinuous Delivery - GDG Cloud Baltimore
Continuous Delivery - GDG Cloud Baltimore
 
Using Error Budgets to Prioritize Work
Using Error Budgets to Prioritize WorkUsing Error Budgets to Prioritize Work
Using Error Budgets to Prioritize Work
 
Introduction to Test Kitchen and InSpec
Introduction to Test Kitchen and InSpecIntroduction to Test Kitchen and InSpec
Introduction to Test Kitchen and InSpec
 
Introduction to Test Kitchen
Introduction to Test KitchenIntroduction to Test Kitchen
Introduction to Test Kitchen
 
Effective Testing with Ansible and InSpec
Effective Testing with Ansible and InSpecEffective Testing with Ansible and InSpec
Effective Testing with Ansible and InSpec
 
Effective Testing with Ansible and InSpec
Effective Testing with Ansible and InSpecEffective Testing with Ansible and InSpec
Effective Testing with Ansible and InSpec
 
DevOps Days India Keynote
DevOps Days India KeynoteDevOps Days India Keynote
DevOps Days India Keynote
 
Compliance Automation with InSpec
Compliance Automation with InSpecCompliance Automation with InSpec
Compliance Automation with InSpec
 
Introduction to Infrastructure as Code & Automation / Introduction to Chef
Introduction to Infrastructure as Code & Automation / Introduction to ChefIntroduction to Infrastructure as Code & Automation / Introduction to Chef
Introduction to Infrastructure as Code & Automation / Introduction to Chef
 
Step AFK: Practical Advice for Career Adavancement
Step AFK: Practical Advice for Career AdavancementStep AFK: Practical Advice for Career Adavancement
Step AFK: Practical Advice for Career Adavancement
 
DevOp with Me!
DevOp with Me!DevOp with Me!
DevOp with Me!
 
Walk This Way - An Introduction to DevOps
Walk This Way - An Introduction to DevOpsWalk This Way - An Introduction to DevOps
Walk This Way - An Introduction to DevOps
 
Mongo db at_customink
Mongo db at_custominkMongo db at_customink
Mongo db at_customink
 

Recently uploaded

Using LLM Agents with Llama 3, LangGraph and Milvus
Using LLM Agents with Llama 3, LangGraph and MilvusUsing LLM Agents with Llama 3, LangGraph and Milvus
Using LLM Agents with Llama 3, LangGraph and Milvus
Zilliz
 
Pigging Unit Lubricant Oil Blending Plant
Pigging Unit Lubricant Oil Blending PlantPigging Unit Lubricant Oil Blending Plant
Pigging Unit Lubricant Oil Blending Plant
LINUS PROJECTS (INDIA)
 
Observability For You and Me with OpenTelemetry
Observability For You and Me with OpenTelemetryObservability For You and Me with OpenTelemetry
Observability For You and Me with OpenTelemetry
Eric D. Schabell
 
Amul milk launches in US: Key details of its new products ...
Amul milk launches in US: Key details of its new products ...Amul milk launches in US: Key details of its new products ...
Amul milk launches in US: Key details of its new products ...
chetankumar9855
 
How Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdfHow Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdf
HackersList
 
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdfAcumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
BrainSell Technologies
 
ARTIFICIAL INTELLIGENCE (AI) IN MUSIC.pdf
ARTIFICIAL INTELLIGENCE (AI) IN MUSIC.pdfARTIFICIAL INTELLIGENCE (AI) IN MUSIC.pdf
ARTIFICIAL INTELLIGENCE (AI) IN MUSIC.pdf
Inglês no Mundo Digital
 
Password Rotation in 2024 is still Relevant
Password Rotation in 2024 is still RelevantPassword Rotation in 2024 is still Relevant
Password Rotation in 2024 is still Relevant
Bert Blevins
 
Choose our Linux Web Hosting for a seamless and successful online presence
Choose our Linux Web Hosting for a seamless and successful online presenceChoose our Linux Web Hosting for a seamless and successful online presence
Choose our Linux Web Hosting for a seamless and successful online presence
rajancomputerfbd
 
How to build a generative AI solution A step-by-step guide (2).pdf
How to build a generative AI solution A step-by-step guide (2).pdfHow to build a generative AI solution A step-by-step guide (2).pdf
How to build a generative AI solution A step-by-step guide (2).pdf
ChristopherTHyatt
 
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
aslasdfmkhan4750
 
The Role of Technology in Payroll Statutory Compliance (1).pdf
The Role of Technology in Payroll Statutory Compliance (1).pdfThe Role of Technology in Payroll Statutory Compliance (1).pdf
The Role of Technology in Payroll Statutory Compliance (1).pdf
paysquare consultancy
 
Salesforce AI & Einstein Copilot Workshop
Salesforce AI & Einstein Copilot WorkshopSalesforce AI & Einstein Copilot Workshop
Salesforce AI & Einstein Copilot Workshop
CEPTES Software Inc
 
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
Bert Blevins
 
Applying Retrieval-Augmented Generation (RAG) to Combat Hallucinations in GenAI
Applying Retrieval-Augmented Generation (RAG) to Combat Hallucinations in GenAIApplying Retrieval-Augmented Generation (RAG) to Combat Hallucinations in GenAI
Applying Retrieval-Augmented Generation (RAG) to Combat Hallucinations in GenAI
ssuserd4e0d2
 
Evolution of iPaaS - simplify IT workloads to provide a unified view of data...
Evolution of iPaaS - simplify IT workloads to provide a unified view of  data...Evolution of iPaaS - simplify IT workloads to provide a unified view of  data...
Evolution of iPaaS - simplify IT workloads to provide a unified view of data...
Torry Harris
 
[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf
[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf
[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf
Kief Morris
 
Calgary MuleSoft Meetup APM and IDP .pptx
Calgary MuleSoft Meetup APM and IDP .pptxCalgary MuleSoft Meetup APM and IDP .pptx
Calgary MuleSoft Meetup APM and IDP .pptx
ishalveerrandhawa1
 
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
Priyanka Aash
 
find out more about the role of autonomous vehicles in facing global challenges
find out more about the role of autonomous vehicles in facing global challengesfind out more about the role of autonomous vehicles in facing global challenges
find out more about the role of autonomous vehicles in facing global challenges
huseindihon
 

Recently uploaded (20)

Using LLM Agents with Llama 3, LangGraph and Milvus
Using LLM Agents with Llama 3, LangGraph and MilvusUsing LLM Agents with Llama 3, LangGraph and Milvus
Using LLM Agents with Llama 3, LangGraph and Milvus
 
Pigging Unit Lubricant Oil Blending Plant
Pigging Unit Lubricant Oil Blending PlantPigging Unit Lubricant Oil Blending Plant
Pigging Unit Lubricant Oil Blending Plant
 
Observability For You and Me with OpenTelemetry
Observability For You and Me with OpenTelemetryObservability For You and Me with OpenTelemetry
Observability For You and Me with OpenTelemetry
 
Amul milk launches in US: Key details of its new products ...
Amul milk launches in US: Key details of its new products ...Amul milk launches in US: Key details of its new products ...
Amul milk launches in US: Key details of its new products ...
 
How Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdfHow Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdf
 
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdfAcumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
 
ARTIFICIAL INTELLIGENCE (AI) IN MUSIC.pdf
ARTIFICIAL INTELLIGENCE (AI) IN MUSIC.pdfARTIFICIAL INTELLIGENCE (AI) IN MUSIC.pdf
ARTIFICIAL INTELLIGENCE (AI) IN MUSIC.pdf
 
Password Rotation in 2024 is still Relevant
Password Rotation in 2024 is still RelevantPassword Rotation in 2024 is still Relevant
Password Rotation in 2024 is still Relevant
 
Choose our Linux Web Hosting for a seamless and successful online presence
Choose our Linux Web Hosting for a seamless and successful online presenceChoose our Linux Web Hosting for a seamless and successful online presence
Choose our Linux Web Hosting for a seamless and successful online presence
 
How to build a generative AI solution A step-by-step guide (2).pdf
How to build a generative AI solution A step-by-step guide (2).pdfHow to build a generative AI solution A step-by-step guide (2).pdf
How to build a generative AI solution A step-by-step guide (2).pdf
 
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
 
The Role of Technology in Payroll Statutory Compliance (1).pdf
The Role of Technology in Payroll Statutory Compliance (1).pdfThe Role of Technology in Payroll Statutory Compliance (1).pdf
The Role of Technology in Payroll Statutory Compliance (1).pdf
 
Salesforce AI & Einstein Copilot Workshop
Salesforce AI & Einstein Copilot WorkshopSalesforce AI & Einstein Copilot Workshop
Salesforce AI & Einstein Copilot Workshop
 
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
 
Applying Retrieval-Augmented Generation (RAG) to Combat Hallucinations in GenAI
Applying Retrieval-Augmented Generation (RAG) to Combat Hallucinations in GenAIApplying Retrieval-Augmented Generation (RAG) to Combat Hallucinations in GenAI
Applying Retrieval-Augmented Generation (RAG) to Combat Hallucinations in GenAI
 
Evolution of iPaaS - simplify IT workloads to provide a unified view of data...
Evolution of iPaaS - simplify IT workloads to provide a unified view of  data...Evolution of iPaaS - simplify IT workloads to provide a unified view of  data...
Evolution of iPaaS - simplify IT workloads to provide a unified view of data...
 
[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf
[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf
[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf
 
Calgary MuleSoft Meetup APM and IDP .pptx
Calgary MuleSoft Meetup APM and IDP .pptxCalgary MuleSoft Meetup APM and IDP .pptx
Calgary MuleSoft Meetup APM and IDP .pptx
 
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
 
find out more about the role of autonomous vehicles in facing global challenges
find out more about the role of autonomous vehicles in facing global challengesfind out more about the role of autonomous vehicles in facing global challenges
find out more about the role of autonomous vehicles in facing global challenges
 

Testing Terraform

  • 2. @nathenharvey What am I talking about • Suppose you use a tool like Terraform to create your infrastructure • You're onboard with infrastructure as code • Code should be tested • How can we test Terraform?
  • 3. @nathenharvey 1. Deploy n-tier cloud infra 2. Deploy some app 3. Profit A Motivational Example Load Balancer VM Instance VM Instance ...
  • 4. @nathenharvey 1. Deploy n-tier cloud infra 2. Deploy some app ??? 3. Profit A Motivational Example Load Balancer VM Instance VM Instance ...
  • 5. @nathenharvey So how do you do that in Terraform?
  • 6. @nathenharvey Terraform on AWS: Define an Instance (VM) resource "aws_instance" "web" { count = 3 instance_type = "t2.micro" ami = "${lookup(var.aws_amis, var.aws_region)}" key_name = "${var.key_name}" subnet_id = "${aws_subnet.default.id}" vpc_security_group_ids = [ "${aws_security_group.lb_to_webservers.id}", "${aws_security_group.ssh_from_office.id}", ] ... }
  • 7. @nathenharvey Terraform on AWS: Define Load Balancer (ELB) resource "aws_elb" "web" { name = "testing-terraform-elb" subnets = ["${aws_subnet.default.id}"] security_groups = [ "${aws_security_group.world_to_elb.id}", "${aws_security_group.lb_to_webservers.id}", ] instances = ["${aws_instance.web.*.id}"] listener { instance_port = 80 instance_protocol = "http" lb_port = 80 lb_protocol = "http" } }
  • 8. @nathenharvey Terraform on AWS: Define a Firewall Rule resource "aws_security_group" "ssh_from_office" { name = "testing-terraform-ssh" vpc_id = "${aws_vpc.testing_terraform.id}" # SSH access from special office addresses ingress { from_port = 22 to_port = 22 protocol = "tcp" cidr_blocks = "${var.ssh_cidrs}" } # outbound internet access egress { from_port = 0 to_port = 0 protocol = "-1" cidr_blocks = ["0.0.0.0/0"] } }
  • 9. @nathenharvey Terraform on AWS: Define a Firewall Rule resource "aws_security_group" "ssh_from_office" { name = "testing-terraform-ssh" vpc_id = "${aws_vpc.testing_terraform.id}" # SSH access from special office addresses ingress { from_port = 22 to_port = 22 protocol = "tcp" cidr_blocks = "${var.ssh_cidrs}" } # outbound internet access egress { from_port = 0 to_port = 0 protocol = "-1" cidr_blocks = ["0.0.0.0/0"] } } variable "ssh_cidrs" { default = [ "173.239.212.22/32", "12.130.117.75/32" ] }
  • 10. $ What's the plan, Phil? terraform plan -out plan.out Refreshing Terraform state in-memory prior to plan... The refreshed state will be used to calculate this plan, but will not be persisted to local or remote state storage. ... Plan: 11 to add, 0 to change, 0 to destroy. ------------------------------------------------------------------------ This plan was saved to: plan.out To perform exactly these actions, run the following command to apply: terraform apply "plan.out"
  • 11. $ Make it so! terraform apply "plan.out" aws_vpc.testing_terraform: Creating... assign_generated_ipv6_cidr_block: "" => "false" cidr_block: "" => "10.0.0.0/16" default_network_acl_id: "" => "<computed>" default_route_table_id: "" => "<computed>" default_security_group_id: "" => "<computed>” ... aws_elb.web: Creation complete after 25s (ID: testing-terraform-elb) Apply complete! Resources: 11 added, 0 changed, 0 destroyed. Outputs: address = testing-terraform-elb-1345186905.us-east-1.elb.amazonaws.com
  • 13. @nathenharvey Part of a balanced diet
  • 14. $ Verify with Terraform terraform plan Refreshing Terraform state in-memory prior to plan... The refreshed state will be used to calculate this plan, but will not be persisted to local or remote state storage. aws_vpc.testing_terraform: Refreshing state... (ID: vpc-091427c0ca8ed3c29) ... aws_elb.web: Refreshing state... (ID: testing-terraform-elb) ------------------------------------------------------------------------ No changes. Infrastructure is up-to-date. This means that Terraform did not detect any differences between your configuration and real physical resources that exist. As a result, no actions need to be performed.
  • 19. $ Audit with Terraform terraform plan An execution plan has been generated and is shown below. Resource actions are indicated with the following symbols: ~ update in-place Terraform will perform the following actions: ~ aws_instance.web[0] vpc_security_group_ids.#: "3" => "2" vpc_security_group_ids.1298918294: "sg-01eefd0164f2de498" => "sg-01eefd0164f2de498" vpc_security_group_ids.35497876: "sg-0c6388fa3e956cc15" => "" vpc_security_group_ids.645334896: "sg-03bca2a0e861c01e7" => "sg-03bca2a0e861c01e7” Plan: 0 to add, 1 to change, 0 to destroy.
  • 20. @nathenharvey Detected the new security group Will detach it Is that enough? Awesome! Terraform found the change!
  • 21. @nathenharvey It only audits what is known in the Terraform config All change is drift (considered bad) Only express what you want, not what you don't How does terraform plan fall short?
  • 24. @nathenharvey PART OF A PROCESS OF CONTINUOUS COMPLIANCE Scan for Compliance Build & Test Locally Build & Test CI/CD Remediate Verify A SIMPLE EXAMPLE OF AN INSPEC CIS RULE InSpec ▪ Translate compliance into Code ▪ Clearly express statements of policy ▪ Move risk to build/test from runtime ▪ Find issues early ▪ Write code quickly ▪ Run code anywhere ▪ Inspect machines, data and APIs Turn security and compliance into code control 'cis-1.4.1' do title '1.4.1 Enable SELinux in /etc/grub.conf' desc ' Do not disable SELinux and enforcing in your GRUB configuration. These are important security features that prevent attackers from escalating their access to your systems. For reference see … ' impact 1.0 expect(grub_conf.param 'selinux').to_not eq '0' expect(grub_conf.param 'enforcing').to_not eq '0' end
  • 25. $ InSpec Shell inspec shell –t aws:// Welcome to the interactive InSpec Shell To find out how to use it, type: help You are currently running on: Name: aws Families: cloud, api Release: aws-sdk-v2.11.50
  • 26. $ InSpec Shell inspec shell –t aws:// Welcome to the interactive InSpec Shell To find out how to use it, type: help You are currently running on: Name: aws Families: cloud, api Release: aws-sdk-v2.11.50 Targeting AWS!
  • 27. inspec> InSpec Shell – Tab Completion aws_<TAB> aws_cloudtrail_trail aws_iam_access_keys aws_iam_users aws_security_group aws_cloudtrail_trails aws_iam_group aws_kms_key aws_security_groups aws_cloudwatch_alarm aws_iam_groups aws_kms_keys aws_sns_subscription aws_cloudwatch_log_metric_filter aws_iam_password_policy aws_rds_instance aws_sns_topic aws_config_delivery_channel aws_iam_policies aws_route_table aws_sns_topics aws_config_recorder aws_iam_policy aws_route_tables aws_subnet aws_ec2_instance aws_iam_role aws_s3_bucket aws_subnets aws_ec2_instances aws_iam_root_user aws_s3_bucket_object aws_vpc aws_iam_access_key aws_iam_user aws_s3_buckets aws_vpcs
  • 28. inspec> Find the shady security group aws_security_group('sg-0c6388fa3e956cc15').group_name => "uat_executive"
  • 29. inspec> Check the Rules aws_security_group('sg-0c6388fa3e956cc15').inbound_rules => [{:from_port=>22, :ip_protocol=>"tcp", :ip_ranges=>[{:cidr_ip=>"0.0.0.0/0"}], :ipv_6_ranges=>[{:cidr_ipv_6=>"::/0"}], :prefix_list_ids=>[], :to_port=>22, :user_id_group_pairs=>[]}]
  • 30. inspec> describe aws_security_group('sg-0c6388fa3e956cc15') do inspec> it { should_not allow_in ipv4_range: '0.0.0.0/0' } inspec> end Write a proper test
  • 31. inspec> describe aws_security_group('sg-0c6388fa3e956cc15') do inspec> it { should_not allow_in ipv4_range: '0.0.0.0/0' } inspec> end Profile: inspec-shell Version: (not specified) EC2 Security Group sg-0c6388fa3e956cc15 × should not allow in {} expected `EC2 Security Group sg-0c6388fa3e956cc15.allow_in?({})` to return false, got true Test Summary: 0 successful, 1 failure, 0 skipped Write a proper test
  • 32. @nathenharvey An InSpec Control security_groups.rb control 'Make sure unrestricted SSH is not permitted' do # Loop over each of the security group IDs in the region aws_security_groups.group_ids.each do |group_id| # Examine a security group in detail describe aws_security_group(group_id) do # Examine Ingress rules, and complain if # there is unrestricted SSH it { should_not allow_in(port: 22, ipv4_range: '0.0.0.0/0') } end end end
  • 33. $ InSpec Shell inspec exec –t aws:// secruity_groups.rb Profile: tests from security_groups.rb (tests from security_groups.rb) Version: (not specified) Target: aws:// × Make sure unrestricted SSH is not permitted: EC2 Security Group sg-003262589de21dbf5 (15 failed) ✔ EC2 Security Group sg-003262589de21dbf5 should not allow in {} ✔ EC2 Security Group sg-00f0b54bd7c8d93a1 should not allow in {} × EC2 Security Group sg-0c6388fa3e956cc15 should not allow in {} expected `EC2 Security Group sg-0c6388fa3e956cc15.allow_in?({})` to return false, got true ... Profile Summary: 0 successful controls, 1 control failure, 0 controls skipped Test Summary: 4 successful, 15 failures, 0 skipped
  • 35. @nathenharvey What else to validate? Concern Terraform Plan InSpec Number and type of instances requested All instances are part of our app Right security groups created and attached No security group allows in SSH Only security group open to the world should be port 80 for the ELB ELB correctly configured Should only be one ELB
  • 36. @nathenharvey Check instances instances.rb control "Should only have instances associated with my app" do aws_ec2_instances.instance_ids.each do |instance_id| describe aws_ec2_instance(instance_id) do its('instance_type') { should cmp 't2.micro' } its('tags') { should include(key:'X-Application', value:'Testing Terraform') } end end end
  • 37. @nathenharvey More Security Groups security_groups.rb control "The only world-open security groups should be on the ELB" do elb_sg_ids = aws_elbs.security_group_ids aws_security_groups.group_ids.each do |sg_id| sg = aws_security_group(sg_id) if sg.allow_in? ipv4_range: '0.0.0.0/0' describe sg do its('group_id') { should be_in elb_sg_ids } it { should allow_in_only port: 80 } end end end end
  • 38. $ Put it all together with a profile inspec init profile my_app Create new profile at /Users/nathenharvey/projects/nathenharvey/testing- terraform/inspec/profiles/my_app * Create directory libraries * Create file README.md * Create directory controls * Create file controls/example.rb * Create file inspec.yml * Create file libraries/.gitkeep
  • 39. $ Put it all together with a profile inspec exec -t aws:// my_app Profile: tests from security_groups.rb (tests from security_groups.rb) Version: (not specified) Target: aws:// × Make sure unrestricted SSH is not permitted: EC2 Security Group sg-003262589de21dbf5 (15 failed) ✔ EC2 Security Group sg-003262589de21dbf5 should not allow in {} ✔ EC2 Security Group sg-00f0b54bd7c8d93a1 should not allow in {} × EC2 Security Group sg-01b504b800f32e1ff should not allow in {} expected `EC2 Security Group sg-01b504b800f32e1ff.allow_in?({})` to return false, got true ... Profile Summary: 0 successful controls, 3 control failures, 0 controls skipped Test Summary: 43 successful, 65 failures, 0 skipped
  • 40. @nathenharvey Terraform: A Power Tool for the Cloud! Terraform and InSpec? InSpec: A Verification tool for OS's and API's
  • 41. @nathenharvey Terraform: A Power Tool for the Cloud! Terraform and InSpec! InSpec: A Verification tool for OS's and API's
  • 43. $ Install InSpec-Iggy gem install inspec-iggy Successfully installed inspec-iggy-0.2.0 1 gem installed
  • 44. $ Create a Profile from tfstate file inspec terraform generate --tfstate terraform.tfstate > my_terra.rb
  • 45. $ Run InSpec inspec exec -t aws:// my_terra.rb inspec exec -t aws:// my_terra.rb Profile: tests from my_terra.rb (tests from my_terra.rb) Version: (not specified) Target: aws:// ✔ aws_ec2_instance::i-03663e4b9cb2858d6: Iggy terraform.tfstate aws_ec2_instance::i-03663e4b9cb2858d6 ✔ EC2 Instance i-03663e4b9cb2858d6 should exist ... Profile Summary: 8 successful controls, 0 control failures, 0 controls skipped Test Summary: 32 successful, 0 failures, 0 skipped
  • 46. @nathenharvey Join us on Slack! ● http://community-slack.chef.io ● #general (for Chef stuff) ● #inspec
  • 47. @nathenharvey What questions can I answer for you? https://github.com/nathenharvey/testing-terraform

Editor's Notes

  1. Config drift is different than scanning for a violation - it could just be here that a real change was intended