diff --git a/.github/workflows/env-deploy.yml b/.github/workflows/env-deploy.yml index 324cf007..25c504e0 100644 --- a/.github/workflows/env-deploy.yml +++ b/.github/workflows/env-deploy.yml @@ -19,15 +19,21 @@ on: description: "AWS Secret Access Key" required: true github_access_token: - description: 'Github Token' + description: "Github Token" required: true + outputs: + create_url: + description: "URL of the create endpoint" + value: ${{ jobs.terraform_environment_workflow.outputs.url }} jobs: terraform_environment_workflow: runs-on: ubuntu-latest - # environment: - # name: ${{ inputs.workspace_name }} popup environment - # url: ${{ steps.terraform_outputs.outputs.url }} + environment: + name: ${{ inputs.workspace_name }} popup environment + url: ${{ steps.terraform_outputs.outputs.url }} + outputs: + url: ${{ steps.terraform_outputs.outputs.url }} steps: - uses: actions/checkout@v4 with: @@ -73,11 +79,11 @@ jobs: terraform apply -lock-timeout=300s -input=false -auto-approve -parallelism=30 working-directory: ./terraform/environment - # - name: Terraform Outputs - # id: terraform_outputs - # env: - # TF_WORKSPACE: ${{ inputs.workspace_name }} - # TF_VAR_app_version: ${{ inputs.version_tag }} - # run: | - # echo "url=$(terraform output -raw app_fqdn)" >> $GITHUB_OUTPUT - # working-directory: ./terraform/environment + - name: Terraform Outputs + id: terraform_outputs + env: + TF_WORKSPACE: ${{ inputs.workspace_name }} + TF_VAR_app_version: ${{ inputs.version_tag }} + run: | + echo "url=$(terraform output -raw lambda_url)" >> $GITHUB_OUTPUT + working-directory: ./terraform/environment diff --git a/.github/workflows/env-test.yml b/.github/workflows/env-test.yml new file mode 100644 index 00000000..305bc3f4 --- /dev/null +++ b/.github/workflows/env-test.yml @@ -0,0 +1,52 @@ +name: "[Job] Test environment" + +on: + workflow_call: + inputs: + create_url: + description: "URL of the create endpoint" + required: true + type: string + secrets: + aws_access_key_id: + description: "AWS Access Key ID" + required: true + aws_secret_access_key: + description: "AWS Secret Access Key" + required: true + +defaults: + run: + shell: bash + +permissions: + id-token: write + contents: write + security-events: write + pull-requests: read + +jobs: + test: + runs-on: ubuntu-latest + name: Test + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: "0" + - uses: actions/setup-go@v4 + with: + go-version: "1.21" + - uses: unfor19/install-aws-cli-action@v1 + - name: Configure AWS + uses: aws-actions/configure-aws-credentials@v4 + with: + aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }} + aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} + aws-region: eu-west-1 + role-to-assume: arn:aws:iam::493907465011:role/lpa-store-ci + role-duration-seconds: 3600 + role-session-name: GitHubActions + - name: POST to server + env: + URL: ${{ inputs.create_url }} + run: make test-api diff --git a/.github/workflows/workflow-pr.yml b/.github/workflows/workflow-pr.yml index fbf35673..2d6d5085 100644 --- a/.github/workflows/workflow-pr.yml +++ b/.github/workflows/workflow-pr.yml @@ -73,7 +73,7 @@ jobs: deploy-pr-env: name: Deploy PR Environment - needs: [build, generate-environment-workspace-name] + needs: [build, generate-tags, generate-environment-workspace-name] uses: ./.github/workflows/env-deploy.yml with: workspace_name: ${{ needs.generate-environment-workspace-name.outputs.environment_workspace_name }} @@ -82,3 +82,13 @@ jobs: aws_access_key_id: ${{ secrets.AWS_ACCESS_KEY_ID }} aws_secret_access_key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} github_access_token: ${{ secrets.GITHUB_TOKEN }} + + test-pr-env: + name: Test PR Environment + needs: [deploy-pr-env] + uses: ./.github/workflows/env-test.yml + with: + create_url: ${{ needs.deploy-pr-env.outputs.create_url }} + secrets: + aws_access_key_id: ${{ secrets.AWS_ACCESS_KEY_ID }} + aws_secret_access_key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} diff --git a/.gitignore b/.gitignore index e7a4baa1..19aef862 100644 --- a/.gitignore +++ b/.gitignore @@ -14,6 +14,8 @@ secrets.auto.tfvars .env venv/ env/ +# built items +signer/test-api # structurizr .structurizr docs/architecture/dsl/**/workspace.json diff --git a/Makefile b/Makefile index 12b71c88..6eec8b31 100644 --- a/Makefile +++ b/Makefile @@ -12,8 +12,11 @@ up: down: docker compose down +test-api: URL ?= http://localhost:9000/create test-api: - curl -XPOST localhost:9000/create -d '{"uid":"test","version":"1"}' -i + go build -o ./signer/test-api ./signer && \ + chmod +x ./signer/test-api && \ + ./signer/test-api POST $(URL) '{"uid":"M-AL9A-7EY3-075D","version":"1"}' create-tables: docker compose run --rm aws dynamodb describe-table --table-name deeds || \ diff --git a/docker-compose.yml b/docker-compose.yml index 8690d7e4..02d8fecc 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -16,6 +16,7 @@ services: AWS_DYNAMODB_ENDPOINT: http://ddb:8000 AWS_ACCESS_KEY_ID: X AWS_SECRET_ACCESS_KEY: X + DDB_TABLE_NAME_DEEDS: deeds volumes: - "./lambda/.aws-lambda-rie:/aws-lambda" entrypoint: /aws-lambda/aws-lambda-rie /var/task/main diff --git a/go.work b/go.work index 045287ee..227064f5 100644 --- a/go.work +++ b/go.work @@ -4,4 +4,5 @@ use ( ./lambda/create ./lambda/shared ./mock-apigw + ./signer ) diff --git a/lambda/create/main.go b/lambda/create/main.go index c28339bd..b47feecb 100644 --- a/lambda/create/main.go +++ b/lambda/create/main.go @@ -2,7 +2,6 @@ package main import ( "encoding/json" - "log" "os" "time" @@ -30,10 +29,9 @@ type Lambda struct { logger Logger } -func (l *Lambda) HandleEvent(event events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) { +func (l *Lambda) HandleEvent(event events.LambdaFunctionURLRequest) (events.LambdaFunctionURLResponse, error) { var data shared.Case - log.Print(event) - response := events.APIGatewayProxyResponse{ + response := events.LambdaFunctionURLResponse{ StatusCode: 500, Body: "{\"code\":\"INTERNAL_SERVER_ERROR\",\"detail\":\"Internal server error\"}", } @@ -94,7 +92,7 @@ func main() { l := &Lambda{ ddb: dynamodb.New(sess), - tableName: "deeds", + tableName: os.Getenv("DDB_TABLE_NAME_DEEDS"), logger: logging.New(os.Stdout, "opg-data-lpa-deed"), } diff --git a/lambda/shared/problem.go b/lambda/shared/problem.go index 7d57eaa0..ecde2118 100644 --- a/lambda/shared/problem.go +++ b/lambda/shared/problem.go @@ -42,7 +42,7 @@ var ProblemInvalidRequest Problem = Problem{ Detail: "Invalid request", } -func (problem Problem) Respond() (events.APIGatewayProxyResponse, error) { +func (problem Problem) Respond() (events.LambdaFunctionURLResponse, error) { var errorString = "" for _, ve := range problem.Errors { errorString += fmt.Sprintf("%s %s, ", ve.Source, ve.Detail) @@ -64,7 +64,7 @@ func (problem Problem) Respond() (events.APIGatewayProxyResponse, error) { body = []byte("{\"code\":\"INTERNAL_SERVER_ERROR\",\"detail\":\"Internal server error\"}") } - return events.APIGatewayProxyResponse{ + return events.LambdaFunctionURLResponse{ StatusCode: code, Body: string(body), }, nil diff --git a/signer/go.mod b/signer/go.mod new file mode 100644 index 00000000..4c7eceac --- /dev/null +++ b/signer/go.mod @@ -0,0 +1,7 @@ +module github.com/ministryofjustice/opg-data-lpa-deed/signer + +go 1.20 + +require github.com/aws/aws-sdk-go v1.45.24 + +require github.com/jmespath/go-jmespath v0.4.0 // indirect diff --git a/signer/go.sum b/signer/go.sum new file mode 100644 index 00000000..a67754b2 --- /dev/null +++ b/signer/go.sum @@ -0,0 +1,42 @@ +github.com/aws/aws-sdk-go v1.45.24 h1:TZx/CizkmCQn8Rtsb11iLYutEQVGK5PK9wAhwouELBo= +github.com/aws/aws-sdk-go v1.45.24/go.mod h1:aVsgQcEevwlmQ7qHE9I3h+dtQgpqhFB+i8Phjh7fkwI= +github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg= +github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo= +github.com/jmespath/go-jmespath/internal/testify v1.5.1 h1:shLQSRRSCCPj3f2gpwzGwWFoC7ycTf1rcQZHOlsJ6N8= +github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.1.0/go.mod h1:Cx3nUiGt4eDBEyega/BKRp+/AlGL8hYe7U9odMt2Cco= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/term v0.1.0/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/signer/main.go b/signer/main.go new file mode 100644 index 00000000..f7e15fe5 --- /dev/null +++ b/signer/main.go @@ -0,0 +1,47 @@ +package main + +import ( + "fmt" + "io" + "log" + "net/http" + "os" + "strings" + "time" + + "github.com/aws/aws-sdk-go/aws/session" + v4 "github.com/aws/aws-sdk-go/aws/signer/v4" +) + +func main() { + sess := session.Must(session.NewSession()) + signer := v4.NewSigner(sess.Config.Credentials) + + method := os.Args[1] + host := os.Args[2] + body := strings.NewReader(os.Args[3]) + + req, err := http.NewRequest(method, host, body) + if err != nil { + panic(err) + } + + req.Header.Add("Content-type", "application/json") + + signer.Sign(req, body, "lambda", "eu-west-1", time.Now()) + + client := http.Client{} + resp, err := client.Do(req) + if err != nil { + panic(err) + } + + if resp.StatusCode >= 400 { + log.Printf("Response code %d", resp.StatusCode) + buf := new(strings.Builder) + _, _ = io.Copy(buf, resp.Body) + log.Printf("error response: %s", buf.String()) + + panic(fmt.Sprintf("invalid status code %d", resp.StatusCode)) + } +} diff --git a/terraform/environment/dynamodb.tf b/terraform/environment/dynamodb.tf index 339d81a8..07f4be74 100644 --- a/terraform/environment/dynamodb.tf +++ b/terraform/environment/dynamodb.tf @@ -2,7 +2,8 @@ resource "aws_dynamodb_table" "deeds_table" { name = "deeds-${local.environment_name}" billing_mode = "PAY_PER_REQUEST" deletion_protection_enabled = local.environment.is_production - stream_enabled = false + stream_enabled = true + stream_view_type = "NEW_AND_OLD_IMAGES" hash_key = "uid" server_side_encryption { diff --git a/terraform/environment/outputs.tf b/terraform/environment/outputs.tf new file mode 100644 index 00000000..b5315fdd --- /dev/null +++ b/terraform/environment/outputs.tf @@ -0,0 +1,4 @@ +output "lambda_url" { + description = "Public URL of 'create' Lambda function" + value = module.eu_west_1.lambda_url +} diff --git a/terraform/environment/region/kms.tf b/terraform/environment/region/kms.tf new file mode 100644 index 00000000..573e67f7 --- /dev/null +++ b/terraform/environment/region/kms.tf @@ -0,0 +1,72 @@ +resource "aws_kms_key" "cloudwatch" { + description = "CloudWatch ${terraform.workspace} ${data.aws_region.current.name}" + deletion_window_in_days = 10 + policy = data.aws_iam_policy_document.cloudwatch_kms.json + enable_key_rotation = true + + provider = aws.region +} + +resource "aws_kms_alias" "cloudwatch_standard_alias" { + name = "alias/cloudwatch-${var.environment_name}" + target_key_id = aws_kms_key.cloudwatch.key_id + + provider = aws.region +} + +data "aws_iam_policy_document" "cloudwatch_kms" { + statement { + sid = "Enable Root account permissions on Key" + effect = "Allow" + actions = ["kms:*"] + resources = ["*"] + principals { + type = "AWS" + identifiers = [ + "arn:aws:iam::${data.aws_caller_identity.current.account_id}:root", + ] + } + } + statement { + sid = "Allow Key to be used for Encryption" + effect = "Allow" + resources = ["*"] + actions = [ + "kms:Encrypt", + "kms:Decrypt", + "kms:ReEncrypt*", + "kms:GenerateDataKey*", + "kms:DescribeKey", + ] + principals { + type = "Service" + identifiers = ["logs.${data.aws_region.current.name}.amazonaws.com"] + } + } + statement { + sid = "Key Administrator" + effect = "Allow" + resources = ["*"] + actions = [ + "kms:Create*", + "kms:Describe*", + "kms:Enable*", + "kms:List*", + "kms:Put*", + "kms:Update*", + "kms:Revoke*", + "kms:Disable*", + "kms:Get*", + "kms:Delete*", + "kms:TagResource", + "kms:UntagResource", + "kms:ScheduleKeyDeletion", + "kms:CancelKeyDeletion" + ] + + principals { + type = "AWS" + identifiers = ["arn:aws:iam::${data.aws_caller_identity.current.account_id}:role/breakglass"] + } + } +} diff --git a/terraform/environment/region/main.tf b/terraform/environment/region/main.tf new file mode 100644 index 00000000..9b595f64 --- /dev/null +++ b/terraform/environment/region/main.tf @@ -0,0 +1,51 @@ +locals { + functions = toset([ + "create", + # "get", + # "update", + ]) +} + +module "lambda" { + for_each = local.functions + source = "../../modules/lambda" + + environment_name = var.environment_name + lambda_name = each.key + ecr_image_uri = "${data.aws_ecr_repository.lambda[each.key].repository_url}:${var.app_version}" + cloudwatch_kms_key_id = aws_kms_key.cloudwatch.arn + + environment_variables = { + DDB_TABLE_NAME_DEEDS = var.dynamodb_name + } + + providers = { + aws = aws.region + } +} + +data "aws_ecr_repository" "lambda" { + for_each = local.functions + name = "lpa-store/lambda/api-${each.key}" + provider = aws.management +} + +resource "aws_iam_role_policy" "lambda" { + for_each = local.functions + name = "LambdaAllowDynamoDB" + role = module.lambda[each.key].iam_role_id + policy = data.aws_iam_policy_document.lambda_access_ddb.json + provider = aws.region +} + +data "aws_iam_policy_document" "lambda_access_ddb" { + statement { + sid = "allowDynamoDB" + effect = "Allow" + resources = [var.dynamodb_arn] + actions = [ + "dynamodb:PutItem", + "dynamodb:GetItem", + ] + } +} diff --git a/terraform/environment/region/outputs.tf b/terraform/environment/region/outputs.tf new file mode 100644 index 00000000..b001474c --- /dev/null +++ b/terraform/environment/region/outputs.tf @@ -0,0 +1,4 @@ +output "lambda_url" { + description = "Public URL of 'create' Lambda function" + value = module.lambda["create"].function_url +} diff --git a/terraform/environment/region/terraform.tf b/terraform/environment/region/terraform.tf new file mode 100644 index 00000000..5f2854df --- /dev/null +++ b/terraform/environment/region/terraform.tf @@ -0,0 +1,25 @@ +terraform { + required_version = ">= 1.4.0" + + required_providers { + aws = { + source = "hashicorp/aws" + configuration_aliases = [ + aws.region, + aws.management, + ] + } + } +} + +data "aws_region" "current" { + provider = aws.region +} + +data "aws_caller_identity" "current" { + provider = aws.region +} + +data "aws_default_tags" "current" { + provider = aws.region +} diff --git a/terraform/environment/region/variables.tf b/terraform/environment/region/variables.tf new file mode 100644 index 00000000..8d8518dc --- /dev/null +++ b/terraform/environment/region/variables.tf @@ -0,0 +1,19 @@ +variable "environment_name" { + description = "The name of the environment the region is deployed to" + type = string +} + +variable "app_version" { + description = "Version of application to deploy" + type = string +} + +variable "dynamodb_arn" { + description = "ARN of DynamoDB table" + type = string +} + +variable "dynamodb_name" { + description = "Name of DynamoDB table" + type = string +} diff --git a/terraform/environment/regions.tf b/terraform/environment/regions.tf new file mode 100644 index 00000000..bd2f9bac --- /dev/null +++ b/terraform/environment/regions.tf @@ -0,0 +1,27 @@ +module "eu_west_1" { + source = "./region" + + app_version = var.app_version + dynamodb_arn = aws_dynamodb_table.deeds_table.arn + dynamodb_name = aws_dynamodb_table.deeds_table.name + environment_name = local.environment_name + + providers = { + aws.region = aws.eu_west_1 + aws.management = aws.management_eu_west_1 + } +} + +module "eu_west_2" { + source = "./region" + + app_version = var.app_version + dynamodb_arn = aws_dynamodb_table_replica.deeds_table.arn + dynamodb_name = aws_dynamodb_table.deeds_table.name + environment_name = local.environment_name + + providers = { + aws.region = aws.eu_west_2 + aws.management = aws.management_eu_west_2 + } +} diff --git a/terraform/environment/terraform.tf b/terraform/environment/terraform.tf index de16922a..03574ae2 100644 --- a/terraform/environment/terraform.tf +++ b/terraform/environment/terraform.tf @@ -60,7 +60,7 @@ provider "aws" { } provider "aws" { - alias = "management" + alias = "management_eu_west_1" region = "eu-west-1" assume_role { @@ -72,3 +72,17 @@ provider "aws" { tags = local.default_tags } } + +provider "aws" { + alias = "management_eu_west_2" + region = "eu-west-2" + + assume_role { + role_arn = "arn:aws:iam::311462405659:role/${var.management_role}" + session_name = "terraform-session" + } + + default_tags { + tags = local.default_tags + } +} diff --git a/terraform/environment/variables.tf b/terraform/environment/variables.tf index b4d7be11..7f816db7 100644 --- a/terraform/environment/variables.tf +++ b/terraform/environment/variables.tf @@ -39,3 +39,9 @@ variable "management_role" { type = string default = "lpa-store-ci" } + +variable "app_version" { + description = "Version of application to deploy" + type = string + default = "latest" +} diff --git a/terraform/modules/lambda/iam.tf b/terraform/modules/lambda/iam.tf new file mode 100644 index 00000000..26bc8dfb --- /dev/null +++ b/terraform/modules/lambda/iam.tf @@ -0,0 +1,69 @@ +resource "aws_iam_role" "lambda" { + name = "lambda-${var.lambda_name}-${var.environment_name}-${data.aws_region.current.name}" + assume_role_policy = data.aws_iam_policy_document.lambda_assume.json + + lifecycle { + create_before_destroy = true + } +} + +data "aws_iam_policy_document" "lambda_assume" { + statement { + actions = ["sts:AssumeRole"] + + principals { + type = "Service" + identifiers = ["lambda.amazonaws.com"] + } + } +} + +resource "aws_iam_role_policy_attachment" "aws_xray_write_only_access" { + role = aws_iam_role.lambda.name + policy_arn = "arn:aws:iam::aws:policy/AWSXrayWriteOnlyAccess" +} + +resource "aws_iam_role_policy_attachment" "vpc_access_execution_role" { + role = aws_iam_role.lambda.name + policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole" +} + +resource "aws_iam_role_policy" "lambda" { + name = "LambdaAllowLogging" + role = aws_iam_role.lambda.id + policy = data.aws_iam_policy_document.lambda.json +} + +data "aws_iam_policy_document" "lambda" { + statement { + sid = "allowLogging" + effect = "Allow" + resources = [aws_cloudwatch_log_group.lambda.arn] + actions = [ + "logs:CreateLogStream", + "logs:PutLogEvents", + "logs:DescribeLogStreams" + ] + } +} + +resource "aws_lambda_permission" "allow_lambda_execution_operator" { + statement_id = "AllowExecutionOperator" + action = "lambda:InvokeFunction" + function_name = aws_lambda_function.main.function_name + principal = "arn:aws:iam::${data.aws_caller_identity.current.account_id}:role/operator" +} + +resource "aws_lambda_permission" "allow_lambda_url_execution_operator" { + statement_id = "AllowUrlExecutionOperator" + action = "lambda:InvokeFunctionUrl" + function_name = aws_lambda_function.main.function_name + principal = "arn:aws:iam::${data.aws_caller_identity.current.account_id}:role/operator" +} + +resource "aws_lambda_permission" "allow_lambda_url_execution_ci" { + statement_id = "AllowUrlExecutionCI" + action = "lambda:InvokeFunctionUrl" + function_name = aws_lambda_function.main.function_name + principal = "arn:aws:iam::${data.aws_caller_identity.current.account_id}:role/lpa-store-ci" +} diff --git a/terraform/modules/lambda/main.tf b/terraform/modules/lambda/main.tf new file mode 100644 index 00000000..e1d5d860 --- /dev/null +++ b/terraform/modules/lambda/main.tf @@ -0,0 +1,29 @@ +resource "aws_cloudwatch_log_group" "lambda" { + name = "/aws/lambda/${var.lambda_name}-${var.environment_name}" + kms_key_id = var.cloudwatch_kms_key_id +} + +resource "aws_lambda_function" "main" { + function_name = "${var.lambda_name}-${var.environment_name}" + image_uri = var.ecr_image_uri + package_type = "Image" + role = aws_iam_role.lambda.arn + timeout = 5 + depends_on = [aws_cloudwatch_log_group.lambda] + + tracing_config { + mode = "Active" + } + + dynamic "environment" { + for_each = length(keys(var.environment_variables)) == 0 ? [] : [true] + content { + variables = var.environment_variables + } + } +} + +resource "aws_lambda_function_url" "main" { + function_name = aws_lambda_function.main.function_name + authorization_type = "AWS_IAM" +} diff --git a/terraform/modules/lambda/outputs.tf b/terraform/modules/lambda/outputs.tf new file mode 100644 index 00000000..6c23ced8 --- /dev/null +++ b/terraform/modules/lambda/outputs.tf @@ -0,0 +1,9 @@ +output "function_url" { + description = "Public URL of Lambda function" + value = aws_lambda_function_url.main.function_url +} + +output "iam_role_id" { + description = "ID of IAM role created for lambda" + value = aws_iam_role.lambda.id +} diff --git a/terraform/modules/lambda/terraform.tf b/terraform/modules/lambda/terraform.tf new file mode 100644 index 00000000..8815440e --- /dev/null +++ b/terraform/modules/lambda/terraform.tf @@ -0,0 +1,13 @@ +terraform { + required_version = ">= 1.4.0" + + required_providers { + aws = { + source = "hashicorp/aws" + } + } +} + +data "aws_region" "current" {} + +data "aws_caller_identity" "current" {} diff --git a/terraform/modules/lambda/variables.tf b/terraform/modules/lambda/variables.tf new file mode 100644 index 00000000..9a186c70 --- /dev/null +++ b/terraform/modules/lambda/variables.tf @@ -0,0 +1,25 @@ +variable "environment_name" { + description = "The name of the environment the lambda is deployed to" + type = string +} + +variable "lambda_name" { + description = "The name of the lambda function" + type = string +} + +variable "ecr_image_uri" { + description = "The URI of the image lambda should use" + type = string +} + +variable "cloudwatch_kms_key_id" { + description = "KMS key used to encrypt CloudWatch logs" + type = string +} + +variable "environment_variables" { + description = "A map that defines environment variables for the Lambda Function" + type = map(string) + default = {} +}