正确转义长序列的systemd命令

时间:2018-12-15 22:53:31

标签: amazon-web-services systemd

我有以下systemd单位

[Unit]
Description=Tag EBS Volumes without tags with AutoScaling Group tags
[Service]
Type=oneshot
ExecStartPre=/bin/bash -c "/usr/bin/curl -s https://stedolan.github.io/jq/download/linux64/jq > /usr/local/bin/jq && chmod +x /usr/local/bin/jq"
ExecStart=/bin/bash
      -c 'AWS_REGION=$(/usr/bin/curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone | sed 's/[a-z]$//'); \
          INSTANCE_ID=$(/usr/bin/curl -s http://169.254.169.254/latest/meta-data/instance-id); \
          VOLUMES=$(/usr/local/bin/aws ec2 describe-volumes --region $AWS_REGION --filters Name=attachment.instance-id,Values=$INSTANCE_ID | /usr/local/bin/jq -r '"'"'.Volumes[] | select(.Tags == null) | .Attachments[].VolumeId'"'"'); \
          AUTOSCALING_GROUP=$(/usr/local/bin/aws autoscaling describe-auto-scaling-instances --region $AWS_REGION --instance-ids $INSTANCE_ID | /usr/local/bin/jq -r .AutoScalingInstances[].AutoScalingGroupName); \
          TAGS=$(/usr/local/bin/aws autoscaling describe-tags --region $AWS_REGION --filters Name=auto-scaling-group,Values=$AUTOSCALINGGROUP --query '"'"'Tags[*].{Key:Key,Value:Value}'"'"'); \
          /usr/local/bin/aws ec2 create-tags --region "$AWS_REGION" --resources "$VOLUMES" --tags "$TAGS";'

我想问一下您是否有一些建议,以使其更具可读性和工作性。我无法正确转义该序列,并且在执行该序列时遇到错误。

Dec 16 09:43:36 ip-172-20-39-162 systemd[1]: Started Tag EBS Volumes without tags with AutoScaling Group tags.
Dec 16 10:21:03 ip-172-20-39-162 systemd[1]: [/lib/systemd/system/kops-hook-tag-ebs-volumes.service:11] Unknown lvalue '-c 'AWS_REGION' in section 'Service'

1 个答案:

答案 0 :(得分:1)

单纯地看您的问题,您就缺少在线上的转义符

ExecStart=/bin/bash

应该是

ExecStart=/bin/bash \
 -c 'AWS_REGION=$(/usr/bin/curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone | sed 's/[a-z]$//'); \
          INSTANCE_ID=$(/usr/bin/curl -s http://169.254.169.254/latest/meta-data/instance-id); \
          VOLUMES=$(/usr/local/bin/aws ec2 describe-volumes --region $AWS_REGION --filters Name=attachment.instance-id,Values=$INSTANCE_ID | /usr/local/bin/jq -r '"'"'.Volumes[] | select(.Tags == null) | .Attachments[].VolumeId'"'"'); \
          AUTOSCALING_GROUP=$(/usr/local/bin/aws autoscaling describe-auto-scaling-instances --region $AWS_REGION --instance-ids $INSTANCE_ID | /usr/local/bin/jq -r .AutoScalingInstances[].AutoScalingGroupName); \
          TAGS=$(/usr/local/bin/aws autoscaling describe-tags --region $AWS_REGION --filters Name=auto-scaling-group,Values=$AUTOSCALINGGROUP --query '"'"'Tags[*].{Key:Key,Value:Value}'"'"'); \
          /usr/local/bin/aws ec2 create-tags --region "$AWS_REGION" --resources "$VOLUMES" --tags "$TAGS";'

简化事情;我建议在ExecStartPre

中设置您的环境变量