How can I change LaunchConfig settings with Cloudformation? - amazon-web-services

I have an AutoScale and a LaunchConfig that I created earlier. I want to replace AMI ID with Cloudformation in LaunchConfig. How can I do that ?
I wonder if there is any sample template that will be a reference for me?

Simple example you can find : https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-launchconfig.html#aws-properties-as-launchconfig--examples
---
AWSTemplateFormatVersion: 2010-09-09
Parameters:
LatestAmiId:
Description: Region specific image from the Parameter Store
Type: 'AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>'
Default: '/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2'
InstanceType:
Description: Amazon EC2 instance type for the instances
Type: String
AllowedValues:
- t3.micro
- t3.small
- t3.medium
Default: t3.micro
Resources:
myLaunchConfig:
Type: AWS::AutoScaling::LaunchConfiguration
Properties:
ImageId: !Ref LatestAmiId
SecurityGroups:
- Ref: "myEC2SecurityGroup"
InstanceType:
Ref: "InstanceType"
BlockDeviceMappings:
- DeviceName: /dev/sda1
Ebs:
VolumeSize: 30
VolumeType: "gp3"
- DeviceName: /dev/sdm
Ebs:
VolumeSize: 100
DeleteOnTermination: "false"

Related

How do I reference launch template version number in auto scaling group?

How do I add a reference to the latest version number of the launch template in the auto-scaling group? The launch template and auto scaling group are in separate files as the launch template is used by other autoscaling groups as well. Can Fn::GetAtt and Ref be used here to refer to another resource located in a separate file? If so, how can I use it? The end goal is when I make an update to the launch template, the autoscaling group should automatically refer to the latest launch template.
Note - I am creating the launch template completely separate before creating the auto-scaling group. It works this way, but I would like the auto-scaling group to refer to the latest launch template. It currently defaults to version 1.
launch_template.yaml
---
AWSTemplateFormatVersion: '2010-09-09'
Resources:
LaunchTemplate:
Type: 'AWS::EC2::LaunchTemplate'
Properties:
LaunchTemplateName: testtemplate
LaunchTemplateData:
IamInstanceProfile:
Arn: >-
arn:aws:iam::blah
ImageId: ami-12345
InstanceRequirements:
InstanceGenerations:
- current
MemoryMiB:
Min: 8192
VCpuCount:
Min: 2
Max: 4
BlockDeviceMappings:
- Ebs:
VolumeSize: 16
VolumeType: gp2
DeleteOnTermination: true
Encrypted: true
DeviceName: /dev/xvda
Monitoring:
Enabled: true
KeyName: testkey
SecurityGroupIds:
- sg-1234
PrivateDnsNameOptions:
HostnameType: ip-name
InstanceInitiatedShutdownBehavior: terminate
autoscaling_group.yaml
---
Resources:
testautoscalinggroup:
Type: AWS::AutoScaling::AutoScalingGroup
Properties:
AutoScalingGroupName: test-autoscaling-group
MaxSize: '2'
MinSize: '1'
DesiredCapacity: '1'
VPCZoneIdentifier:
- subnet-1234
TargetGroupARNs:
- Ref: targetgroup
MixedInstancesPolicy:
InstancesDistribution:
OnDemandAllocationStrategy: lowest-price
LaunchTemplate:
LaunchTemplateSpecification:
LaunchTemplateName: testtemplate
Tags:
- Key: Cluster
Value: test
PropagateAtLaunch: true
dynamicscalingpolicy:
Type: AWS::AutoScaling::ScalingPolicy
Properties:
AutoScalingGroupName:
Ref: testautoscalinggroup
PolicyType: TargetTrackingScaling
TargetTrackingConfiguration:
DisableScaleIn: false
PredefinedMetricSpecification:
PredefinedMetricType: ASGAverageCPUUtilization
TargetValue: 30
targetgroup:
Type: 'AWS::ElasticLoadBalancingV2::TargetGroup'
Properties:
HealthCheckEnabled: true
HealthCheckIntervalSeconds: 30
HealthCheckProtocol: TCP
HealthCheckTimeoutSeconds: 10
HealthyThresholdCount: 3
Name: testtargetgroup
Protocol: TCP_UDP
Port: 53
UnhealthyThresholdCount: 3
VpcId: vpc-1234

AWS- cloudformation "import existing resource" is giving an error

