Skip to content

Instantly share code, notes, and snippets.

@shimo164
Last active May 16, 2023 21:29
Show Gist options
  • Select an option

  • Save shimo164/6677b9a0b7efbd7298a029fd9b6718c8 to your computer and use it in GitHub Desktop.

Select an option

Save shimo164/6677b9a0b7efbd7298a029fd9b6718c8 to your computer and use it in GitHub Desktop.
Update or remove environment variables of a Lambda function using AWS CLI commands in a shell script
#!/bin/bash
# This script updates AWS Lambda environment variables using the AWS CLI.
# It can add or update environment variables, and remove specified variables.
#
# Parameters:
# function_name: The name of the Lambda function you want to update
# region: The AWS region where your Lambda function is located
# env_vars_key_value_upsert: An array containing key-value pairs of environment variables to add or update
# env_vars_key_remove: An array containing keys of environment variables to remove
# Set the region variable
region="ap-northeast-1"
# Set your function name directly in the script
function_name="your_lambda_function_name"
# Define your environment variables as key-value pairs to add or update
env_vars_key_value_upsert=(
"MY_ENV1" "value1"
"MY_ENV2" "value2"
)
# Specify environment variables to remove
env_vars_key_remove=("MY_ENV3" "MY_ENV4")
# Retrieve the existing environment variables
existing_env_vars=$(aws lambda get-function-configuration \
--function-name "$function_name" \
--region "$region" \
--query 'Environment.Variables' \
--output json)
# Update or insert new environment variables
updated_env_vars="$existing_env_vars"
for ((i = 0; i < ${#env_vars_key_value_upsert[@]}; i+=2)); do
updated_env_vars=$(echo "$updated_env_vars" \
| jq --arg key "${env_vars_key_value_upsert[$i]}" --arg value "${env_vars_key_value_upsert[$i + 1]}" \
'.[$key] = $value')
done
# Remove specified environment variables
for key in "${env_vars_key_remove[@]}"; do
updated_env_vars=$(echo "$updated_env_vars" \
| jq --arg key "$key" \
'del(.[$key])')
done
# Update the Lambda function configuration with the new environment variables
aws lambda update-function-configuration \
--function-name "$function_name" \
--environment "{\"Variables\": $updated_env_vars}" \
--region "$region"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment