From 2e4ed2de90e235afdb0f75bdaa26aca896f8123e Mon Sep 17 00:00:00 2001 From: Tylor Stewart Date: Fri, 20 Sep 2019 10:55:08 +1000 Subject: [PATCH] add feature for region self to use ec2metadata service for configuration --- cmd/sync/aws.go | 22 ++++++++++++++++++++++ examples/aws.md | 2 +- 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/cmd/sync/aws.go b/cmd/sync/aws.go index 25665847..aa36b9ba 100644 --- a/cmd/sync/aws.go +++ b/cmd/sync/aws.go @@ -7,6 +7,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/aws/ec2metadata" "github.com/aws/aws-sdk-go/service/ec2" "github.com/aws/aws-sdk-go/service/ec2/ec2iface" yaml "gopkg.in/yaml.v2" @@ -26,6 +27,27 @@ func NewAWSClient(data []byte) (*AWSClient, error) { return nil, fmt.Errorf("error validating config: %v", err) } + if cfg.Region == "self" { + httpClient := &http.Client{Timeout: connTimeoutInSecs * time.Second} + params := &aws.Config{HTTPClient: httpClient} + + metaSession, err := session.NewSession(params) + if err != nil { + return nil, err + } + + metaClient := ec2metadata.New(metaSession) + if !metaClient.Available() { + return nil, fmt.Errorf("ec2metadata service is unavailable") + } + + region, err := metaClient.Region() + if err != nil { + return nil, fmt.Errorf("unable to retreive region from ec2metadata: %v", err) + } + cfg.Region = region + } + awsClient.config = cfg err = awsClient.configure() diff --git a/examples/aws.md b/examples/aws.md index f49b4236..4478531b 100644 --- a/examples/aws.md +++ b/examples/aws.md @@ -35,7 +35,7 @@ upstreams: * The `api_endpoint` key defines the NGINX Plus API endpoint. * The `sync_interval_in_seconds` key defines the synchronization interval: nginx-asg-sync checks for scaling updates every 5 seconds. * The `cloud_provider` key defines a cloud provider that will be used. The default is `AWS`. This means the key can be empty if using AWS. Possible values are: `AWS`, `Azure`. -* The `region` key defines the AWS region where we deploy NGINX Plus and the Auto Scaling groups. +* The `region` key defines the AWS region where we deploy NGINX Plus and the Auto Scaling groups. Setting `region` to `self` will use the EC2 Metadata service to retreive the region of the current instance. * The `upstreams` key defines the list of upstream groups. For each upstream group we specify: * `name` – The name we specified for the upstream block in the NGINX Plus configuration. * `autoscaling_group` – The name of the corresponding Auto Scaling group. Use of wildcards is supported.