Use the Conformity Knowledge Base AI to help improve your Cloud Posture

Web-Tier EC2 Instance Using IAM Roles

Trend Cloud One™ – Conformity is a continuous assurance tool that provides peace of mind for your cloud infrastructure, delivering over 1000 automated best practice checks.

Risk Level: Medium (should be achieved)
Rule ID: EC2-069

Ensure that your web-tier Amazon EC2 instances are using IAM roles to grant any necessary permissions to the web applications running on these instances as the applications can assume the role applied to their instances. This conformity rule assumes that all the AWS cloud resources (including EC2 instances) created within your web tier are tagged with <web_tier_tag>:<web_tier_tag_value>, where <web_tier_tag> represents the tag name and <web_tier_tag_value> represents the tag value. Before running this rule by the Trend Cloud One™ – Conformity engine, the web-tier tags must be configured in the rule settings, on your Conformity account console.

This rule can help you with the following compliance standards:

  • CISAWSF
  • APRA
  • MAS

For further details on compliance standards supported by Conformity, see here.

This rule resolution is part of the Conformity Security & Compliance tool for AWS.

Security

Web applications that run on Amazon EC2 instances need credentials in order to access other AWS services. An IAM role attached to a web-tier instance provides these authentication credentials in a secure way. Multiple benefits are gained when your web-tier applications are using IAM roles to sign their API requests with AWS credentials. For example, you don't have to manage credentials anymore as the authentication details provided by the IAM roles are temporary and automatically rotated behind the scenes. You can also use a single role for multiple EC2 instances within your web tier, manage the role policies in one place, and allow policies to propagate automatically to all the associated instances. You can also restrict which role an IAM user can assign to a web-tier EC2 instance during the launch process in order to stop the user from trying to gain elevated access.

Note: Make sure that you replace all <web_tier_tag>:<web_tier_tag_value> tag placeholders outlined in the conformity rule content with your own tag set created for the web tier.


Audit

To determine if your web-tier EC2 instances are using IAM roles to sign AWS API requests, perform the following actions:

Using AWS Console

01 Sign in to your Trend Cloud One™ – Conformity account, access Web-Tier EC2 Instances with IAM Roles conformity rule settings, and identify the tag set defined for the AWS cloud resources created for your web tier (e.g. <web_tier_tag>:<web_tier_tag_value>).

02 Sign in to the AWS Management Console.

03 Navigate to Amazon EC2 console at https://console.aws.amazon.com/ec2/.

04 In the navigation panel, under Instances, choose Instances.

05 Click inside the Filter instances box located under the console top menu, and choose the tag set defined for your web-tier resources, identified at step no. 1, from the Tags list. This filtering technique will return only the EC2 instances tagged for the web tier. If the web-tier tag is not included in the Tags list, there are no Amazon EC2 instances tagged within your web tier and the Audit process ends here. If the web-tier tag is included in the Tags list and the Amazon EC2 console returns one or more instances, continue the Audit process with the next step.

06 Select the web-tier Amazon EC2 instance that you want to examine.

07 Choose the Details tab from the console bottom panel to access the instance configuration details.

08 In the Instance summary section, check the IAM Role configuration attribute value. If the IAM Role attribute does not have a value, the selected web-tier Amazon EC2 instance is not associated with an IAM role (instance profile).

09 Repeat steps no. 6 – 8 for each web-tier Amazon EC2 instance returned as result at step no. 5.

10 Change the AWS cloud region from the navigation bar and repeat the audit process for other regions.

Using AWS CLI

01 Sign in to your Trend Cloud One™ – Conformity account, access Web-Tier EC2 Instances with IAM Roles conformity rule settings, and identify the tag set defined for the AWS cloud resources created for your web tier (e.g. <web_tier_tag>:<web_tier_tag_value>).

02 Run describe-instances command (OSX/Linux/UNIX) using custom query filters to list the IDs of all the Amazon EC2 instances available in the selected AWS cloud region:

