Skip to content

Commit

Permalink
Merge pull request #58 from hairyhenderson/55-default-region
Browse files Browse the repository at this point in the history
Adding ability to provide default for ec2region function
  • Loading branch information
hairyhenderson authored Sep 2, 2016
2 parents 1fb1dbb + e6a2cfb commit 17983b5
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 4 deletions.
11 changes: 10 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -245,14 +245,23 @@ us-east-1

#### `ec2region`

Queries AWS to get the region. Returns `unknown` if it can't be determined for some reason.
Queries AWS to get the region. An optional default can be provided, or returns
`unknown` if it can't be determined for some reason.

##### Example

_In EC2_
```console
$ echo '{{ ec2region }}' | ./gomplate
us-east-1
```
_Not in EC2_
```console
$ echo '{{ ec2region }}' | ./gomplate
unknown
$ echo '{{ ec2region "foo" }}' | ./gomplate
foo
```

#### `ec2tag`

Expand Down
11 changes: 8 additions & 3 deletions aws/ec2meta.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,10 +71,15 @@ func (e *Ec2Meta) Dynamic(key string, def ...string) string {
}

// Region -
func (e *Ec2Meta) Region() string {
doc := e.Dynamic("instance-identity/document", `{"region":"unknown"}`)
func (e *Ec2Meta) Region(def ...string) string {
defaultRegion := returnDefault(def)
if defaultRegion == "" {
defaultRegion = "unknown"
}

doc := e.Dynamic("instance-identity/document", `{"region":"`+defaultRegion+`"}`)
obj := &InstanceDocument{
Region: "unknown",
Region: defaultRegion,
}
err := json.Unmarshal([]byte(doc), &obj)
if err != nil {
Expand Down
7 changes: 7 additions & 0 deletions aws/ec2meta_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,13 @@ func TestRegion_NoRegion(t *testing.T) {
assert.Equal(t, "unknown", ec2meta.Region())
}

func TestRegion_NoRegionWithDefault(t *testing.T) {
server, ec2meta := MockServer(200, "{}")
defer server.Close()

assert.Equal(t, "foo", ec2meta.Region("foo"))
}

func TestRegion_KnownRegion(t *testing.T) {
server, ec2meta := MockServer(200, `{"region":"us-east-1"}`)
defer server.Close()
Expand Down

0 comments on commit 17983b5

Please sign in to comment.