SlideShare a Scribd company logo
Copyright © 2019
HashiCorp
I Don't Know
What I'm Doing:
A Newbie Guide for
Golang for DevOps
Feb 5th 2019
@petersouter
“Technical Account Manager at HashiCorp
Peter Souter
Based in...
London, UK
This is my 4th CfgMgmentCamp
Been coming since 2014 (missed last year due
to baby!)
Worn a lot of hats in my time...
Developer, Consultant, Pre-Sales, TAM
Interested in...
Making people’s operational life easier and
more secure
DEVOPS ALL THE THINGS
Introductions - Who is this guy?
@petersouter
“
A Quick Primer on Golang
“The Go programming language was conceived in late 2007 as an
answer to some of the problems we were seeing developing software
infrastructure at Google.
[…]
Go was designed and developed to make working in [modern
infrastructure] more productive.
Besides its better-known aspects such as built-in concurrency and
garbage collection, Go's design considerations include rigorous
dependency management, the adaptability of software architecture as
systems grow, and robustness across the boundaries between
components.”
https://talks.golang.org/2012/splash.article#TOC_1
@petersouter
“
How did Golang get so popular in a DevOps world?
▪ Compiled binary
▪ Platform independent
▪ Static type checking
▪ Extremely fast
▪ Excellent CLI libraries
▪ Everyone else was doing it!
Simon Waldherr [CC BY-SA 4.0], from Wikimedia Commons
@petersouter
“ Docker
Kubernetes
Etcd
Prometheus
Grafana
Juju
Tsuru
A few examples
@petersouter
“
HashiCorp <3 Go
Terraform
Vault
Consul
Nomad
Packer
Vagrant (Coming soon…?)
@petersouter
“
Another quick quote...
"Why Go?" I've talked a lot about this and for HashiCorp in particular
"Everyone else is doing it" wasn't a thing: Docker wasn't out yet,
CoreOS didn't exist, etc.
We chose Go through process of elimination. Also, I've said before that
Go is painfully pragmatic. Is it the safest? Nope. Is it the fastest? Nope.
Is it the biggest ecosystem? Nope. etc. But its damn "good enough"
at just about everything. And that's big!
- Mitchell Hashimoto
@petersouter
“
HashiCorp has a _lot_ of Go libraries
@petersouter
“
So finally after years of playing around...
“Ok, I should probably try this
stuff out then...”
@petersouter
“
Who else here is a “glue developer”?
More of an Ops background than Dev
Rubyist/Pythonista/Perler
Experience is more on scripting
Can PR a “good-ish” fix if needed!
@petersouter
“
Where am I at now?
“I know enough to get into
trouble”
@petersouter
“
Also known as...
@petersouter
“
Good things to know...
We don’t have time to go through
all the minutiae of Golang but let's
talk about the things that stuck out
to me the most...
@petersouter
“
Comparing two popular languages...
A quick primer of basics for
Golang vs Ruby
With help from
https://medium.com/devnetwork/golang-for-ruby-developers-c0a0ce19e3677
and
https://gobyexample.com/
@petersouter
“ // Golang
var a int = 1
// OR
// this dynamically declares
// type for variable a as int.
var a = 1
// this dynamically defines
variable a // and declares its
type as int.
a := 1
Golang vs Ruby: Variables
#Ruby
# since Ruby is
#dynamically typed we
#cant force a type
a = 1
# unless we specify the
creation method
a = Integer(1)
a.class
=> Integer
@petersouter
“
Golang vs Ruby: Types re-assignment
#Ruby
a = 1
a = "Hello"
a := 1
a := 2
// fine!
a = "Hello"
// not fine!
: cannot use "hello" (type
string) as type int is
assignment
@petersouter
“
Golang vs Ruby: Hash/Map
#Ruby:
hash = {conf_name:
'cfgmgmtcamp', location:
'Ghent'}
# access location
location =
hash[:location]
//Go
hash := map[string]string{"conf_name":
"cfgmgmtcamp", "location": "Ghent"}
// access location
location := hash["location"]
@petersouter
“
Golang vs Ruby: Arrays
#Ruby
array = [1,2,3]
//Go
array := [3]int{1,2,3}
// or if we’re lazy, let the compiler
// count for us!
array := [...]int{1,2,3}
@petersouter
“
Slices: Unindexed arrays
package main
import "fmt"
func main() {
s := make([]string, 3)
fmt.Println("empty on creation:", s)
s[0] = "a"
s[1] = "b"
s[2] = "c"
// s[3] = "d" - Wont work: panic: runtime error: index
out of range
fmt.Println("added elements manually to limit of 3:", s)
// check length
fmt.Println("Length before append is:", len(s))
s = append(s, "d")
fmt.Println("Length after append is:", len(s))
fmt.Println("Elements after append:", s)
}
empty on creation: [ ]
added elements manually to limit of 3: [a b c]
Length before append is: 3
Length after append is: 4
Elements after append: [a b c d]
Adapted from
https://gobyexample.com/slices
[CC BY 3.0]
@petersouter
“
Slices: Memory Management
package main
import (
"io/ioutil"
"regexp"
"fmt"
)
var digitRegexp = regexp.MustCompile("[0-9]+")
// ruh roh, the returned slice points into an array containing the entire file!
func FindDigits(filename string) []byte {
b, _ := ioutil.ReadFile(filename)
return digitRegexp.Find(b)
}
// instead: copy the interesting data to a new slice before returning it.
// old array gets garbage collected
func CopyDigits(filename string) []byte {
b, _ := ioutil.ReadFile(filename)
b = digitRegexp.Find(b)
c := make([]byte, len(b))
copy(c, b)
return c
}
@petersouter
“
Golang vs Ruby: Unused variables
# Ruby
a = [1,2,3]
b = “123”
puts b
# No problem with unused
# variables in Ruby!
sum := 0
a := [3]int{1,2,3}
for index, num := range a {
sum += num
}
// not fine!
: index declared and not used
for _, n := range a {
sum += n
}
// a-ok!
pathFile, _ := os.Stat(path)
// Bad! This code will crash if path does not exist.
if pathFile.IsDir() {
fmt.Printf("%s is a directory!n", path)
}
@petersouter
“
Errors: err != nil
result, err := SomethingNeat()
if err != nil {
return nil, err
}
another, err := MoreNeatStuff(foo)
if err != nil {
return nil, err
}
another, err := AndAgain(baz)
if err != nil {
return nil, err
}
@petersouter
“
Errors: err != nil
@petersouter
“
Errors: err != nil
@petersouter
“
Errors: Don’t worry about it...
“After you've been programming in Go a while you'll appreciate that
having to check the error for every function makes you think about
what it actually means if that function goes wrong and how you should
be dealing with it.”
-Nick Craig Wood
@petersouter
“
Errors: Slightly nicer
if err := SomethingNeat(); err != nil {
return err
}
@petersouter
“
Errors: Giving More Context
type SyntaxError struct {
msg string // description of error
Offset int64 // error after reading Offset bytes
}
func (e *SyntaxError) Error() string {
return e.msg
}
if err := dec.Decode(&val); err != nil {
if serr, ok := err.(*json.SyntaxError); ok {
line, col := findLine(f, serr.Offset)
return fmt.Errorf("%s:%d:%d: %v", f.Name(), line, col, err)
}
return err
}
@petersouter
“
Errors: DRY-ing multiple errors
import "fmt"
func validError(errs ...error) error {
for i, _ := range errs {
if errs[i] != nil {
return errs[i]
}
}
return nil
}
func doSomething(x int) (int, error) {
if x == 2 {
return 0, fmt.Errorf("Oh noes: %d", x)
}
return x, nil
}
func handled() error {
x, err1 := doSomething(2)
y, err2 := doSomething(3)
if e := validError(err1, err2); e != nil {
return e
}
fmt.Println(x, y)
return nil
}
Adapted from
https://stackoverflow.com/questi
ons/18771569/avoid-checking-if-
error-is-nil-repetition
@petersouter
“
Errors: The Future in Go 2.0 (check/handle)
// old way
func printSum(a, b string) error {
x, err := strconv.Atoi(a)
if err != nil {
return err
}
y, err := strconv.Atoi(b)
if err != nil {
return err
}
fmt.Println("result:", x + y)
return nil
}
// new way
func printSum(a, b string) error {
handle err { return err }
x := check strconv.Atoi(a)
y := check strconv.Atoi(b)
fmt.Println("result:", x + y)
return nil
}
@petersouter
“
Best IDE for Go beginners IMHO?
Visual Code Studio
Or
GoLand
@petersouter
“
VSC - Automatically add imports
@petersouter
“
VSC - Automatic test macros
@petersouter
“
Lastly...packaging
• go mod actually simplifies a lot!
• No longer have to worry about $GOPATH
• go mod init converts from previous
approaches (Glide, Dep, Govendor etc)
• Otherwise, look into dep which was the
previously blessed approach
@petersouter
“
We only have 25 mins...
• Testing
• Makefiles
• JSON Marshaling
• Deferring
• Pointers
• Mutexes
• Channels
@petersouter
“I wanted to add some missing fields to the GCP
auth backend in the Vault Terraform provider:
• "bound_zones"
• "bound_regions"
• "bound_instance_groups"
• "Bound_labels"
Some help for starting on TF development
https://www.terraform.io/docs/extend/writing-custom-providers.html)
Real life example: Vault Terraform
Provider
@petersouter
“
Ok, lets look at the existing code:
https://github.com/terraform-providers/terraform-provider-vault/pull/227/files
"bound_service_accounts": &schema.Schema{
Type: schema.TypeSet,
Elem: &schema.Schema{
Type: schema.TypeString,
},
Optional: true,
Computed: true,
},
“
Ok, lets look at the existing code:
https://github.com/terraform-providers/terraform-provider-vault/pull/227/files
"bound_zones": &schema.Schema{
Type: schema.TypeSet,
Elem: &schema.Schema{
Type: schema.TypeString,
},
Optional: true,
Computed: true,
},
“
Now how do we actually do a lookup?
https://github.com/terraform-providers/terraform-provider-vault/pull/227/files
if v, ok := d.GetOk("bound_service_accounts"); ok {
data["bound_service_accounts"] = v.(*schema.Set).List()
}
“
Now how do we actually do a lookup?
https://github.com/terraform-providers/terraform-provider-vault/pull/227/files
if v, ok := d.GetOk("bound_zones"); ok {
data["bound_zones"] = v.(*schema.Set).List()
}
“
Yay! We’re a go Developer now!
https://github.com/terraform-provi
ders/terraform-provider-vault/pull/
227
Merged! 🎉
“
But we were on easy mode...
But really we didn’t have to flex our go muscles
too much…
A lot of the existing work guided us…
Lets start from scratch and flex a little!
“
Project - A git helper CLI app
I want a simple git cli app to do
some basic cleanup of repos
“
List branches that have already
been merged into master, then give
the option to delete the branch
Project - gitsweeper
dir, err := os.Getwd()
if err != nil {
log.Fatalf("Error opening current directory: %s", err)
return
}
repo, err := git.PlainOpen(dir)
if err != nil {
log.Fatalf("Error reading %s as Git repo: %s", dir, err)
return
}
branchRefs, err := repo.Branches()
if err != nil {
log.Fatalf("list branches failed: %s", err)
}
fmt.Printf("There are %d branchesn", len(branchHeads))
for branchName, branchHead := range branchHeads {
fmt.Printf("Branch %s head is: %sn", branchName, branchHead)
}
nonMasterBranchRefs := branchHeads
delete(nonMasterBranchRefs, "master")
masterCommits, err := repo.Log(&git.LogOptions{From: branchHeads["master"]})
err = masterCommits.ForEach(func(commit *object.Commit) error {
for branchName, branchHead := range nonMasterBranchRefs {
if branchHead.String() == commit.Hash.String() {
fmt.Printf("Branch %s head (%s) was found in master, so has been merged!n", branchName, branchHead)
}
}
return nil
})
“
Ta-dah! All working!
https://github.com/petems/gitsweeper
Now I’m a golang developer 👨💻
“
Conclusion
▪ Go is a great language for a
devops world, and well worth
learning
▪ It’s not as hard to learn as you
think - If I can do it, anyone can!
▪ Get your hands dirty: try making
a CLI app or submit patches to
your favourite tools
▪ There’s a ton of great resources
out there!
“
Great Links
▪ https://gobyexample.com/
▪ https://tour.golang.org/welcome/1
▪ https://www.openmymind.net/The-Little-Go-Book/
▪ http://www.golang-book.com/books/intro
▪ https://www.terraform.io/docs/extend/writing-custom-providers.ht
ml
▪ https://www.hashicorp.com/resources/creating-terraform-provider-f
or-anything
Thank you.
hello@hashicorp.comwww.hashicorp.com

