Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@fertapric
Last active December 10, 2018 05:00
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fertapric/e7e985b53a9b1c328e5e014000ec8440 to your computer and use it in GitHub Desktop.
Save fertapric/e7e985b53a9b1c328e5e014000ec8440 to your computer and use it in GitHub Desktop.
Script to run a Docker container with the same configuration as the ECS service: environment variables and Docker image. It uses ecs-env: https://gist.github.com/fertapric/4ae3a1209e7118c275821ce35512daec
$ ecs-run
Run a Docker container with the same configuration as an ECS service.
It uses the same image and environment variables of the ECS task definition.
Supported AWS CLI environment variables:
- AWS_ACCESS_KEY_ID: AWS access key.
- AWS_SECRET_ACCESS_KEY: AWS secret key.
- AWS_SESSION_TOKEN: session token.
- AWS_DEFAULT_REGION: AWS region.
- AWS_DEFAULT_PROFILE: name of the CLI profile to use.
- AWS_CONFIG_FILE: path to a CLI config file.
Usage: ecs-run [OPTIONS] SERVICE [COMMAND] [ARG...]
Options:
-h, --help Print usage
--add-host list Add a custom host-to-IP mapping (host:ip) (default [])
-a, --attach list Attach to STDIN, STDOUT or STDERR (default [])
--blkio-weight uint16 Block IO (relative weight), between 10 and 1000, or 0 to disable (default 0)
--blkio-weight-device weighted-device Block IO weight (relative device weight) (default [])
--cap-add list Add Linux capabilities (default [])
--cap-drop list Drop Linux capabilities (default [])
--cgroup-parent string Optional parent cgroup for the container
--cidfile string Write the container ID to the file
--cpu-count int CPU count (Windows only)
--cpu-percent int CPU percent (Windows only)
--cpu-period int Limit CPU CFS (Completely Fair Scheduler) period
--cpu-quota int Limit CPU CFS (Completely Fair Scheduler) quota
--cpu-rt-period int Limit CPU real-time period in microseconds
--cpu-rt-runtime int Limit CPU real-time runtime in microseconds
-c, --cpu-shares int CPU shares (relative weight)
--cpus decimal Number of CPUs (default 0.000)
--cpuset-cpus string CPUs in which to allow execution (0-3, 0,1)
--cpuset-mems string MEMs in which to allow execution (0-3, 0,1)
--credentialspec string Credential spec for managed service account (Windows only)
-d, --detach Run container in background and print container ID
--detach-keys string Override the key sequence for detaching a container
--device list Add a host device to the container (default [])
--device-read-bps throttled-device Limit read rate (bytes per second) from a device (default [])
--device-read-iops throttled-device Limit read rate (IO per second) from a device (default [])
--device-write-bps throttled-device Limit write rate (bytes per second) to a device (default [])
--device-write-iops throttled-device Limit write rate (IO per second) to a device (default [])
--disable-content-trust Skip image verification (default true)
--dns list Set custom DNS servers (default [])
--dns-option list Set DNS options (default [])
--dns-search list Set custom DNS search domains (default [])
--entrypoint string Overwrite the default ENTRYPOINT of the image
-e, --env list Set environment variables (default [])
--env-file list Read in a file of environment variables (default [])
--expose list Expose a port or a range of ports (default [])
--group-add list Add additional groups to join (default [])
--health-cmd string Command to run to check health
--health-interval duration Time between running the check (ns|us|ms|s|m|h) (default 0s)
--health-retries int Consecutive failures needed to report unhealthy
--health-timeout duration Maximum time to allow one check to run (ns|us|ms|s|m|h) (default 0s)
-h, --hostname string Container host name
--init Run an init inside the container that forwards signals and reaps processes
--init-path string Path to the docker-init binary
-i, --interactive Keep STDIN open even if not attached
--io-maxbandwidth string Maximum IO bandwidth limit for the system drive (Windows only)
--io-maxiops uint Maximum IOps limit for the system drive (Windows only)
--ip string Container IPv4 address (e.g. 172.30.100.104)
--ip6 string Container IPv6 address (e.g. 2001:db8::33)
--ipc string IPC namespace to use
--isolation string Container isolation technology
--kernel-memory string Kernel memory limit
-l, --label list Set meta data on a container (default [])
--label-file list Read in a line delimited file of labels (default [])
--link list Add link to another container (default [])
--link-local-ip list Container IPv4/IPv6 link-local addresses (default [])
--log-driver string Logging driver for the container
--log-opt list Log driver options (default [])
--mac-address string Container MAC address (e.g. 92:d0:c6:0a:29:33)
-m, --memory string Memory limit
--memory-reservation string Memory soft limit
--memory-swap string Swap limit equal to memory plus swap: '-1' to enable unlimited swap
--memory-swappiness int Tune container memory swappiness (0 to 100) (default -1)
--name string Assign a name to the container
--network string Connect a container to a network (default "default")
--network-alias list Add network-scoped alias for the container (default [])
--no-healthcheck Disable any container-specified HEALTHCHECK
--oom-kill-disable Disable OOM Killer
--oom-score-adj int Tune host's OOM preferences (-1000 to 1000)
--pid string PID namespace to use
--pids-limit int Tune container pids limit (set -1 for unlimited)
--privileged Give extended privileges to this container
-p, --publish list Publish a container's port(s) to the host (default [])
-P, --publish-all Publish all exposed ports to random ports
--read-only Mount the container's root filesystem as read only
--restart string Restart policy to apply when a container exits (default "no")
--rm Automatically remove the container when it exits
--runtime string Runtime to use for this container
--security-opt list Security Options (default [])
--shm-size string Size of /dev/shm, default value is 64MB
--sig-proxy Proxy received signals to the process (default true)
--stop-signal string Signal to stop a container, SIGTERM by default (default "SIGTERM")
--stop-timeout int Timeout (in seconds) to stop a container
--storage-opt list Storage driver options for the container (default [])
--sysctl map Sysctl options (default map[])
--tmpfs list Mount a tmpfs directory (default [])
-t, --tty Allocate a pseudo-TTY
--ulimit ulimit Ulimit options (default [])
-u, --user string Username or UID (format: <name|uid>[:<group|gid>])
--userns string User namespace to use
--uts string UTS namespace to use
-v, --volume list Bind mount a volume (default [])
--volume-driver string Optional volume driver for the container
--volumes-from list Mount volumes from the specified container(s) (default [])
-w, --workdir string Working directory inside the container
#!/bin/bash
set -e
function docker_run_options {
echo "$(docker run --help)" | grep "^\s*-" | grep -v -- "--help"
}
function is_docker_run_option {
# Supported option formats:
# -o
# -o value
# --option
# --option value
# --option=value
# -o, --option
# -o, --option value
# -o, --option=value
option=$(docker_run_options | grep "\s$1[, =]")
if [ -n "$option" ]
then
return 0
else
return 1
fi
}
function is_docker_run_option_with_arguments {
# docker_run_options | grep "\s$1[, =]"
# These commands filter the list of options to extract the given option.
#
# Option without argument:
# --rm Automatically remove the container when it exits
# Option with argument:
# -v, --volume list Bind mount a volume (default [])
#
# sed -E "s/[[:space:]]{2,}[a-zA-Z0-9].*//g"
# This command removes the description. It assumes descriptions can be detected by
# two or more spaces followed by a letter or a number:
#
# Option without argument:
# --rm
# Option with argument:
# -v, --volume list
#
# sed -E "s/-[^ ]+//g"
# tr -d " "
# This command removes the option flags. Basically, everything that starts with a
# dash. It also trims the final result:
#
# Option without argument:
#
# Option with argument:
# list
#
argument=$(
docker_run_options \
| grep "\s$1[, =]" \
| sed -E "s/[[:space:]]{2,}[a-zA-Z0-9].*//g" \
| sed -E "s/-[^ ]+//g" \
| tr -d " "
)
if [ -n "$argument" ]
then
return 0
else
return 1
fi
}
function print_help {
echo "Run a Docker container with the same configuration as an ECS service."
echo
echo "It uses the same image and environment variables of the ECS task definition."
echo
echo "Supported AWS CLI environment variables:"
echo " - AWS_ACCESS_KEY_ID: AWS access key."
echo " - AWS_SECRET_ACCESS_KEY: AWS secret key."
echo " - AWS_SESSION_TOKEN: session token."
echo " - AWS_DEFAULT_REGION: AWS region."
echo " - AWS_DEFAULT_PROFILE: name of the CLI profile to use."
echo " - AWS_CONFIG_FILE: path to a CLI config file."
echo
echo "Usage: $0 [OPTIONS] SERVICE [COMMAND] [ARG...]"
echo
echo "Options:"
echo " -h, --help Print usage"
echo "$(docker_run_options)" | sed "s/^/ /g"
exit
}
docker_options=()
while [[ "$1" == -* ]]
do
if is_docker_run_option $1
then
if is_docker_run_option_with_arguments $1
then
docker_options+=($1 $2 )
shift
else
docker_options+=($1 )
fi
shift
else
print_help
fi
done
if [ $# -eq 0 ]
then
print_help
fi
service=$1; shift
region=${AWS_DEFAULT_REGION-eu-west-1}
image=$(
aws ecs describe-task-definition --task-definition $service-taskdef --region $region \
| grep image \
| grep $service \
| cut -d '"' -f 4
)
env_vars=$(${BASH_SOURCE%/*}/ecs-env $service)
docker_env_vars=()
for env_var in $env_vars; do docker_env_vars+=(-e "$env_var"); done
docker run "${docker_env_vars[@]}" "${docker_options[@]}" $image "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment