Home

Awesome

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.

<!-- BEGINNING OF PRE-COMMIT-TERRAFORM DOCS HOOK -->

Requirements

NameVersion
<a name="requirement_terraform"></a> terraform>= 1.0
<a name="requirement_aws"></a> aws>= 5.0
<a name="requirement_time"></a> time>= 0.7

Providers

NameVersion
<a name="provider_aws"></a> aws5.37.0

Modules

NameSourceVersion
<a name="module_kms_key"></a> kms_keycloudposse/kms-key/aws0.12.1
<a name="module_logs_bucket"></a> logs_bucketcloudposse/s3-bucket/aws3.1.2
<a name="module_logs_label"></a> logs_labelcloudposse/label/null0.25.0
<a name="module_role_label"></a> role_labelcloudposse/label/null0.25.0
<a name="module_this"></a> thiscloudposse/label/null0.25.0

Resources

NameType
aws_autoscaling_group.defaultresource
aws_cloudwatch_log_group.session_loggingresource
aws_iam_instance_profile.defaultresource
aws_iam_role.defaultresource
aws_iam_role_policy.session_loggingresource
aws_iam_role_policy_attachment.defaultresource
aws_launch_template.defaultresource
aws_security_group.defaultresource
aws_security_group_rule.allow_all_egressresource
aws_ssm_document.session_loggingresource
aws_ami.amazon_linux_2data source
aws_caller_identity.currentdata source
aws_iam_policy_document.defaultdata source
aws_iam_policy_document.session_loggingdata source
aws_region.currentdata source
aws_s3_bucket.logs_bucketdata source

Inputs