More Related Content

Similar to I don't know what I'm Doing: A newbie guide for Golang for DevOps

He stopped using for/while loops, you won't believe what happened next!
He stopped using for/while loops, you won't believe what happened next!He stopped using for/while loops, you won't believe what happened next!
He stopped using for/while loops, you won't believe what happened next!
François-Guillaume Ribreau
 
How to get started with Site Reliability Engineering
How to get started with Site Reliability EngineeringHow to get started with Site Reliability Engineering
How to get started with Site Reliability Engineering
Andrew Kirkpatrick
 
OpenFest 2012 : Leveraging the public internet
OpenFest 2012 : Leveraging the public internetOpenFest 2012 : Leveraging the public internet
OpenFest 2012 : Leveraging the public internettkisason
 
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
Mike Harris
 
Monitoring your Python with Prometheus (Python Ireland April 2015)
Monitoring your Python with Prometheus (Python Ireland April 2015)Monitoring your Python with Prometheus (Python Ireland April 2015)
Monitoring your Python with Prometheus (Python Ireland April 2015)
Brian Brazil
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
Daniel Greenfeld
 
Eight Rules for Making Your First Great Game
Eight Rules for Making Your First Great GameEight Rules for Making Your First Great Game
Eight Rules for Making Your First Great Game
Nick Pruehs
 
