serverless icon indicating copy to clipboard operation
serverless copied to clipboard

Access Outputs from CF template in serverless.yml

Open picsoung opened this issue 10 years ago • 39 comments

Hi y'all,

Trying to transition to v1, and porting my CF template too.

I am wondering if I am facing the same issue as in #1699. Trying to access to outputs under resources from Cloudformation.

In my CF template, I am creating a VPC, subnets and such that I want to reuse in the config of my functions.

my serverless.yml

provider:
  name: aws
  vpc:
    securityGroupIds:
     - Ref: vpcSecurityGroup
    subnetIds:
      - Ref: PrivateSubnet1
      - Ref: PrivateSubnet2

then under resources

resources:
  Resources:
    VPC:
      Type: AWS::EC2::VPC
      Properties:
        CidrBlock: 10.0.0.0/16
    PrivateSubnet1:
      Type: AWS::EC2::Subnet
      Properties:
        VpcId:
          Ref: VPC
        CidrBlock: 10.0.1.0/24
    SecurityGroup:
      Type: AWS::EC2::SecurityGroup
      Properties:
        GroupDescription: Limits security group egress traffic
        VpcId:
          Ref: VPC
        SecurityGroupIngress:
        - IpProtocol: "-1"
        SecurityGroupEgress:
        - IpProtocol: "-1"
          CidrIp: 0.0.0.0/0
Outputs:
    vpcSecurityGroup:
      Description: Id of the SecurityGroup
      Value:
        Fn::GetAtt:
          - SecurityGroup
          - GroupId

But this setup gives the following error:

Template format error: Unresolved resource dependencies
     [vpcSecurityGroup] in the Resources block of the template

