shell脚本设置从标签Amazon EC2的主机名 [英] shell script to set amazon ec2 hostname from tags

查看:398
本文介绍了shell脚本设置从标签Amazon EC2的主机名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从标签名称设置Amazon EC2的主机名

I am trying to set amazon EC2 hostname from the tag "Name"

和发现答案提取标签的实例数据。

And found the answer to extract tags from instance data.

ec2-describe-tags \
  --filter "resource-type=instance" \
  --filter "resource-id=$(ec2-metadata -i | cut -d ' ' -f2)" \
  --filter "key=Name" | cut -f5

结果是:

+------------+--------------+------+--------+
| resourceId | resourceType | key  | value  |
+------------+--------------+------+--------+
| i-1xxxxxxx | instance     | Name | dev200 |
+------------+--------------+------+--------+

我可以看到,我几乎没有,但我如何才能从上面的结果值(dev200)?然后,我可以在使用它:

I can see that I am almost there, but how do I get the value(dev200) from the result above? Then I can use it in:

echo $HOSTNAME > /etc/hostname

P.S。我有实例BASH,但我在庆典文档的完全丧失。可有人点我到正确的段落?

p.s. I have BASH on the instance, but I am completely lost in the bash document. can someone point me to the correct paragraph?

推荐答案

在某些错误和审判,拿到剧本的工作:

After some error and trial, got the script working:

#!/bin/bash
hostname=`ec2-describe-tags --filter "resource-type=instance" \
  --filter "resource-id=$(ec2-metadata -i | cut -d ' ' -f2)" \
  --filter "key=Name" | grep Name`

IFS="|" read -ra NAME <<< "$hostname"
hostname=${NAME[4]}
echo $hostname

用于IFS得到解析成数组的字符串,幸运的是我知道的第4个元素始终是主机名。

Used IFS to get the string parsed into arrays, and luckily I know the 4th element is always the hostname.

EDIT(20-DEC-2012):在很短的时间,因为这被张贴,几个相关的EC2命令行工具已被修改,和标志改变或去precated(例如,从-i标志上面似乎不再工作ec2metadata的当前版本)。考虑到这一点,这里是命令行脚本,我用来获取当前机器的​​名称标签(不能说的脚本的其余部分):

EDIT (20-DEC-2012): In the short time since this was posted, several of the relevant ec2 command line tools have been modified, and flags changed or deprecated (e.g., the -i flag from above no longer seems to work on the current version of ec2metadata). Bearing that in mind, here is the command line script I used to get the current machine's "Name" tag (can't speak to the rest of the script):

ec2-describe-tags --filter "resource-type=instance" --filter "resource-id=$(ec2metadata --instance-id)" | awk '{print $5}'

在Debian / Ubuntu的,需要的apt-get安装云-utils的EC2-API工具来得到这些工作(后者仅在Ubuntu的多元宇宙)。

On Debian/Ubuntu, you need to apt-get install cloud-utils ec2-api-tools to get these working (the later is only on Ubuntu Multiverse).

这篇关于shell脚本设置从标签Amazon EC2的主机名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