Does my DIV look big in this?
Does my DIV look big in this?Does my DIV look big in this?
Does my DIV look big in this?
glen_a_smith
 
Infrastructure as code might be literally impossible part 2
Infrastructure as code might be literally impossible part 2Infrastructure as code might be literally impossible part 2
Infrastructure as code might be literally impossible part 2
ice799
 
node.js, javascript and the future
node.js, javascript and the futurenode.js, javascript and the future
node.js, javascript and the futureJeff Miccolis
 
Puppet at GitHub / ChatOps
Puppet at GitHub / ChatOpsPuppet at GitHub / ChatOps
Puppet at GitHub / ChatOps
Puppet
 
Measuring Software development with GrimoireLab
Measuring Software development with GrimoireLabMeasuring Software development with GrimoireLab
Measuring Software development with GrimoireLab
Valerio Cosentino
 
1.6 米嘉 gobuildweb
1.6 米嘉 gobuildweb1.6 米嘉 gobuildweb
1.6 米嘉 gobuildweb
Leo Zhou
 
Protect Your Payloads: Modern Keying Techniques
Protect Your Payloads: Modern Keying TechniquesProtect Your Payloads: Modern Keying Techniques
Protect Your Payloads: Modern Keying Techniques
Leo Loobeek
 
13 practical tips for writing secure golang applications
13 practical tips for writing secure golang applications13 practical tips for writing secure golang applications
13 practical tips for writing secure golang applications
Karthik Gaekwad
 
