как передать роль в Terratest - PullRequest
1 голос
/ 15 января 2020

Я работаю над написанием тестового примера для модуля terraform. У меня есть предполагаемая роль, и я хотел бы сдать ее на мой go тест. Я не уверен, как пройти это. Я определил его как const, а затем, как я должен передать его так, чтобы он вызывался во время инициализации terraform и применения, уничтожения terraform.

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))
}

Ответы [ 2 ]

3 голосов
/ 15 января 2020

**

Этот код не подлежит тестированию, поэтому вы не можете его протестировать.

** https://github.com/gruntwork-io/terratest/blob/f3916f7a5f58e3fedf603388d3e3e8052d6a47a3/modules/aws/auth.go#L18

Я могу sh они могли бы изменить его следующим образом:

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)
0 голосов
/ 17 января 2020

Единственный способ передать эту переменную TERRATEST_IAM_ROLE в качестве переменной среды os, как указано в документе. Вы также можете определить ее в своем бэкэнд-файле, но он не будет выбран, если у вас есть тестовые примеры assert, которые считывают значения, так как он использует aws cli

Итак, я сделал что-то подобное, и это сработало.

import (

    "os"


)
 os.Setenv("TERRATEST_IAM_ROLE", "arn:aws:iam::xxxx/xxxx")
...