Ejemplo n.º 1
0
// NewDynamoDBClient returns an *dynamodb.Client with a connection to the region
// configured via the AWS_REGION environment variable.
// It returns an error if the connection cannot be made or the table does not exist.
func NewDynamoDBClient(table string) (*Client, error) {
	creds := credentials.NewChainCredentials(
		[]credentials.Provider{
			&credentials.EnvProvider{},
			&credentials.EC2RoleProvider{},
		})
	_, err := creds.Get()
	if err != nil {
		return nil, err
	}
	var c *aws.Config
	if os.Getenv("DYNAMODB_LOCAL") != "" {
		log.Debug("DYNAMODB_LOCAL is set")
		c = &aws.Config{Endpoint: "http://localhost:8000"}
	} else {
		c = nil
	}
	d := dynamodb.New(c)
	// Check if the table exists
	_, err = d.DescribeTable(&dynamodb.DescribeTableInput{TableName: &table})
	if err != nil {
		return nil, err
	}
	return &Client{d, table}, nil
}
Ejemplo n.º 2
0
func getAuth() (creds *credentials.Credentials) {
	return credentials.NewChainCredentials(
		[]credentials.Provider{
			&credentials.EnvProvider{},
			&credentials.EC2RoleProvider{},
		})
}
Ejemplo n.º 3
0
	"io"
	"net/http"
	"os"
	"time"

	"github.com/awslabs/aws-sdk-go/aws/credentials"
)

// DefaultChainCredentials is a Credentials which will find the first available
// credentials Value from the list of Providers.
//
// This should be used in the default case. Once the type of credentials are
// known switching to the specific Credentials will be more efficient.
var DefaultChainCredentials = credentials.NewChainCredentials(
	[]credentials.Provider{
		&credentials.EnvProvider{},
		&credentials.SharedCredentialsProvider{Filename: "", Profile: ""},
		&credentials.EC2RoleProvider{ExpiryWindow: 5 * time.Minute},
	})

// The default number of retries for a service. The value of -1 indicates that
// the service specific retry default will be used.
const DefaultRetries = -1