Us 17-krug-hacking-severless-runtimes
Us 17-krug-hacking-severless-runtimesUs 17-krug-hacking-severless-runtimes
Us 17-krug-hacking-severless-runtimes
Ravishankar Somasundaram
 
Regex Considered Harmful: Use Rosie Pattern Language Instead
Regex Considered Harmful: Use Rosie Pattern Language InsteadRegex Considered Harmful: Use Rosie Pattern Language Instead
Regex Considered Harmful: Use Rosie Pattern Language Instead
All Things Open
 
Javascript done right - Open Web Camp III
Javascript done right - Open Web Camp IIIJavascript done right - Open Web Camp III
Javascript done right - Open Web Camp IIIDirk Ginader
 

Similar to I don't know what I'm Doing: A newbie guide for Golang for DevOps (20)

He stopped using for/while loops, you won't believe what happened next!
He stopped using for/while loops, you won't believe what happened next!He stopped using for/while loops, you won't believe what happened next!
He stopped using for/while loops, you won't believe what happened next!
 
Intro
IntroIntro
Intro
 
How to get started with Site Reliability Engineering
How to get started with Site Reliability EngineeringHow to get started with Site Reliability Engineering
How to get started with Site Reliability Engineering
 
OpenFest 2012 : Leveraging the public internet
OpenFest 2012 : Leveraging the public internetOpenFest 2012 : Leveraging the public internet
OpenFest 2012 : Leveraging the public internet
 
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
 
Monitoring your Python with Prometheus (Python Ireland April 2015)
Monitoring your Python with Prometheus (Python Ireland April 2015)Monitoring your Python with Prometheus (Python Ireland April 2015)
Monitoring your Python with Prometheus (Python Ireland April 2015)
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
 
Django at Scale
Django at ScaleDjango at Scale
Django at Scale
 
Eight Rules for Making Your First Great Game
Eight Rules for Making Your First Great GameEight Rules for Making Your First Great Game
Eight Rules for Making Your First Great Game
 
Does my DIV look big in this?
Does my DIV look big in this?Does my DIV look big in this?
Does my DIV look big in this?
 
Infrastructure as code might be literally impossible part 2
Infrastructure as code might be literally impossible part 2Infrastructure as code might be literally impossible part 2
Infrastructure as code might be literally impossible part 2
 
node.js, javascript and the future
node.js, javascript and the futurenode.js, javascript and the future
node.js, javascript and the future
 
