Testing Terraform

Nathen Harvey
Nathen HarveyDeveloper Advocate
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
1 of 48

Recommended

Advanced Weapons Training for the Empire by
Advanced Weapons Training for the EmpireAdvanced Weapons Training for the Empire
Advanced Weapons Training for the EmpireJeremy Johnson
3K views54 slides
Gauntlt Rugged By Example by
Gauntlt Rugged By Example Gauntlt Rugged By Example
Gauntlt Rugged By Example James Wickett
1.8K views106 slides
Small Python Tools for Software Release Engineering by
Small Python Tools for Software Release EngineeringSmall Python Tools for Software Release Engineering
Small Python Tools for Software Release Engineeringpycontw
1.8K views69 slides
ruxc0n 2012 by
ruxc0n 2012ruxc0n 2012
ruxc0n 2012mimeframe
49.3K views113 slides
Terraform - Taming Modern Clouds by
Terraform  - Taming Modern CloudsTerraform  - Taming Modern Clouds
Terraform - Taming Modern CloudsNic Jackson
383 views57 slides
InSpec Workshop at Velocity London 2018 by
InSpec Workshop at Velocity London 2018InSpec Workshop at Velocity London 2018
InSpec Workshop at Velocity London 2018Mandi Walls
350 views63 slides

More Related Content

What's hot

Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk... by
Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...
Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...Ivan Piskunov
1K views61 slides
How to add a new hypervisor to CloudStack:Lessons learned from Hyper-V effort by
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 effortDonal Lafferty
519 views15 slides
Attacking Oracle with the Metasploit Framework by
Attacking Oracle with the Metasploit FrameworkAttacking Oracle with the Metasploit Framework
Attacking Oracle with the Metasploit FrameworkChris Gates
89.3K views59 slides
FreeBSD: Dev to Prod by
FreeBSD: Dev to ProdFreeBSD: Dev to Prod
FreeBSD: Dev to ProdSean Chittenden
1.1K views101 slides
BuildStuff.LT 2018 InSpec Workshop by
BuildStuff.LT 2018 InSpec WorkshopBuildStuff.LT 2018 InSpec Workshop
BuildStuff.LT 2018 InSpec WorkshopMandi Walls
241 views65 slides
IstSec'14 - İbrahim BALİÇ - Automated Malware Analysis by
IstSec'14 - İbrahim BALİÇ -  Automated Malware AnalysisIstSec'14 - İbrahim BALİÇ -  Automated Malware Analysis
IstSec'14 - İbrahim BALİÇ - Automated Malware AnalysisBGA Cyber Security
2K views30 slides

What's hot(20)

Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk... by Ivan Piskunov
Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...
Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...
Ivan Piskunov1K views
How to add a new hypervisor to CloudStack:Lessons learned from Hyper-V effort by Donal Lafferty
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 Lafferty519 views
Attacking Oracle with the Metasploit Framework by Chris Gates
Attacking Oracle with the Metasploit FrameworkAttacking Oracle with the Metasploit Framework
Attacking Oracle with the Metasploit Framework
Chris Gates89.3K views
BuildStuff.LT 2018 InSpec Workshop by Mandi Walls
BuildStuff.LT 2018 InSpec WorkshopBuildStuff.LT 2018 InSpec Workshop
BuildStuff.LT 2018 InSpec Workshop
Mandi Walls241 views
IstSec'14 - İbrahim BALİÇ - Automated Malware Analysis by BGA Cyber Security
IstSec'14 - İbrahim BALİÇ -  Automated Malware AnalysisIstSec'14 - İbrahim BALİÇ -  Automated Malware Analysis
IstSec'14 - İbrahim BALİÇ - Automated Malware Analysis
Threat stack aws by Jen Andre
Threat stack awsThreat stack aws
Threat stack aws
Jen Andre1.6K views
Embedded software development using BDD by Itamar Hassin
Embedded software development using BDDEmbedded software development using BDD
Embedded software development using BDD
Itamar Hassin3.3K views
Security in PHP - 那些在滲透測試的小技巧 by Orange Tsai
Security in PHP - 那些在滲透測試的小技巧Security in PHP - 那些在滲透測試的小技巧
Security in PHP - 那些在滲透測試的小技巧
Orange Tsai20.6K views
Meder Kydyraliev - Mining Mach Services within OS X Sandbox by DefconRussia
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
DefconRussia1.5K views
Inspec one tool to rule them all by Kimball Johnson
Inspec one tool to rule them allInspec one tool to rule them all
Inspec one tool to rule them all
Kimball Johnson374 views
Terraform Introduction by soniasnowfrog
Terraform IntroductionTerraform Introduction
Terraform Introduction
soniasnowfrog3.3K views
2019 Chef InSpec Jumpstart Part 2 of 2 by Larry Eichenbaum
2019 Chef InSpec Jumpstart Part 2 of 22019 Chef InSpec Jumpstart Part 2 of 2
2019 Chef InSpec Jumpstart Part 2 of 2
Larry Eichenbaum302 views
Infrastructure as Code with Terraform by Tim Berry
Infrastructure as Code with TerraformInfrastructure as Code with Terraform
Infrastructure as Code with Terraform
Tim Berry3.7K views
So you want to be a security expert by Royce Davis
So you want to be a security expertSo you want to be a security expert
So you want to be a security expert
Royce Davis1.9K views
Adventures in Asymmetric Warfare by Will Schroeder
Adventures in Asymmetric WarfareAdventures in Asymmetric Warfare
Adventures in Asymmetric Warfare
Will Schroeder2.8K views
Defending Your Network by Adam Getchell
Defending Your NetworkDefending Your Network
Defending Your Network
Adam Getchell10.6K views

