DEV Community

Cover image for Create AWS Step Function and Lambda using Terraform and GitLab CI
Shubham Pawar
Shubham Pawar

Posted on • Updated on

Create AWS Step Function and Lambda using Terraform and GitLab CI

Install Terraform

  • Download Terraform binary and unzip the package.

  • Set terraform path to unzipped binary location. Terraform runs as a single binary named terraform. Any other files in the package can be safely removed and Terraform will still function.

  • Verify the setup by using command terraform version in CLI.

Install AWS CLI

  • Download and run the AWS CLI MSI installer for Windows (64-bit):

  • To confirm the installation, open the Start menu, search for cmd to open a command prompt window, and at the command prompt use the aws --version command.

0

Build a infrastructure

  • Create a directory for your configuration  mkdir terraform
  • Change the directory and create a file main.tf.

1

  • Initialize the directory with terraform init.

2

  • Run terraform plan to see any changes are required for infrastructure.
  • Format and validate the configuration 3
  • Apply the configuration now with the terraform apply command.

4                      

Configuring Gitlab CI for Terraform

  • Create a file on the root of your repository called .gitlab-ci.yml
  • Get your access key ID and secret access key.
  • Set aws variables go to - gitlab project → settings → CI/CD → Variables

        

Sample GitLab pipeline

stages:
  - validate
  - plan
  - apply
  - destroy
image:
  name: hashicorp/terraform:light
  entrypoint:
    - '/usr/bin/env'
    - 'PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'
before_script:
  - export AWS_ACCESS_KEY=${AWS_ACCESS_KEY_ID}
  - export AWS_SECRET_ACCESS_KEY=${AWS_SECRET_ACCESS_KEY}
  - rm -rf .terraform
  - cd terraform/
  - terraform --version
  - terraform init

validate:
  stage: validate
  script:
    - terraform validate
  only:
    - branches

plan:
  stage: plan
  script:
    - terraform plan -out "planfile"
  dependencies:
    - validate
  artifacts:
    paths:
      - planfile

apply:
  stage: apply
  script:
    - terraform apply -input=false "planfile"
  dependencies:
    - plan
  when: manual
  only:
    - main

destroy:
  stage: destroy
  script:
    - echo "Destroying resources"
    - terraform destroy -state=$STATE --auto-approve
  dependencies:
    - apply
  when: manual
  only:
    refs:
      - main
Enter fullscreen mode Exit fullscreen mode

Sample terraform code for lambda and step function

Oldest comments (1)

Collapse
 
ilidio profile image
Ilídio Martins

It work great form me. Thank you