Publish a SharePoint Farm Using CloudFormation

SharePoint Farm

We’ll show you how to automate and deploy a SharePoint Farm fast using CloudFormation the right way.

Have you ever needed to quickly create a brand new SharePoint Farm and give the users access through the internet? Like when your client says: “Hey Rafael, we just watched all the SharePoint 2016 sessions from Ignite and we are really excited about it. How fast and cost effectively can you build us a single and disposable SharePoint 2016 Preview box?”
We know what you are thinking: “Of course, I can run CF with pre-baked AMIs, associate an Elastic IP to the instances and give the IP to the customer”.
Yes, you can absolutely do that, but you will pretty much have that repetitive and manual SharePoint’s Alternate Access Mappings (AAM from now on) set up every single time you need to run a new Stack. What’s more, SharePoint  does not “like” being accessed from external networks without an AAM set.
Let’s say now that you already have your test (drive?) domain running on Route 53. During the creation process of your new Stack you can set up in parallel your whole public access on AWS and SharePoint layers automatically by just using Route 53, Load Balancing and CloudFormation’s UserData.
The goal here is to simply run a CloudFormation script and have an access URL at the end, in the Output sections. Check out our small index of topics and feel free to skip to the one that interests you most. You may already know some of this stuff we are showing here.
Index
Cloud Formation overview
 We will split the CloudFormation script down below in 3 parts, Load Balancer, EC2 Instance and Route 53. SharePoint Farms will be easy once you read through this. Some are complex, some are basic and you may have some experience with so I will keep it simple and dive into the stuff that might be new to you.
{
    "AWSTemplateFormatVersion": "2010-09-09",
    "Resources": {
        "myWaitHandle": {
            "Type": "AWS::CloudFormation::WaitConditionHandle",
            "Properties": {}
        },
        "myWaitCondition": {
            "Type": "AWS::CloudFormation::WaitCondition",
            "DependsOn": "Instance",
            "Properties": {
                "Handle": {
                    "Ref": "myWaitHandle"
                },
                "Timeout": "4500"
            }
        },
        "ElasticIP": {
            "Type": "AWS::EC2::EIP",
            "Properties": {
                "InstanceId": {
                    "Ref": "Instance"
                }
            }
        },
        "LoadBalancer": {
            "Type": "AWS::ElasticLoadBalancing::LoadBalancer",
            "Properties": {
                "Instances": [
                    "INSTANCE ID"
                ],
                "Listeners": [
                    {
                        "InstancePort": "80",
                        "LoadBalancerPort": "80",
                        "Protocol": "HTTP"
                    }
                ],
                "SecurityGroups": [
                    "SECURITY GROUP ID"
                ],
                "Subnets": [
                    "SUBNET ID"
                ],
                "HealthCheck": {
                    "Target": "TCP:80",
                    "HealthyThreshold": "10",
                    "UnhealthyThreshold": "2",
                    "Interval": "10",
                    "Timeout": "5"
                }
            }
        },
        "SecurityGroup": {
            "Type": "AWS::EC2::SecurityGroup",
            "Properties": {
                "GroupDescription": "Enable HTTP and RDP",
                "VpcId": "[YOUR VPC ID]",
                "SecurityGroupIngress": [
                    {
                        "IpProtocol": "tcp",
                        "FromPort": "80",
                        "ToPort": "80",
                        "CidrIp": "0.0.0.0/0"
                    }
                ]
            }
        },
        "Instance": {
            "Type": "AWS::EC2::Instance",
            "Properties": {
                "InstanceType": "t1.micro",
                "SubnetId": "SUBNET ID",
                "ImageId": "AMI ID",
                "EbsOptimized": "true",
                "SecurityGroupIds": [
                    {
                        "Ref": "SecurityGroup"
                    }
                ],
                "KeyName": "SharePoint",
                "UserData": {
                    "Fn::Base64": {
                        "Fn::Join": [
                            "",
                            [
                                "<powershell>\n",
                                "Add-PSSnapin 'Microsoft.SharePoint.PowerShell'\n",
                                "$publicIPAddress = 'http://",
                                {
                                    "Ref": "SecurityGroup"
                                },
                                ".td-bea-services.com'\n",
                                "New-SPAlternateURL $publicIPAddress -Zone Internet -WebApplication '[YOUR WEB APPLICATION's NAME]'\n",
                                "c:\\sharepoint\\IIS-Warmup.ps1\n",
                                "Set-DefaultAWSRegion -Region eu-central-1\n",
                                "Set-AWSCredentials -AccessKey '[YOUR ACCESS KEY]' -SecretKey '[YOUR SECRET KEY]'\n",
                                "Initialize-AWSDefaults\n",
                                "cfn-signal.exe --success true ",
                                {
                                    "Fn::Base64": {
                                        "Ref": "myWaitHandle"
                                    }
                                },
                                "\n",
                                "</powershell>"
                            ]
                        ]
                    }
                }
            }
        },
        "MyDNSRecord": {
            "Type": "AWS::Route53::RecordSet",
            "Properties": {
                "HostedZoneId": "[YOUR HOSTED ZONE ID]",
                "Comment": "CNAME redirect to Load Balancer.",
                "Name": {
                    "Fn::Join": [
                        "",
                        [
                            {
                                "Ref": "SecurityGroup"
                            },
                            ".[YOUR HOSTED ZONE's DOMAIN]."
                        ]
                    ]
                },
                "Type": "CNAME",
                "TTL": "60",
                "ResourceRecords": [
                    {
                        "Fn::GetAtt": [
                            "LoadBalancer",
                            "DNSName"
                        ]
                    }
                ]
            }
        }
    },
    "Outputs": {
        "URL": {
            "Description": "\n\n\n\nClick the URL below to access SharePoint",
            "Value": {
                "Fn::Join": [
                    "",
                    [
                        "<a href='http://",
                        {
                            "Ref": "SecurityGroup"
                        },
                        ".[YOUR HOSTED ZONE's DOMAIN]",
                        "' target='_blank'>",
                        "Click here to open SharePoint",
                        "</a>"
                    ]
                ]
            }
        }
    }
}
Load Balancer
We are assuming you have already used CloudFormation a few times and understand what the script above is doing, so we don’t think it is necessary for us to go though what a CloudFormation is and its functions.
As you can see above, our script has an Elastic Load Balancer, which is balancing just one EC2 instance, and that’s fine for the sake of learning. Later on you can add as many instances as you want and the result will be the same.
Now let’s check the code and it’s results on the AWS Console:
{
    "AWSTemplateFormatVersion": "2010-09-09",
    "Resources": {
        "LoadBalancer": {
            "Type": "AWS::ElasticLoadBalancing::LoadBalancer",
            "Properties": {
                "Instances": [
                    "INSTANCE1"
                ],
                "Listeners": [
                    {
                        "InstancePort": "80",
                        "LoadBalancerPort": "80",
                        "Protocol": "HTTP"
                    }
                ],
                "SecurityGroups": [
                    "SECURITYGROUP1"
                ],
                "Subnets": [
                    "SUBNET1"
                ],
                "HealthCheck": {
                    "Target": "TCP:80",
                    "HealthyThreshold": "10",
                    "UnhealthyThreshold": "2",
                    "Interval": "10",
                    "Timeout": "5"
                }
            }
        }
    },
    "Outputs": {}
}