aws ec2 describe-instances
  --region us-east-1
  --output table
  --query 'Reservations[*].Instances[*].InstanceId'

03 The command output should return a table with the requested instance IDs:

-------------------------
|   DescribeInstances   |
+-----------------------+
|  i-01234abcd1234abcd  |
|  i-0abcabcabc1234567  |
+-----------------------+

04 Run describe-tags command (OSX/Linux/UNIX) using the ID of the Amazon EC2 instance that you want to examine as the identifier parameter and custom query filters to describe the tags defined for the selected EC2 instance:

aws ec2 describe-tags
  --region us-east-1
  --filters "Name=resource-id,Values=i-01234abcd1234abcd"
  --query 'Tags[*].{Value:Value, Key:Key}'

05 The describe-tags command should return one of the following outputs:

  1. If the command output returns an empty array (i.e. []), as shown in the example below, the verified Amazon EC2 instance is not tagged, therefore the Audit process for the selected resource ends here:
    []
    
  2. If the describe-tags command output returns a tag set that is different from the one identified at step no. 1, as shown in the example below, the verified EC2 instance does not belong to your web tier, therefore the Audit process for the selected resource ends here:
    [
    	{
    		"Value": "Tenancy",
    		"Key": "Default"
    	}
    ]
    
  3. If the command output returns a tag set that matches the one identified at step no. 1 (e.g. <web_tier_tag>:<web_tier_tag_value>), as shown in the example below, the verified EC2 instance is tagged as a web-tier resource, therefore the Audit process continues with the next step:
    [
    	{
    		"Key": "<web_tier_tag>",
    		"Value": "<web_tier_tag_value>"
    	}
    ]
    

06 Run describe-instances command (OSX/Linux/UNIX) using the ID of the web-tier EC2 instance that you want to examine as the identifier parameter and custom query filters to determine whether the selected Amazon EC2 instance is configured with an IAM role:

aws ec2 describe-instances
  --region us-east-1
  --instance-ids i-01234abcd1234abcd
  --query 'Reservations[*].Instances[*].IamInstanceProfile.Arn[]'

07 The command output should return the Amazon Resource Name (ARN) of the associated IAM role:

[]

If the describe-instances command output returns an empty array (i.e. []), as shown in the example above, the selected web-tier Amazon EC2 instance is not associated with an IAM role (instance profile).

08 Repeat steps no. 6 and 7 for each web-tier EC2 instance available in the selected AWS region.

09 Change the AWS cloud region by updating the --region command parameter value and repeat the audit process for other regions.

Remediation / Resolution

To assign IAM roles to your existing web-tier EC2 instances, you must re-create your EC2 instances with the appropriate instance profile configuration. To implement IAM role based access for your web-tier Amazon EC2 instances, perform the following actions:

Using AWS CloudFormation

01 CloudFormation template (JSON). Replace <web_tier_tag> and <web_tier_tag_value> tag placeholders with your own tag set created for the web tier:

{
	"AWSTemplateFormatVersion": "2010-09-09",
	"Description": "Web-Tier Instance with IAM role",
	"Resources": {
		"IAMRole": {
			"Type": "AWS::IAM::Role",
			"Properties": {
				"RoleName": "cc-web-tier-iam-role",
				"Description": "IAM role that provides full access to Web-Tier EC2 instances",
				"AssumeRolePolicyDocument": {
					"Version": "2012-10-17",
					"Statement": [
					{
						"Effect": "Allow",
						"Principal": {
							"Service": [
								"ec2.amazonaws.com"
							]
						},
						"Action": [
							"sts:AssumeRole"
						]
					}
					]
				},
				"ManagedPolicyArns": [
					"arn:aws:iam::aws:policy/AmazonEC2FullAccess"
				],
				"Path": "/"
			}
		},
		"EC2InstanceProfile": {
			"Type": "AWS::IAM::InstanceProfile",
			"Properties": {
				"InstanceProfileName": "WebTierInstanceProfile",
				"Path": "/",
				"Roles": [
					{
					"Ref": "IAMRole"
					}
				]
			}
		},
		"WebTierInstance": {
			"Type": "AWS::EC2::Instance",
			"Properties": {
				"ImageId": "ami-0abcd1234abcd1234",
				"InstanceType": "t3.micro",
				"KeyName": "ssh-key",
				"SubnetId": "subnet-abcd1234",
				"SecurityGroupIds": [
					"sg-01234abcd1234abcd"
				],
				"Tags": [
					{
						"Key": "<web_tier_tag>",
						"Value": "<web_tier_tag_value>"
					}
				],
				"IamInstanceProfile": {
					"Ref": "EC2InstanceProfile"
				}
			}
		}
	}
}

