Skip to content

masterpointio/terraform-aws-ssm-agent

Repository files navigation

Masterpoint Logo

Release

terraform-aws-ssm-agent

A Terraform Module to create a simple, autoscaled SSM Agent EC2 instance along with its corresponding IAM instance profile. This is intended to be used with SSM Session Manager and other SSM functionality to replace the need for a Bastion host and further secure your cloud environment. This includes an SSM document to enable session logging to S3 and CloudWatch for auditing purposes.

Big shout out to the following projects which this project uses/depends on/mentions:

  1. gjbae1212/gossm
  2. cloudposse/terraform-null-label
  3. cloudposse/terraform-aws-vpc
  4. cloudposse/terraform-aws-dynamic-subnets
  5. cloudposse/terraform-aws-kms-key
  6. cloudposse/terraform-aws-s3-bucket
  7. Cloud Posse's Terratest Setup.

SSM Agent Session Manager Example

Usage

Module Usage:

module "ssm_agent" {
  source     = "masterpointio/ssm-agent/aws"
  version    = "0.15.1"
  stage      = var.stage
  namespace  = var.namespace
  vpc_id     = module.vpc.vpc_id
  subnet_ids = module.subnets.private_subnet_ids
}

module "vpc" {
  source  = "cloudposse/vpc/aws"
  version = "2.1.0"

  namespace = var.namespace
  stage     = var.stage
  name      = var.name

  ipv4_primary_cidr_block          = "10.0.0.0/16"
  assign_generated_ipv6_cidr_block = true
}

module "subnets" {
  source    = "cloudposse/dynamic-subnets/aws"
  version   = "2.3.0"
  namespace = var.namespace
  stage     = var.stage

  availability_zones = var.availability_zones
  vpc_id             = module.vpc.vpc_id
  igw_id             = [module.vpc.igw_id]
  ipv4_cidr_block    = [module.vpc.vpc_cidr_block]
  ipv6_enabled       = var.ipv6_enabled
}

Connecting to your new SSM Agent:

INSTANCE_ID=$(aws autoscaling describe-auto-scaling-instances | jq --raw-output ".AutoScalingInstances | .[0] | .InstanceId")
aws ssm start-session --target $INSTANCE_ID

OR

Use the awesome gossm project.

Requirements

Name Version
terraform >= 1.0
aws >= 5.0
time >= 0.7

Providers

Name Version
aws 5.37.0

Modules

Name Source Version
kms_key cloudposse/kms-key/aws 0.12.1
logs_bucket cloudposse/s3-bucket/aws 3.1.2
logs_label cloudposse/label/null 0.25.0
role_label cloudposse/label/null 0.25.0
this cloudposse/label/null 0.25.0

Resources

Name Type
aws_autoscaling_group.default resource
aws_cloudwatch_log_group.session_logging resource
aws_iam_instance_profile.default resource
aws_iam_role.default resource
aws_iam_role_policy.session_logging resource
aws_iam_role_policy_attachment.default resource
aws_launch_template.default resource
aws_security_group.default resource
aws_security_group_rule.allow_all_egress resource
aws_ssm_document.session_logging resource
aws_ami.amazon_linux_2 data source
aws_caller_identity.current data source
aws_iam_policy_document.default data source
aws_iam_policy_document.session_logging data source
aws_region.current data source
aws_s3_bucket.logs_bucket data source

Inputs

