问题
I'm trying to run an AWS CLI command to modify the DefaultActions block of one of my ALB listeners. I do this on my terminal.
$ aws elbv2 modify-listener --listener-arn arn:aws:elasticloadbalancing:us-east-1:1234567890:listener/app/my-alb/123456789 --default-actions '[{"Type": "redirect", "RedirectConfig": {"Protocol": "HTTPS", "Port": "443", "Host": "#{host}", "Query": "#{query}", "Path": "/#{path}", "StatusCode": "HTTP_301"}}]'
How would I code this in a Jenkins pipeline so the single-quotes and double-quotes in the --default-actions string are preserved? I do this now
def defaultActions = '[{"Type": "redirect", "RedirectConfig": {"Protocol": "HTTPS", "Port": "443", "Host": "#{host}", "Query": "#{query}", "Path": "/#{path}", "StatusCode": "HTTP_301"}}]'
sh """
aws elbv2 modify-listener --listener-arn arn:aws:elasticloadbalancing:us-east-1:1234567890:listener/app/my-alb/123456789 --default-actions \\'$defaultActions\\'
"""
But it is interpreted as this, where the double-quotes are removed.
aws elbv2 modify-listener --listener-arn arn:aws:elasticloadbalancing:us-east-1:803597461034:listener/app/sb-zift-admin-lb/375b68a2c9e7550c/fbb5e9154eb73ab5 --default-Actions '[{Type: redirect, RedirectConfig: {Protocol: HTTPS, Port: 443, Host: #{host}, Query: #{query}, Path: /#{path}, StatusCode: HTTP_301}}]'
On a side note, I'm doing this in AWS CLI since I understand that even though the API is available, the option is not available in Cloudformation yet.
回答1:
You need to escape double quotes in defaultActions
string as well. The sh
pipeline step performs parameter expansion before passing it to the shell. In your case escaping "
with double slash like \\"
should do the trick:
def defaultActions = '[{\\"Type\\": \\"redirect\\", \\"RedirectConfig\\": {\\"Protocol\\": \\"HTTPS\\", \\"Port\\": \\"443\\", \\"Host\\": \\"#{host}\\", \\"Query\\": \\"#{query}\\", \\"Path\\": \\"/#{path}\\", \\"StatusCode\\": \\"HTTP_301\\"}}]'
sh """
aws elbv2 modify-listener --listener-arn arn:aws:elasticloadbalancing:us-east-1:1234567890:listener/app/my-alb/123456789 --default-actions \\'${defaultActions}\\'
"""
I have run an example with echo
command instead aws
and it produced expected result:
+ echo elbv2 modify-listener --listener-arn arn:aws:elasticloadbalancing:us-east-1:1234567890:listener/app/my-alb/123456789 --default-actions '[{"Type": "redirect", "RedirectConfig": {"Protocol": "HTTPS", "Port": "443", "Host": "#{host}", "Query": "#{query}", "Path": "/#{path}", "StatusCode": "HTTP_301"}}]'
elbv2 modify-listener --listener-arn arn:aws:elasticloadbalancing:us-east-1:1234567890:listener/app/my-alb/123456789 --default-actions '[{"Type": "redirect", "RedirectConfig": {"Protocol": "HTTPS", "Port": "443", "Host": "#{host}", "Query": "#{query}", "Path": "/#{path}", "StatusCode": "HTTP_301"}}]'
来源:https://stackoverflow.com/questions/52843748/how-to-escape-quotes-in-a-aws-cli-in-a-jenkins-pipeline