We recommend trying this snipped by yourself and checking what happens. Simply update the resource IDs at the marked lines and create a new CloudFormation Stack with the text file.

Make sure your health checks are reliable, since Route 53 will rely on those checks. In our case, we are checking the TCP:80, which does not require any specific target. If you want to check a specific URL in your server, you need to use HTTP:80 + target URL.
We did a small test to make sure the TCP:80 is working by simply stopping the IIS site, waiting for 2 attempts + 10 seconds interval between them and twice 5 seconds timeout.
Go to your Load Balancers section under EC2 console and this is what you will find:
SharePoint Farm image
After you start your IIS site again, the “Status” property will change from “0 of 1 instances in service” to “1 of 1 instances in service”.
The “DNS Name” property from our load balancer will be used later on as a CNAME in Route 53. More on that in a bit.
EC2 Instance
{
    "AWSTemplateFormatVersion": "2010-09-09",
    "Resources": {
        "TestDriveInstance": {
            "Type": "AWS::EC2::Instance",
            "Properties": {
                "InstanceType": "t2.micro",
                "SubnetId": "SUBNET ID",
                "ImageId": "AMI ID",
                "EbsOptimized": "true",
                "SecurityGroupIds": [
                    {
                        "Ref": "SecurityGroup"
                    }
                ],
                "KeyName": "KeyPair",
                "UserData": {
                    "Fn::Base64": {
                        "Fn::Join": [
                            "",
                            [
                                "<powershell>\n",
                                "Add-PSSnapin 'Microsoft.SharePoint.PowerShell'\n",
                                "$publicIPAddress = 'http://",
                                {
                                    "Ref": "SecurityGroup"
                                },
                                ".YOUR INTERNET DOMAIN'\n",
                                "New-SPAlternateURL $publicIPAddress -Zone Internet -WebApplication 'WEB APPLICATION URL'\n",
                                "c:\\sharepoint\\IIS-Warmup.ps1\n",
                                "Set-DefaultAWSRegion -Region eu-central-1\n",
                                "Set-AWSCredentials -AccessKey 'ACCESS KEY' -SecretKey 'SECRET KEY'\n",
                                "Initialize-AWSDefaults\n",
                                "cfn-signal.exe --success true ",
                                {
                                    "Fn::Base64": {
                                        "Ref": "myWaitHandle"
                                    }
                                },
                                "\n",
                                "</powershell>"
                            ]
                        ]
                    }
                }
            }
        }
    }
}

