我正在为地形模块编写测试用例。我有一个假设角色,我想把它传递给我的围棋测试。我不知道如何通过它.我将其定义为 const,然后我应该如何传递它,以便在地形形态初始化和地形应用、销毁期间唤起它。
package test
import (
"testing"
"github.com/gruntwork-io/terratest/modules/aws"
"github.com/gruntwork-io/terratest/modules/terraform"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// An example of how to test the Terraform module in examples/terraform-aws-network-example using Terratest.
func TestTerraformAwsNetworkExample(t *testing.T) {
t.Parallel()
const authAssumeRoleEnvVar = "TERRATEST_IAM_ROLE"
// Give the VPC and the subnets correct CIDRs
vpcCidr := "1x.x.x.x/20"
Env := "staging"
privateSubnetCidr := []string{"1x.x.x.x/30"}
publicSubnetCidr := []string{"1x.x.x.x/30"}
Tag := map[string]string{"owner":"xxx"}
awsRegion := "us-east-1"
terraformOptions := &terraform.Options{
// The path to where our Terraform code is located
TerraformDir: "..",
// Variables to pass to our Terraform code using -var options
Vars: map[string]interface{}{
"vpc_cidr": vpcCidr,
"env": Env,
"private_subnet_cidrs": privateSubnetCidr,
"public_subnet_cidrs": publicSubnetCidr,
"tags" : Tag,
},
EnvVars: map[string]string{
"AWS_DEFAULT_REGION": awsRegion,
},
}
// At the end of the test, run `terraform destroy` to clean up any resources that were created
defer terraform.Destroy(t, terraformOptions)
// This will run `terraform init` and `terraform apply` and fail the test if there are any errors
terraform.InitAndApply(t, terraformOptions)
// Run `terraform output` to get the value of an output variable
publicSubnetId := terraform.Output(t, terraformOptions, "public_subnet_ids")
privateSubnetId := terraform.Output(t, terraformOptions, "private_subnet_ids")
vpcId := terraform.Output(t, terraformOptions, "vpc_id")
subnets := aws.GetSubnetsForVpc(t, vpcId, awsRegion)
require.Equal(t, 2, len(subnets))
// Verify if the network that is supposed to be public is really public
assert.True(t, aws.IsPublicSubnet(t, publicSubnetId, awsRegion))
// Verify if the network that is supposed to be private is really private
assert.False(t, aws.IsPublicSubnet(t, privateSubnetId, awsRegion))
}
**
这段代码不可测试,因此无法对其进行测试。
** https://github.com/gruntwork-io/terratest/blob/f3916f7a5f58e3fedf603388d3e3e8052d6a47a3/modules/aws/auth.go#L18
我希望他们可以像这样重构它:
var AuthAssumeRoleEnvVar string
func SetAuthAssumeRoleEnvVar(role string){
AuthAssumeRoleEnvVar = role
}
func NewAuthenticatedSession(region string) (*session.Session, error) {
if assumeRoleArn, ok := os.LookupEnv(AuthAssumeRoleEnvVar); ok {
return NewAuthenticatedSessionFromRole(region, assumeRoleArn)
} else {
return NewAuthenticatedSessionFromDefaultCredentials(region)
}
}
因此我们可以将其称为:
aws.SetAuthAssumeRoleEnvVar("testrole")
aws.NewAuthenticatedSession(region)
将此变量TERRATEST_IAM_ROLE作为操作系统环境变量传递的唯一方法,如文档中所述 您也可以将其定义为后端文件,但如果您有读取值的断言测试用例,则不会选取该文件,因为它使用 aws cli
所以我做了一些事情,它奏效了。
import (
"os"
)
os.Setenv("TERRATEST_IAM_ROLE", "arn:aws:iam::xxxx/xxxx")