I'm new to cloudformation- I have manual created EC2 instance2 and another EC2 instance1 using cloudformation sample yaml file.
I want to add the manually created instance2 using "import existing resource" option.
but i'm getting below error-
You have modified resources [MyInstance] in your template that are not being imported. Update, create or delete operations cannot be executed during import operations.
below is the yaml file
AWSTemplateFormatVersion: "2010-09-09"
Metadata:
Generator: "former2"
Description: ""
Resources:
EC2Instance:
Type: "AWS::EC2::Instance"
Properties:
ImageId: "ami-0742b4e673072006f"
InstanceType: "t2.micro"
AvailabilityZone: !GetAtt EC2Instance2.AvailabilityZone
Tenancy: "default"
SubnetId: "subnet-09ec4c74f9226b0a5"
EbsOptimized: false
SecurityGroupIds:
- "sg-0ba5c892cb4456045"
SourceDestCheck: true
BlockDeviceMappings:
-
DeviceName: "/dev/xvda"
Ebs:
Encrypted: false
VolumeSize: 8
SnapshotId: "snap-097c45e6d3c6e0d1b"
VolumeType: "gp2"
DeleteOnTermination: true
HibernationOptions:
Configured: false
EnclaveOptions:
Enabled: false
EC2Instance2:
Type: "AWS::EC2::Instance"
DeletionPolicy: "Retain"
Properties:
ImageId: "ami-05fa00d4c63e32076"
InstanceType: "t2.micro"
KeyName: "ThisIsTestKeyPair"
AvailabilityZone: !Sub "${AWS::Region}a"
Tenancy: "default"
SubnetId: "subnet-09ec4c74f9226b0a5"
EbsOptimized: false
SecurityGroupIds:
- "sg-0847c55c903c6b01d"
SourceDestCheck: true
BlockDeviceMappings:
-
DeviceName: "/dev/xvda"
Ebs:
Encrypted: false
VolumeSize: 8
SnapshotId: "snap-0834d7afbcb68e0b7"
VolumeType: "gp2"
DeleteOnTermination: true
Tags:
-
Key: "Name"
Value: "EC-manual-for-CF-testing"
HibernationOptions:
Configured: false
EnclaveOptions:
Enabled: false
You can't create/updated resources in CFN at the same time as you import other resources. You have to do it one, by one:
Remove EC2Instance2 from your template and deploy EC2Instance
Add EC2Instance and import the second instance.

Resizing root volume size of ec2 instance with cloudformation

I have an instance created with cloudformation like below:
EC2Instance:
Type: AWS::EC2::Instance
Properties:
ImageId: !Ref ServerAMI
InstanceType: !Ref ServerInstanceType
KeyName: !Ref KeyName
BlockDeviceMappings:
- DeviceName: /dev/xvda
Ebs:
VolumeSize: 30
NetworkInterfaces:
- AssociatePublicIpAddress: 'false'
DeleteOnTermination: 'true'
DeviceIndex: '0'
GroupSet:
- Ref: ServerSecurityGroup
SubnetId: !Ref SubnetID
Tags:
- { Key: Name, Value: !Ref AWS::StackName }
My root volume in this case is created at 30GB. If I try increase this root volume size by setting the VolumeSize value then my ec2 instance is terminated and recreated.
Yet in the console I am able to increase the size of my root volume without recreation of my instance.
Is there any work around for this in order to prevent ec2 instance from being terminated when trying to increase root volume size via cloudformation?
Edit:
Here is a small test stack I'm using to test this again. Deployed once, then change VolumeSize and redeploy - it wants to replace the instance:
AWSTemplateFormatVersion: '2010-09-09'
Description: Test stack for a single ec2 instance
Parameters:
ServerAMI:
Type: String
Default: ami-096f43ef67d75e998
ServerInstanceType:
Type: String
Default: t2.small
DefaultVPCID:
Type: String
SubnetID:
Type: String
KeyName:
Type: AWS::EC2::KeyPair::KeyName
Resources:
EC2Instance:
Type: AWS::EC2::Instance
Properties:
ImageId: !Ref ServerAMI
InstanceType: !Ref ServerInstanceType
KeyName: !Ref KeyName
BlockDeviceMappings:
- DeviceName: /dev/xvda #Linux
Ebs:
VolumeSize: 30
NetworkInterfaces:
- AssociatePublicIpAddress: 'false'
DeleteOnTermination: 'true'
DeviceIndex: '0'
GroupSet:
- Ref: ServerSecurityGroup
SubnetId: !Ref SubnetID
Tags:
- { Key: Name, Value: !Ref AWS::StackName }
ServerSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: Webserver security group
VpcId: !Ref DefaultVPCID
SecurityGroupIngress:
- { IpProtocol: tcp, FromPort: '22', ToPort: '22', CidrIp: '127.0.0.1/32', Description: 'Test Instance' }
Unfortunately, I don't believe you can - per the CloudFormation documentation:
After the instance is running, you can modify only the DeleteOnTermination parameter for the attached volumes without interrupting the instance. Modifying any other parameter results in instance replacement.

How to launch an Amazon EC2 in a particular VPC in YAML CloudFormation template