Puppet at GitHub / ChatOps
Puppet at GitHub / ChatOpsPuppet at GitHub / ChatOps
Puppet at GitHub / ChatOps
 
Measuring Software development with GrimoireLab
Measuring Software development with GrimoireLabMeasuring Software development with GrimoireLab
Measuring Software development with GrimoireLab
 
1.6 米嘉 gobuildweb
1.6 米嘉 gobuildweb1.6 米嘉 gobuildweb
1.6 米嘉 gobuildweb
 
Protect Your Payloads: Modern Keying Techniques
Protect Your Payloads: Modern Keying TechniquesProtect Your Payloads: Modern Keying Techniques
Protect Your Payloads: Modern Keying Techniques
 
13 practical tips for writing secure golang applications
13 practical tips for writing secure golang applications13 practical tips for writing secure golang applications
13 practical tips for writing secure golang applications
 
Us 17-krug-hacking-severless-runtimes
Us 17-krug-hacking-severless-runtimesUs 17-krug-hacking-severless-runtimes
Us 17-krug-hacking-severless-runtimes
 
Regex Considered Harmful: Use Rosie Pattern Language Instead
Regex Considered Harmful: Use Rosie Pattern Language InsteadRegex Considered Harmful: Use Rosie Pattern Language Instead
Regex Considered Harmful: Use Rosie Pattern Language Instead
 
Javascript done right - Open Web Camp III
Javascript done right - Open Web Camp IIIJavascript done right - Open Web Camp III
Javascript done right - Open Web Camp III
 

More from Peter Souter

Head in the Clouds: Testing Infra as Code - Config Management 2020
Head in the Clouds: Testing Infra as Code - Config Management 2020Head in the Clouds: Testing Infra as Code - Config Management 2020
Head in the Clouds: Testing Infra as Code - Config Management 2020
Peter Souter
 
Consul Connect - EPAM SEC - 22nd september 2018
Consul Connect - EPAM SEC - 22nd september 2018Consul Connect - EPAM SEC - 22nd september 2018
Consul Connect - EPAM SEC - 22nd september 2018
Peter Souter
 
Monitoring a Vault and Consul cluster - 24th May 2018
Monitoring a Vault and Consul cluster - 24th May 2018Monitoring a Vault and Consul cluster - 24th May 2018
Monitoring a Vault and Consul cluster - 24th May 2018
Peter Souter
 
Maintaining Layer 8
Maintaining Layer 8Maintaining Layer 8
Maintaining Layer 8
Peter Souter
 
Knee deep in the undef - Tales from refactoring old Puppet codebases
Knee deep in the undef  - Tales from refactoring old Puppet codebasesKnee deep in the undef  - Tales from refactoring old Puppet codebases
Knee deep in the undef - Tales from refactoring old Puppet codebases
Peter Souter
 
Compliance and auditing with Puppet
Compliance and auditing with PuppetCompliance and auditing with Puppet
Compliance and auditing with Puppet
Peter Souter
 
Lock it down
Lock it downLock it down
Lock it down
Peter Souter
 
Hardening Your Config Management - Security and Attack Vectors in Config Mana...
Hardening Your Config Management - Security and Attack Vectors in Config Mana...Hardening Your Config Management - Security and Attack Vectors in Config Mana...
Hardening Your Config Management - Security and Attack Vectors in Config Mana...
Peter Souter
 
Puppet module anti patterns
Puppet module anti patternsPuppet module anti patterns
Puppet module anti patterns
Peter Souter
 
Little Puppet Tools To Make Your Life Better
Little Puppet Tools To Make Your Life BetterLittle Puppet Tools To Make Your Life Better
Little Puppet Tools To Make Your Life Better
Peter Souter
 
Testing servers like software
Testing servers like softwareTesting servers like software
Testing servers like software
Peter Souter
 

More from Peter Souter (11)

Head in the Clouds: Testing Infra as Code - Config Management 2020
Head in the Clouds: Testing Infra as Code - Config Management 2020Head in the Clouds: Testing Infra as Code - Config Management 2020
Head in the Clouds: Testing Infra as Code - Config Management 2020
 
Consul Connect - EPAM SEC - 22nd september 2018
Consul Connect - EPAM SEC - 22nd september 2018Consul Connect - EPAM SEC - 22nd september 2018
Consul Connect - EPAM SEC - 22nd september 2018
 
Monitoring a Vault and Consul cluster - 24th May 2018
Monitoring a Vault and Consul cluster - 24th May 2018Monitoring a Vault and Consul cluster - 24th May 2018
Monitoring a Vault and Consul cluster - 24th May 2018
 
