AWS Boto3 使用 describe_launch_configurations 建立 create_launch_configuration

AWS Python

平常我們在使用 create_launch_configuration 可能就會直接建立大概的方法是如下

建立 create_launch_configuration

resp = client.create_launch_configuration({
  iam_instance_profile: "my-iam-role", 
  image_id: "ami-12345678", 
  instance_type: "m3.medium", 
  launch_configuration_name: "my-launch-config", 
  security_groups: [
    "sg-eb2af88e", 
  ], 
})

可是有時候會基於舊的 launch configurations 建立這時候會遇到一個問題是直接使用上述方法沒有辦法把參數餵入那應該怎麼辦呢?

查詢 describe_launch_configurations

我們先來看一下 describe_launch_configurations 查詢後會長怎樣

resp = client.describe_launch_configurations({
  launch_configuration_names: [
    "my-launch-config", 
  ], 
})

resp.to_h outputs the following:
{
  launch_configurations: [
    {
      associate_public_ip_address: true, 
      block_device_mappings: [
      ], 
      created_time: Time.parse("2014-05-07T17:39:28.599Z"), 
      ebs_optimized: false, 
      image_id: "ami-043a5034", 
      instance_monitoring: {
        enabled: true, 
      }, 
      instance_type: "t1.micro", 
      launch_configuration_arn: "arn:aws:autoscaling:us-west-2:123456789012:launchConfiguration:98d3b196-4cf9-4e88-8ca1-8547c24ced8b:launchConfigurationName/my-launch-config", 
      launch_configuration_name: "my-launch-config", 
      security_groups: [
        "sg-67ef0308", 
      ], 
    }, 
  ], 
}

如上我們就會發現有滿多參數是可以直接帶入 create_launch_configuration 那可以怎麼做呢?

結合 describe_launch_configurations 與 create_launch_configuration

例如我們想要保留 image_id 就可以使用 describe_launch_configurations 取得 resp['LaunchConfigurations'][0].image_id 然後把它放入

基本上使用以下的方法就可以完成想要完成的功能,如果想要參數設定成為變數也會變得比較簡單

resp = client.describe_launch_configurations({
  launch_configuration_names: [
    "my-launch-config", 
  ], 
})

iam_instance_profile = resp['LaunchConfigurations'][0].iam_instance_profile
image_id = resp['LaunchConfigurations'][0].image_id

params = {}
if iam_instance_profile:
    params['iam_instance_profile'] = iam_instance_profile
if image_id:
    params['image_id'] = image_id
params['instance_type'] = "m3.medium"
params['launch_configuration_name'] = "my-launch-config"
params['security_groups'] = [
    "sg-eb2af88e", 
]
resp = client.create_launch_configuration(**params)

參考資料