I also tried to access directly, using Fn:GetAtt without success :(

Would you confirm you can not access Outputs values, yet? Thanks

picsoung avatar Sep 29 '16 15:09 picsoung

Yes, I can confirm that you cannot access the CFN outputs currently. Maybe it could help to create the VPN/Subnet resources outside of serverless (e.g. with plain CloudFormation) and then pass e.g. PrivateSubnet1 to serverless as a parameter or a env var.

s0enke avatar Sep 29 '16 18:09 s0enke

A new CloudFormation feature released recently enables exporting stack outputs which can be referenced from other templates. http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/walkthrough-crossstackref.html

pgasiorowski avatar Sep 29 '16 18:09 pgasiorowski

Sorry I completely missed what you were doing. Yes this won't work in the current framework. It wouldn't be hard to add support for this style of reference.

andymac4182 avatar Sep 29 '16 21:09 andymac4182

How would this not result in circular references? When you first launch the service the outputs do not exist, so how can the provider object reference them?

rowanu avatar Sep 29 '16 22:09 rowanu

If you allow CloudFormation refs as part of the VPC config then it will be handled in CloudFormation and not be a circular reference. Well that is purely how I think it would work after 2min of thinking about it.

andymac4182 avatar Sep 29 '16 23:09 andymac4182

If you're just using Refs to CFN Logical Ids, then it might work (but would be hard to validate, and would break your stack if you got it wrong).

You cannot reference CFN Outputs (as defined in the resources example above) before the stack has been created.

rowanu avatar Sep 30 '16 00:09 rowanu

In Serverless 0.5, it was handled separately with s-resources-cf.json at the root level, and s-function.json at the function level. And you can reference to outputs from CF. I am trying to have a similar behavior.

Or something where I will first deploy the stack, then my functions like project init and deploy in the past.

Having a separate file, would work, but it defeats the idea of having everything handled by serverless :(

picsoung avatar Sep 30 '16 10:09 picsoung

+1 - Really need this feature.

Without this feature, basically we all have to run a separate "init environment" script (terraform for me) which outputs things to a .json file such as SQS URL or DynamoDB ARN which I then refer to in the serverless.yml file. It would be nice/ideal to not have to also run CF/TF separately from Serverless to provision and/or version an environment since CF is now supported in serverless v1.0+. I know the cross-linking feature of CF is brand new... but this feature feels like it absolutely should already be in Serverless. I've recently migrated a few of my own CF scripts to use this cross-linking.

In order to make this possible, your Serverless CF stack may need to consist of more than one stack, having one stack able to initialize and then have the second stack refer to the outputs of previous stack. eg: Cross-Stack CF.

This would allow for two stacks, the first, lower-level stack being the environment provisioning (Eg: creating DynamoDB tables, SQS queues, SNS topics, etc) and then the next/final-level stack being the actual serverless lambda/api-gateway/cloudwatch-events code deployment. I envision re-deployments of a serverless codebase to only touch the second stack, unless you customize the evnironment CF in serverless.yml then it also re-runs the first stack.

AndrewFarley avatar Nov 17 '16 11:11 AndrewFarley

RE: cross-stack references...

Maybe I misunderstand what people are asking for here but I have been using the following in my services using a published version of SLS:

service: my-thing-service
# ...
resources:
  #...
  Outputs:
    MyThingArn:
      Description: The ARN for My Thing
      Value:
        'Fn::GetAtt': [ MyThing, Arn ]
      Export:
        Name: '${self:service}:${self:custom.stage}:MyThingArn'

Then, in another service, I am using the following:

functions:
  userOfThing:
    handler: userOfThing.handler
    environment:
      MY_THING:
        'Fn::ImportValue': 'my-thing-service:${self:custom.stage}:MyThingArn'

And this totally allows me to have no need for the "requested feature" here. There are a few things to keep in mind (see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-importvalue.html) but accepting those limitations and considerations, I think everything you'd want to do can be done.

For @picsoung's original question, which appears to be a "within stack" use case, I don't know why the original logical ID wouldn't be used:

provider:
  name: aws
  vpc:
    securityGroupIds:
     - 'Fn::GetAtt': SecurityGroup
    subnetIds:
      - Ref: PrivateSubnet1
      - Ref: PrivateSubnet2

Please, if I am missing something, let me know but I think this is "old way of doing things" mixing with the new way where you don't need to do that thing anymore.

erikerikson avatar Dec 21 '16 01:12 erikerikson

Update: this doesn't pre-date the cross-stack references - I must be 😕 with another issue...

@erikerikson nope, you're right - this issue ~~pre-dates the cross-stack references announcement, and~~ should be closed.

Any other outputs should be retrieved by using API calls (i.e. via an SDK).

rowanu avatar Dec 21 '16 01:12 rowanu

Ah, cool. Hopefully it'll help someone searching issues for a solution then. :)

erikerikson avatar Dec 21 '16 01:12 erikerikson

@erikerikson's advice to use Ref's in environment variables is excellent. I couldn't figure it out from serverless.com docs, so maybe it could be mentioned in the Variables and Resources sections.

kennu avatar Jan 06 '17 21:01 kennu

Thanks @erikerikson's solution works well on the VPC section :)

But unfortunately I cant' make it work under environment section

And also feels like it can only look under Ressources part, not on Outputs:

 Template format error: Unresolved resource dependencies
     [snsTopic] in the Resources block of the template

I tried:

environment:
     SERVERLESS_REGION: ${self:provider.region}
     KEY: "ahahahah"
     ELASTICACHE_ENDPOINT:
       - 'Fn::GetAtt': elasticCache.RedisEndpoint.Address
     SNS_TOPIC_ARN:
       - Ref: SNStopic

And that's what I get

An error occurred while provisioning your stack: HelloLambdaFunction
     - Value of property Variables must be an object with
     String (or simple type) properties.

Any tips on how we can reference to CF into environement? thanks

picsoung avatar Jan 13 '17 16:01 picsoung

@picsoung try to remove -

    ELASTICACHE_ENDPOINT:
       Fn::GetAtt: elasticCache.RedisEndpoint.Address
     SNS_TOPIC_ARN:
       Ref: SNStopic

Like the FEED_URL in this https://github.com/SC5/serverless-blog-workshop/blob/rss/serverless.yml

laardee avatar Jan 13 '17 17:01 laardee

I'm trying to use Fn::ImportValue but it doesn't work.

Template:

resources:
  Resources:
    BFCDN:
      Type: AWS::CloudFront::Distribution
      Properties:
        DistributionConfig:
          Origins:
            - DomainName:
              "Fn::Sub":
                - "${bucket}.s3.amazonaws.com"
                -
                  - bucket:
                    "Fn::ImportValue": BFBucket

Error when running deploy:

  Serverless Error ---------------------------------------

     Invalid variable reference syntax for variable bucket.
     You can only reference env vars, options, & files. You
     can check our docs for more info.

I see there's an example by @erikerikson in https://github.com/serverless/serverless/issues/2240#issuecomment-268411199 how to use this with functions, but that's because environment is passed straight in (as far as I can tell)... and doesn't explain how to import values for use within the serverless.yml template.

bjfletcher avatar Jan 15 '17 14:01 bjfletcher

@bjfletcher "Fn::ImportValue" is resolved by CloudFormation so for something that configures the local behavior of the framework (such as the bucket to deploy to) it won't work. You'll need to hard code the bucket name, either in a config file that you load in your serverless.yml or directly in serverless.yml

erikerikson avatar Jan 16 '17 02:01 erikerikson

There might be a feasible way to do that but no one has offered an implementation yet :D

erikerikson avatar Jan 16 '17 02:01 erikerikson

thanks @laardee indeed it worked like this:

 ELASTICACHE_ENDPOINT:
     Fn::GetAtt:
       - elasticCache
       - RedisEndpoint.Address
   SNS_TOPIC_ARN:
     Ref: SNStopic

But I could not take advantage of the Outputs section of my CF template.

Here I've seen someone using "${self:resources.Outputs.ResourceName.ResourceAttribute}"

That could be another way, and it worth documenting it

picsoung avatar Jan 16 '17 18:01 picsoung

Hi @picsoung, @laardee, @erikerikson can you please help me with an example on how to setup the Outputs/References DynamoDB streams and a function using it? I was not able to replicate the example above

Not working example:

functions:
  myFunction:
    handler: handler.myFunction
    events:
      - stream:
          arn: ${self:resources.Outputs.MyTableStreamArn.Value}
          startingPosition: 'LATEST'
          batchSize: 100

Outputs:
    MyTableStreamArn:
      Description: The ARN of the DynamoDB stream of myTable
      Value:
        Fn::GetAtt: [ myTable, StreamArn ]

karloscodes avatar Feb 21 '17 12:02 karloscodes

This should be possible with the new cf variable type where one can reference stack outputs.

pmuens avatar May 19 '17 14:05 pmuens