
EC2 인스턴스의 IP 주소를 명령줄에 삽입하는 복잡한 방법은 다음과 같습니다. 작동하지만 몇 가지 명백한 문제가 있으며 이를 해결할 수 있는 좋은 방법을 찾고 있습니다.
TOKEN=`curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"`
IP=`curl -H "X-aws-ec2-metadata-token: \$TOKEN" -v http://169.254.169.254/latest/meta-data/local-ipv4`
if [ "$color_prompt" = yes ]; then
PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@$IP-\H\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
else
PS1='$IP${debian_chroot:+($debian_chroot)}\u@$IP-\H:\w\$ '
fi
내 방법에는 해결하고 싶은 몇 가지 문제가 있습니다.
- Bash를 로드하거나 로그인할 때 원치 않는 출력이 많이 생성됩니다.
Last login: Thu Dec 17 16:57:37 2020 from 22.123.17.122
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 56 100 56 0 0 11200 0 --:--:-- --:--:-- --:--:-- 11200
* Expire in 0 ms for 6 (transfer 0x560383dabf90)
* Trying 169.254.169.254...
* TCP_NODELAY set
* Expire in 200 ms for 4 (transfer 0x560383dabf90)
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0* Connected to 169.254.169.254 (169.254.169.254) port 80 (#0)
> GET /latest/meta-data/local-ipv4 HTTP/1.1
> Host: 169.254.169.254
> User-Agent: curl/7.64.0
> Accept: */*
> X-aws-ec2-metadata-token: AQAAAEjtIasdfadfasdf5ksdjkjkkasdfe947xQ==
>
* HTTP 1.0, assume close after body
< HTTP/1.0 200 OK
< Accept-Ranges: bytes
< Content-Length: 12
< Content-Type: text/plain
< Date: Thu, 17 Dec 2020 22:52:25 GMT
< Last-Modified: Tue, 15 Dec 2020 14:11:17 GMT
< X-Aws-Ec2-Metadata-Token-Ttl-Seconds: 21600
< Connection: close
< Server: EC2ws
<
{ [12 bytes data]
100 12 100 12 0 0 2400 0 --:--:-- --:--:-- --:--:-- 2400
* Closing connection 0
- 또 다른 문제는 이것이 bash에 로그인하거나 bash를 다시 로드할 때마다 실행된다는 것입니다. IP 주소가 이미 알려진 경우 이를 우회할 수 있는 방법을 찾고 싶습니다.
답변1
출력의 대부분을 차지하는 두 번째 명령줄에서 컬의 자세한 출력을 구체적으로 요청하셨습니다. 을 제거해야 합니다 -v
. 그런 다음 진행률 표시기를 억제하려면 -s
(두 명령 모두에서)를 사용하십시오. 오류가 없는 한 출력이 남지 않습니다.
시작할 때 이것을 실행하고 결과 IP 주소를 파일에 쓴 다음 bash 프로필에서 해당 파일의 내용을 읽는 것이 더 나을 것입니다. (이는 인스턴스가 실행되는 동안 IP 주소가 변경되지 않으며 AFAIK가 발생하지 않는다고 가정합니다.)
다음과 같은 로컬 시작 스크립트를 고려해보세요.
#!/usr/bin/env bash
TOKEN=`curl -s -X PUT -H "X-aws-ec2-metadata-token-ttl-seconds: 21600" http://169.254.169.254/latest/api/token`
curl -s -H "X-aws-ec2-metadata-token: \$TOKEN" -o /tmp/local-ipv4 http://169.254.169.254/latest/meta-data/local-ipv4
이제 bash 프로필에서 읽을 수 있습니다.
IP=$(cat /tmp/local-ipv4)