02 CloudFormation template (YAML):

AWSTemplateFormatVersion: '2010-09-09'
    Description: Web-Tier Instance with IAM role
    Resources:
        IAMRole:
        Type: AWS::IAM::Role
        Properties:
            RoleName: cc-web-tier-iam-role
            Description: IAM role that provides full access to Web-Tier EC2 instances
            AssumeRolePolicyDocument:
            Version: '2012-10-17'
            Statement:
            - Effect: Allow
                Principal:
                Service:
                - ec2.amazonaws.com
                Action:
                - sts:AssumeRole
            ManagedPolicyArns:
            - arn:aws:iam::aws:policy/AmazonEC2FullAccess
            Path: "/"
        EC2InstanceProfile:
        Type: AWS::IAM::InstanceProfile
        Properties:
            InstanceProfileName: WebTierInstanceProfile
            Path: "/"
            Roles:
            - Ref: IAMRole
        WebTierInstance:
        Type: AWS::EC2::Instance
        Properties:
            ImageId: ami-0abcd1234abcd1234
            InstanceType: t3.micro
            KeyName: ssh-key
            SubnetId: subnet-abcd1234
            SecurityGroupIds:
            - sg-01234abcd1234abcd
            Tags:
            - Key: "<web_tier_tag>"
            Value: "<web_tier_tag_value>"
            IamInstanceProfile:
            Ref: EC2InstanceProfile

Using Terraform (AWS Provider)

01 Terraform configuration file (.tf). Replace <web_tier_tag> and <web_tier_tag_value> tag placeholders with your own tag set created for the web tier:

terraform {
	required_providers {
		aws = {
			source  = "hashicorp/aws"
			version = "~> 3.27"
		}
	}

	required_version = ">= 0.14.9"
}

provider "aws" {
	profile = "default"
	region  = "us-east-1"
}

resource "aws_iam_role" "instance-role" {
	name = "iam-role"
	path = "/"
	managed_policy_arns = [ "arn:aws:iam::aws:policy/AmazonEC2FullAccess" ]

	assume_role_policy = <<EOF
	{
		"Version": "2012-10-17",
		"Statement": [
			{
				"Action": "sts:AssumeRole",
				"Principal": {
					"Service": "ec2.amazonaws.com"
				},
				"Effect": "Allow"
			}
		]
	}
	EOF
}

resource "aws_iam_instance_profile" "instance-profile" {
	name = "ec2-instance-profile"
	role = "${aws_iam_role.instance-role.name}"
}

resource "aws_instance" "web-tier-instance" {

	ami = "ami-0abcd1234abcd1234"
	instance_type = "t3.micro"
	key_name = "ssh-key"
	subnet_id = "subnet-abcd1234"
	vpc_security_group_ids = [ "sg-01234abcd1234abcd" ]
	iam_instance_profile = "${aws_iam_instance_profile.instance-profile.name}"

	tags = {
		Name = "<web_tier_tag>"
		Value = "<web_tier_tag_value>"
	}

}

Using AWS Console

01 Sign in to the AWS Management Console.

02 Navigate to Amazon IAM console at https://console.aws.amazon.com/iam/.

03 In the navigation panel, under Access management, choose Roles.