Name Description Type Default Required
additional_security_group_ids Security groups that will be attached to the app instances list(string) [] no
additional_tag_map Additional key-value pairs to add to each map in tags_as_list_of_maps. Not added to tags or id.
This is for some rare cases where resources want additional configuration of tags
and therefore take a list of maps with tag key, value, and additional configuration.
map(string) {} no
ami The AMI to use for the SSM Agent EC2 Instance. If not provided, the latest Amazon Linux 2023 AMI will be used. Note: This will update periodically as AWS releases updates to their AL2023 AMI. Pin to a specific AMI if you would like to avoid these updates. string "" no
associate_public_ip_address Associate public IP address bool null no
attributes ID element. Additional attributes (e.g. workers or cluster) to add to id,
in the order they appear in the list. New attributes are appended to the
end of the list. The elements of the list are joined by the delimiter
and treated as a single ID element.
list(string) [] no
cloudwatch_retention_in_days The number of days to retain session logs in CloudWatch. This is only relevant if the session_logging_enabled variable is true. number 365 no
context Single object for setting entire context at once.
See description of individual variables for details.
Leave string and numeric variables as null to use default value.
Individual variable settings (non-null) override settings in context object,
except for attributes, tags, and additional_tag_map, which are merged.
any
{
"additional_tag_map": {},
"attributes": [],
"delimiter": null,
"descriptor_formats": {},
"enabled": true,
"environment": null,
"id_length_limit": null,
"label_key_case": null,
"label_order": [],
"label_value_case": null,
"labels_as_tags": [
"unset"
],
"name": null,
"namespace": null,
"regex_replace_chars": null,
"stage": null,
"tags": {},
"tenant": null
}
no
create_run_shell_document Whether or not to create the SSM-SessionManagerRunShell SSM Document. bool true no
delimiter Delimiter to be used between ID elements.
Defaults to - (hyphen). Set to "" to use no delimiter at all.
string null no
descriptor_formats Describe additional descriptors to be output in the descriptors output map.
Map of maps. Keys are names of descriptors. Values are maps of the form
{<br> format = string<br> labels = list(string)<br>}
(Type is any so the map values can later be enhanced to provide additional options.)
format is a Terraform format string to be passed to the format() function.
labels is a list of labels, in order, to pass to format() function.
Label values will be normalized before being passed to format() so they will be
identical to how they appear in id.
Default is {} (descriptors output will be empty).
any {} no
desired_capacity Desired number of instances in the Auto Scaling Group number 1 no
enabled Set to false to prevent the module from creating any resources bool null no
environment ID element. Usually used for region e.g. 'uw2', 'us-west-2', OR role 'prod', 'staging', 'dev', 'UAT' string null no
id_length_limit Limit id to this many characters (minimum 6).
Set to 0 for unlimited length.
Set to null for keep the existing setting, which defaults to 0.
Does not affect id_full.
number null no
instance_type The instance type to use for the SSM Agent EC2 instance. string "t4g.nano" no
key_pair_name The name of the key-pair to associate with the SSM Agent instances. This can be (and probably should) left empty unless you specifically plan to use AWS-StartSSHSession. string null no
label_key_case Controls the letter case of the tags keys (label names) for tags generated by this module.
Does not affect keys of tags passed in via the tags input.
Possible values: lower, title, upper.
Default value: title.
string null no
label_order The order in which the labels (ID elements) appear in the id.
Defaults to ["namespace", "environment", "stage", "name", "attributes"].
You can omit any of the 6 labels ("tenant" is the 6th), but at least one must be present.
list(string) null no
label_value_case Controls the letter case of ID elements (labels) as included in id,
set as tag values, and output by this module individually.
Does not affect values of tags passed in via the tags input.
Possible values: lower, title, upper and none (no transformation).
Set this to title and set delimiter to "" to yield Pascal Case IDs.
Default value: lower.
string null no
labels_as_tags Set of labels (ID elements) to include as tags in the tags output.
Default is to include all labels.
Tags with empty values will not be included in the tags output.
Set to [] to suppress all generated tags.
Notes:
The value of the name tag, if included, will be the id, not the name.
Unlike other null-label inputs, the initial setting of labels_as_tags cannot be
changed in later chained modules. Attempts to change it will be silently ignored.
set(string)
[
"default"
]
no
max_size Maximum number of instances in the Auto Scaling Group number 2 no
metadata_http_endpoint_enabled Whether or not to enable the metadata http endpoint bool true no
metadata_http_protocol_ipv6_enabled Enable IPv6 metadata endpoint bool false no
metadata_imdsv2_enabled Whether or not the metadata service requires session tokens,
also referred to as Instance Metadata Service Version 2 (IMDSv2).
bool true no
min_size Minimum number of instances in the Auto Scaling Group number 1 no
monitoring_enabled Enable detailed monitoring of instance bool true no
name ID element. Usually the component or solution name, e.g. 'app' or 'jenkins'.
This is the only ID element not also included as a tag.
The "name" tag is set to the full id string. There is no tag with the value of the name input.
string null no
namespace ID element. Usually an abbreviation of your organization name, e.g. 'eg' or 'cp', to help ensure generated IDs are globally unique string null no
permissions_boundary The ARN of the permissions boundary that will be applied to the SSM Agent role. string "" no
protect_from_scale_in Allows setting instance protection for scale in actions on the ASG. bool false no
regex_replace_chars Terraform regular expression (regex) string.
Characters matching the regex will be removed from the ID elements.
If not set, "/[^a-zA-Z0-9-]/" is used to remove all characters other than hyphens, letters and digits.
string null no
region The region to deploy the S3 bucket for session logs. If not supplied, the module will use the current region. string "" no
scale_in_protected_instances Behavior when encountering instances protected from scale in are found. Available behaviors are Refresh, Ignore, and Wait. Default is Ignore. string "Ignore" no
session_logging_bucket_name The name of the S3 Bucket to ship session logs to. This will remove creation of an independent session logging bucket. This is only relevant if the session_logging_enabled variable is true. string "" no
session_logging_enabled To enable CloudWatch and S3 session logging or not. Note this does not apply to SSH sessions as AWS cannot log those sessions. bool true no
session_logging_encryption_enabled To enable CloudWatch and S3 session logging encryption or not. bool true no
session_logging_kms_key_alias Alias name for session_logging KMS Key. This is only applied if 2 conditions are met: (1) session_logging_kms_key_arn is unset, (2) session_logging_encryption_enabled = true. string "alias/session_logging" no
session_logging_kms_key_arn BYO KMS Key instead of using the created KMS Key. The session_logging_encryption_enabled variable must still be true for this to be applied. string "" no
session_logging_ssm_document_name Name for session_logging SSM document. This is only applied if 2 conditions are met: (1) session_logging_enabled = true, (2) create_run_shell_document = true. string "SSM-SessionManagerRunShell" no
stage ID element. Usually used to indicate role, e.g. 'prod', 'staging', 'source', 'build', 'test', 'deploy', 'release' string null no
subnet_ids The Subnet IDs which the SSM Agent will run in. These should be private subnets. list(string) n/a yes
tags Additional tags (e.g. {'BusinessUnit': 'XYZ'}).
Neither the tag keys nor the tag values will be modified by this module.
map(string) {} no
tenant ID element _(Rarely used, not included by default)_. A customer identifier, indicating who this instance of a resource is for string null no
user_data The user_data to use for the SSM Agent EC2 instance. You can use this to automate installation of psql or other required command line tools. string "#!/bin/bash\n# NOTE: Since we're using a latest Amazon Linux AMI, we shouldn't need this,\n# but we'll update it to be sure.\ncd /tmp\nsudo yum install -y https://s3.amazonaws.com/ec2-downloads-windows/SSMAgent/latest/linux_amd64/amazon-ssm-agent.rpmnsudo systemctl enable amazon-ssm-agent\nsudo systemctl start amazon-ssm-agent\n" no
vpc_id The ID of the VPC which the EC2 Instance will run in. string n/a yes

Outputs

Name Description
autoscaling_group_id The ID of the SSM Agent Autoscaling Group.
instance_name The name tag value of the Bastion instance.
launch_template_id The ID of the SSM Agent Launch Template.
role_id The ID of the SSM Agent Role.
security_group_id The ID of the SSM Agent Security Group.
session_logging_bucket_arn The ARN of the SSM Agent Session Logging S3 Bucket.
session_logging_bucket_id The ID of the SSM Agent Session Logging S3 Bucket.