// DefaultConfig is the default all service configuration will be based off of.
var DefaultConfig = &Config{
	Credentials:             DefaultChainCredentials,
	Endpoint:                "",
	Region:                  os.Getenv("AWS_REGION"),
	DisableSSL:              false,
	ManualSend:              false,
	HTTPClient:              http.DefaultClient,
Ejemplo n.º 4
0
// Provider returns a terraform.ResourceProvider.
func Provider() terraform.ResourceProvider {
	// TODO: Move the validation to this, requires conditional schemas
	// TODO: Move the configuration to this, requires validation

	// These variables are closed within the `getCreds` function below.
	// This function is responsible for reading credentials from the
	// environment in the case that they're not explicitly specified
	// in the Terraform configuration.
	//
	// By using the getCreds function here instead of making the default
	// empty, we avoid asking for input on credentials if they're available
	// in the environment.
	var credVal credentials.Value
	var credErr error
	var once sync.Once
	getCreds := func() {
		// Build the list of providers to look for creds in
		providers := []credentials.Provider{
			&credentials.EnvProvider{},
			&credentials.SharedCredentialsProvider{},
		}

		// We only look in the EC2 metadata API if we can connect
		// to the metadata service within a reasonable amount of time
		conn, err := net.DialTimeout("tcp", "169.254.169.254:80", 100*time.Millisecond)
		if err == nil {
			conn.Close()
			providers = append(providers, &credentials.EC2RoleProvider{})
		}

		credVal, credErr = credentials.NewChainCredentials(providers).Get()

		// If we didn't successfully find any credentials, just
		// set the error to nil.
		if credErr == credentials.ErrNoValidProvidersFoundInChain {
			credErr = nil
		}
	}

	// getCredDefault is a function used by DefaultFunc below to
	// get the default value for various parts of the credentials.
	// This function properly handles loading the credentials, checking
	// for errors, etc.
	getCredDefault := func(def interface{}, f func() string) (interface{}, error) {
		once.Do(getCreds)

		// If there was an error, that is always first
		if credErr != nil {
			return nil, credErr
		}

		// If the value is empty string, return nil (not set)
		val := f()
		if val == "" {
			return def, nil
		}

		return val, nil
	}

	// The actual provider
	return &schema.Provider{
		Schema: map[string]*schema.Schema{
			"access_key": &schema.Schema{
				Type:     schema.TypeString,
				Required: true,
				DefaultFunc: func() (interface{}, error) {
					return getCredDefault(nil, func() string {
						return credVal.AccessKeyID
					})
				},
				Description: descriptions["access_key"],
			},

			"secret_key": &schema.Schema{
				Type:     schema.TypeString,
				Required: true,
				DefaultFunc: func() (interface{}, error) {
					return getCredDefault(nil, func() string {
						return credVal.SecretAccessKey
					})
				},
				Description: descriptions["secret_key"],
			},

			"token": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
				DefaultFunc: func() (interface{}, error) {
					return getCredDefault("", func() string {
						return credVal.SessionToken
					})
				},
				Description: descriptions["token"],
			},

			"region": &schema.Schema{
				Type:     schema.TypeString,
				Required: true,
				DefaultFunc: schema.MultiEnvDefaultFunc([]string{
					"AWS_REGION",
					"AWS_DEFAULT_REGION",
				}, nil),
				Description:  descriptions["region"],
				InputDefault: "us-east-1",
			},

			"max_retries": &schema.Schema{
				Type:        schema.TypeInt,
				Optional:    true,
				Default:     11,
				Description: descriptions["max_retries"],
			},

			"allowed_account_ids": &schema.Schema{
				Type:          schema.TypeSet,
				Elem:          &schema.Schema{Type: schema.TypeString},
				Optional:      true,
				ConflictsWith: []string{"forbidden_account_ids"},
				Set: func(v interface{}) int {
					return hashcode.String(v.(string))
				},
			},

			"forbidden_account_ids": &schema.Schema{
				Type:          schema.TypeSet,
				Elem:          &schema.Schema{Type: schema.TypeString},
				Optional:      true,
				ConflictsWith: []string{"allowed_account_ids"},
				Set: func(v interface{}) int {
					return hashcode.String(v.(string))
				},
			},
		},

		ResourcesMap: map[string]*schema.Resource{
			"aws_app_cookie_stickiness_policy": resourceAwsAppCookieStickinessPolicy(),
			"aws_autoscaling_group":            resourceAwsAutoscalingGroup(),
			"aws_autoscaling_notification":     resourceAwsAutoscalingNotification(),
			"aws_autoscaling_policy":           resourceAwsAutoscalingPolicy(),
			"aws_cloudwatch_metric_alarm":      resourceAwsCloudWatchMetricAlarm(),
			"aws_customer_gateway":             resourceAwsCustomerGateway(),
			"aws_db_instance":                  resourceAwsDbInstance(),
			"aws_db_parameter_group":           resourceAwsDbParameterGroup(),
			"aws_db_security_group":            resourceAwsDbSecurityGroup(),
			"aws_db_subnet_group":              resourceAwsDbSubnetGroup(),
			"aws_dynamodb_table":               resourceAwsDynamoDbTable(),
			"aws_ebs_volume":                   resourceAwsEbsVolume(),
			"aws_ecs_cluster":                  resourceAwsEcsCluster(),
			"aws_ecs_service":                  resourceAwsEcsService(),
			"aws_ecs_task_definition":          resourceAwsEcsTaskDefinition(),
			"aws_eip":                          resourceAwsEip(),
			"aws_elasticache_cluster":          resourceAwsElasticacheCluster(),
			"aws_elasticache_parameter_group":  resourceAwsElasticacheParameterGroup(),
			"aws_elasticache_security_group":   resourceAwsElasticacheSecurityGroup(),
			"aws_elasticache_subnet_group":     resourceAwsElasticacheSubnetGroup(),
			"aws_elb":                          resourceAwsElb(),
			"aws_flow_log":                     resourceAwsFlowLog(),
			"aws_iam_access_key":               resourceAwsIamAccessKey(),
			"aws_iam_group_policy":             resourceAwsIamGroupPolicy(),
			"aws_iam_group":                    resourceAwsIamGroup(),
			"aws_iam_group_membership":         resourceAwsIamGroupMembership(),
			"aws_iam_instance_profile":         resourceAwsIamInstanceProfile(),
			"aws_iam_policy":                   resourceAwsIamPolicy(),
			"aws_iam_role_policy":              resourceAwsIamRolePolicy(),
			"aws_iam_role":                     resourceAwsIamRole(),
			"aws_iam_server_certificate":       resourceAwsIAMServerCertificate(),
			"aws_iam_user_policy":              resourceAwsIamUserPolicy(),
			"aws_iam_user":                     resourceAwsIamUser(),
			"aws_instance":                     resourceAwsInstance(),
			"aws_internet_gateway":             resourceAwsInternetGateway(),
			"aws_key_pair":                     resourceAwsKeyPair(),
			"aws_kinesis_stream":               resourceAwsKinesisStream(),
			"aws_lambda_function":              resourceAwsLambdaFunction(),
			"aws_launch_configuration":         resourceAwsLaunchConfiguration(),
			"aws_lb_cookie_stickiness_policy":  resourceAwsLBCookieStickinessPolicy(),
			"aws_main_route_table_association": resourceAwsMainRouteTableAssociation(),
			"aws_network_acl":                  resourceAwsNetworkAcl(),
			"aws_network_interface":            resourceAwsNetworkInterface(),
			"aws_proxy_protocol_policy":        resourceAwsProxyProtocolPolicy(),
			"aws_route53_delegation_set":       resourceAwsRoute53DelegationSet(),
			"aws_route53_record":               resourceAwsRoute53Record(),
			"aws_route53_zone_association":     resourceAwsRoute53ZoneAssociation(),
			"aws_route53_zone":                 resourceAwsRoute53Zone(),
			"aws_route53_health_check":         resourceAwsRoute53HealthCheck(),
			"aws_route_table":                  resourceAwsRouteTable(),
			"aws_route_table_association":      resourceAwsRouteTableAssociation(),
			"aws_s3_bucket":                    resourceAwsS3Bucket(),
			"aws_security_group":               resourceAwsSecurityGroup(),
			"aws_security_group_rule":          resourceAwsSecurityGroupRule(),
			"aws_spot_instance_request":        resourceAwsSpotInstanceRequest(),
			"aws_sqs_queue":                    resourceAwsSqsQueue(),
			"aws_sns_topic":                    resourceAwsSnsTopic(),
			"aws_sns_topic_subscription":       resourceAwsSnsTopicSubscription(),
			"aws_subnet":                       resourceAwsSubnet(),
			"aws_volume_attachment":            resourceAwsVolumeAttachment(),
			"aws_vpc_dhcp_options_association": resourceAwsVpcDhcpOptionsAssociation(),
			"aws_vpc_dhcp_options":             resourceAwsVpcDhcpOptions(),
			"aws_vpc_peering_connection":       resourceAwsVpcPeeringConnection(),
			"aws_vpc":                          resourceAwsVpc(),
			"aws_vpn_connection":               resourceAwsVpnConnection(),
			"aws_vpn_connection_route":         resourceAwsVpnConnectionRoute(),
			"aws_vpn_gateway":                  resourceAwsVpnGateway(),
		},

		ConfigureFunc: providerConfigure,
	}
}
Ejemplo n.º 5
0
import (
	"io"
	"net/http"
	"os"

	"github.com/awslabs/aws-sdk-go/aws/credentials"
)

// DefaultChainCredentials is a Credentials which will find the first available
// credentials Value from the list of Providers.
//
// This should be used in the default case. Once the type of credentials are
// known switching to the specific Credentials will be more efficient.
var DefaultChainCredentials = credentials.NewChainCredentials(
	[]credentials.Provider{
		&credentials.EnvProvider{},
		&credentials.SharedCredentialsProvider{Filename: "", Profile: ""},
		&credentials.EC2RoleProvider{},
	})

// The default number of retries for a service. The value of -1 indicates that
// the service specific retry default will be used.
const DefaultRetries = -1

// DefaultConfig is the default all service configuration will be based off of.
var DefaultConfig = &Config{
	Credentials:             DefaultChainCredentials,
	Endpoint:                "",
	Region:                  os.Getenv("AWS_REGION"),
	DisableSSL:              false,
	ManualSend:              false,
	HTTPClient:              http.DefaultClient,