Sunday, December 22, 2024

Automate AWS deployments with HCP Terraform and GitHub Actio…

Share


Saravanan Gnanaguru is a HashiCorp Ambassador

Using GitHub Actions with HashiCorp Terraform to automate infrastructure as code workflows directly from version control is a popular early path for many developer teams. However, this setup can make it difficult to stop configuration drift as your infrastructure codebase grows.

Rather than running Terraform on the GitHub Actions instance runner, it’s much easier and safer to run configurations remotely via HCP Terraform. This ensures that the creation, modification, and deletion of Terraform resources is handled on a managed cloud platform rather than on the GitHub Actions runner. HCP Terraform has many more systems and safeguards for team Terraform management and drift prevention.

This post shows how to use HCP Terraform to define AWS infrastructure and GitHub Actions to automate infrastructure changes. You’ll learn how to set up a GitHub Actions workflow that interacts with HCP Terraform to automate the deployment of AWS infrastructure, such as Amazon EC2 instances.

»

example repository. The example repository’s GitHub Actions include a workflow that creates the AWS resources defined in the repository. Whenever the repository trigger event happens on the main branch, it runs the workflow defined in the .github/workflows directory. It then performs the infrastructure creation or management in AWS. The figure below outlines the interaction between the GitHub repository, Actions, HCP Terraform, and AWS.

HCP Terraform and GitHub Actions workflow

Here’s how to implement this workflow.

»

»

dynamic provider credentials allow Terraform runs to assume an IAM role through native OpenID Connect (OIDC) integration and obtain temporary security credentials for each run. These AWS credentials allow you to call AWS APIs that the IAM role has access to at runtime. These credentials are usable for only one hour by default, so their usefulness to an attacker is limited.

For more on how to securely access AWS from HCP Terraform with OIDC federation, check out the Access AWS from HCP Terraform with OIDC federation blog.

»

instructions available in the HCP Terraform documentation. This example creates a user API token for the GitHub Action workflow.

Open the GitHub repository with the Terraform configuration.

Click on “Settings” in the repository menu. From the left sidebar, select “Secrets” and then choose “Actions”.

To add a new repository secret, click on “New repository secret”. Name the secret TF_API_TOKEN and add the HCP Terraform API token to the “Value” field. Click “Add secret” to save the new secret.

Naming the secret

By following these steps, you will securely provide your AWS credentials to HCP Terraform and also provide the HCP Terraform API token to GitHub Actions, enabling automated infrastructure deployment through a GitHub Actions workflow.

»

workflow YAML file defining one job with four steps to initialize, plan, apply, and destroy Terraform. This workflow uses the HashiCorp official marketplace actions for performing the Terraform command operations.

# This workflow will create AWS resource using HCP Terraform
# It is reusable workflow that can be called in other workflows
 
name: AWS Infra Creation Using in HCP Terraform
 
on:
 workflow_call:
   secrets:
       TF_API_TOKEN:
           required: true
 push:
   branches: [ "main" ]
 pull_request:
   branches: [ "main" ]
 workflow_dispatch:
 
env:
 tfcode_path: tfcloud_samples/amazon_ec2
 tfc_organisation: demo-tf-org # Replace it with your TFC Org
 tfc_hostname: app.terraform.io
 tfc_workspace: demo-tf-workspace # Replace it with your TFC Workspace
 
