问题描述
我正在尝试使用EC2s用户数据设置环境变量,但我似乎无济于事
I am trying to set environment variables with EC2s user data, but nothing i do seems to work
这是我尝试过的用户数据脚本
here are the User data scripts i tried
#!/bin/bash
echo "export HOST_URL=checkEmai-LoadBala-ICHJ82KG5C7P-23235232.us-east-1.elb.amazonaws.com" >> /env.sh
source /env.sh
另一个:
#!/bin/bash
echo "#!/bin/bash" >> /env.sh
echo "export HOST_URL=checkEmai-LoadBala-ICHJ82KG5C7P-67323523.us-east-1.elb.amazonaws.com" >> /env.sh
chmod +x /env.sh
/env.sh
它们都绝对不执行任何操作,并且如果我登录并发出命令source /env.sh
或/env.sh
,它将起作用.所以这一定是我要禁止的事情.
They both do absolutly nothing, and if i log in and issue the command source /env.sh
or /env.sh
it works. so this must be something forbidden that i am trying to do.
这是/var/log/cloud-init-output.log
使用-e -x
+ echo 'export HOST_URL=checkEmai-LoadBala-ICHJ82KG5C7P-2141709021.us-east-1.elb.amazonaws.com'
+ source /env.sh
++ export HOST_URL=checkEmai-LoadBala-ICHJ82KG5C7P-2141709022.us-east-1.elb.amazonaws.com
++ HOST_URL=checkEmai-LoadBala-ICHJ82KG5C7P-2141709022.us-east-1.elb.amazonaws.com
仍然,echo $HOST_URL
为空
根据要求,完整的UserData脚本
As requested, the full UserData script
#!/bin/bash
set -e -x
echo "export HOST_URL=checkEmai-LoadBala-ICHJ82KG5C7P-2141709021.us-east-1.elb.amazonaws.com" >> /env.sh
source /env.sh
/startup.sh staging 2649
推荐答案
为EC2实例定义环境变量的一种更可配置的方法是使用系统管理器参数存储.这种方法将使管理大量EC2实例的不同参数变得更加容易,这两个实例均使用 AWS KMS 以及纯文本格式.它还将允许以最小的EC2实例级别更改来更改参数值.步骤如下.
One of the more configurable approach to define environment variables for EC2 instances, is to use Systems Manager Parameter Store. This approach will make it easier to manage different parameters for large number of EC2 instances, both encrypted using AWS KMS as well as in plain text. It will also allows to change the parameter values with minimal changes in EC2 instance level. The steps are as follows.
- 在 EC2系统管理器中定义字符串参数(使用KMS加密或未加密).参数存储.
- 在EC2担任的IAM角色中,授予访问参数存储区所需的权限.
- 使用适用于EC2 System Manager的AWS CLI命令,使用获取参数或获取参数 AWS CLI命令和根据需要控制命令输出.
- Define string parameters (Encrypted with KMS or Unencrypted) in EC2 Systems Manager Parameter Store.
- In the IAM role EC2 assumes, give required permission to access the parameter store.
- Using the AWS CLI commands for EC2 System Manager, read the parameters and export to environment variables in User Data section using Get-Parameter or Get-Parameters AWS CLI commands and controlling command output as required.
例如使用获取参数用于检索db_connection_string参数(未加密)的命令.
e.g Using Get-Parameter command to retrieve db_connection_string parameter(Unencrypted).
export DB_CONNECTION =$(aws --region=us-east-2 ssm get-parameter --name "db_connection" --query 'Value')
注意:有关设置AWS KMS密钥,定义加密的字符串,管理IAM策略和等等,请参阅以下文章.
Note: For more details in setting up AWS KMS Keys, defining encrypted strings, managing IAM policies & etc., refer the following articles.
- Securing Application Secrets with EC2 Parameter Store
- Simple Secrets Management via AWS’ EC2 Parameter Store
这篇关于如何通过用户数据在EC2实例上设置环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!