04 Click on the Create role button from the console top menu to create the IAM role that allows web-tier EC2 instances to call AWS services on your behalf:

  1. On the Select type of trusted entity page, perform the following operations:
    • Select the AWS service category.
    • For Choose a use case, select the EC2 – Allows EC2 instances to call AWS services on your behalf use case. Choose Next: Permissions to continue the setup process.
  2. On the Attach permissions policies page, select the customer-managed and/or AWS-managed policies that you want to attach to your new IAM role. If you need to create a new customer-managed policy for your IAM role, choose Create policy and run the setup wizard based on your access requirements. (Optional) For Set permissions boundary, set a permissions boundary to control the maximum permissions that the new role can have. Choose Next: Tags to continue.
  3. On the Add tags (optional) page, use the configuration controls to create and apply tags to the new IAM role. You can use the tags to organize, track, or control access for your role. Choose Next: Review to continue.
  4. On the Review page, provide a unique name for your role in the Role name box, enter a short description (optional), review the resource configuration information, and choose Create role to create your new IAM role.

05 Navigate to Amazon EC2 console at https://console.aws.amazon.com/ec2/.

06 In the navigation panel, under Instances, choose Instances.

07 Select the web-tier EC2 instance that you want to re-create (the one without an instance profile).

08 Click on the Actions dropdown menu from the console top menu, select Image and templates, and choose Create image.

09 On the Create image setup page, provide the following information:

  1. In the Image name box, enter a unique name for the new AMI.
  2. (Optional) In the Image description box, provide a short description that reflects the usage of the selected web-tier instance.
  3. Deselect Enable under No reboot so that Amazon EC2 service can guarantee the file system integrity for the new AMI.
  4. (Optional) For Tags, choose Tag image and snapshots together and use the Add tag button to create and apply user-defined tags to the new image.
  5. Choose Create image to create your new AMI.

10 Once the new image is ready, use it to re-create your web-tier Amazon EC2 instance with the new IAM role (instance profile). On the Instances listing page, choose Launch instances and perform the following operations:

  1. For Step 1: Choose an Amazon Machine Image (AMI), choose My AMIs tab, and select the Amazon Machine Image (AMI) created at step no. 9.
  2. For Step 2: Choose an Instance Type, select the required instance type (must match the instance type used by the source web-tier instance). Choose Next: Configure Instance Details to continue the setup process.
  3. For Step 3: Configure Instance Details, perform the following operations:
    • From the IAM role dropdown list, select the name of the IAM role created at step no. 4.
    • Configure the instance network, identity management, behavior, and metadata settings. The new instance configuration must match the source instance configuration. Choose Next: Add Storage to continue the setup process.
  4. For Step 4: Add Storage, configure the storage device settings. Choose Next: Add Tags to set up the instance tags.
  5. For Step 5: Add Tags, use the Add tag button to apply the web-tier tags (e.g. <web_tier_tag>:<web_tier_tag_value>) to the new Amazon EC2 instance. Use the same web-tier tag set as the one defined in the conformity rule settings. Choose Configure Security Group to continue the setup process.
  6. For Step 6: Configure Security Group, choose Select an existing security group and select the security group(s) associated with the source web-tier EC2 instance. Choose Review and Launch to continue.
  7. For Step 7: Review Instance Launch, review your EC2 instance configuration details, then choose Launch.
  8. In the Select an existing key pair or create a new key pair configuration box, select Choose an existing key pair and use the same key pair as the source instance. Select the I acknowledge that I have access to the selected private key file (<key-name>.pem), and that without this file, I won't be able to log into my instance checkbox for confirmation, then choose Launch Instances to launch your new web-tier Amazon EC2 instance.
  9. Choose View Instances to return to the Instances page.

