0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

AWSリソース作成と同時にタグ付けする

Last updated at Posted at 2019-01-16

リソース作成後にわざわざIDを拾ってきてタグ付けするのが面倒だったので、CLIコマンドをくっ付けました。

つかいかた

ec2_create_subnet.shの中でec2_create_subnet.shをロードしてます。
必要な変数は呼び出す側(ec2_create_subnet.sh)で定義します。

引数1に文字列「exe」を渡すと実行します。
それ以外の文字列を渡すと、Dry-runで実行します。

Nameタグ付け

ec2_create_name_tag.sh
# !/bin/bash

ec2CreateNameTag(){
	aws ec2 create-tags \
	 --resources ${RESOURCE_ID} \
	 --tags "Key=Name,Value=${TAGS_VALUE}"
}

Subnet作成

ec2_create_subnet.sh
# !/bin/bash
source ./ec2_create_name_tag.sh
AZ_VALUE="a"
REGION_NAME="ap-northeast-1"
AVAILABILITY_ZONE="${REGION_NAME}${AZ_VALUE}"
CIDR="1.2.3.240/28"
VPC_ID="vpc-00aa0aa000aa00000"
DRY_OR_NOT=""
TAGS_VALUE="subnet-nameTagValue${AZ_VALUE^}"
if [ -n "$1" ];
then
	if [ "exe" = "$1" ];
	then
		DRY_OR_NOT="--no-dry-run"
	else
		DRY_OR_NOT="--dry-run"
	fi
else
	echo "Argument1 is required."
	exit 9
fi	
RESOURCE_ID=`aws ec2 create-subnet \
 --availability-zone ${AVAILABILITY_ZONE} \
 --cidr-block ${CIDR} \
 --vpc-id ${VPC_ID} \
 ${DRY_OR_NOT} | jq -r '.Subnet.SubnetId'`
if [ $? -eq 0 ];
then
	echo "Subnet ID: ${RESOURCE_ID}"
	ec2CreateNameTag
else
	echo "Create subnet is failed."
fi

...CloudFormation使おう

CloudFormation使いました

create_subnet_backendA.json
{
	"AWSTemplateFormatVersion" : "2010-09-09",
	"Resources":{
		"subnetBackendA": {
			"Type": "AWS::EC2::Subnet",
			"Properties": {
				"VpcId": "vpc-00aa0aa000aa00000",
				"CidrBlock": "1.2.3.240/28",
				"AvailabilityZone": "ap-northeast-1a",
				"Tags": [{"Key": "Name", "Value": "subnet-nameTagValueA"}]
			}
		}
	}
}
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?