packer-cn/builder/ucloud/uhost/builder_acc_test.go

223 lines
5.7 KiB
Go
Raw Normal View History

2019-06-13 03:16:49 -04:00
package uhost
import (
"fmt"
build using HCL2 (#8423) This follows #8232 which added the code to generate the code required to parse HCL files for each packer component. All old config files of packer will keep on working the same. Packer takes one argument. When a directory is passed, all files in the folder with a name ending with “.pkr.hcl” or “.pkr.json” will be parsed using the HCL2 format. When a file ending with “.pkr.hcl” or “.pkr.json” is passed it will be parsed using the HCL2 format. For every other case; the old packer style will be used. ## 1. the hcl2template pkg can create a packer.Build from a set of HCL (v2) files I had to make the packer.coreBuild (which is our one and only packer.Build ) a public struct with public fields ## 2. Components interfaces get a new ConfigSpec Method to read a file from an HCL file. This is a breaking change for packer plugins. a packer component can be a: builder/provisioner/post-processor each component interface now gets a `ConfigSpec() hcldec.ObjectSpec` which allows packer to tell what is the layout of the hcl2 config meant to configure that specific component. This ObjectSpec is sent through the wire (RPC) and a cty.Value is now sent through the already existing configuration entrypoints: Provisioner.Prepare(raws ...interface{}) error Builder.Prepare(raws ...interface{}) ([]string, error) PostProcessor.Configure(raws ...interface{}) error close #1768 Example hcl files: ```hcl // file amazon-ebs-kms-key/run.pkr.hcl build { sources = [ "source.amazon-ebs.first", ] provisioner "shell" { inline = [ "sleep 5" ] } post-processor "shell-local" { inline = [ "sleep 5" ] } } // amazon-ebs-kms-key/source.pkr.hcl source "amazon-ebs" "first" { ami_name = "hcl2-test" region = "us-east-1" instance_type = "t2.micro" kms_key_id = "c729958f-c6ba-44cd-ab39-35ab68ce0a6c" encrypt_boot = true source_ami_filter { filters { virtualization-type = "hvm" name = "amzn-ami-hvm-????.??.?.????????-x86_64-gp2" root-device-type = "ebs" } most_recent = true owners = ["amazon"] } launch_block_device_mappings { device_name = "/dev/xvda" volume_size = 20 volume_type = "gp2" delete_on_termination = "true" } launch_block_device_mappings { device_name = "/dev/xvdf" volume_size = 500 volume_type = "gp2" delete_on_termination = true encrypted = true } ami_regions = ["eu-central-1"] run_tags { Name = "packer-solr-something" stack-name = "DevOps Tools" } communicator = "ssh" ssh_pty = true ssh_username = "ec2-user" associate_public_ip_address = true } ```
2019-12-17 05:25:56 -05:00
"os"
"testing"
2019-10-12 04:46:21 -04:00
ucloudcommon "github.com/hashicorp/packer/builder/ucloud/common"
2019-06-13 03:16:49 -04:00
"github.com/hashicorp/packer/packer"
"github.com/stretchr/testify/assert"
2019-06-13 03:16:49 -04:00
builderT "github.com/hashicorp/packer/helper/builder/testing"
)
func TestBuilderAcc_validateRegion(t *testing.T) {
t.Parallel()
if os.Getenv(builderT.TestEnvVar) == "" {
t.Skip(fmt.Sprintf("Acceptance tests skipped unless env '%s' set", builderT.TestEnvVar))
return
}
testAccPreCheck(t)
2019-10-12 04:46:21 -04:00
access := &ucloudcommon.AccessConfig{Region: "cn-bj2"}
2019-06-13 03:16:49 -04:00
err := access.Config()
if err != nil {
t.Fatalf("Error on initing UCloud AccessConfig, %s", err)
}
err = access.ValidateRegion("cn-sh2")
if err != nil {
t.Fatalf("Expected pass with valid region but failed: %s", err)
}
err = access.ValidateRegion("invalidRegion")
if err == nil {
t.Fatal("Expected failure due to invalid region but passed")
}
}
func TestBuilderAcc_basic(t *testing.T) {
t.Parallel()
builderT.Test(t, builderT.TestCase{
PreCheck: func() {
testAccPreCheck(t)
},
Builder: &Builder{},
Template: testBuilderAccBasic,
})
}
const testBuilderAccBasic = `
{ "builders": [{
"type": "test",
"region": "cn-bj2",
"availability_zone": "cn-bj2-02",
"instance_type": "n-basic-2",
"source_image_id":"uimage-f1chxn",
"ssh_username":"root",
"image_name": "packer-test-basic_{{timestamp}}"
}]
}`
func TestBuilderAcc_ubuntu(t *testing.T) {
t.Parallel()
builderT.Test(t, builderT.TestCase{
PreCheck: func() {
testAccPreCheck(t)
},
Builder: &Builder{},
Template: testBuilderAccUbuntu,
})
}
const testBuilderAccUbuntu = `
{ "builders": [{
"type": "test",
"region": "cn-bj2",
"availability_zone": "cn-bj2-02",
"instance_type": "n-basic-2",
"source_image_id":"uimage-irofn4",
"ssh_username":"ubuntu",
2019-06-13 06:38:07 -04:00
"image_name": "packer-test-ubuntu_{{timestamp}}"
2019-06-13 03:16:49 -04:00
}]
}`
func TestBuilderAcc_regionCopy(t *testing.T) {
t.Parallel()
projectId := os.Getenv("UCLOUD_PROJECT_ID")
builderT.Test(t, builderT.TestCase{
PreCheck: func() {
testAccPreCheck(t)
},
Builder: &Builder{},
2019-06-13 06:38:07 -04:00
Template: testBuilderAccRegionCopy(projectId),
2019-06-13 03:16:49 -04:00
Check: checkRegionCopy(
projectId,
2019-10-12 04:46:21 -04:00
[]ucloudcommon.ImageDestination{
{ProjectId: projectId, Region: "cn-sh2", Name: "packer-test-regionCopy-sh", Description: "test"},
2019-06-13 03:16:49 -04:00
}),
})
}
2019-06-13 06:38:07 -04:00
func testBuilderAccRegionCopy(projectId string) string {
return fmt.Sprintf(`
2019-06-13 03:16:49 -04:00
{
"builders": [{
"type": "test",
"region": "cn-bj2",
"availability_zone": "cn-bj2-02",
"instance_type": "n-basic-2",
"source_image_id":"uimage-f1chxn",
"ssh_username":"root",
2019-06-13 06:38:07 -04:00
"image_name": "packer-test-regionCopy-bj",
"image_copy_to_mappings": [{
"project_id": %q,
"region": "cn-sh2",
"name": "packer-test-regionCopy-sh",
"description": "test"
2019-06-13 03:16:49 -04:00
}]
}]
2019-06-13 06:38:07 -04:00
}`, projectId)
}
2019-06-13 03:16:49 -04:00
2019-10-12 04:46:21 -04:00
func checkRegionCopy(projectId string, imageDst []ucloudcommon.ImageDestination) builderT.TestCheckFunc {
2019-06-13 03:16:49 -04:00
return func(artifacts []packer.Artifact) error {
if len(artifacts) > 1 {
return fmt.Errorf("more than 1 artifact")
}
artifactSet := artifacts[0]
2019-10-12 04:46:21 -04:00
artifact, ok := artifactSet.(*ucloudcommon.Artifact)
2019-06-13 03:16:49 -04:00
if !ok {
return fmt.Errorf("unknown artifact: %#v", artifactSet)
}
2019-10-12 04:46:21 -04:00
destSet := ucloudcommon.NewImageInfoSet(nil)
2019-06-13 03:16:49 -04:00
for _, dest := range imageDst {
2019-10-12 04:46:21 -04:00
destSet.Set(ucloudcommon.ImageInfo{
2019-06-13 03:16:49 -04:00
Region: dest.Region,
ProjectId: dest.ProjectId,
})
}
for _, r := range artifact.UCloudImages.GetAll() {
if r.ProjectId == projectId && r.Region == "cn-bj2" {
destSet.Remove(r.Id())
continue
}
if destSet.Get(r.ProjectId, r.Region) == nil {
return fmt.Errorf("project%s : region%s is not the target but found in artifacts", r.ProjectId, r.Region)
}
destSet.Remove(r.Id())
}
if len(destSet.GetAll()) > 0 {
return fmt.Errorf("the following copying targets not found in corresponding artifacts : %#v", destSet.GetAll())
}
client, _ := testUCloudClient()
for _, r := range artifact.UCloudImages.GetAll() {
if r.ProjectId == projectId && r.Region == "cn-bj2" {
continue
}
2019-10-12 04:46:21 -04:00
imageSet, err := client.DescribeImageByInfo(r.ProjectId, r.Region, r.ImageId)
2019-06-13 03:16:49 -04:00
if err != nil {
2019-10-12 04:46:21 -04:00
if ucloudcommon.IsNotFoundError(err) {
2019-06-13 03:16:49 -04:00
return fmt.Errorf("image %s in artifacts can not be found", r.ImageId)
}
return err
}
if r.Region == "cn-sh2" && imageSet.ImageName != "packer-test-regionCopy-sh" {
return fmt.Errorf("the name of image %q in artifacts should be %s, got %s", r.ImageId, "packer-test-regionCopy-sh", imageSet.ImageName)
}
}
return nil
}
}
func testAccPreCheck(t *testing.T) {
if v := os.Getenv("UCLOUD_PUBLIC_KEY"); v == "" {
t.Fatal("UCLOUD_PUBLIC_KEY must be set for acceptance tests")
}
if v := os.Getenv("UCLOUD_PRIVATE_KEY"); v == "" {
t.Fatal("UCLOUD_PRIVATE_KEY must be set for acceptance tests")
}
if v := os.Getenv("UCLOUD_PROJECT_ID"); v == "" {
t.Fatal("UCLOUD_PROJECT_ID must be set for acceptance tests")
}
}
func TestUCloudClientBaseUrlConfigurable(t *testing.T) {
const url = "baseUrl"
2019-10-24 01:49:33 -04:00
access := &ucloudcommon.AccessConfig{BaseUrl: url}
client, err := access.Client()
assert.Nil(t, err)
2019-10-24 01:49:33 -04:00
assert.Equal(t, url, client.UAccountConn.Client.GetConfig().BaseUrl, "account conn's base url not configurable")
assert.Equal(t, url, client.UHostConn.Client.GetConfig().BaseUrl, "host conn's base url not configurable")
assert.Equal(t, url, client.UNetConn.Client.GetConfig().BaseUrl, "net conn's base url not configurable")
assert.Equal(t, url, client.VPCConn.Client.GetConfig().BaseUrl, "vpc conn's base url not configurable")
}
2019-10-12 04:46:21 -04:00
func testUCloudClient() (*ucloudcommon.UCloudClient, error) {
access := &ucloudcommon.AccessConfig{Region: "cn-bj2"}
2019-06-13 03:16:49 -04:00
err := access.Config()
if err != nil {
return nil, err
}
client, err := access.Client()
if err != nil {
return nil, err
}
return client, nil
}