11 (Optional) After you have verified your new web-tier EC2 instance, you can transfer the Elastic IP (EIP) from the source instance to the new instance. If the source instance does not have an EIP attached, you must update the domain DNS record(s) or any other application settings that point to the source instance, in order to switch to the new instance IP. To transfer the Elastic IP, perform the following actions:

  1. In the navigation panel, under Network & Security, select Elastic IPs.
  2. Select the Elastic IP address attached to the source instance, choose Actions, and select Disassociate Elastic IP address.
  3. In the Dissociate Elastic IP address confirmation box, review the EIP details, then choose Disassociate.
  4. Select the same IP address, choose Actions and select Associate Elastic IP address.
  5. In the Associate Elastic IP address configuration box, perform the following:
    • For Resource type, choose Instance.
    • For Instance, select the ID of the new web-tier instance created at step no. 10.
    • Choose Associate to attach the Elastic IP.

12 (Optional) You can terminate the source web-tier EC2 instance in order to stop incurring charges for that resource. To shut down the instance, perform the following actions:

  1. In the navigation panel, under Instances, choose Instances.
  2. Select the web-tier instance that you want to terminate.
  3. Choose Instance state and select Terminate instance.
  4. In the Terminate instance? confirmation box, review the instance details, then choose Terminate to shut down the selected Amazon EC2 instance.

13 Repeat steps no. 2 – 12 for each web-tier EC2 instance that you want to re-create, available within the current AWS region.

14 Change the AWS cloud region from the console navigation bar and repeat the remediation process for other regions.

Using AWS CLI

01 Define the trust relationship policy for your new IAM role. Paste the following policy document to a JSON file named cc-iam-role-trust-policy.json:

{
	"Version": "2012-10-17",
	"Statement": [
		{
			"Effect": "Allow",
			"Principal": {
				"Service": "ec2.amazonaws.com"
			},
			"Action": "sts:AssumeRole"
		}
	]
}

02 Run create-role command (OSX/Linux/UNIX) to create the IAM role that allows web-tier EC2 instances to call AWS services on your behalf using the trust relationship policy defined at the previous step:

aws iam create-role
  --role-name cc-web-tier-iam-role
  --assume-role-policy-document file://cc-iam-role-trust-policy.json

03 The command output should return the metadata available for the new IAM role:

{
	"Role": {
		"AssumeRolePolicyDocument": {
			"Version": "2012-10-17",
			"Statement": [
				{
					"Action": "sts:AssumeRole",
					"Effect": "Allow",
					"Principal": {
						"Service": "ec2.amazonaws.com"
					}
				}
			]
		},
		"RoleId": "AAAABBBBCCCCDDDDEEEE",
		"CreateDate": "2021-01-25T10:00:00Z",
		"RoleName": "cc-web-tier-iam-role",
		"Path": "/",
		"Arn": "arn:aws:iam::123456789012:role/cc-web-tier-iam-role"
	}
}

04 Run attach-role-policy command (OSX/Linux/UNIX) to attach an AWS-managed policy to the newly created web-tier IAM role. Use the --policy-arn command parameter to specify the ARN of the AWS-managed policy that you want to attach to your IAM role. In the following command request example, the "AmazonEC2FullAccess" managed policy provides full access to Amazon EC2 via AWS Management Console (the command does not produce an output):

aws iam attach-role-policy
  --role-name cc-web-tier-iam-role
  --policy-arn arn:aws:iam::aws:policy/AmazonEC2FullAccess

05 Create the required web-tier instance profile. An instance profile is basically a container for the IAM role that is attached to the Amazon EC2 instance during the launch process. Run create-instance-profile command (OSX/Linux/UNIX) to create the new instance profile:

aws iam create-instance-profile
  --region us-east-1
  --instance-profile-name cc-web-tier-instance-profile

06 The command output should return the metadata for the new instance profile:

{
	"InstanceProfile": {
		"InstanceProfileId": "ABCDABCDABCDABCDABCD",
		"Roles": [],
		"CreateDate": "2021-04-08T10:00:00.000Z",
		"InstanceProfileName": "cc-web-tier-instance-profile",
		"Path": "/",
		"Arn": "arn:aws:iam::123456789012:instance-profile/cc-web-tier-instance-profile"
	}
}