Similar to Testing Terraform

Modern tooling to assist with developing applications on FreeBSD by
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 FreeBSDSean Chittenden
861 views83 slides
Docker Security workshop slides by
Docker Security workshop slidesDocker Security workshop slides
Docker Security workshop slidesDocker, Inc.
5.3K views122 slides
Dive into DevOps | March, Building with Terraform, Volodymyr Tsap by
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 TsapProvectus
405 views42 slides
Shopping for Vulnerabilities - How Cloud Service Provider Marketplaces can He... by
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
26 views20 slides
Enterprise Vulnerability Management - ZeroNights16 by
Enterprise Vulnerability Management - ZeroNights16Enterprise Vulnerability Management - ZeroNights16
Enterprise Vulnerability Management - ZeroNights16Alexander Leonov
8.4K views30 slides
Azure from scratch part 4 by
Azure from scratch part 4Azure from scratch part 4
Azure from scratch part 4Girish Kalamati
293 views97 slides

Similar to Testing Terraform(20)

Modern tooling to assist with developing applications on FreeBSD by Sean Chittenden
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 Chittenden861 views
Docker Security workshop slides by Docker, Inc.
Docker Security workshop slidesDocker Security workshop slides
Docker Security workshop slides
Docker, Inc.5.3K views
Dive into DevOps | March, Building with Terraform, Volodymyr Tsap by Provectus
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
Provectus405 views
Shopping for Vulnerabilities - How Cloud Service Provider Marketplaces can He... by Alexandre Sieira
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 Sieira26 views
Enterprise Vulnerability Management - ZeroNights16 by Alexander Leonov
Enterprise Vulnerability Management - ZeroNights16Enterprise Vulnerability Management - ZeroNights16
Enterprise Vulnerability Management - ZeroNights16
Alexander Leonov8.4K views
SaltConf14 - Ben Cane - Using SaltStack in High Availability Environments by SaltStack
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
SaltStack5K views
(ARC402) Deployment Automation: From Developers' Keyboards to End Users' Scre... by Amazon Web Services
(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 by Kevin Harvey
Continuous Integration Testing in DjangoContinuous Integration Testing in Django
Continuous Integration Testing in Django
Kevin Harvey13.6K views
An intro to Docker, Terraform, and Amazon ECS by Yevgeniy Brikman
An intro to Docker, Terraform, and Amazon ECSAn intro to Docker, Terraform, and Amazon ECS
An intro to Docker, Terraform, and Amazon ECS
Yevgeniy Brikman31.5K views
Continuous Delivery: The Next Frontier by Carlos Sanchez
Continuous Delivery: The Next FrontierContinuous Delivery: The Next Frontier
Continuous Delivery: The Next Frontier
Carlos Sanchez1.6K views
Test-Driven Infrastructure with Chef by Michael Lihs
Test-Driven Infrastructure with ChefTest-Driven Infrastructure with Chef
Test-Driven Infrastructure with Chef
Michael Lihs1.6K views
Reusable, composable, battle-tested Terraform modules by Yevgeniy Brikman
Reusable, composable, battle-tested Terraform modulesReusable, composable, battle-tested Terraform modules
Reusable, composable, battle-tested Terraform modules
Yevgeniy Brikman28.4K views
Automated Intrusion Detection and Response on AWS by Teri Radichel
Automated Intrusion Detection and Response on AWSAutomated Intrusion Detection and Response on AWS
Automated Intrusion Detection and Response on AWS
Teri Radichel618 views
Philly security shell meetup by Nicole Johnson
Philly security shell meetupPhilly security shell meetup
Philly security shell meetup
Nicole Johnson130 views
DevOpsDaysRiga 2017: Mandi Walls - Building security into your workflow with ... by DevOpsDays Riga
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 Riga114 views
Keeping Your Kubernetes Cluster Secure by Gene Gotimer
Keeping Your Kubernetes Cluster SecureKeeping Your Kubernetes Cluster Secure
Keeping Your Kubernetes Cluster Secure
Gene Gotimer95 views
Antons Kranga Building Agile Infrastructures by Antons Kranga
Antons Kranga   Building Agile InfrastructuresAntons Kranga   Building Agile Infrastructures
Antons Kranga Building Agile Infrastructures
Antons Kranga1.8K views
InSpec at DevOps ATL Meetup January 22, 2020 by Mandi Walls
InSpec at DevOps ATL Meetup January 22, 2020InSpec at DevOps ATL Meetup January 22, 2020
InSpec at DevOps ATL Meetup January 22, 2020
Mandi Walls214 views

More from Nathen Harvey

Accelerate Your DevOps Journey by
Accelerate Your DevOps JourneyAccelerate Your DevOps Journey
Accelerate Your DevOps JourneyNathen Harvey
334 views67 slides
Continuous Delivery - GDG Cloud Baltimore by
Continuous Delivery - GDG Cloud BaltimoreContinuous Delivery - GDG Cloud Baltimore
Continuous Delivery - GDG Cloud BaltimoreNathen Harvey
118 views39 slides
Using Error Budgets to Prioritize Work by
Using Error Budgets to Prioritize WorkUsing Error Budgets to Prioritize Work
Using Error Budgets to Prioritize WorkNathen Harvey
333 views62 slides
Introduction to Test Kitchen and InSpec by
Introduction to Test Kitchen and InSpecIntroduction to Test Kitchen and InSpec
Introduction to Test Kitchen and InSpecNathen Harvey
981 views63 slides
Introduction to Test Kitchen by
Introduction to Test KitchenIntroduction to Test Kitchen
Introduction to Test KitchenNathen Harvey
2.5K views34 slides
Effective Testing with Ansible and InSpec by
Effective Testing with Ansible and InSpecEffective Testing with Ansible and InSpec
Effective Testing with Ansible and InSpecNathen Harvey
1.2K views83 slides

More from Nathen Harvey(14)

Accelerate Your DevOps Journey by Nathen Harvey
Accelerate Your DevOps JourneyAccelerate Your DevOps Journey
Accelerate Your DevOps Journey
Nathen Harvey334 views
Continuous Delivery - GDG Cloud Baltimore by Nathen Harvey
Continuous Delivery - GDG Cloud BaltimoreContinuous Delivery - GDG Cloud Baltimore
Continuous Delivery - GDG Cloud Baltimore
Nathen Harvey118 views
Using Error Budgets to Prioritize Work by Nathen Harvey
Using Error Budgets to Prioritize WorkUsing Error Budgets to Prioritize Work
Using Error Budgets to Prioritize Work
Nathen Harvey333 views
Introduction to Test Kitchen and InSpec by Nathen Harvey
Introduction to Test Kitchen and InSpecIntroduction to Test Kitchen and InSpec
Introduction to Test Kitchen and InSpec
Nathen Harvey981 views
Introduction to Test Kitchen by Nathen Harvey
Introduction to Test KitchenIntroduction to Test Kitchen
Introduction to Test Kitchen
Nathen Harvey2.5K views
Effective Testing with Ansible and InSpec by Nathen Harvey
Effective Testing with Ansible and InSpecEffective Testing with Ansible and InSpec
Effective Testing with Ansible and InSpec
Nathen Harvey1.2K views
Effective Testing with Ansible and InSpec by Nathen Harvey
Effective Testing with Ansible and InSpecEffective Testing with Ansible and InSpec
Effective Testing with Ansible and InSpec
Nathen Harvey7.8K views
DevOps Days India Keynote by Nathen Harvey
DevOps Days India KeynoteDevOps Days India Keynote
DevOps Days India Keynote
Nathen Harvey431 views
Compliance Automation with InSpec by Nathen Harvey
Compliance Automation with InSpecCompliance Automation with InSpec
Compliance Automation with InSpec
Nathen Harvey1.1K views
Introduction to Infrastructure as Code & Automation / Introduction to Chef by Nathen Harvey
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 Harvey911 views
Step AFK: Practical Advice for Career Adavancement by Nathen Harvey
Step AFK: Practical Advice for Career AdavancementStep AFK: Practical Advice for Career Adavancement
Step AFK: Practical Advice for Career Adavancement
Nathen Harvey656 views
Walk This Way - An Introduction to DevOps by Nathen Harvey
Walk This Way - An Introduction to DevOpsWalk This Way - An Introduction to DevOps
Walk This Way - An Introduction to DevOps
Nathen Harvey2.5K views

Recently uploaded

Automating a World-Class Technology Conference; Behind the Scenes of CiscoLive by
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLiveAutomating a World-Class Technology Conference; Behind the Scenes of CiscoLive
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLiveNetwork Automation Forum
46 views35 slides
Mitigating Common CloudStack Instance Deployment Failures - Jithin Raju - Sha... by
Mitigating Common CloudStack Instance Deployment Failures - Jithin Raju - Sha...Mitigating Common CloudStack Instance Deployment Failures - Jithin Raju - Sha...
Mitigating Common CloudStack Instance Deployment Failures - Jithin Raju - Sha...ShapeBlue
74 views18 slides
DRBD Deep Dive - Philipp Reisner - LINBIT by
DRBD Deep Dive - Philipp Reisner - LINBITDRBD Deep Dive - Philipp Reisner - LINBIT
DRBD Deep Dive - Philipp Reisner - LINBITShapeBlue
62 views21 slides
CloudStack and GitOps at Enterprise Scale - Alex Dometrius, Rene Glover - AT&T by
CloudStack and GitOps at Enterprise Scale - Alex Dometrius, Rene Glover - AT&TCloudStack and GitOps at Enterprise Scale - Alex Dometrius, Rene Glover - AT&T
CloudStack and GitOps at Enterprise Scale - Alex Dometrius, Rene Glover - AT&TShapeBlue
56 views34 slides
Backup and Disaster Recovery with CloudStack and StorPool - Workshop - Venko ... by
Backup and Disaster Recovery with CloudStack and StorPool - Workshop - Venko ...Backup and Disaster Recovery with CloudStack and StorPool - Workshop - Venko ...
Backup and Disaster Recovery with CloudStack and StorPool - Workshop - Venko ...ShapeBlue
77 views12 slides
KVM Security Groups Under the Hood - Wido den Hollander - Your.Online by
KVM Security Groups Under the Hood - Wido den Hollander - Your.OnlineKVM Security Groups Under the Hood - Wido den Hollander - Your.Online
KVM Security Groups Under the Hood - Wido den Hollander - Your.OnlineShapeBlue
102 views19 slides

Recently uploaded(20)

Automating a World-Class Technology Conference; Behind the Scenes of CiscoLive by Network Automation Forum
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLiveAutomating a World-Class Technology Conference; Behind the Scenes of CiscoLive
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLive
Mitigating Common CloudStack Instance Deployment Failures - Jithin Raju - Sha... by ShapeBlue
Mitigating Common CloudStack Instance Deployment Failures - Jithin Raju - Sha...Mitigating Common CloudStack Instance Deployment Failures - Jithin Raju - Sha...
Mitigating Common CloudStack Instance Deployment Failures - Jithin Raju - Sha...
ShapeBlue74 views
DRBD Deep Dive - Philipp Reisner - LINBIT by ShapeBlue
DRBD Deep Dive - Philipp Reisner - LINBITDRBD Deep Dive - Philipp Reisner - LINBIT
DRBD Deep Dive - Philipp Reisner - LINBIT
ShapeBlue62 views
CloudStack and GitOps at Enterprise Scale - Alex Dometrius, Rene Glover - AT&T by ShapeBlue
CloudStack and GitOps at Enterprise Scale - Alex Dometrius, Rene Glover - AT&TCloudStack and GitOps at Enterprise Scale - Alex Dometrius, Rene Glover - AT&T
CloudStack and GitOps at Enterprise Scale - Alex Dometrius, Rene Glover - AT&T
ShapeBlue56 views
Backup and Disaster Recovery with CloudStack and StorPool - Workshop - Venko ... by ShapeBlue
Backup and Disaster Recovery with CloudStack and StorPool - Workshop - Venko ...Backup and Disaster Recovery with CloudStack and StorPool - Workshop - Venko ...
Backup and Disaster Recovery with CloudStack and StorPool - Workshop - Venko ...
ShapeBlue77 views
KVM Security Groups Under the Hood - Wido den Hollander - Your.Online by ShapeBlue
KVM Security Groups Under the Hood - Wido den Hollander - Your.OnlineKVM Security Groups Under the Hood - Wido den Hollander - Your.Online
KVM Security Groups Under the Hood - Wido den Hollander - Your.Online
ShapeBlue102 views
DRaaS using Snapshot copy and destination selection (DRaaS) - Alexandre Matti... by ShapeBlue
DRaaS using Snapshot copy and destination selection (DRaaS) - Alexandre Matti...DRaaS using Snapshot copy and destination selection (DRaaS) - Alexandre Matti...
DRaaS using Snapshot copy and destination selection (DRaaS) - Alexandre Matti...
ShapeBlue46 views
TrustArc Webinar - Managing Online Tracking Technology Vendors_ A Checklist f... by TrustArc
TrustArc Webinar - Managing Online Tracking Technology Vendors_ A Checklist f...TrustArc Webinar - Managing Online Tracking Technology Vendors_ A Checklist f...
TrustArc Webinar - Managing Online Tracking Technology Vendors_ A Checklist f...
TrustArc77 views
【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院 by IttrainingIttraining
【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院
【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院
Keynote Talk: Open Source is Not Dead - Charles Schulz - Vates by ShapeBlue
Keynote Talk: Open Source is Not Dead - Charles Schulz - VatesKeynote Talk: Open Source is Not Dead - Charles Schulz - Vates
Keynote Talk: Open Source is Not Dead - Charles Schulz - Vates
ShapeBlue119 views
What’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlue by ShapeBlue
What’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlueWhat’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlue
What’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlue
ShapeBlue131 views
Data Integrity for Banking and Financial Services by Precisely
Data Integrity for Banking and Financial ServicesData Integrity for Banking and Financial Services
Data Integrity for Banking and Financial Services
Precisely56 views
ESPC 2023 - Protect and Govern your Sensitive Data with Microsoft Purview in ... by Jasper Oosterveld
ESPC 2023 - Protect and Govern your Sensitive Data with Microsoft Purview in ...ESPC 2023 - Protect and Govern your Sensitive Data with Microsoft Purview in ...
ESPC 2023 - Protect and Govern your Sensitive Data with Microsoft Purview in ...
State of the Union - Rohit Yadav - Apache CloudStack by ShapeBlue
State of the Union - Rohit Yadav - Apache CloudStackState of the Union - Rohit Yadav - Apache CloudStack
State of the Union - Rohit Yadav - Apache CloudStack
ShapeBlue145 views
NTGapps NTG LowCode Platform by Mustafa Kuğu
NTGapps NTG LowCode Platform NTGapps NTG LowCode Platform
NTGapps NTG LowCode Platform
Mustafa Kuğu141 views
Five Things You SHOULD Know About Postman by Postman
Five Things You SHOULD Know About PostmanFive Things You SHOULD Know About Postman
Five Things You SHOULD Know About Postman
Postman40 views
Elevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlue by ShapeBlue
Elevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlueElevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlue
Elevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlue
ShapeBlue96 views
Centralized Logging Feature in CloudStack using ELK and Grafana - Kiran Chava... by ShapeBlue
Centralized Logging Feature in CloudStack using ELK and Grafana - Kiran Chava...Centralized Logging Feature in CloudStack using ELK and Grafana - Kiran Chava...
Centralized Logging Feature in CloudStack using ELK and Grafana - Kiran Chava...
ShapeBlue48 views

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