How can I launch an Amazon EC2 instance in a particular subnet of a VPC using a YAML template in CloudFormation?
If anyone comes access this in the future, I was able to solve this by specifying the following: AvailabilityZone, SecurityGroupIds (not SecurityGroups), and SubnetId.
Resources:
EC2Instance:
Properties:
AvailabilityZone: us-east-1b
ImageId: ami-Id
InstanceType:
Ref: InstanceType
KeyName:
Ref: KeyName
Tags:
-
Key: "Name"
Value:
Ref: InstanceName
SecurityGroupIds:
- sg-idHere
SubnetId: subnet-idHere
Type: "AWS::EC2::Instance"
Make sure that the security group is available to the VPC you are trying to use. The SubnetId should represent the VPC.
Hierarchy:
VPC->SubnetID->SecurityGroupId
Here is the CF template for create a ec2 instance in region singapore. I have just used this template. If you are running in the other region please change ImageId name to met with you region
---
AWSTemplateFormatVersion: '2010-09-09'
Description: 'VPC with private subnets in two availability zones'
Parameters:
PrivateSubnet:
Description: Private Subnet to Attach NAT Gateway.
Type: AWS::EC2::Subnet::Id
InstanceType:
Description: EC2 instance type
Type: String
Default: t2.micro
AllowedValues: [t2.micro, t2.small, t2.medium, t2.large, m3.medium, m3.large,
m3.xlarge, m3.2xlarge, m4.large, m4.xlarge, m4.2xlarge, m4.4xlarge, m4.10xlarge,
c4.large, c4.xlarge, c4.2xlarge, c4.4xlarge, c4.8xlarge, c3.large, c3.xlarge,
c3.2xlarge, c3.4xlarge, c3.8xlarge, r3.large, r3.xlarge, r3.2xlarge, r3.4xlarge,
r3.8xlarge, i2.xlarge, i2.2xlarge, i2.4xlarge, i2.8xlarge]
ConstraintDescription: Please choose a valid instance type.
SSHKeyName:
Description: EC2 instance type
Type: String
ConstraintDescription: Please choose a valid KeyName
VolumeSize:
Description: size of volume
Type: Number
Default: 20
ConstraintDescription: Please choose a valid Number
AllowedValues: [20, 30, 40, 50]
IOPS:
Description: total ipos
Type: Number
Default: 100
ConstraintDescription: Please choose a valid Number
AllowedValues: [100, 200, 500, 1000]
ImageId:
Type: String
Description: 'value for region singapore. If you using other version please choose right'
Default: 'ami-33e4bc49'
Resources:
EC2Example:
Type: "AWS::EC2::Instance"
Properties:
SubnetId: !Ref PrivateSubnet
ImageId: !Ref ImageId
InstanceType: !Ref InstanceType
KeyName: !Ref SSHKeyName
BlockDeviceMappings:
-
DeviceName: /dev/sda1
Ebs:
VolumeType: io1
Iops: !Ref IOPS
DeleteOnTermination: false
VolumeSize: !Ref VolumeSize
Outputs:
EC2Example:
Description: 'Ec2 instance EC2Example'
Value: !Ref EC2Example
Export:
Name: !Sub '${AWS::StackName}-EC2Example'
The CloudFormation template includes a SubnetId parameter:
Type: "AWS::EC2::Instance"
Properties:
SubnetId: String
Simply insert the ID of the existing Subnet (eg subnet-1234abcd).

Encountered unsupported property EBS

I'm having some issues with a Cloudformation Template where when I attempt to roll it out it keeps failing on the instance creation prompting the error ' Encountered unsupported property EBS' which in turn causes a rollback. I find this quite interesting because I appear to have all of the necessary properties in there at the moment:
Also Including some links that could help speed up the research:
Instance Setup,
Block Device Mapping, &
Block Specific Properties
Resources:
Web01:
Type: AWS::EC2::Instance
Properties:
SecurityGroups:
- Ref: SecurityGoupSocoDrELB
- Ref: SecurityGoupSocoDrData
KeyName:
Ref: KeyPairName
ImageId: !FindInMap
- RegionMap
- Ref: "AWS::Region"
- AMI
Monitoring: 'false'
SubnetId:
Ref: SocoDrSubnet02
PrivateIpAddress: xxxxxxxx
InstanceInitiatedShutdownBehavior: 'stop'
InstanceType:
Ref: InstanceType
#I think the error occurs here-
BlockDeviceMappings:
- DeviceName: /dev/xvda
- EBS:
DeleteOnTermination: 'true'
VolumeType: gp2
VolumeSize: '300'
For reference I'm including other appropriate sections but the problem is stemming from the Resource's Instance section:
Parameters:
KeyPairName:
Description: The EC2 Key Pair to allow SSH access to the instance
Type: AWS::EC2::KeyPair::KeyName
# INSTANCE
InstanceType:
Type: String
AllowedValues:
- t2.nano
- t2.micro
- t2.small
- t2.medium
- t2.large
- t2.xlarge
- t2.2xlarge
Default: t2.small
Mappings:
RegionMap:
us-east-2:
AMI: ami-014a7d64
The correct property is Ebs and not EBS. Documentation can be found here.