#A simple example on how to run terraform

1 messages · Page 1 of 1 (latest)

slow bison
#

Skipping the boilerplate code. The functions referenced are posted below. I also stripped out the nuances when using CI=true since it differs a bit from running the pipeline on localhost, especially AWS SSO.

What was nice about the aws-go-sdk and SSO is that I can switch account sessions easily by loading an sso profile for shared to push the image to ECR and then dev to run the terraform container.

Let's:

  • build a JS app and output the artifacts to a host dir.
  • get the ECR registry password
  • build and publish an image to ECR, using the previously built artifacts
  • pass the image name output to the terraform container
  • get the AWS credentials for the terraform container
  • run terraform init
  • run terraform plan
#
    // rest of code
    env := getEnv("ENVIRONMENT") // dev,stage,prod,shared
    baseImage := "node:18"
    ecrRegistry := getEnv("AWS_ECR_REGISTRY")
    awsRegion := getEnv("AWS_DEFAULT_REGION", "eu-west-1")
    service := getEnv("ECS_SERVICE")
    buildDir := install.Pipeline("build").
        WithEntrypoint(nil).
        WithWorkdir("/app").
        WithExec([]string{
            "yarn", "run", "build",
        }).Directory("./dist")

    secret := client.SetSecret("password", getEcrToken())
    sha := getEnv("GIT_SHA")
    creds := getAWSCredentials()

    addr, err := client.Container().
        From(baseImage).
        WithWorkdir("/app").WithMountedCache("./node_modules", client.CacheVolume("node_modules")).
        WithDirectory("/app/dist", buildDir).
        WithRegistryAuth(ecrRegistry, "AWS", secret).
        Publish(ctx, fmt.Sprintf("%s/%s:%s", ecrRegistry, service, sha))

    if err != nil {
        log.Fatal(err)
    }

    fmt.Println("Published at:", addr)
    tfImage := fmt.Sprintf("hashicorp/terraform:%s", getEnv("TF_VERSION", "1.4.5"))
    tf := client.Container().
        From(tfImage).
        WithWorkdir("/ci").
        WithDirectory("/ci", client.Host().Directory(fmt.Sprintf("%s/terraform", baseDir))).
        WithEnvVariable("TF_VAR_image_tag", sha).
        WithEnvVariable("AWS_ACCESS_KEY_ID", creds.AccessKeyID).
        WithEnvVariable("AWS_SECRET_ACCESS_KEY", creds.SecretAccessKey).
        WithEnvVariable("AWS_SESSION_TOKEN", creds.SessionToken).
        WithEnvVariable("AWS_DEFAULT_REGION", awsRegion).
        WithExec([]string{"init", "--reconfigure", fmt.Sprintf("-backend-config=backend/%s.tfbackend", env)}).
        WithExec([]string{"plan", "--var-file", "terraform.tfvars", "--var-file", fmt.Sprintf("vars/%s.tfvars", env)})
}