SlideShare una empresa de Scribd logo
1 de 39
Automated Deployment Building a simple automated deployment platform with PHP and Linux Michael Peacock@michaelpeacockmichaelpeacock.co.uk
whois? Senior / Lead Web Developer Zend Certified Engineer Published Author PHP 5 Social Networking, PHP 5 E-Commerce development & more
Deployment: (an) old style approach Take website offline / put into maintenance mode Backup everything Upload new files - FTP Upgrade database Put online, and hope for the best Do it twice: once for staging and once for deployment
http://xkcd.com/303/
The problem Down time for upgrades Manual process FTP takes time;  forgot to CHMOD?  Clients want to see progress now! Bugs and issues can lie dormant for some time
What about... Many existing solutions are geared towards large projects What about... the little guy; the small agency the web app start up on an entry level VPS?
What's in store? A few simple techniques, scripts and ideas that we currently use to make deployment easy
Deployment: the basics Get your latest code from version control, and stick it online Keep a central record of all the CHMOD / CHOWNing that you need to do Swap around your database connection details and other suitable configuration files
SVN Export Start with a simple svn export Store the date/time in a variable  Create two folders, named with the current date/time. One within the web root, one outside of it Two exports: public and private (or one export, and some moving around of folders – up to you!)
#!/bin/bash DATE=`date +%H-%M-%e-%m-%y` mkdir  /var/www/staging/$DATE/ mkdir /var/www/staging-private/$DATE/ svn export --quiet --username phpne --password PhpN3 httP://localhost/svn/project/trunk /var/www/staging/$DATE/ svn export --quiet --username phpne --password PhpN3 http://localhost/svn/project/private /var/www/staging-private/$DATE/
SVN Export Keep your servers svn client happy! It will ask what to do with the svn password, and nobody will listen – so tell it! sudonano /var/www/.subversion/servers store-plaintext-passwords = no
Autonomy ln –s /staging /live
Autonomy When the latest code is checked out, tests have been run, uploads imported, configuration changed and database patched we need to swap this into place instantly The answer: symlinks
#!/bin/bash DATE=`date +%H-%M-%e-%m-%y` ... rm /home/user/public_html/ ln –s /var/www/staging/$DATE/ /home/user/public_html/ Sadly, you can’t edit a symlink, hence rm
My user profile pictures aren’t in version control…
User contributed files Store them elsewhere? On a content delivery network? On a sub-domain Symlink them Copy them in post svn export? A bit nasty and takes time, and what about new user uploads during the copying process?
The database
Photo of database table not found, or mysql gone away error message http://www.flickr.com/photos/meandmybadself/165846637/
Database changes: patches For database changes to apply on deploy, you need some deploy aware code in your project.   Multi-query patch processing Schema compare; its easy to forget a database patch! Backup database before applying patches
public function updateDatabase( $patchID, $some=false )  {  	// look for the next patch  	if( file_exists( FRAMEWORK_PATH . '../database/patches/' . ++$patchID . '.php' ) )  	{  		$sql = file_get_contents( FRAMEWORK_PATH . 	'../database/patches/' . $patchID . '.php' ); 		// apply the changes from the patch  mysqli_multi_query( $sql );  		// lather, rinse and repeat 		$this->updateDatabase( $patchID, true );  	}  	else if( $some )  	{  		// All done? Update patch ID in database mysqli_query(“UPDATE settings SET `value`=” . $patchID-1 . “ WHERE `key`=‘database-patch-id’ ” ); 		exit();   	}  } Apply your database patches
$testTables = array(); mysqli_select_db( $config['patched_db'] ); $result = mysql_query("SHOW TABLES"); while( $row = mysql_fetch_row($result) )  { 	$testTables[ $row[0] ] = array(); } foreach( $testTables as $table => $fields ) { 	$result = mysql_query("SHOW COLUMNS FROM " . $table ); 	while( $row = mysql_fetch_assoc( $result ) )  	{ 		$tables[ $table ][ $row['Field'] ] = $row; 	} } Turn your database schema into an array
Compare your patched database to what you expected http://joefreeman.co.uk/blog/2009/07/php-script-to-compare-mysql-database-schemas/
Databases: Test Database If you are applying changes to your database structure, you will need another test database Changes are first applied to the test database Comparisons run against it Unit testing run against code working with that database When all is clear, the live database can be patched and upgraded
Ask the audience Database integration, patching, testing and deployment is probably the weakest link in this deployment chain
Unit testing While its good practice to only commit code which passes unit tests, sometimes a commit can break existing code if you are a lazy svn updater Run the unit tests against sandboxed code before pushing the deployment live Did the deployment fail?
Unit testing Both PHPUnit and PHP SimpleTest have command line interface Options: Parse the output and look for errors; then continue once its done Store a report, and require manual approval before continuing with deployment phpunit –testdox-text somefile.txt MyTests *this isn’t a stage I’ve actually implemented in our deployment pipeline, just something I’m working on
The problem with including Unit Tests Running unit tests take time We need to log deployment attempts, and try and deploy them once the tests have been run We need a central deployment system
Photo of USB “kill switch” http://www.flickr.com/photos/stevendepolo/3517227492/
Triggering deployment: PHP echo shell_exec( ‘/var/deploy/deploy.sh ’ . $project . ‘ ‘ . $environment ); What about root? Deployment script requires root access? Update sudoers file
PHP Deploy as Root Edit the sudoers file Sudovisudo Create an alias for your deployment scripts Cmnd_Alias DPLY = /var/deploy/script1, /var/deploy/script2 Let the webserver execute as root, without requiring a password www-data	ALL=(ALL)	NOPASSWD:	    DPLY
Automating deployment Cron Postcommit hooks Do this for your bleeding edge staging area; its good to continually test code in its live server environment Scheduled deployments
Deployment Infrastructure Deploying projects across multiple servers? Send your commands over SSH to a remote server Implement a skeleton deployment system on each server, called from a central deployment area
Build a deployment platform Projects Deployment areas: Bleeding Staging Production Configurations, reports and deployment schedules
Recap Export your repository Apply your permission changes Swap in/out the appropriate configuration files Backup your (test) database Patch your database Unit test validation Swap in/out your configuration files Pull in user contributed files Backup your environment database Patch your live database Update your symlinks
Rolling back Shit! That last deployment didn’t go as planned! Symlinks let you keep copies Database backup before patches were applied – just incase Database patch rollback files – allows you to keep new data but undo structural changes Make an undo button in your deployment platform; if you don’t you will need it – if you do, you wont*! * OK, I lied, you probably will at some point
Caveats Queue cheesy stock photo of confused bean figure
Caveats Some useful pointers when having multiple versions online (bleeding, staging and production) Keep robots out (robots.txt meta_robots) You don’t want search engines taking your users to the staging environment, nor do you want to be peanalised for duplicate content Keep unwanted users out (.htaccess or limited user database) Make it clear that the environment is non-production – in case a production user stumbles upon staging!
Conclusion Deployment needs to take into account a lot of things Small and simple home-brew scripts, processes and techniques should help you out Look at pulling them together into a simple web-based deployment centre
Deploy your projects quickly! @michaelpeacock mkpeacock@gmail.com michaelpeacock.co.uk http://slidesha.re/phpdeploy  http://www.flickr.com/photos/jurvetson/4853963652/sizes/m/in/photostream/

Más contenido relacionado

La actualidad más candente

Virtualization auditing & security deck v1.0
Virtualization auditing & security deck v1.0Virtualization auditing & security deck v1.0
Virtualization auditing & security deck v1.0
Concentrated Technology
 
Practical SVN for PHP Developers
Practical SVN for PHP DevelopersPractical SVN for PHP Developers
Practical SVN for PHP Developers
Lorna Mitchell
 
ScalabilityAvailability
ScalabilityAvailabilityScalabilityAvailability
ScalabilityAvailability
webuploader
 
Subversion on-the-fly replication
Subversion on-the-fly replicationSubversion on-the-fly replication
Subversion on-the-fly replication
normanmaurer
 
WebSphere : High Performance Extensible Logging
WebSphere : High Performance Extensible LoggingWebSphere : High Performance Extensible Logging
WebSphere : High Performance Extensible Logging
Joseph's WebSphere Library
 
The Pensions Trust - VM Backup Experiences
The Pensions Trust - VM Backup ExperiencesThe Pensions Trust - VM Backup Experiences
The Pensions Trust - VM Backup Experiences
glbsolutions
 
Subversion Overview
Subversion OverviewSubversion Overview
Subversion Overview
polarion
 

La actualidad más candente (20)

Virtualization auditing & security deck v1.0
Virtualization auditing & security deck v1.0Virtualization auditing & security deck v1.0
Virtualization auditing & security deck v1.0
 
Svn Basic Tutorial
Svn Basic TutorialSvn Basic Tutorial
Svn Basic Tutorial
 
Subversion workshop
Subversion workshopSubversion workshop
Subversion workshop
 
Nguyễn Vũ Hưng: Subversion best practices
Nguyễn Vũ Hưng: Subversion best practicesNguyễn Vũ Hưng: Subversion best practices
Nguyễn Vũ Hưng: Subversion best practices
 
Getting Started With Subversion
Getting Started With SubversionGetting Started With Subversion
Getting Started With Subversion
 
Practical SVN for PHP Developers
Practical SVN for PHP DevelopersPractical SVN for PHP Developers
Practical SVN for PHP Developers
 
ScalabilityAvailability
ScalabilityAvailabilityScalabilityAvailability
ScalabilityAvailability
 
Users guide
Users guideUsers guide
Users guide
 
Subversion on-the-fly replication
Subversion on-the-fly replicationSubversion on-the-fly replication
Subversion on-the-fly replication
 
Version Control with Subversion
Version Control with SubversionVersion Control with Subversion
Version Control with Subversion
 
Top ESXi command line v2.0
Top ESXi command line v2.0Top ESXi command line v2.0
Top ESXi command line v2.0
 
From VB Script to PowerShell
From VB Script to PowerShellFrom VB Script to PowerShell
From VB Script to PowerShell
 
Maven 2 - more than a build tool
Maven 2 - more than a build toolMaven 2 - more than a build tool
Maven 2 - more than a build tool
 
WebSphere : High Performance Extensible Logging
WebSphere : High Performance Extensible LoggingWebSphere : High Performance Extensible Logging
WebSphere : High Performance Extensible Logging
 
The Pensions Trust - VM Backup Experiences
The Pensions Trust - VM Backup ExperiencesThe Pensions Trust - VM Backup Experiences
The Pensions Trust - VM Backup Experiences
 
Flyway - database migrations made easy
Flyway - database migrations made easyFlyway - database migrations made easy
Flyway - database migrations made easy
 
Subversion Retake
Subversion RetakeSubversion Retake
Subversion Retake
 
SVN Tool Information : Best Practices
SVN Tool Information  : Best PracticesSVN Tool Information  : Best Practices
SVN Tool Information : Best Practices
 
Subversion Overview
Subversion OverviewSubversion Overview
Subversion Overview
 
SVN Best Practices
SVN Best PracticesSVN Best Practices
SVN Best Practices
 

Destacado

Angel capital primer_10aug2010_bw
Angel capital primer_10aug2010_bwAngel capital primer_10aug2010_bw
Angel capital primer_10aug2010_bw
Bryan Watson
 
Poch dela rosa_how to use google call phone.ppt
Poch dela rosa_how to use google call phone.pptPoch dela rosa_how to use google call phone.ppt
Poch dela rosa_how to use google call phone.ppt
pocholo_dlr
 
Pecha kucha example
Pecha kucha examplePecha kucha example
Pecha kucha example
Bow83
 
Chapter1.3 alghonors
Chapter1.3 alghonorsChapter1.3 alghonors
Chapter1.3 alghonors
nglaze10
 
New week 9
New week 9New week 9
New week 9
nglaze10
 
Golding show Projektleírás
Golding show ProjektleírásGolding show Projektleírás
Golding show Projektleírás
vvirag81
 
Chapter1.5 alghonors
Chapter1.5 alghonorsChapter1.5 alghonors
Chapter1.5 alghonors
nglaze10
 
монгол хэл 2
монгол хэл 2монгол хэл 2
монгол хэл 2
buzuuhai
 
хүн орчин
хүн орчинхүн орчин
хүн орчин
buzuuhai
 

Destacado (20)

Angel capital primer_10aug2010_bw
Angel capital primer_10aug2010_bwAngel capital primer_10aug2010_bw
Angel capital primer_10aug2010_bw
 
Tárgyfelvétel - alap változat
Tárgyfelvétel - alap változatTárgyfelvétel - alap változat
Tárgyfelvétel - alap változat
 
Poch dela rosa_how to use google call phone.ppt
Poch dela rosa_how to use google call phone.pptPoch dela rosa_how to use google call phone.ppt
Poch dela rosa_how to use google call phone.ppt
 
Bretelle1
Bretelle1Bretelle1
Bretelle1
 
Pecha kucha example
Pecha kucha examplePecha kucha example
Pecha kucha example
 
4.4 notes
4.4 notes4.4 notes
4.4 notes
 
7 Email Deliverability Myths
7 Email Deliverability Myths7 Email Deliverability Myths
7 Email Deliverability Myths
 
Chapter1.3 alghonors
Chapter1.3 alghonorsChapter1.3 alghonors
Chapter1.3 alghonors
 
New week 9
New week 9New week 9
New week 9
 
Golding show Projektleírás
Golding show ProjektleírásGolding show Projektleírás
Golding show Projektleírás
 
Chapter1.5 alghonors
Chapter1.5 alghonorsChapter1.5 alghonors
Chapter1.5 alghonors
 
Coral Catastrophe
Coral CatastropheCoral Catastrophe
Coral Catastrophe
 
Potenciar las habilidades del pensamiento empleando las redes
Potenciar las habilidades del pensamiento empleando las redesPotenciar las habilidades del pensamiento empleando las redes
Potenciar las habilidades del pensamiento empleando las redes
 
7.3
7.37.3
7.3
 
End of Year Tax Reporting—Make sure your credit union is prepared! (Webinar S...
End of Year Tax Reporting—Make sure your credit union is prepared! (Webinar S...End of Year Tax Reporting—Make sure your credit union is prepared! (Webinar S...
End of Year Tax Reporting—Make sure your credit union is prepared! (Webinar S...
 
TNS Aisa - Češi v síti - Advertising Conference 2012 - IAC
TNS Aisa - Češi v síti - Advertising Conference 2012 - IACTNS Aisa - Češi v síti - Advertising Conference 2012 - IAC
TNS Aisa - Češi v síti - Advertising Conference 2012 - IAC
 
Aloitus
AloitusAloitus
Aloitus
 
монгол хэл 2
монгол хэл 2монгол хэл 2
монгол хэл 2
 
хүн орчин
хүн орчинхүн орчин
хүн орчин
 
When Opportunity Meets Action by White Sheep Social Marketing
When Opportunity Meets Action by White Sheep Social MarketingWhen Opportunity Meets Action by White Sheep Social Marketing
When Opportunity Meets Action by White Sheep Social Marketing
 

Similar a Automated Deployment

Sa106 – practical solutions for connections administrators
Sa106 – practical solutions for connections administratorsSa106 – practical solutions for connections administrators
Sa106 – practical solutions for connections administrators
Sharon James
 
Embracing Distributed Version Control
Embracing Distributed Version ControlEmbracing Distributed Version Control
Embracing Distributed Version Control
Nowell Strite
 
Slides from LAX & DEN usergroup meetings
Slides from LAX & DEN usergroup meetingsSlides from LAX & DEN usergroup meetings
Slides from LAX & DEN usergroup meetings
10n Software, LLC
 
DCSF19 Transforming a 15+ Year Old Semiconductor Manufacturing Environment
DCSF19 Transforming a 15+ Year Old Semiconductor Manufacturing EnvironmentDCSF19 Transforming a 15+ Year Old Semiconductor Manufacturing Environment
DCSF19 Transforming a 15+ Year Old Semiconductor Manufacturing Environment
Docker, Inc.
 

Similar a Automated Deployment (20)

Care and Feeding of Large Web Applications
Care and Feeding of Large Web ApplicationsCare and Feeding of Large Web Applications
Care and Feeding of Large Web Applications
 
Ready, Set, Upgrade!
Ready, Set, Upgrade!Ready, Set, Upgrade!
Ready, Set, Upgrade!
 
North east user group tour
North east user group tourNorth east user group tour
North east user group tour
 
Migrating to SharePoint 2013 - Business and Technical Perspective
Migrating to SharePoint 2013 - Business and Technical PerspectiveMigrating to SharePoint 2013 - Business and Technical Perspective
Migrating to SharePoint 2013 - Business and Technical Perspective
 
Care and feeding notes
Care and feeding notesCare and feeding notes
Care and feeding notes
 
IUG ATL PC 9.5
IUG ATL PC 9.5IUG ATL PC 9.5
IUG ATL PC 9.5
 
Schema migration (DB migration) with Phinx
Schema migration (DB migration) with PhinxSchema migration (DB migration) with Phinx
Schema migration (DB migration) with Phinx
 
Best practices for share point solution deployment
Best practices for share point solution deploymentBest practices for share point solution deployment
Best practices for share point solution deployment
 
Sa106 – practical solutions for connections administrators
Sa106 – practical solutions for connections administratorsSa106 – practical solutions for connections administrators
Sa106 – practical solutions for connections administrators
 
WordPress Architecture for Tech-Savvy Managers
WordPress Architecture for Tech-Savvy ManagersWordPress Architecture for Tech-Savvy Managers
WordPress Architecture for Tech-Savvy Managers
 
SharePoint Upgrade (WSS 2.0 to WSS 3.0 and SPS 2003 to MOSS 2007) by Joel Ole...
SharePoint Upgrade (WSS 2.0 to WSS 3.0 and SPS 2003 to MOSS 2007) by Joel Ole...SharePoint Upgrade (WSS 2.0 to WSS 3.0 and SPS 2003 to MOSS 2007) by Joel Ole...
SharePoint Upgrade (WSS 2.0 to WSS 3.0 and SPS 2003 to MOSS 2007) by Joel Ole...
 
SynapseIndia drupal presentation on drupal info
SynapseIndia drupal  presentation on drupal infoSynapseIndia drupal  presentation on drupal info
SynapseIndia drupal presentation on drupal info
 
Azure DevOps for JavaScript Developers
Azure DevOps for JavaScript DevelopersAzure DevOps for JavaScript Developers
Azure DevOps for JavaScript Developers
 
Embracing Distributed Version Control
Embracing Distributed Version ControlEmbracing Distributed Version Control
Embracing Distributed Version Control
 
Connections install in 45 mins
Connections install in 45 minsConnections install in 45 mins
Connections install in 45 mins
 
Slides from LAX & DEN usergroup meetings
Slides from LAX & DEN usergroup meetingsSlides from LAX & DEN usergroup meetings
Slides from LAX & DEN usergroup meetings
 
SoCalCodeCamp Upgrade Microsoft Office SharePoint Server 2007 to SharePoint S...
SoCalCodeCamp Upgrade Microsoft Office SharePoint Server 2007 to SharePoint S...SoCalCodeCamp Upgrade Microsoft Office SharePoint Server 2007 to SharePoint S...
SoCalCodeCamp Upgrade Microsoft Office SharePoint Server 2007 to SharePoint S...
 
Practical solutions for connections administrators
Practical solutions for connections administratorsPractical solutions for connections administrators
Practical solutions for connections administrators
 
DCSF19 Transforming a 15+ Year Old Semiconductor Manufacturing Environment
DCSF19 Transforming a 15+ Year Old Semiconductor Manufacturing EnvironmentDCSF19 Transforming a 15+ Year Old Semiconductor Manufacturing Environment
DCSF19 Transforming a 15+ Year Old Semiconductor Manufacturing Environment
 
Scaling 101 test
Scaling 101 testScaling 101 test
Scaling 101 test
 

Último

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Último (20)

Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 

Automated Deployment

  • 1. Automated Deployment Building a simple automated deployment platform with PHP and Linux Michael Peacock@michaelpeacockmichaelpeacock.co.uk
  • 2. whois? Senior / Lead Web Developer Zend Certified Engineer Published Author PHP 5 Social Networking, PHP 5 E-Commerce development & more
  • 3. Deployment: (an) old style approach Take website offline / put into maintenance mode Backup everything Upload new files - FTP Upgrade database Put online, and hope for the best Do it twice: once for staging and once for deployment
  • 5. The problem Down time for upgrades Manual process FTP takes time; forgot to CHMOD? Clients want to see progress now! Bugs and issues can lie dormant for some time
  • 6. What about... Many existing solutions are geared towards large projects What about... the little guy; the small agency the web app start up on an entry level VPS?
  • 7. What's in store? A few simple techniques, scripts and ideas that we currently use to make deployment easy
  • 8. Deployment: the basics Get your latest code from version control, and stick it online Keep a central record of all the CHMOD / CHOWNing that you need to do Swap around your database connection details and other suitable configuration files
  • 9. SVN Export Start with a simple svn export Store the date/time in a variable Create two folders, named with the current date/time. One within the web root, one outside of it Two exports: public and private (or one export, and some moving around of folders – up to you!)
  • 10. #!/bin/bash DATE=`date +%H-%M-%e-%m-%y` mkdir /var/www/staging/$DATE/ mkdir /var/www/staging-private/$DATE/ svn export --quiet --username phpne --password PhpN3 httP://localhost/svn/project/trunk /var/www/staging/$DATE/ svn export --quiet --username phpne --password PhpN3 http://localhost/svn/project/private /var/www/staging-private/$DATE/
  • 11. SVN Export Keep your servers svn client happy! It will ask what to do with the svn password, and nobody will listen – so tell it! sudonano /var/www/.subversion/servers store-plaintext-passwords = no
  • 12. Autonomy ln –s /staging /live
  • 13. Autonomy When the latest code is checked out, tests have been run, uploads imported, configuration changed and database patched we need to swap this into place instantly The answer: symlinks
  • 14. #!/bin/bash DATE=`date +%H-%M-%e-%m-%y` ... rm /home/user/public_html/ ln –s /var/www/staging/$DATE/ /home/user/public_html/ Sadly, you can’t edit a symlink, hence rm
  • 15. My user profile pictures aren’t in version control…
  • 16. User contributed files Store them elsewhere? On a content delivery network? On a sub-domain Symlink them Copy them in post svn export? A bit nasty and takes time, and what about new user uploads during the copying process?
  • 18. Photo of database table not found, or mysql gone away error message http://www.flickr.com/photos/meandmybadself/165846637/
  • 19. Database changes: patches For database changes to apply on deploy, you need some deploy aware code in your project. Multi-query patch processing Schema compare; its easy to forget a database patch! Backup database before applying patches
  • 20. public function updateDatabase( $patchID, $some=false ) { // look for the next patch if( file_exists( FRAMEWORK_PATH . '../database/patches/' . ++$patchID . '.php' ) ) { $sql = file_get_contents( FRAMEWORK_PATH . '../database/patches/' . $patchID . '.php' ); // apply the changes from the patch mysqli_multi_query( $sql ); // lather, rinse and repeat $this->updateDatabase( $patchID, true ); } else if( $some ) { // All done? Update patch ID in database mysqli_query(“UPDATE settings SET `value`=” . $patchID-1 . “ WHERE `key`=‘database-patch-id’ ” ); exit(); } } Apply your database patches
  • 21. $testTables = array(); mysqli_select_db( $config['patched_db'] ); $result = mysql_query("SHOW TABLES"); while( $row = mysql_fetch_row($result) ) { $testTables[ $row[0] ] = array(); } foreach( $testTables as $table => $fields ) { $result = mysql_query("SHOW COLUMNS FROM " . $table ); while( $row = mysql_fetch_assoc( $result ) ) { $tables[ $table ][ $row['Field'] ] = $row; } } Turn your database schema into an array
  • 22. Compare your patched database to what you expected http://joefreeman.co.uk/blog/2009/07/php-script-to-compare-mysql-database-schemas/
  • 23. Databases: Test Database If you are applying changes to your database structure, you will need another test database Changes are first applied to the test database Comparisons run against it Unit testing run against code working with that database When all is clear, the live database can be patched and upgraded
  • 24. Ask the audience Database integration, patching, testing and deployment is probably the weakest link in this deployment chain
  • 25. Unit testing While its good practice to only commit code which passes unit tests, sometimes a commit can break existing code if you are a lazy svn updater Run the unit tests against sandboxed code before pushing the deployment live Did the deployment fail?
  • 26. Unit testing Both PHPUnit and PHP SimpleTest have command line interface Options: Parse the output and look for errors; then continue once its done Store a report, and require manual approval before continuing with deployment phpunit –testdox-text somefile.txt MyTests *this isn’t a stage I’ve actually implemented in our deployment pipeline, just something I’m working on
  • 27. The problem with including Unit Tests Running unit tests take time We need to log deployment attempts, and try and deploy them once the tests have been run We need a central deployment system
  • 28. Photo of USB “kill switch” http://www.flickr.com/photos/stevendepolo/3517227492/
  • 29. Triggering deployment: PHP echo shell_exec( ‘/var/deploy/deploy.sh ’ . $project . ‘ ‘ . $environment ); What about root? Deployment script requires root access? Update sudoers file
  • 30. PHP Deploy as Root Edit the sudoers file Sudovisudo Create an alias for your deployment scripts Cmnd_Alias DPLY = /var/deploy/script1, /var/deploy/script2 Let the webserver execute as root, without requiring a password www-data ALL=(ALL) NOPASSWD: DPLY
  • 31. Automating deployment Cron Postcommit hooks Do this for your bleeding edge staging area; its good to continually test code in its live server environment Scheduled deployments
  • 32. Deployment Infrastructure Deploying projects across multiple servers? Send your commands over SSH to a remote server Implement a skeleton deployment system on each server, called from a central deployment area
  • 33. Build a deployment platform Projects Deployment areas: Bleeding Staging Production Configurations, reports and deployment schedules
  • 34. Recap Export your repository Apply your permission changes Swap in/out the appropriate configuration files Backup your (test) database Patch your database Unit test validation Swap in/out your configuration files Pull in user contributed files Backup your environment database Patch your live database Update your symlinks
  • 35. Rolling back Shit! That last deployment didn’t go as planned! Symlinks let you keep copies Database backup before patches were applied – just incase Database patch rollback files – allows you to keep new data but undo structural changes Make an undo button in your deployment platform; if you don’t you will need it – if you do, you wont*! * OK, I lied, you probably will at some point
  • 36. Caveats Queue cheesy stock photo of confused bean figure
  • 37. Caveats Some useful pointers when having multiple versions online (bleeding, staging and production) Keep robots out (robots.txt meta_robots) You don’t want search engines taking your users to the staging environment, nor do you want to be peanalised for duplicate content Keep unwanted users out (.htaccess or limited user database) Make it clear that the environment is non-production – in case a production user stumbles upon staging!
  • 38. Conclusion Deployment needs to take into account a lot of things Small and simple home-brew scripts, processes and techniques should help you out Look at pulling them together into a simple web-based deployment centre
  • 39. Deploy your projects quickly! @michaelpeacock mkpeacock@gmail.com michaelpeacock.co.uk http://slidesha.re/phpdeploy http://www.flickr.com/photos/jurvetson/4853963652/sizes/m/in/photostream/

Notas del editor

  1. Store expected schema, and generate schema array from applied patches.