猿问

如何在 terratest 中通过承担角色

我正在为 terraform 模块编写测试用例。我有一个假设角色,我想将它传递给我的 go 测试。我不知道如何通过它。我将它定义为一个常量,然后我应该如何传递它以便它在 terraform init 和 terraform apply、destroy 期间被唤起。


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,


        },

    }

}


素胚勾勒不出你
浏览 104回答 2
2回答

慕尼黑8549860

将此变量TERRATEST_IAM_ROLE作为文档中提到的os环境变量传递的唯一方法您也可以将其定义为您的后端文件,但如果您有读取值的断言测试用例,则不会被拾取,因为它使用aws cli所以我做了这件事,它奏效了。import (    "os") os.Setenv("TERRATEST_IAM_ROLE", "arn:aws:iam::xxxx/xxxx")

SMILET

**这段代码是不可测试的,所以你不能测试它。** https://github.com/gruntwork-io/terratest/blob/f3916f7a5f58e3fedf603388d3e3e8052d6a47a3/modules/aws/auth.go#L18我希望他们可以像这样重构它:var AuthAssumeRoleEnvVar stringfunc 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)
随时随地看视频慕课网APP

相关分类

Go
我要回答