NameDescriptionTypeDefaultRequired
<a name="input_additional_security_group_ids"></a> additional_security_group_idsSecurity groups that will be attached to the app instanceslist(string)[]no
<a name="input_additional_tag_map"></a> additional_tag_mapAdditional key-value pairs to add to each map in tags_as_list_of_maps. Not added to tags or id.<br>This is for some rare cases where resources want additional configuration of tags<br>and therefore take a list of maps with tag key, value, and additional configuration.map(string){}no
<a name="input_ami"></a> amiThe 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
<a name="input_associate_public_ip_address"></a> associate_public_ip_addressAssociate public IP addressboolnullno
<a name="input_attributes"></a> attributesID element. Additional attributes (e.g. workers or cluster) to add to id,<br>in the order they appear in the list. New attributes are appended to the<br>end of the list. The elements of the list are joined by the delimiter<br>and treated as a single ID element.list(string)[]no
<a name="input_cloudwatch_retention_in_days"></a> cloudwatch_retention_in_daysThe number of days to retain session logs in CloudWatch. This is only relevant if the session_logging_enabled variable is true.number365no
<a name="input_context"></a> contextSingle object for setting entire context at once.<br>See description of individual variables for details.<br>Leave string and numeric variables as null to use default value.<br>Individual variable settings (non-null) override settings in context object,<br>except for attributes, tags, and additional_tag_map, which are merged.any<pre>{<br> "additional_tag_map": {},<br> "attributes": [],<br> "delimiter": null,<br> "descriptor_formats": {},<br> "enabled": true,<br> "environment": null,<br> "id_length_limit": null,<br> "label_key_case": null,<br> "label_order": [],<br> "label_value_case": null,<br> "labels_as_tags": [<br> "unset"<br> ],<br> "name": null,<br> "namespace": null,<br> "regex_replace_chars": null,<br> "stage": null,<br> "tags": {},<br> "tenant": null<br>}</pre>no
<a name="input_create_run_shell_document"></a> create_run_shell_documentWhether or not to create the SSM-SessionManagerRunShell SSM Document.booltrueno
<a name="input_delimiter"></a> delimiterDelimiter to be used between ID elements.<br>Defaults to - (hyphen). Set to "" to use no delimiter at all.stringnullno
<a name="input_descriptor_formats"></a> descriptor_formatsDescribe additional descriptors to be output in the descriptors output map.<br>Map of maps. Keys are names of descriptors. Values are maps of the form<br>{<br> format = string<br> labels = list(string)<br>}<br>(Type is any so the map values can later be enhanced to provide additional options.)<br>format is a Terraform format string to be passed to the format() function.<br>labels is a list of labels, in order, to pass to format() function.<br>Label values will be normalized before being passed to format() so they will be<br>identical to how they appear in id.<br>Default is {} (descriptors output will be empty).any{}no
<a name="input_desired_capacity"></a> desired_capacityDesired number of instances in the Auto Scaling Groupnumber1no
<a name="input_enabled"></a> enabledSet to false to prevent the module from creating any resourcesboolnullno
<a name="input_environment"></a> environmentID element. Usually used for region e.g. 'uw2', 'us-west-2', OR role 'prod', 'staging', 'dev', 'UAT'stringnullno
<a name="input_id_length_limit"></a> id_length_limitLimit id to this many characters (minimum 6).<br>Set to 0 for unlimited length.<br>Set to null for keep the existing setting, which defaults to 0.<br>Does not affect id_full.numbernullno
<a name="input_instance_type"></a> instance_typeThe instance type to use for the SSM Agent EC2 instance.string"t4g.nano"no
<a name="input_key_pair_name"></a> key_pair_nameThe 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.stringnullno
<a name="input_label_key_case"></a> label_key_caseControls the letter case of the tags keys (label names) for tags generated by this module.<br>Does not affect keys of tags passed in via the tags input.<br>Possible values: lower, title, upper.<br>Default value: title.stringnullno
<a name="input_label_order"></a> label_orderThe order in which the labels (ID elements) appear in the id.<br>Defaults to ["namespace", "environment", "stage", "name", "attributes"].<br>You can omit any of the 6 labels ("tenant" is the 6th), but at least one must be present.list(string)nullno
<a name="input_label_value_case"></a> label_value_caseControls the letter case of ID elements (labels) as included in id,<br>set as tag values, and output by this module individually.<br>Does not affect values of tags passed in via the tags input.<br>Possible values: lower, title, upper and none (no transformation).<br>Set this to title and set delimiter to "" to yield Pascal Case IDs.<br>Default value: lower.stringnullno
<a name="input_labels_as_tags"></a> labels_as_tagsSet of labels (ID elements) to include as tags in the tags output.<br>Default is to include all labels.<br>Tags with empty values will not be included in the tags output.<br>Set to [] to suppress all generated tags.<br>Notes:<br> The value of the name tag, if included, will be the id, not the name.<br> Unlike other null-label inputs, the initial setting of labels_as_tags cannot be<br> changed in later chained modules. Attempts to change it will be silently ignored.set(string)<pre>[<br> "default"<br>]</pre>no
<a name="input_max_size"></a> max_sizeMaximum number of instances in the Auto Scaling Groupnumber2no
<a name="input_metadata_http_endpoint_enabled"></a> metadata_http_endpoint_enabledWhether or not to enable the metadata http endpointbooltrueno
<a name="input_metadata_http_protocol_ipv6_enabled"></a> metadata_http_protocol_ipv6_enabledEnable IPv6 metadata endpointboolfalseno
<a name="input_metadata_imdsv2_enabled"></a> metadata_imdsv2_enabledWhether or not the metadata service requires session tokens,<br>also referred to as Instance Metadata Service Version 2 (IMDSv2).booltrueno
<a name="input_min_size"></a> min_sizeMinimum number of instances in the Auto Scaling Groupnumber1no
<a name="input_monitoring_enabled"></a> monitoring_enabledEnable detailed monitoring of instancebooltrueno
<a name="input_name"></a> nameID element. Usually the component or solution name, e.g. 'app' or 'jenkins'.<br>This is the only ID element not also included as a tag.<br>The "name" tag is set to the full id string. There is no tag with the value of the name input.stringnullno
<a name="input_namespace"></a> namespaceID element. Usually an abbreviation of your organization name, e.g. 'eg' or 'cp', to help ensure generated IDs are globally uniquestringnullno
<a name="input_permissions_boundary"></a> permissions_boundaryThe ARN of the permissions boundary that will be applied to the SSM Agent role.string""no
<a name="input_protect_from_scale_in"></a> protect_from_scale_inAllows setting instance protection for scale in actions on the ASG.boolfalseno
<a name="input_regex_replace_chars"></a> regex_replace_charsTerraform regular expression (regex) string.<br>Characters matching the regex will be removed from the ID elements.<br>If not set, "/[^a-zA-Z0-9-]/" is used to remove all characters other than hyphens, letters and digits.stringnullno
<a name="input_region"></a> regionThe region to deploy the S3 bucket for session logs. If not supplied, the module will use the current region.string""no
<a name="input_scale_in_protected_instances"></a> scale_in_protected_instancesBehavior when encountering instances protected from scale in are found. Available behaviors are Refresh, Ignore, and Wait. Default is Ignore.string"Ignore"no
<a name="input_session_logging_bucket_name"></a> session_logging_bucket_nameThe 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
<a name="input_session_logging_enabled"></a> session_logging_enabledTo enable CloudWatch and S3 session logging or not. Note this does not apply to SSH sessions as AWS cannot log those sessions.booltrueno
<a name="input_session_logging_encryption_enabled"></a> session_logging_encryption_enabledTo enable CloudWatch and S3 session logging encryption or not.booltrueno
<a name="input_session_logging_kms_key_alias"></a> session_logging_kms_key_aliasAlias 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
<a name="input_session_logging_kms_key_arn"></a> session_logging_kms_key_arnBYO 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
<a name="input_session_logging_ssm_document_name"></a> session_logging_ssm_document_nameName 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
<a name="input_stage"></a> stageID element. Usually used to indicate role, e.g. 'prod', 'staging', 'source', 'build', 'test', 'deploy', 'release'stringnullno
<a name="input_subnet_ids"></a> subnet_idsThe Subnet IDs which the SSM Agent will run in. These should be private subnets.list(string)n/ayes
<a name="input_tags"></a> tagsAdditional tags (e.g. {'BusinessUnit': 'XYZ'}).<br>Neither the tag keys nor the tag values will be modified by this module.map(string){}no
<a name="input_tenant"></a> tenantID element _(Rarely used, not included by default)_. A customer identifier, indicating who this instance of a resource is forstringnullno
<a name="input_user_data"></a> user_dataThe 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
<a name="input_vpc_id"></a> vpc_idThe ID of the VPC which the EC2 Instance will run in.stringn/ayes

Outputs

NameDescription
<a name="output_autoscaling_group_id"></a> autoscaling_group_idThe ID of the SSM Agent Autoscaling Group.
<a name="output_instance_name"></a> instance_nameThe name tag value of the Bastion instance.
<a name="output_launch_template_id"></a> launch_template_idThe ID of the SSM Agent Launch Template.
<a name="output_role_id"></a> role_idThe ID of the SSM Agent Role.
<a name="output_security_group_id"></a> security_group_idThe ID of the SSM Agent Security Group.
<a name="output_session_logging_bucket_arn"></a> session_logging_bucket_arnThe ARN of the SSM Agent Session Logging S3 Bucket.
<a name="output_session_logging_bucket_id"></a> session_logging_bucket_idThe ID of the SSM Agent Session Logging S3 Bucket.
<!-- END OF PRE-COMMIT-TERRAFORM DOCS HOOK -->