07 Run add-role-to-instance-profile command (OSX/Linux/UNIX) to integrate the web-tier IAM role created at step no. 2 with the instance profile created at step no. 5 (the command does not produce an output):

aws iam add-role-to-instance-profile
  --role-name cc-web-tier-iam-role
  --instance-profile-name cc-web-tier-instance-profile

08 Run describe-instances command (OSX/Linux/UNIX) to list the configuration information available for the web-tier EC2 instance that you want to re-create (the one without an instance profile):

aws ec2 describe-instances
  --region us-east-1
  --instance-ids i-01234abcd1234abcd
  --query 'Reservations[*].Instances[]'

09 The command output should return an array with the requested configuration information:

[
	{
		"AmiLaunchIndex": 0,
		"ImageId": "ami-0abcd1234abcd1234",
		"InstanceId": "i-01234abcd1234abcd",
		"InstanceType": "t2.micro",
		"KeyName": "conformity",
		"LaunchTime": "2021-03-10T10:00:00+00:00",
		"Monitoring": {
			"State": "disabled"
		},
		"Placement": {
			"AvailabilityZone": "us-east-1a",
			"GroupName": "",
			"Tenancy": "default"
		},
		"PrivateDnsName": "ip-10-0-0-15.ec2.internal",
		"PrivateIpAddress": "10.0.0.15",
		"ProductCodes": [],
		"PublicDnsName": "ec2-10-0-1-20.compute-1.amazonaws.com",
		"PublicIpAddress": "10.0.1.20",
		"State": {
			"Code": 16,
			"Name": "running"
		},
		"StateTransitionReason": "",
		"SubnetId": "subnet-abcd1234",
		"VpcId": "vpc-1234abcd",
		"Architecture": "x86_64",
		"BlockDeviceMappings": [
			{
				"DeviceName": "/dev/xvda",
				"Ebs": {
					"AttachTime": "2021-03-10T10:00:00+00:00",
					"DeleteOnTermination": true,
					"Status": "attached",
					"VolumeId": "vol-0abcd1234abcd1234"
				}
			}
		],
		"ClientToken": "",
		"EbsOptimized": false,
		"EnaSupport": true,
		"Hypervisor": "xen",
		"IamInstanceProfile": "",
		"NetworkInterfaces": [
			{
				"Association": {
					"IpOwnerId": "amazon",
					"PublicDnsName": "ec2-10-0-1-20.compute-1.amazonaws.com",
					"PublicIp": "10.0.1.20"
				},
				"Attachment": {
					"AttachTime": "2021-03-10T10:00:00+00:00",
					"AttachmentId": "eni-attach-0abcd1234abcd1234",
					"DeleteOnTermination": true,
					"DeviceIndex": 0,
					"Status": "attached",
					"NetworkCardIndex": 0
				},
				"Description": "Primary network interface",
				"Groups": [
					{
						"GroupName": "cc-prod-security-group",
						"GroupId": "sg-01234abcd1234abcd"
					}
				],
				"Ipv6Addresses": [],
				"MacAddress": "0e:53:19:7b:62:6b",
				"NetworkInterfaceId": "eni-0abcd1234abcd1234",
				"OwnerId": "123456789012",
				"PrivateDnsName": "ip-10-0-0-15.ec2.internal",
				"PrivateIpAddress": "10.0.0.15",
				"PrivateIpAddresses": [
					{
						"Association": {
							"IpOwnerId": "amazon",
							"PublicDnsName": "ec2-10-0-1-20.compute-1.amazonaws.com",
							"PublicIp": "10.0.1.20"
						},
						"Primary": true,
						"PrivateDnsName": "ip-10-0-0-15.ec2.internal",
						"PrivateIpAddress": "10.0.0.15"
					}
				],
				"SourceDestCheck": true,
				"Status": "in-use",
				"SubnetId": "subnet-abcd1234",
				"VpcId": "vpc-1234abcd",
				"InterfaceType": "interface"
			}
		],
		"RootDeviceName": "/dev/xvda",
		"RootDeviceType": "ebs",
		"SecurityGroups": [
			{
				"GroupName": "cc-prod-security-group",
				"GroupId": "sg-01234abcd1234abcd"
			}
		],
		"SourceDestCheck": true,
		"VirtualizationType": "hvm",
		"CpuOptions": {
			"CoreCount": 2,
			"ThreadsPerCore": 4
		},
		"CapacityReservationSpecification": {
			"CapacityReservationPreference": "open"
		},
		"HibernationOptions": {
			"Configured": false
		},
		"MetadataOptions": {
			"State": "applied",
			"HttpTokens": "optional",
			"HttpPutResponseHopLimit": 1,
			"HttpEndpoint": "enabled"
		},
		"EnclaveOptions": {
			"Enabled": false
		}
	}
]