jobs:
 aws_tfc_job:
   name: Create AWS Infra Using TFC
 
   runs-on: ubuntu-latest
 
   steps:
   - name: Checkout tf code in runner environment
     uses: actions/checkout@v3.5.2
 
   # Configure HCP Terraform API token, since we are using remote backend option of HCP Terraform in AWS code
   - name: Setup Terraform CLI
     uses: hashicorp/setup-terraform@v2.0.2
     with:
       cli_config_credentials_token: ${{ secrets.TF_API_TOKEN }}
 
   # Add the AWS Creds as ENV variable in HCP Terraform workspace, since the tf run happens in HCP Terraform environment
 
   # Invoke the Terraform commands
   - name: Terraform init and validate
     run: |
       echo `pwd`
       echo "** Running Terraform Init**"
       terraform init
        
       echo "** Running Terraform Validate**"
       terraform validate
     working-directory: ${{ env.tfcode_path }}
 
   - name: Terraform Plan
     uses: hashicorp/tfc-workflows-github/actions/create-run@v1.3.0
     id: run
     with:
       workspace: ${{ env.tfc_workspace }}
       plan_only: true
       message: "Plan Run from GitHub Actions"
       ## Can specify hostname,token,organization as direct inputs
       hostname: ${{ env.tfc_hostname }}
       token: ${{ secrets.TF_API_TOKEN }}
       organization: ${{ env.tfc_organisation }}
 
   - name: Terraform Plan Output
     uses: hashicorp/tfc-workflows-github/actions/plan-output@v1.3.0
     id: plan-output
     with:
       hostname: ${{ env.tfc_hostname }}
       token: ${{ secrets.TF_API_TOKEN }}
       organization: ${{ env.tfc_organisation }}
       plan: ${{ steps.run.outputs.plan_id }}
  
   - name: Reference Plan Output
     run: |
       echo "Plan status: ${{ steps.plan-output.outputs.plan_status }}"
       echo "Resources to Add: ${{ steps.plan-output.outputs.add }}"
       echo "Resources to Change: ${{ steps.plan-output.outputs.change }}"
       echo "Resources to Destroy: ${{ steps.plan-output.outputs.destroy }}"
 
 # Once the user verifies the Terraform Plan, the user can run the Terraform Apply and Destroy commands
 apply_terraform_plan:
     needs: aws_tfc_job
     if: github.event_name == 'workflow_dispatch'
     runs-on: ubuntu-latest
     steps:
     - name: Checkout
       uses: actions/checkout@v3.5.2
     - name: Setup Terraform CLI
       uses: hashicorp/setup-terraform@v2.0.2
       with:
         cli_config_credentials_token: ${{ secrets.TF_API_TOKEN }}
 
     # Invoke the Terraform commands
     - name: Terraform init and validate
       run: |
         echo `pwd`
         echo "** Running Terraform Init**"
         terraform init
      
         echo "** Running Terraform Validate**"
         terraform validate
       working-directory: ${{ env.tfcode_path }}
    
     - name: Terraform Apply
       run: echo "** Running Terraform Apply**"; terraform apply -auto-approve
       working-directory: ${{ env.tfcode_path }}
      - name: Terraform Destroy
       run: echo "** Running Terraform Destroy**"; terraform destroy -auto-approve
       working-directory: ${{ env.tfcode_path }}

Let’s review each section of the workflow.

»

  • workflow_call: This allows the workflow to be reused in other workflows. It requires the TF_API_TOKEN secret.
  • push: Triggers the workflow when there is a push to the main branch.
  • pull_request: Triggers the workflow when a pull request is made to the main branch.
  • workflow_dispatch: Allows the GitHub Actions interface to manually trigger the workflow.
# This workflow will create AWS resource using HCP Terraform
# It is reusable workflow that can be called in other workflows
 
name: AWS Infra Creation Using in HCP Terraform
 
on:
 workflow_call:
   secrets:
       TF_API_TOKEN:
           required: true
 push:
   branches: [ "main" ]
 pull_request:
   branches: [ "main" ]
 workflow_dispatch:

»

»

»

dynamic credentials. The GitHub Actions workflow does not directly handle the credentials, which minimizes the blast radius of compromised credentials through the workflow. HCP Terraform provides additional features like access controls, private module registry, and policy enforcement to ensure that infrastructure changes are secure and compliant with organizational policies.

This guide has walked you through setting up a basic workflow, but the flexibility of both platforms allows for customization to fit your specific needs.

For further questions on best practices, please refer to the GitHub Actions and HCP Terraform FAQs available in this repository. As mentioned before, this repository includes the full code example used in this post. For more information on GitHub Actions, review GitHub’s documentation. To learn more about automating Terraform with GitHub Actions, review the official tutorial on the HashiCorp Developer portal and the starter workflow templates to use HCP Terraform with GitHub Actions.



Source link

Read more

Local News