Terratest 使用 Terraform 测试配置的 EC2 实例时出现错误,我正在使用 count 创建多个实例,并且似乎函数 (GetPublicIpOfEc2Instance) 在返回多个实例 id 时感到困惑,有没有办法让它接受多个值?
--- FAIL: TestRecourcesProvisioning (295.89s)
ec2.go:121:
Error Trace: ec2.go:121
flugel_test.go:50
Error: Received unexpected error:
InvalidInstanceID.Malformed: Invalid id: "[i-0d1e09244e6bdb*** i-0257c214b3242c***]"
status code: 400, request id: ***-8c64-449f-b830-***
Test: TestRecourcesProvisioning
FAIL
FAIL command-line-arguments 295.909s
FAIL
地形测试代码:
package test
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"strings"
"testing"
"github.com/gruntwork-io/terratest/modules/aws"
"github.com/gruntwork-io/terratest/modules/random"
"github.com/gruntwork-io/terratest/modules/terraform"
"github.com/stretchr/testify/assert"
)
func TestRecourcesProvisioning(f *testing.T) {
f.Parallel()
// Specify A Region And Names For Resourses For Provisioning
approvedRegions := []string{"us-west-1"}
awsRegion := aws.GetRandomRegion(f, approvedRegions, nil)
expectedNameIns := fmt.Sprintf("ex-%s", random.UniqueId())
expectedBucket_name := fmt.Sprintf("ex-%s", strings.ToLower(random.UniqueId()))
terraformOptions := &terraform.Options{
// The Path To Terrafom Code
TerraformDir: "../",
// Variables Will Be Passed To Terraform Code
Vars: map[string]interface{}{
"instance_name": expectedNameIns,
"s3_name": expectedBucket_name,
"lb_name": fmt.Sprintf("ex-%s", random.UniqueId()),
"tg_name": fmt.Sprintf("ex-%s", random.UniqueId()),
"bucket_name": fmt.Sprintf("ex-%s", strings.ToLower(random.UniqueId())),
},
}
defer terraform.Destroy(f, terraformOptions)
terraform.InitAndApply(f, terraformOptions)
actualInstanceId := terraform.Output(f, terraformOptions, "instance_id")
actualPublicIP := terraform.Output(f, terraformOptions, "instance_public_ip")
actualBucketId := terraform.Output(f, terraformOptions, "bucket_id")
albDNS := terraform.Output(f, terraformOptions, "ex_lb_dns")
tagName := "Name"
exptectedPublicIP := aws.GetPublicIpOfEc2Instance(f, actualInstanceId, awsRegion)
expectedBucketID := aws.FindS3BucketWithTag(f, awsRegion, tagName, expectedBucket_name)
url := fmt.Sprintf("http://%s", albDNS)
resp, err := http.Get(url)
if err != nil {
log.Fatalln(err)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalln(err)
}
sb := string(body)
log.Printf(sb)
assert.Equal(f, actualPublicIP, exptectedPublicIP)
assert.Equal(f, expectedBucketID, actualBucketId)
assert.Contains(f, sb, "Hello World!")
}
地形代码:
resource "aws_instance" "ex_ec2" {
ami = var.ami_id
instance_type = "t2.micro"
key_name = "ex"
subnet_id = "${element(aws_subnet.ex_subnet.*.id, count.index)}"
associate_public_ip_address = true
security_groups = [aws_security_group.ec2_sg.id]
count = 2
user_data = file("userdata.sh")
tags = {
Name = var.instance_name
Owner = var.owner
}