Search code examples
shellif-statementjenkinsaws-cloudformationmultibranch-pipeline

Using If statement with shell commands in jenkins Declarative pipeline cloudformation


I am integrating aws cloudformation into my jenkins pipeline. I want execute a

$ aws cloudformation describe-stacks --stack-name dev-nics-proxyservlet-svc --region us-west-2

command to see if I have a stack out there with the name I am looking for. If the command finds that the stack exists, I want to delete the stack:

$ aws cloudformation delete-stack --stack-name dev-nics-proxyservlet-svc

But if the stack doesnt exists, I want to create the stack:

aws cloudformation create-stack --stack-name dev-nics-proxyservlet-svc --region us-west-2 --template-body file://dev-nics-proxyservlet-cluster.yml --parameters file://dev-nics-proxyservlet-svc-param.json --capabilities "CAPABILITY_IAM" "CAPABILITY_NAMED_IAM"

How can I can write this shell comman in a declarative multibranch jenkins pipeline? Any help is appreciated. Thanks!


Solution

  • I think something along these lines should work:

    if aws cloudformation describe-stacks --stack-name dev-nics-proxyservlet-svc --region us-west-2 &>/dev/null 
    then
        aws cloudformation delete-stack --stack-name dev-nics-proxyservlet-svc
    else
        aws cloudformation create-stack --stack-name dev-nics-proxyservlet-svc --region us-west-2 --template-body file://dev-nics-proxyservlet-cluster.yml --parameters file://dev-nics-proxyservlet-svc-param.json --capabilities "CAPABILITY_IAM" "CAPABILITY_NAMED_IAM"
    fi
    

    The if works by checiking exit code of aws cloudformation describe-stacks. If its 0, then stack exists, if not 0, then it does not exist.