10 Run create-image command (OSX/Linux/UNIX) to create an image from the source EC2 instance described at the previous step. Include the --no-reboot command parameter to guarantee the file system integrity for your new AMI:

aws ec2 create-image
  --region us-east-1
  --instance-id i-01234abcd1234abcd
  --name "Web-Tier EC2 Instance AMI"
  --description "Web-Tier Stack AMI"
  --no-reboot

11 The command output should return the ID of the new Amazon Machine Image (AMI):

{
	"ImageId": "ami-0abcdabcdabcdabcd"
}

12 Execute run-instances command (OSX/Linux/UNIX) to launch a new web-tier Amazon EC2 instance from the AMI created at the previous steps. Use the information returned at step no. 9 for the instance configuration parameters. Configure the --iam-instance-profile command parameter with the name of the instance profile created at step no. 5. Replace <web_tier_tag> and <web_tier_tag_value> with your own web-tier tag set:

aws ec2 run-instances
  --region us-east-1
  --image-id ami-0abcdabcdabcdabcd
  --count 1
  --instance-type t2.micro
  --key-name conformity
  --security-group-ids sg-01234abcd1234abcd
  --iam-instance-profile Name="cc-web-tier-instance-profile"
  --tag-specifications 'ResourceType=instance,Tags=[{Key=<web_tier_tag>,Value=<web_tier_tag_value>}]'

13 The command output should return the configuration metadata for the newly created EC2 instance:

{
	"Groups": [],
	"Instances": [
		{
			"AmiLaunchIndex": 0,
			"ImageId": "ami-0abcdabcdabcdabcd",
			"InstanceId": "i-01234123412341234",
			"InstanceType": "t2.micro",
			"KeyName": "conformity.aws",
			"LaunchTime": "2021-03-22T17:29:43+00:00",
			"Monitoring": {
				"State": "disabled"
			},
			"Placement": {
				"AvailabilityZone": "us-east-1e",
				"GroupName": "",
				"Tenancy": "default"
			},
			"PrivateDnsName": "ip-10-0-0-5.ec2.internal",
			"PrivateIpAddress": "10.0.0.5",
			"ProductCodes": [],
			"PublicDnsName": "",
			"State": {
				"Code": 0,
				"Name": "pending"
			},
			"StateTransitionReason": "",
			"SubnetId": "subnet-abcdabcd",
			"VpcId": "vpc-1234abcd",
			"Architecture": "x86_64",
			"BlockDeviceMappings": [],
			"EbsOptimized": false,
			"EnaSupport": true,
			"Hypervisor": "xen",
			"IamInstanceProfile": {
				"Arn": "arn:aws:iam::123456789012:instance-profile/cc-web-tier-instance-profile",
				"Id": "ABCDABCDABCDABCDABCD"
			},
			"NetworkInterfaces": [
				{
					"Attachment": {
						"AttachTime": "2021-03-22T17:29:43+00:00",
						"AttachmentId": "eni-attach-0abcd1234abcd1234",
						"DeleteOnTermination": true,
						"DeviceIndex": 0,
						"Status": "attaching",
						"NetworkCardIndex": 0
					},
					"Description": "",
					"Groups": [
						{
							"GroupName": "cc-prod-security-group",
							"GroupId": "sg-01234abcd1234abcd"
						}
					],
					"Ipv6Addresses": [],
					"MacAddress": "06:00:c7:12:51:99",
					"NetworkInterfaceId": "eni-0abcd1234abcd1234",
					"OwnerId": "123456789012",
					"PrivateDnsName": "ip-10-0-0-5.ec2.internal",
					"PrivateIpAddress": "10.0.0.5",
					"PrivateIpAddresses": [
						{
							"Primary": true,
							"PrivateDnsName": "ip-10-0-0-5.ec2.internal",
							"PrivateIpAddress": "10.0.0.5"
						}
					],
					"SourceDestCheck": true,
					"Status": "in-use",
					"SubnetId": "subnet-abcdabcd",
					"VpcId": "vpc-1234abcd",
					"InterfaceType": "interface"
				}
			],
			"RootDeviceName": "/dev/xvda",
			"RootDeviceType": "ebs",
			"SecurityGroups": [
				{
					"GroupName": "cc-prod-security-group",
					"GroupId": "sg-01234abcd1234abcd"
				}
			],
			"SourceDestCheck": true,
			"Tags": [
				{
					"Key": "&tl;web_tier_tag>",
					"Value": "&tl;web_tier_tag_value>"
				}
			],
			"StateReason": {
				"Code": "pending",
				"Message": "pending"
			},
			"VirtualizationType": "hvm",
		"HibernationOptions": {
				"Configured": true
			},
			"CpuOptions": {
				"CoreCount": 1,
				"ThreadsPerCore": 1
			},
			"CapacityReservationSpecification": {
				"CapacityReservationPreference": "open"
			},
			"MetadataOptions": {
				"State": "pending",
				"HttpTokens": "optional",
				"HttpPutResponseHopLimit": 1,
				"HttpEndpoint": "enabled"
			},
			"EnclaveOptions": {
				"Enabled": false
			}
		}
	],
	"OwnerId": "123456789012",
	"ReservationId": "r-0abcd1234abcd1234"
}

14 (Optional) After you have verified your new web-tier EC2 instance, you can transfer the Elastic IP (EIP) from the source instance to the new instance. If the source instance does not have an EIP attached, you must update the domain DNS record(s) or any other application settings that point to the source instance, in order to switch to the new instance IP. To transfer the Elastic IP, perform the following commands:

  1. Run disassociate-address command (OSX/Linux/UNIX) to detach the Elastic IP (EIP) address from the source EC2 instance (the command does not produce an output):
    aws ec2 disassociate-address
      --association-id eipassoc-0abcd1234abcd1234
    
  2. Run associate-address command (OSX/Linux/UNIX) to associate the EIP address detached at the previous step with the new EC2 instance:
    aws ec2 associate-address
      --instance-id i-01234123412341234
      --allocation-id eipalloc-0abcd1234abcd1234
    
  3. The command output should return the EIP association ID:
    {
    	"AssociationId": "eipassoc-01234abcd1234abcd"
    }
    

15 (Optional) You can terminate the source web-tier EC2 instance in order to stop incurring charges for that resource. To shut down the instance, run terminate-instances command (OSX/Linux/UNIX) using the source instance ID as the identifier parameter:

aws ec2 terminate-instances
  --instance-ids i-01234abcd1234abcd

16 The output should return the terminate-instances command request metadata:

{
	"TerminatingInstances": [
		{
			"CurrentState": {
				"Code": 32,
				"Name": "shutting-down"
			},
			"InstanceId": "i-01234abcd1234abcd",
			"PreviousState": {
				"Code": 16,
				"Name": "running"
			}
		}
	]
}

17 Repeat steps no. 1 – 16 for each web-tier EC2 instance that you want to re-create, available in the selected AWS region.

18 Change the AWS cloud region by updating the --region command parameter value and repeat the remediation process for other regions.

References

Publication date Mar 14, 2018