The AWS::EC2::Instance is the core resource in our CloudFormation and we will spend some tome on it. We will go through the resource’s properties now:
InstanceType, SubnetId, ImageId, EbsOptimized, SecurityGroupIds, and KeyName are all properties you are should be familiar with so I won’t spend much time on them.
UserData is the last property remaining and where the magic happens. You can use either <script></script> or <powershell></powershell> tags. In this case, we will use <powershell> since all the administrative cmdlets for SharePoint are in PowerShell.
See below how the script would look if it was running in a real EC2 instance on a PowerShell console:
SharePoint Farm image 2
After running the selected text, go to Alternate Access Mappings in Central Administration and check whether you got a new “Internet” zone with your public URL.
SharePoint Farm image 3

The other part of the script was not really necessary for this example, but it is very important that you warm up your IIS after a reset command as we did above. This means that when the CloudFormation script is done running, users will start immediately accessing your SharePoint Farm with the URL provided on the Output and you don’t want the first ones to wait several minutes while your IIS is compiling and loading the memory for the first time. If you’ve never heard about IIS-Warmup, let us know and we’d be glad to answer you or even do a separate post about it if needed. There is a recent post that addresses CloudFormation and AWS deployment automation very well and it might be worth reviewing. 

Set-DefaultAWSRegion -Region eu-central-1
Set-AWSCredentials -AccessKey 'ACCESS KEY' -SecretKey 'SECRET KEY'
Initialize-AWSDefaults
cfn-signal.exe --success true {"Fn::Base64": {"Ref":"myWaitHandle"}}

With the 4 cmdlets above, you accomplish the following tasks (numbers correspond to the lines above):

  1. Ensure your next commands will run on the eu-central-1 region
  2. Set your AWS credentials
  3. Load the profile of user above into your powershell session
  4. Send a signal back to the CloudFormation script telling that the UserData is finished running, so the CloudFormation script can continue to the next resources. The signal just mentioned is a resulting hash from the {“Fn::Base64”: {“Ref”:”myWaitHandle”}} cmdlet. Read more about it here.

You have the choice to set the first 3 cmdlets as default settings in a pre-baked AMI, which means you would only use have the cfn-signal in your UserData instead.

Route 53 CNAME Record
{
    "AWSTemplateFormatVersion": "2010-09-09",
    "Resources": {
        "MyDNSRecord": {
            "Type": "AWS::Route53::RecordSet",
            "Properties": {
                "HostedZoneId": "[YOUR HOSTED ZONE ID]",
                "Comment": "CNAME redirect to Load Balancer.",
                "Name": {
                    "Fn::Join": [
                        "",
                        [
                            {
                                "Ref": "SecurityGroup"
                            },
                            ".[YOUR HOSTED ZONE's DOMAIN]."
                        ]
                    ]
                },
                "Type": "CNAME",
                "TTL": "60",
                "ResourceRecords": [
                    {
                        "Fn::GetAtt": [
                            "LoadBalancer",
                            "DNSName"
                        ]
                    }
                ]
            }
        }
    }
}

One of the last steps of your CloudFormation script is creating the CNAME entry in Route 53 pointing to your Load Balancer’s DNS Name.

The highlighted lines are the most important settings and where a new CNAME entry is created. This entry has a TTL of 60 seconds (btw 60 seconds is the minimum available) and will consider health checks first:
This will be the resulting CNAME record after the CloudFormation script ends running:
SharePoint Farm image 4
Some of the CloudFormation’s resource properties do not have the same names on the Console and you should see the additional names.

Conclusion
With just a few lines of scripting in your UserDate section, you can automate a simple and important aspect that is the public access for your SharePoint Farm. This process dramatically shortens the time between your client’s excited request, and the moment you grant them access to your finished SharePoint Farm. I want to point out that instead of EC2 instances, SharePoint could also run on Microsoft Azure Virtual Machine instances.
If you want more reading on CloudFormation and AWS Michael Sheehy wrote an excellent post this past summer. I hope you enjoyed this blog and that you can now deploy your SharePoint Farms much faster and with greater automation. As always, feel free to ask questions or share experiences in the comments section below.
Cloud Academy