Maintaining Layer 8
Maintaining Layer 8Maintaining Layer 8
Maintaining Layer 8
 
Knee deep in the undef - Tales from refactoring old Puppet codebases
Knee deep in the undef  - Tales from refactoring old Puppet codebasesKnee deep in the undef  - Tales from refactoring old Puppet codebases
Knee deep in the undef - Tales from refactoring old Puppet codebases
 
Compliance and auditing with Puppet
Compliance and auditing with PuppetCompliance and auditing with Puppet
Compliance and auditing with Puppet
 
Lock it down
Lock it downLock it down
Lock it down
 
Hardening Your Config Management - Security and Attack Vectors in Config Mana...
Hardening Your Config Management - Security and Attack Vectors in Config Mana...Hardening Your Config Management - Security and Attack Vectors in Config Mana...
Hardening Your Config Management - Security and Attack Vectors in Config Mana...
 
Puppet module anti patterns
Puppet module anti patternsPuppet module anti patterns
Puppet module anti patterns
 
Little Puppet Tools To Make Your Life Better
Little Puppet Tools To Make Your Life BetterLittle Puppet Tools To Make Your Life Better
Little Puppet Tools To Make Your Life Better
 
Testing servers like software
Testing servers like softwareTesting servers like software
Testing servers like software
 

Recently uploaded

GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
ThomasParaiso2
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
Kumud Singh
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
Alex Pruden
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
Neo4j
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
Rohit Gautam
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
DianaGray10
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
RinaMondal9
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 

Recently uploaded (20)

GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 

