Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

amazon web services - script to get Instance Status 1/2 or 2/2 of instance launched via AMI whose instance id is not known before in terraform using external data source

Can i have script to get Instance Status check of 1/2 or 2/2 of instance launched via AMI whose instance id is not known before applying terraform apply in terraform using external data source . enter image description here Instance name launched via AMI : QA-server-via-ami Ami Name : QA-ami enter image description here

    Error : 
    Error: failed to execute "bash":
    An error occurred (InvalidInstanceID.Malformed) when calling the 
    DescribeInstanceStatus operation: Invalid id: "QA-server-via-ami.id"
    on main.tf line 94, in data "external" "instance_status":
    94: data "external" "instance_status"}
Main TF Code :
    resource "aws_ami_from_instance" "QA-ami" {
    name   = "QA-ami"
    source_instance_id = "i-00f4e52*****"
    }

    resource "aws_instance" "QA-server-via-ami" {
    ami = aws_ami_from_instance.QA-ami.id
    instance_type = "var.instance_type_QA"
    }

    data "external" "instance_status" {
    program = ["bash", "${path.module}/get_instance_status.sh"]
    query = {
    id = "QA-server-via-ami.id"
    }
    } 
get_instance_status.sh :
    #!/bin/bash

    set -e

    eval "$(jq -r '@sh "INSTANCE_ID=(QA-server-via-ami.id)"')"

    status=$(aws ec2 describe-instance-status --instance-ids ${INSTANCE_ID} -- 
    output json --query 'InstanceStatuses[0]')

    instance_status=$(echo ${status} | jq -r '.InstanceStatus.Details[0].Status')
    system_status=$(echo ${status} | jq -r '.SystemStatus.Details[0].Status')

    jq -n --arg inst_status "$instance_status" 
      --arg sys_status "$system_status" 
      '{"instance_status":$inst_status,"system_status":$sys_status}'
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since you creating instance using:

resource "aws_instance" "QA-server-via-ami"

then to get its ID you can use:

aws_instance.QA-server-via-ami.id

So to pass it to your external data source:

data "external" "instance_status" {
    program = ["bash", "${path.module}/get_instance_status.sh"]
    query = {
      id = aws_instance.QA-server-via-ami.id
    }
} 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...