func resourceAwsWafByteMatchSetCreate(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).wafconn

	log.Printf("[INFO] Creating ByteMatchSet: %s", d.Get("name").(string))

	// ChangeToken
	var ct *waf.GetChangeTokenInput

	res, err := conn.GetChangeToken(ct)
	if err != nil {
		return errwrap.Wrapf("[ERROR] Error getting change token: {{err}}", err)
	}

	params := &waf.CreateByteMatchSetInput{
		ChangeToken: res.ChangeToken,
		Name:        aws.String(d.Get("name").(string)),
	}

	resp, err := conn.CreateByteMatchSet(params)

	if err != nil {
		return errwrap.Wrapf("[ERROR] Error creating ByteMatchSet: {{err}}", err)
	}

	d.SetId(*resp.ByteMatchSet.ByteMatchSetId)

	return resourceAwsWafByteMatchSetUpdate(d, meta)
}
func resourcePostgreSQLDatabaseDelete(d *schema.ResourceData, meta interface{}) error {
	c := meta.(*Client)
	conn, err := c.Connect()
	if err != nil {
		return errwrap.Wrapf("Error connecting to PostgreSQL: {{err}}", err)
	}
	defer conn.Close()

	dbName := d.Get(dbNameAttr).(string)

	if isTemplate := d.Get(dbIsTemplateAttr).(bool); isTemplate {
		// Template databases must have this attribute cleared before
		// they can be dropped.
		if err := doSetDBIsTemplate(conn, dbName, false); err != nil {
			return errwrap.Wrapf("Error updating database IS_TEMPLATE during DROP DATABASE: {{err}}", err)
		}
	}

	if err := setDBIsTemplate(conn, d); err != nil {
		return err
	}

	query := fmt.Sprintf("DROP DATABASE %s", pq.QuoteIdentifier(dbName))
	_, err = conn.Query(query)
	if err != nil {
		return errwrap.Wrapf("Error dropping database: {{err}}", err)
	}

	d.SetId("")

	return nil
}
func resourceAwsWafByteMatchSetDelete(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).wafconn

	log.Printf("[INFO] Deleting ByteMatchSet: %s", d.Get("name").(string))
	err := updateByteMatchSetResource(d, meta, waf.ChangeActionDelete)
	if err != nil {
		return errwrap.Wrapf("[ERROR] Error deleting ByteMatchSet: {{err}}", err)
	}

	var ct *waf.GetChangeTokenInput

	resp, err := conn.GetChangeToken(ct)

	req := &waf.DeleteByteMatchSetInput{
		ChangeToken:    resp.ChangeToken,
		ByteMatchSetId: aws.String(d.Id()),
	}

	_, err = conn.DeleteByteMatchSet(req)

	if err != nil {
		return errwrap.Wrapf("[ERROR] Error deleting ByteMatchSet: {{err}}", err)
	}

	return nil
}
func resourcePostgreSQLSchemaDelete(d *schema.ResourceData, meta interface{}) error {
	c := meta.(*Client)
	c.catalogLock.Lock()
	defer c.catalogLock.Unlock()

	conn, err := c.Connect()
	if err != nil {
		return err
	}
	defer conn.Close()

	txn, err := conn.Begin()
	if err != nil {
		return err
	}
	defer txn.Rollback()

	schemaName := d.Get(schemaNameAttr).(string)

	// NOTE(sean@): Deliberately not performing a cascading drop.
	query := fmt.Sprintf("DROP SCHEMA %s", pq.QuoteIdentifier(schemaName))
	_, err = txn.Query(query)
	if err != nil {
		return errwrap.Wrapf("Error deleting schema: {{err}}", err)
	}

	if err := txn.Commit(); err != nil {
		return errwrap.Wrapf("Error committing schema: {{err}}", err)
	}

	d.SetId("")

	return nil
}
Ejemplo n.º 5
0
func (c *ConsulBackend) setAdvertiseAddr(addr string) (err error) {
	if addr == "" {
		return fmt.Errorf("advertise address must not be empty")
	}

	url, err := url.Parse(addr)
	if err != nil {
		return errwrap.Wrapf(fmt.Sprintf(`failed to parse advertise URL "%v": {{err}}`, addr), err)
	}

	var portStr string
	c.advertiseHost, portStr, err = net.SplitHostPort(url.Host)
	if err != nil {
		if url.Scheme == "http" {
			portStr = "80"
		} else if url.Scheme == "https" {
			portStr = "443"
		} else if url.Scheme == "unix" {
			portStr = "-1"
			c.advertiseHost = url.Path
		} else {
			return errwrap.Wrapf(fmt.Sprintf(`failed to find a host:port in advertise address "%v": {{err}}`, url.Host), err)
		}
	}
	c.advertisePort, err = strconv.ParseInt(portStr, 10, 0)
	if err != nil || c.advertisePort < -1 || c.advertisePort > 65535 {
		return errwrap.Wrapf(fmt.Sprintf(`failed to parse valid port "%v": {{err}}`, portStr), err)
	}

	return nil
}
func updateXssMatchSetResource(d *schema.ResourceData, meta interface{}, ChangeAction string) error {
	conn := meta.(*AWSClient).wafconn

	var ct *waf.GetChangeTokenInput

	resp, err := conn.GetChangeToken(ct)
	if err != nil {
		return errwrap.Wrapf("[ERROR] Error getting change token: {{err}}", err)
	}

	req := &waf.UpdateXssMatchSetInput{
		ChangeToken:   resp.ChangeToken,
		XssMatchSetId: aws.String(d.Id()),
	}

	xssMatchTuples := d.Get("xss_match_tuples").(*schema.Set)
	for _, xssMatchTuple := range xssMatchTuples.List() {
		xmt := xssMatchTuple.(map[string]interface{})
		xssMatchTupleUpdate := &waf.XssMatchSetUpdate{
			Action: aws.String(ChangeAction),
			XssMatchTuple: &waf.XssMatchTuple{
				FieldToMatch:       expandFieldToMatch(xmt["field_to_match"].(*schema.Set).List()[0].(map[string]interface{})),
				TextTransformation: aws.String(xmt["text_transformation"].(string)),
			},
		}
		req.Updates = append(req.Updates, xssMatchTupleUpdate)
	}

	_, err = conn.UpdateXssMatchSet(req)
	if err != nil {
		return errwrap.Wrapf("[ERROR] Error updating XssMatchSet: {{err}}", err)
	}

	return nil
}
func resourcePostgreSQLDatabaseDelete(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*Client)
	conn, err := client.Connect()
	if err != nil {
		return errwrap.Wrapf("Error connecting to PostgreSQL: {{err}}", err)
	}
	defer conn.Close()

	dbName := d.Get("name").(string)
	connUsername := client.username
	dbOwner := d.Get("owner").(string)
	//needed in order to set the owner of the db if the connection user is not a superuser
	err = grantRoleMembership(conn, dbOwner, connUsername)
	if err != nil {
		return err
	}

	query := fmt.Sprintf("DROP DATABASE %s", pq.QuoteIdentifier(dbName))
	_, err = conn.Query(query)
	if err != nil {
		return errwrap.Wrapf("Error dropping database: {{err}}", err)
	}

	d.SetId("")

	return nil
}
Ejemplo n.º 8
0
func (intermediate *intermediateAwsPolicyDocument) document() (*awsPolicyDocument, error) {
	var statements []*awsPolicyStatement

	switch s := intermediate.Statements.(type) {
	case []interface{}:
		if err := mapstructure.Decode(s, &statements); err != nil {
			return nil, errwrap.Wrapf("Error parsing statement: {{err}}", err)
		}
	case map[string]interface{}:
		var singleStatement *awsPolicyStatement
		if err := mapstructure.Decode(s, &singleStatement); err != nil {
			return nil, errwrap.Wrapf("Error parsing statement: {{err}}", err)
		}
		statements = append(statements, singleStatement)
	default:
		return nil, errors.New("Unknown error parsing statement")
	}

	document := &awsPolicyDocument{
		Version:    intermediate.Version,
		Id:         intermediate.Id,
		Statements: statements,
	}

	return document, nil
}
Ejemplo n.º 9
0
// setupPolicyStore is used to initialize the policy store
// when the vault is being unsealed.
func (c *Core) setupPolicyStore() error {
	// Create a sub-view
	view := c.systemBarrierView.SubView(policySubPath)

	// Create the policy store
	c.policyStore = NewPolicyStore(view, &dynamicSystemView{core: c})

	// Ensure that the default policy exists, and if not, create it
	policy, err := c.policyStore.GetPolicy("default")
	if err != nil {
		return errwrap.Wrapf("error fetching default policy from store: {{err}}", err)
	}
	if policy == nil {
		err := c.policyStore.createDefaultPolicy()
		if err != nil {
			return err
		}
	}

	// Ensure that the cubbyhole response wrapping policy exists
	policy, err = c.policyStore.GetPolicy(cubbyholeResponseWrappingPolicyName)
	if err != nil {
		return errwrap.Wrapf("error fetching default policy from store: {{err}}", err)
	}
	if policy == nil || policy.Raw != cubbyholeResponseWrappingPolicy {
		err := c.policyStore.createCubbyholeResponseWrappingPolicy()
		if err != nil {
			return err
		}
	}

	return nil
}
func resourcePostgreSQLDatabaseCreate(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*Client)
	conn, err := client.Connect()
	if err != nil {
		return errwrap.Wrapf("Error connecting to PostgreSQL: {{err}}", err)
	}
	defer conn.Close()

	dbName := d.Get("name").(string)
	dbOwner := d.Get("owner").(string)
	connUsername := client.username

	var dbOwnerCfg string
	if dbOwner != "" {
		dbOwnerCfg = fmt.Sprintf("WITH OWNER=%s", pq.QuoteIdentifier(dbOwner))
	} else {
		dbOwnerCfg = ""
	}

	//needed in order to set the owner of the db if the connection user is not a superuser
	err = grantRoleMembership(conn, dbOwner, connUsername)
	if err != nil {
		return err
	}

	query := fmt.Sprintf("CREATE DATABASE %s %s", pq.QuoteIdentifier(dbName), dbOwnerCfg)
	_, err = conn.Query(query)
	if err != nil {
		return errwrap.Wrapf(fmt.Sprintf("Error creating database %s: {{err}}", dbName), err)
	}

	d.SetId(dbName)

	return resourcePostgreSQLDatabaseRead(d, meta)
}
func resourceArmLoadBalancerNatRuleCreate(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*ArmClient)
	lbClient := client.loadBalancerClient

	loadBalancer, exists, err := retrieveLoadBalancerById(d.Get("loadbalancer_id").(string), meta)
	if err != nil {
		return errwrap.Wrapf("Error Getting LoadBalancer By ID {{err}}", err)
	}
	if !exists {
		d.SetId("")
		log.Printf("[INFO] LoadBalancer %q not found. Removing from state", d.Get("name").(string))
		return nil
	}

	_, _, exists = findLoadBalancerNatRuleByName(loadBalancer, d.Get("name").(string))
	if exists {
		return fmt.Errorf("A NAT Rule with name %q already exists.", d.Get("name").(string))
	}

	newNatRule, err := expandAzureRmLoadBalancerNatRule(d, loadBalancer)
	if err != nil {
		return errwrap.Wrapf("Error Expanding NAT Rule {{err}}", err)
	}

	natRules := append(*loadBalancer.Properties.InboundNatRules, *newNatRule)
	loadBalancer.Properties.InboundNatRules = &natRules
	resGroup, loadBalancerName, err := resourceGroupAndLBNameFromId(d.Get("loadbalancer_id").(string))
	if err != nil {
		return errwrap.Wrapf("Error Getting LoadBalancer Name and Group: {{err}}", err)
	}

	_, err = lbClient.CreateOrUpdate(resGroup, loadBalancerName, *loadBalancer, make(chan struct{}))
	if err != nil {
		return errwrap.Wrapf("Error Creating / Updating LoadBalancer {{err}}", err)
	}

	read, err := lbClient.Get(resGroup, loadBalancerName, "")
	if err != nil {
		return errwrap.Wrapf("Error Getting LoadBalancer {{err}}", err)
	}
	if read.ID == nil {
		return fmt.Errorf("Cannot read LoadBalancer %s (resource group %s) ID", loadBalancerName, resGroup)
	}

	d.SetId(*read.ID)

	log.Printf("[DEBUG] Waiting for LoadBalancer (%s) to become available", loadBalancerName)
	stateConf := &resource.StateChangeConf{
		Pending: []string{"Accepted", "Updating"},
		Target:  []string{"Succeeded"},
		Refresh: loadbalancerStateRefreshFunc(client, resGroup, loadBalancerName),
		Timeout: 10 * time.Minute,
	}
	if _, err := stateConf.WaitForState(); err != nil {
		return fmt.Errorf("Error waiting for LoadBalancer (%s) to become available: %s", loadBalancerName, err)
	}

	return resourceArmLoadBalancerNatRuleRead(d, meta)
}
Ejemplo n.º 12
0
func resourceAwsSsmDocumentRead(d *schema.ResourceData, meta interface{}) error {
	ssmconn := meta.(*AWSClient).ssmconn

	log.Printf("[DEBUG] Reading SSM Document: %s", d.Id())

	docInput := &ssm.DescribeDocumentInput{
		Name: aws.String(d.Get("name").(string)),
	}

	resp, err := ssmconn.DescribeDocument(docInput)

	if err != nil {
		return errwrap.Wrapf("[ERROR] Error describing SSM document: {{err}}", err)
	}

	doc := resp.Document
	d.Set("created_date", doc.CreatedDate)
	d.Set("description", doc.Description)
	d.Set("hash", doc.Hash)
	d.Set("hash_type", doc.HashType)
	d.Set("name", doc.Name)
	d.Set("owner", doc.Owner)
	d.Set("platform_type", doc.PlatformTypes[0])
	d.Set("status", doc.Status)

	gp, err := getDocumentPermissions(d, meta)

	if err != nil {
		return errwrap.Wrapf("[ERROR] Error reading SSM document permissions: {{err}}", err)
	}

	d.Set("permissions", gp)

	params := make([]map[string]interface{}, 0)
	for i := 0; i < len(doc.Parameters); i++ {

		dp := doc.Parameters[i]
		param := make(map[string]interface{})

		if dp.DefaultValue != nil {
			param["default_value"] = *dp.DefaultValue
		}
		param["description"] = *dp.Description
		param["name"] = *dp.Name
		param["type"] = *dp.Type
		params = append(params, param)
	}

	if len(params) == 0 {
		params = make([]map[string]interface{}, 1)
	}

	if err := d.Set("parameter", params); err != nil {
		return err
	}

	return nil
}
Ejemplo n.º 13
0
func resourcePostgreSQLRoleReadImpl(d *schema.ResourceData, meta interface{}) error {
	c := meta.(*Client)
	conn, err := c.Connect()
	if err != nil {
		return err
	}
	defer conn.Close()

	roleId := d.Id()
	var roleSuperuser, roleInherit, roleCreateRole, roleCreateDB, roleCanLogin, roleReplication, roleBypassRLS bool
	var roleConnLimit int
	var roleName, roleValidUntil string
	err = conn.QueryRow("SELECT rolname, rolsuper, rolinherit, rolcreaterole, rolcreatedb, rolcanlogin, rolreplication, rolconnlimit, COALESCE(rolvaliduntil::TEXT, 'infinity'), rolbypassrls FROM pg_catalog.pg_roles WHERE rolname=$1", roleId).Scan(&roleName, &roleSuperuser, &roleInherit, &roleCreateRole, &roleCreateDB, &roleCanLogin, &roleReplication, &roleConnLimit, &roleValidUntil, &roleBypassRLS)
	switch {
	case err == sql.ErrNoRows:
		log.Printf("[WARN] PostgreSQL role (%s) not found", roleId)
		d.SetId("")
		return nil
	case err != nil:
		return errwrap.Wrapf("Error reading role: {{err}}", err)
	default:
		d.Set(roleNameAttr, roleName)
		d.Set(roleBypassRLSAttr, roleBypassRLS)
		d.Set(roleConnLimitAttr, roleConnLimit)
		d.Set(roleCreateDBAttr, roleCreateDB)
		d.Set(roleCreateRoleAttr, roleCreateRole)
		d.Set(roleEncryptedPassAttr, true)
		d.Set(roleInheritAttr, roleInherit)
		d.Set(roleLoginAttr, roleCanLogin)
		d.Set(roleReplicationAttr, roleReplication)
		d.Set(roleSkipDropRoleAttr, d.Get(roleSkipDropRoleAttr).(bool))
		d.Set(roleSkipReassignOwnedAttr, d.Get(roleSkipReassignOwnedAttr).(bool))
		d.Set(roleSuperuserAttr, roleSuperuser)
		d.Set(roleValidUntilAttr, roleValidUntil)
		d.SetId(roleName)
	}

	if !roleSuperuser {
		// Return early if not superuser user
		return nil
	}

	var rolePassword string
	err = conn.QueryRow("SELECT COALESCE(passwd, '') FROM pg_catalog.pg_shadow AS s WHERE s.usename = $1", roleId).Scan(&rolePassword)
	switch {
	case err == sql.ErrNoRows:
		return errwrap.Wrapf(fmt.Sprintf("PostgreSQL role (%s) not found in shadow database: {{err}}", roleId), err)
	case err != nil:
		return errwrap.Wrapf("Error reading role: {{err}}", err)
	default:
		d.Set(rolePasswordAttr, rolePassword)
		return nil
	}
}
Ejemplo n.º 14
0
func resourceArmLoadBalancerCreate(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*ArmClient)
	loadBalancerClient := client.loadBalancerClient

	log.Printf("[INFO] preparing arguments for Azure ARM LoadBalancer creation.")

	name := d.Get("name").(string)
	location := d.Get("location").(string)
	resGroup := d.Get("resource_group_name").(string)
	tags := d.Get("tags").(map[string]interface{})
	expandedTags := expandTags(tags)

	properties := network.LoadBalancerPropertiesFormat{}

	if _, ok := d.GetOk("frontend_ip_configuration"); ok {
		properties.FrontendIPConfigurations = expandAzureRmLoadBalancerFrontendIpConfigurations(d)
	}

	loadbalancer := network.LoadBalancer{
		Name:       azure.String(name),
		Location:   azure.String(location),
		Tags:       expandedTags,
		Properties: &properties,
	}

	_, err := loadBalancerClient.CreateOrUpdate(resGroup, name, loadbalancer, make(chan struct{}))
	if err != nil {
		return errwrap.Wrapf("Error Creating/Updating LoadBalancer {{err}}", err)
	}

	read, err := loadBalancerClient.Get(resGroup, name, "")
	if err != nil {
		return errwrap.Wrapf("Error Getting LoadBalancer {{err}", err)
	}
	if read.ID == nil {
		return fmt.Errorf("Cannot read LoadBalancer %s (resource group %s) ID", name, resGroup)
	}

	d.SetId(*read.ID)

	log.Printf("[DEBUG] Waiting for LoadBalancer (%s) to become available", name)
	stateConf := &resource.StateChangeConf{
		Pending: []string{"Accepted", "Updating"},
		Target:  []string{"Succeeded"},
		Refresh: loadbalancerStateRefreshFunc(client, resGroup, name),
		Timeout: 10 * time.Minute,
	}
	if _, err := stateConf.WaitForState(); err != nil {
		return fmt.Errorf("Error waiting for LoadBalancer (%s) to become available: %s", name, err)
	}

	return resourecArmLoadBalancerRead(d, meta)
}
func resourcePostgreSQLDatabaseRead(d *schema.ResourceData, meta interface{}) error {
	c := meta.(*Client)
	conn, err := c.Connect()
	if err != nil {
		return err
	}
	defer conn.Close()

	dbId := d.Id()
	var dbName, ownerName string
	err = conn.QueryRow("SELECT d.datname, pg_catalog.pg_get_userbyid(d.datdba) from pg_database d WHERE datname=$1", dbId).Scan(&dbName, &ownerName)
	switch {
	case err == sql.ErrNoRows:
		log.Printf("[WARN] PostgreSQL database (%s) not found", dbId)
		d.SetId("")
		return nil
	case err != nil:
		return errwrap.Wrapf("Error reading database: {{err}}", err)
	}

	var dbEncoding, dbCollation, dbCType, dbTablespaceName string
	var dbConnLimit int
	var dbAllowConns, dbIsTemplate bool
	err = conn.QueryRow(`SELECT pg_catalog.pg_encoding_to_char(d.encoding), d.datcollate, d.datctype, ts.spcname, d.datconnlimit, d.datallowconn, d.datistemplate FROM pg_catalog.pg_database AS d, pg_catalog.pg_tablespace AS ts WHERE d.datname = $1 AND d.dattablespace = ts.oid`, dbId).
		Scan(
			&dbEncoding, &dbCollation, &dbCType, &dbTablespaceName,
			&dbConnLimit, &dbAllowConns, &dbIsTemplate,
		)
	switch {
	case err == sql.ErrNoRows:
		log.Printf("[WARN] PostgreSQL database (%s) not found", dbId)
		d.SetId("")
		return nil
	case err != nil:
		return errwrap.Wrapf("Error reading database: {{err}}", err)
	default:
		d.Set(dbNameAttr, dbName)
		d.Set(dbOwnerAttr, ownerName)
		d.Set(dbEncodingAttr, dbEncoding)
		d.Set(dbCollationAttr, dbCollation)
		d.Set(dbCTypeAttr, dbCType)
		d.Set(dbTablespaceAttr, dbTablespaceName)
		d.Set(dbConnLimitAttr, dbConnLimit)
		d.Set(dbAllowConnsAttr, dbAllowConns)
		d.Set(dbIsTemplateAttr, dbIsTemplate)
		dbTemplate := d.Get(dbTemplateAttr).(string)
		if dbTemplate == "" {
			dbTemplate = "template0"
		}
		d.Set(dbTemplateAttr, dbTemplate)
		return nil
	}
}
func resourceAwsAlbListenerRuleRead(d *schema.ResourceData, meta interface{}) error {
	elbconn := meta.(*AWSClient).elbv2conn

	resp, err := elbconn.DescribeRules(&elbv2.DescribeRulesInput{
		RuleArns: []*string{aws.String(d.Id())},
	})
	if err != nil {
		if isRuleNotFound(err) {
			log.Printf("[WARN] DescribeRules - removing %s from state", d.Id())
			d.SetId("")
			return nil
		}
		return errwrap.Wrapf(fmt.Sprintf("Error retrieving Rules for listener %s: {{err}}", d.Id()), err)
	}

	if len(resp.Rules) != 1 {
		return fmt.Errorf("Error retrieving Rule %q", d.Id())
	}

	rule := resp.Rules[0]

	d.Set("arn", rule.RuleArn)
	if priority, err := strconv.Atoi(*rule.Priority); err != nil {
		return errwrap.Wrapf("Cannot convert rule priority %q to int: {{err}}", err)
	} else {
		d.Set("priority", priority)
	}

	actions := make([]interface{}, len(rule.Actions))
	for i, action := range rule.Actions {
		actionMap := make(map[string]interface{})
		actionMap["target_group_arn"] = *action.TargetGroupArn
		actionMap["type"] = *action.Type
		actions[i] = actionMap
	}
	d.Set("action", actions)

	conditions := make([]interface{}, len(rule.Conditions))
	for i, condition := range rule.Conditions {
		conditionMap := make(map[string]interface{})
		conditionMap["field"] = *condition.Field
		conditionValues := make([]string, len(condition.Values))
		for k, value := range condition.Values {
			conditionValues[k] = *value
		}
		conditionMap["values"] = conditionValues
		conditions[i] = conditionMap
	}
	d.Set("condition", conditions)

	return nil
}
func resourceAwsCloudWatchEventRuleUpdate(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).cloudwatcheventsconn

	if d.HasChange("is_enabled") && d.Get("is_enabled").(bool) {
		log.Printf("[DEBUG] Enabling CloudWatch Event Rule %q", d.Id())
		_, err := conn.EnableRule(&events.EnableRuleInput{
			Name: aws.String(d.Id()),
		})
		if err != nil {
			return err
		}
		log.Printf("[DEBUG] CloudWatch Event Rule (%q) enabled", d.Id())
	}

	input, err := buildPutRuleInputStruct(d)
	if err != nil {
		return errwrap.Wrapf("Updating CloudWatch Event Rule failed: {{err}}", err)
	}
	log.Printf("[DEBUG] Updating CloudWatch Event Rule: %s", input)

	// IAM Roles take some time to propagate
	err = resource.Retry(30*time.Second, func() *resource.RetryError {
		_, err := conn.PutRule(input)
		pattern := regexp.MustCompile("cannot be assumed by principal '[a-z]+\\.amazonaws\\.com'\\.$")
		if err != nil {
			if awsErr, ok := err.(awserr.Error); ok {
				if awsErr.Code() == "ValidationException" && pattern.MatchString(awsErr.Message()) {
					log.Printf("[DEBUG] Retrying update of CloudWatch Event Rule %q", *input.Name)
					return resource.RetryableError(err)
				}
			}
			return resource.NonRetryableError(err)
		}
		return nil
	})
	if err != nil {
		return errwrap.Wrapf("Updating CloudWatch Event Rule failed: {{err}}", err)
	}

	if d.HasChange("is_enabled") && !d.Get("is_enabled").(bool) {
		log.Printf("[DEBUG] Disabling CloudWatch Event Rule %q", d.Id())
		_, err := conn.DisableRule(&events.DisableRuleInput{
			Name: aws.String(d.Id()),
		})
		if err != nil {
			return err
		}
		log.Printf("[DEBUG] CloudWatch Event Rule (%q) disabled", d.Id())
	}

	return resourceAwsCloudWatchEventRuleRead(d, meta)
}
Ejemplo n.º 18
0
// PoliciesAreEquivalent tests for the structural equivalence of two
// AWS policies. It does not read into the semantics, other than treating
// single element string arrays as equivalent to a string without an
// array, as the AWS endpoints do.
//
// It will, however, detect reordering and ignore whitespace.
//
// Returns true if the policies are structurally equivalent, false
// otherwise. If either of the input strings are not valid JSON,
// false is returned along with an error.
func PoliciesAreEquivalent(policy1, policy2 string) (bool, error) {
	policy1doc := &awsPolicyDocument{}
	if err := json.Unmarshal([]byte(policy1), policy1doc); err != nil {
		return false, errwrap.Wrapf("Error unmarshaling policy: {{err}}", err)
	}

	policy2doc := &awsPolicyDocument{}
	if err := json.Unmarshal([]byte(policy2), policy2doc); err != nil {
		return false, errwrap.Wrapf("Error unmarshaling policy: {{err}}", err)
	}

	return policy1doc.equals(policy2doc), nil
}
func resourcePostgreSQLRoleUpdate(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*Client)
	conn, err := client.Connect()
	if err != nil {
		return err
	}
	defer conn.Close()

	d.Partial(true)

	roleName := d.Get("name").(string)

	if d.HasChange("login") {
		loginAttr := getLoginStr(d.Get("login").(bool))
		query := fmt.Sprintf("ALTER ROLE %s %s", pq.QuoteIdentifier(roleName), pq.QuoteIdentifier(loginAttr))
		_, err := conn.Query(query)
		if err != nil {
			return errwrap.Wrapf("Error updating login attribute for role: {{err}}", err)
		}

		d.SetPartial("login")
	}

	password := d.Get("password").(string)
	if d.HasChange("password") {
		encryptedCfg := getEncryptedStr(d.Get("encrypted").(bool))

		query := fmt.Sprintf("ALTER ROLE %s %s PASSWORD '%s'", pq.QuoteIdentifier(roleName), encryptedCfg, password)
		_, err := conn.Query(query)
		if err != nil {
			return errwrap.Wrapf("Error updating password attribute for role: {{err}}", err)
		}

		d.SetPartial("password")
	}

	if d.HasChange("encrypted") {
		encryptedCfg := getEncryptedStr(d.Get("encrypted").(bool))

		query := fmt.Sprintf("ALTER ROLE %s %s PASSWORD '%s'", pq.QuoteIdentifier(roleName), encryptedCfg, password)
		_, err := conn.Query(query)
		if err != nil {
			return errwrap.Wrapf("Error updating encrypted attribute for role: {{err}}", err)
		}

		d.SetPartial("encrypted")
	}

	d.Partial(false)
	return resourcePostgreSQLRoleRead(d, meta)
}
func testAccCheckAWSWafByteMatchSetDisappears(v *waf.ByteMatchSet) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		conn := testAccProvider.Meta().(*AWSClient).wafconn

		// ChangeToken
		var ct *waf.GetChangeTokenInput

		resp, err := conn.GetChangeToken(ct)
		if err != nil {
			return fmt.Errorf("Error getting change token: %s", err)
		}

		req := &waf.UpdateByteMatchSetInput{
			ChangeToken:    resp.ChangeToken,
			ByteMatchSetId: v.ByteMatchSetId,
		}

		for _, ByteMatchTuple := range v.ByteMatchTuples {
			ByteMatchUpdate := &waf.ByteMatchSetUpdate{
				Action: aws.String("DELETE"),
				ByteMatchTuple: &waf.ByteMatchTuple{
					FieldToMatch:         ByteMatchTuple.FieldToMatch,
					PositionalConstraint: ByteMatchTuple.PositionalConstraint,
					TargetString:         ByteMatchTuple.TargetString,
					TextTransformation:   ByteMatchTuple.TextTransformation,
				},
			}
			req.Updates = append(req.Updates, ByteMatchUpdate)
		}

		_, err = conn.UpdateByteMatchSet(req)
		if err != nil {
			return errwrap.Wrapf("[ERROR] Error updating ByteMatchSet: {{err}}", err)
		}

		resp, err = conn.GetChangeToken(ct)
		if err != nil {
			return errwrap.Wrapf("[ERROR] Error getting change token: {{err}}", err)
		}

		opts := &waf.DeleteByteMatchSetInput{
			ChangeToken:    resp.ChangeToken,
			ByteMatchSetId: v.ByteMatchSetId,
		}
		if _, err := conn.DeleteByteMatchSet(opts); err != nil {
			return err
		}
		return nil
	}
}
func resourcePostgreSQLSchemaReadImpl(d *schema.ResourceData, meta interface{}) error {
	c := meta.(*Client)
	conn, err := c.Connect()
	if err != nil {
		return err
	}
	defer conn.Close()

	schemaId := d.Id()
	var schemaName, schemaOwner string
	var schemaACLs []string
	err = conn.QueryRow("SELECT n.nspname, pg_catalog.pg_get_userbyid(n.nspowner), COALESCE(n.nspacl, '{}'::aclitem[])::TEXT[] FROM pg_catalog.pg_namespace n WHERE n.nspname=$1", schemaId).Scan(&schemaName, &schemaOwner, pq.Array(&schemaACLs))
	switch {
	case err == sql.ErrNoRows:
		log.Printf("[WARN] PostgreSQL schema (%s) not found", schemaId)
		d.SetId("")
		return nil
	case err != nil:
		return errwrap.Wrapf("Error reading schema: {{err}}", err)
	default:
		type RoleKey string
		schemaPolicies := make(map[RoleKey]acl.Schema, len(schemaACLs))
		for _, aclStr := range schemaACLs {
			aclItem, err := acl.Parse(aclStr)
			if err != nil {
				return errwrap.Wrapf("Error parsing aclitem: {{err}}", err)
			}

			schemaACL, err := acl.NewSchema(aclItem)
			if err != nil {
				return errwrap.Wrapf("invalid perms for schema: {{err}}", err)
			}

			roleKey := RoleKey(strings.ToLower(schemaACL.Role))
			var mergedPolicy acl.Schema
			if existingRolePolicy, ok := schemaPolicies[roleKey]; ok {
				mergedPolicy = existingRolePolicy.Merge(schemaACL)
			} else {
				mergedPolicy = schemaACL
			}
			schemaPolicies[roleKey] = mergedPolicy
		}

		d.Set(schemaNameAttr, schemaName)
		d.Set(schemaOwnerAttr, schemaOwner)
		d.SetId(schemaName)
		return nil
	}
}
func testAccCheckAWSWafSizeConstraintSetDisappears(v *waf.SizeConstraintSet) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		conn := testAccProvider.Meta().(*AWSClient).wafconn

		var ct *waf.GetChangeTokenInput

		resp, err := conn.GetChangeToken(ct)
		if err != nil {
			return fmt.Errorf("Error getting change token: %s", err)
		}

		req := &waf.UpdateSizeConstraintSetInput{
			ChangeToken:         resp.ChangeToken,
			SizeConstraintSetId: v.SizeConstraintSetId,
		}

		for _, sizeConstraint := range v.SizeConstraints {
			sizeConstraintUpdate := &waf.SizeConstraintSetUpdate{
				Action: aws.String("DELETE"),
				SizeConstraint: &waf.SizeConstraint{
					FieldToMatch:       sizeConstraint.FieldToMatch,
					ComparisonOperator: sizeConstraint.ComparisonOperator,
					Size:               sizeConstraint.Size,
					TextTransformation: sizeConstraint.TextTransformation,
				},
			}
			req.Updates = append(req.Updates, sizeConstraintUpdate)
		}
		_, err = conn.UpdateSizeConstraintSet(req)
		if err != nil {
			return errwrap.Wrapf("[ERROR] Error updating SizeConstraintSet: {{err}}", err)
		}

		resp, err = conn.GetChangeToken(ct)
		if err != nil {
			return errwrap.Wrapf("[ERROR] Error getting change token: {{err}}", err)
		}

		opts := &waf.DeleteSizeConstraintSetInput{
			ChangeToken:         resp.ChangeToken,
			SizeConstraintSetId: v.SizeConstraintSetId,
		}
		if _, err := conn.DeleteSizeConstraintSet(opts); err != nil {
			return err
		}
		return nil
	}
}
func testAccCheckAWSALBTargetGroupDestroy(s *terraform.State) error {
	conn := testAccProvider.Meta().(*AWSClient).elbv2conn

	for _, rs := range s.RootModule().Resources {
		if rs.Type != "aws_alb_target_group" {
			continue
		}

		describe, err := conn.DescribeTargetGroups(&elbv2.DescribeTargetGroupsInput{
			TargetGroupArns: []*string{aws.String(rs.Primary.ID)},
		})

		if err == nil {
			if len(describe.TargetGroups) != 0 &&
				*describe.TargetGroups[0].TargetGroupArn == rs.Primary.ID {
				return fmt.Errorf("Target Group %q still exists", rs.Primary.ID)
			}
		}

		// Verify the error
		if isTargetGroupNotFound(err) {
			return nil
		} else {
			return errwrap.Wrapf("Unexpected error checking ALB destroyed: {{err}}", err)
		}
	}

	return nil
}
Ejemplo n.º 24
0
// TODO: test
func (n *EvalVariableBlock) Eval(ctx EvalContext) (interface{}, error) {
	// Clear out the existing mapping
	for k, _ := range n.Variables {
		delete(n.Variables, k)
	}

	// Get our configuration
	rc := *n.Config
	for k, v := range rc.Config {
		var vStr string
		if err := mapstructure.WeakDecode(v, &vStr); err != nil {
			return nil, errwrap.Wrapf(fmt.Sprintf(
				"%s: error reading value: {{err}}", k), err)
		}

		n.Variables[k] = vStr
	}
	for k, _ := range rc.Raw {
		if _, ok := n.Variables[k]; !ok {
			n.Variables[k] = config.UnknownVariableValue
		}
	}

	return nil, nil
}
func resourceArmLoadBalancerNatRuleRead(d *schema.ResourceData, meta interface{}) error {
	loadBalancer, exists, err := retrieveLoadBalancerById(d.Get("loadbalancer_id").(string), meta)
	if err != nil {
		return errwrap.Wrapf("Error Getting LoadBalancer By ID {{err}}", err)
	}
	if !exists {
		d.SetId("")
		log.Printf("[INFO] LoadBalancer %q not found. Removing from state", d.Get("name").(string))
		return nil
	}

	configs := *loadBalancer.Properties.InboundNatRules
	for _, config := range configs {
		if *config.Name == d.Get("name").(string) {
			d.Set("name", config.Name)

			d.Set("protocol", config.Properties.Protocol)
			d.Set("frontend_port", config.Properties.FrontendPort)
			d.Set("backend_port", config.Properties.BackendPort)

			if config.Properties.FrontendIPConfiguration != nil {
				d.Set("frontend_ip_configuration_id", config.Properties.FrontendIPConfiguration.ID)
			}

			if config.Properties.BackendIPConfiguration != nil {
				d.Set("backend_ip_configuration_id", config.Properties.BackendIPConfiguration.ID)
			}

			break
		}
	}

	return nil
}
func resourcePostgreSQLExtensionCreate(d *schema.ResourceData, meta interface{}) error {
	c := meta.(*Client)
	c.catalogLock.Lock()
	defer c.catalogLock.Unlock()

	conn, err := c.Connect()
	if err != nil {
		return err
	}
	defer conn.Close()

	extName := d.Get(extNameAttr).(string)

	b := bytes.NewBufferString("CREATE EXTENSION ")
	fmt.Fprint(b, pq.QuoteIdentifier(extName))

	if v, ok := d.GetOk(extSchemaAttr); ok {
		fmt.Fprint(b, " SCHEMA ", pq.QuoteIdentifier(v.(string)))
	}

	if v, ok := d.GetOk(extVersionAttr); ok {
		fmt.Fprint(b, " VERSION ", pq.QuoteIdentifier(v.(string)))
	}

	query := b.String()
	_, err = conn.Query(query)
	if err != nil {
		return errwrap.Wrapf("Error creating extension: {{err}}", err)
	}

	d.SetId(extName)

	return resourcePostgreSQLExtensionReadImpl(d, meta)
}
func resourcePostgreSQLExtensionReadImpl(d *schema.ResourceData, meta interface{}) error {
	c := meta.(*Client)

	conn, err := c.Connect()
	if err != nil {
		return err
	}
	defer conn.Close()

	extID := d.Id()
	var extName, extSchema, extVersion string
	err = conn.QueryRow("SELECT e.extname, n.nspname, e.extversion FROM pg_catalog.pg_extension e, pg_catalog.pg_namespace n WHERE n.oid = e.extnamespace AND e.extname = $1", extID).Scan(&extName, &extSchema, &extVersion)
	switch {
	case err == sql.ErrNoRows:
		log.Printf("[WARN] PostgreSQL extension (%s) not found", d.Id())
		d.SetId("")
		return nil
	case err != nil:
		return errwrap.Wrapf("Error reading extension: {{err}}", err)
	default:
		d.Set(extNameAttr, extName)
		d.Set(extSchemaAttr, extSchema)
		d.Set(extVersionAttr, extVersion)
		d.SetId(extName)
		return nil
	}
}
Ejemplo n.º 28
0
func (gh *Client) Authenticate(username string, password string) error {
	var token []byte
	gh.User = &User{
		Login:    username,
		Password: password,
	}

	// conf := &oauth2.Config{
	// 	Endpoint: githubOauth2.Endpoint,
	// }
	gh.Store.Get(s.ConfigBucket, "gh_token", &token)
	if len(token) == 0 {
		var err error
		token, err = gh.createToken()
		if err != nil {
			return errwrap.Wrapf("[Github] Authentication error: %v", err)
		}
	}

	ts := oauth2.StaticTokenSource(
		&oauth2.Token{
			AccessToken: string(token),
		},
	)
	tc := oauth2.NewClient(oauth2.NoContext, ts)

	gh.client = github.NewClient(tc)
	user, _, _ := gh.client.Users.Get("")
	gh.User.Login = *user.Login
	gh.User.issues = map[string][]*github.Issue{}
	gh.User.Password = ""
	gh.Fetch()
	return nil
}
Ejemplo n.º 29
0
func resourceAwsVPCEndpointCreate(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).ec2conn
	input := &ec2.CreateVpcEndpointInput{
		VpcId:       aws.String(d.Get("vpc_id").(string)),
		ServiceName: aws.String(d.Get("service_name").(string)),
	}

	if v, ok := d.GetOk("route_table_ids"); ok {
		list := v.(*schema.Set).List()
		if len(list) > 0 {
			input.RouteTableIds = expandStringList(list)
		}
	}

	if v, ok := d.GetOk("policy"); ok {
		policy, err := normalizeJsonString(v)
		if err != nil {
			return errwrap.Wrapf("policy contains an invalid JSON: {{err}}", err)
		}
		input.PolicyDocument = aws.String(policy)
	}

	log.Printf("[DEBUG] Creating VPC Endpoint: %#v", input)
	output, err := conn.CreateVpcEndpoint(input)
	if err != nil {
		return fmt.Errorf("Error creating VPC Endpoint: %s", err)
	}
	log.Printf("[DEBUG] VPC Endpoint %q created.", *output.VpcEndpoint.VpcEndpointId)

	d.SetId(*output.VpcEndpoint.VpcEndpointId)

	return resourceAwsVPCEndpointRead(d, meta)
}
Ejemplo n.º 30
0
func (w *ContextGraphWalker) ExitEvalTree(
	v dag.Vertex, output interface{}, err error) error {
	log.Printf("[TRACE] Exiting eval tree: %s", dag.VertexName(v))

	// Release the semaphore
	w.Context.parallelSem.Release()

	if err == nil {
		return nil
	}

	// Acquire the lock because anything is going to require a lock.
	w.errorLock.Lock()
	defer w.errorLock.Unlock()

	// Try to get a validation error out of it. If its not a validation
	// error, then just record the normal error.
	verr, ok := err.(*EvalValidateError)
	if !ok {
		return err
	}

	for _, msg := range verr.Warnings {
		w.ValidationWarnings = append(
			w.ValidationWarnings,
			fmt.Sprintf("%s: %s", dag.VertexName(v), msg))
	}
	for _, e := range verr.Errors {
		w.ValidationErrors = append(
			w.ValidationErrors,
			errwrap.Wrapf(fmt.Sprintf("%s: {{err}}", dag.VertexName(v)), e))
	}

	return nil
}