I don't know what I'm Doing: A newbie guide for Golang for DevOps

  • 1. Copyright © 2019 HashiCorp I Don't Know What I'm Doing: A Newbie Guide for Golang for DevOps Feb 5th 2019
  • 2. @petersouter “Technical Account Manager at HashiCorp Peter Souter Based in... London, UK This is my 4th CfgMgmentCamp Been coming since 2014 (missed last year due to baby!) Worn a lot of hats in my time... Developer, Consultant, Pre-Sales, TAM Interested in... Making people’s operational life easier and more secure DEVOPS ALL THE THINGS Introductions - Who is this guy? @petersouter
  • 3. “ A Quick Primer on Golang “The Go programming language was conceived in late 2007 as an answer to some of the problems we were seeing developing software infrastructure at Google. […] Go was designed and developed to make working in [modern infrastructure] more productive. Besides its better-known aspects such as built-in concurrency and garbage collection, Go's design considerations include rigorous dependency management, the adaptability of software architecture as systems grow, and robustness across the boundaries between components.” https://talks.golang.org/2012/splash.article#TOC_1 @petersouter
  • 4. “ How did Golang get so popular in a DevOps world? ▪ Compiled binary ▪ Platform independent ▪ Static type checking ▪ Extremely fast ▪ Excellent CLI libraries ▪ Everyone else was doing it! Simon Waldherr [CC BY-SA 4.0], from Wikimedia Commons @petersouter
  • 7. “ Another quick quote... "Why Go?" I've talked a lot about this and for HashiCorp in particular "Everyone else is doing it" wasn't a thing: Docker wasn't out yet, CoreOS didn't exist, etc. We chose Go through process of elimination. Also, I've said before that Go is painfully pragmatic. Is it the safest? Nope. Is it the fastest? Nope. Is it the biggest ecosystem? Nope. etc. But its damn "good enough" at just about everything. And that's big! - Mitchell Hashimoto @petersouter
  • 8. “ HashiCorp has a _lot_ of Go libraries @petersouter
  • 9. “ So finally after years of playing around... “Ok, I should probably try this stuff out then...” @petersouter
  • 10. “ Who else here is a “glue developer”? More of an Ops background than Dev Rubyist/Pythonista/Perler Experience is more on scripting Can PR a “good-ish” fix if needed! @petersouter
  • 11. “ Where am I at now? “I know enough to get into trouble” @petersouter
  • 13. “ Good things to know... We don’t have time to go through all the minutiae of Golang but let's talk about the things that stuck out to me the most... @petersouter
  • 14. “ Comparing two popular languages... A quick primer of basics for Golang vs Ruby With help from https://medium.com/devnetwork/golang-for-ruby-developers-c0a0ce19e3677 and https://gobyexample.com/ @petersouter
  • 15. “ // Golang var a int = 1 // OR // this dynamically declares // type for variable a as int. var a = 1 // this dynamically defines variable a // and declares its type as int. a := 1 Golang vs Ruby: Variables #Ruby # since Ruby is #dynamically typed we #cant force a type a = 1 # unless we specify the creation method a = Integer(1) a.class => Integer @petersouter
  • 16. “ Golang vs Ruby: Types re-assignment #Ruby a = 1 a = "Hello" a := 1 a := 2 // fine! a = "Hello" // not fine! : cannot use "hello" (type string) as type int is assignment @petersouter
  • 17. “ Golang vs Ruby: Hash/Map #Ruby: hash = {conf_name: 'cfgmgmtcamp', location: 'Ghent'} # access location location = hash[:location] //Go hash := map[string]string{"conf_name": "cfgmgmtcamp", "location": "Ghent"} // access location location := hash["location"] @petersouter
  • 18. “ Golang vs Ruby: Arrays #Ruby array = [1,2,3] //Go array := [3]int{1,2,3} // or if we’re lazy, let the compiler // count for us! array := [...]int{1,2,3} @petersouter
  • 19. “ Slices: Unindexed arrays package main import "fmt" func main() { s := make([]string, 3) fmt.Println("empty on creation:", s) s[0] = "a" s[1] = "b" s[2] = "c" // s[3] = "d" - Wont work: panic: runtime error: index out of range fmt.Println("added elements manually to limit of 3:", s) // check length fmt.Println("Length before append is:", len(s)) s = append(s, "d") fmt.Println("Length after append is:", len(s)) fmt.Println("Elements after append:", s) } empty on creation: [ ] added elements manually to limit of 3: [a b c] Length before append is: 3 Length after append is: 4 Elements after append: [a b c d] Adapted from https://gobyexample.com/slices [CC BY 3.0] @petersouter
  • 20. “ Slices: Memory Management package main import ( "io/ioutil" "regexp" "fmt" ) var digitRegexp = regexp.MustCompile("[0-9]+") // ruh roh, the returned slice points into an array containing the entire file! func FindDigits(filename string) []byte { b, _ := ioutil.ReadFile(filename) return digitRegexp.Find(b) } // instead: copy the interesting data to a new slice before returning it. // old array gets garbage collected func CopyDigits(filename string) []byte { b, _ := ioutil.ReadFile(filename) b = digitRegexp.Find(b) c := make([]byte, len(b)) copy(c, b) return c } @petersouter
  • 21. “ Golang vs Ruby: Unused variables # Ruby a = [1,2,3] b = “123” puts b # No problem with unused # variables in Ruby! sum := 0 a := [3]int{1,2,3} for index, num := range a { sum += num } // not fine! : index declared and not used for _, n := range a { sum += n } // a-ok! pathFile, _ := os.Stat(path) // Bad! This code will crash if path does not exist. if pathFile.IsDir() { fmt.Printf("%s is a directory!n", path) } @petersouter
  • 22. “ Errors: err != nil result, err := SomethingNeat() if err != nil { return nil, err } another, err := MoreNeatStuff(foo) if err != nil { return nil, err } another, err := AndAgain(baz) if err != nil { return nil, err } @petersouter
  • 23. “ Errors: err != nil @petersouter
  • 24. “ Errors: err != nil @petersouter
  • 25. “ Errors: Don’t worry about it... “After you've been programming in Go a while you'll appreciate that having to check the error for every function makes you think about what it actually means if that function goes wrong and how you should be dealing with it.” -Nick Craig Wood @petersouter
  • 26. “ Errors: Slightly nicer if err := SomethingNeat(); err != nil { return err } @petersouter
  • 27. “ Errors: Giving More Context type SyntaxError struct { msg string // description of error Offset int64 // error after reading Offset bytes } func (e *SyntaxError) Error() string { return e.msg } if err := dec.Decode(&val); err != nil { if serr, ok := err.(*json.SyntaxError); ok { line, col := findLine(f, serr.Offset) return fmt.Errorf("%s:%d:%d: %v", f.Name(), line, col, err) } return err } @petersouter
  • 28. “ Errors: DRY-ing multiple errors import "fmt" func validError(errs ...error) error { for i, _ := range errs { if errs[i] != nil { return errs[i] } } return nil } func doSomething(x int) (int, error) { if x == 2 { return 0, fmt.Errorf("Oh noes: %d", x) } return x, nil } func handled() error { x, err1 := doSomething(2) y, err2 := doSomething(3) if e := validError(err1, err2); e != nil { return e } fmt.Println(x, y) return nil } Adapted from https://stackoverflow.com/questi ons/18771569/avoid-checking-if- error-is-nil-repetition @petersouter
  • 29. “ Errors: The Future in Go 2.0 (check/handle) // old way func printSum(a, b string) error { x, err := strconv.Atoi(a) if err != nil { return err } y, err := strconv.Atoi(b) if err != nil { return err } fmt.Println("result:", x + y) return nil } // new way func printSum(a, b string) error { handle err { return err } x := check strconv.Atoi(a) y := check strconv.Atoi(b) fmt.Println("result:", x + y) return nil } @petersouter
  • 30. “ Best IDE for Go beginners IMHO? Visual Code Studio Or GoLand @petersouter
  • 31. “ VSC - Automatically add imports @petersouter
  • 32. “ VSC - Automatic test macros @petersouter
  • 33. “ Lastly...packaging • go mod actually simplifies a lot! • No longer have to worry about $GOPATH • go mod init converts from previous approaches (Glide, Dep, Govendor etc) • Otherwise, look into dep which was the previously blessed approach @petersouter
  • 34. “ We only have 25 mins... • Testing • Makefiles • JSON Marshaling • Deferring • Pointers • Mutexes • Channels @petersouter
  • 35. “I wanted to add some missing fields to the GCP auth backend in the Vault Terraform provider: • "bound_zones" • "bound_regions" • "bound_instance_groups" • "Bound_labels" Some help for starting on TF development https://www.terraform.io/docs/extend/writing-custom-providers.html) Real life example: Vault Terraform Provider @petersouter
  • 36. “ Ok, lets look at the existing code: https://github.com/terraform-providers/terraform-provider-vault/pull/227/files "bound_service_accounts": &schema.Schema{ Type: schema.TypeSet, Elem: &schema.Schema{ Type: schema.TypeString, }, Optional: true, Computed: true, },
  • 37. “ Ok, lets look at the existing code: https://github.com/terraform-providers/terraform-provider-vault/pull/227/files "bound_zones": &schema.Schema{ Type: schema.TypeSet, Elem: &schema.Schema{ Type: schema.TypeString, }, Optional: true, Computed: true, },
  • 38. “ Now how do we actually do a lookup? https://github.com/terraform-providers/terraform-provider-vault/pull/227/files if v, ok := d.GetOk("bound_service_accounts"); ok { data["bound_service_accounts"] = v.(*schema.Set).List() }
  • 39. “ Now how do we actually do a lookup? https://github.com/terraform-providers/terraform-provider-vault/pull/227/files if v, ok := d.GetOk("bound_zones"); ok { data["bound_zones"] = v.(*schema.Set).List() }
  • 40. “ Yay! We’re a go Developer now! https://github.com/terraform-provi ders/terraform-provider-vault/pull/ 227 Merged! 🎉
  • 41. “ But we were on easy mode... But really we didn’t have to flex our go muscles too much… A lot of the existing work guided us… Lets start from scratch and flex a little!
  • 42. “ Project - A git helper CLI app I want a simple git cli app to do some basic cleanup of repos
  • 43. “ List branches that have already been merged into master, then give the option to delete the branch Project - gitsweeper
  • 44. dir, err := os.Getwd() if err != nil { log.Fatalf("Error opening current directory: %s", err) return } repo, err := git.PlainOpen(dir) if err != nil { log.Fatalf("Error reading %s as Git repo: %s", dir, err) return } branchRefs, err := repo.Branches() if err != nil { log.Fatalf("list branches failed: %s", err) }
  • 45. fmt.Printf("There are %d branchesn", len(branchHeads)) for branchName, branchHead := range branchHeads { fmt.Printf("Branch %s head is: %sn", branchName, branchHead) } nonMasterBranchRefs := branchHeads delete(nonMasterBranchRefs, "master") masterCommits, err := repo.Log(&git.LogOptions{From: branchHeads["master"]}) err = masterCommits.ForEach(func(commit *object.Commit) error { for branchName, branchHead := range nonMasterBranchRefs { if branchHead.String() == commit.Hash.String() { fmt.Printf("Branch %s head (%s) was found in master, so has been merged!n", branchName, branchHead) } } return nil })
  • 47. “ Conclusion ▪ Go is a great language for a devops world, and well worth learning ▪ It’s not as hard to learn as you think - If I can do it, anyone can! ▪ Get your hands dirty: try making a CLI app or submit patches to your favourite tools ▪ There’s a ton of great resources out there!
  • 48. “ Great Links ▪ https://gobyexample.com/ ▪ https://tour.golang.org/welcome/1 ▪ https://www.openmymind.net/The-Little-Go-Book/ ▪ http://www.golang-book.com/books/intro ▪ https://www.terraform.io/docs/extend/writing-custom-providers.ht ml ▪ https://www.hashicorp.com/resources/creating-terraform-provider-f or-anything